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/ioeeg/ktlx.py | Ktlx.return_dat | def return_dat(self, chan, begsam, endsam):
"""Read the data based on begsam and endsam.
Parameters
----------
chan : list of int
list of channel indeces
begsam : int
index of the first sample
endsam :
index of the last sample
Returns
-------
ndarray
2-d matrix with data (might contain NaN)
Notes
-----
The sample numbering is not based on the samples in the files (i.e.
the first sample of the first file is NOT the first sample of the
dataset) because it depends on the stamps in the STC file. Usually, the
recording starts and after a few millisecond (maybe one second), the
actual acquisition starts. STC takes the offset into account. This has
the counterintuitive result that if you call read_data, the first few
hundreds samples are nan.
"""
dat = empty((len(chan), endsam - begsam))
dat.fill(NaN)
stc, all_stamp = _read_stc(self._filename.with_suffix('.stc'))
all_erd = all_stamp['segment_name'].astype('U') # convert to str
all_beg = all_stamp['start_stamp']
all_end = all_stamp['end_stamp']
try:
begrec = where((all_end >= begsam))[0][0]
endrec = where((all_beg < endsam))[0][-1]
except IndexError:
return dat
for rec in range(begrec, endrec + 1):
begpos_rec = max(begsam, all_beg[rec])
endpos_rec = min(endsam, all_end[rec] + 1) # check + 1
# this looks weird, but it takes into account whether the values
# are outside of the limits of the file
d1 = begpos_rec - begsam
d2 = endpos_rec - begsam
erd_file = (Path(self.filename) / all_erd[rec]).with_suffix('.erd')
try:
dat_rec = _read_erd(erd_file, begpos_rec, endpos_rec)
dat[:, d1:d2] = dat_rec[chan, :]
except (FileNotFoundError, PermissionError):
lg.warning('{} does not exist'.format(erd_file))
return dat | python | def return_dat(self, chan, begsam, endsam):
"""Read the data based on begsam and endsam.
Parameters
----------
chan : list of int
list of channel indeces
begsam : int
index of the first sample
endsam :
index of the last sample
Returns
-------
ndarray
2-d matrix with data (might contain NaN)
Notes
-----
The sample numbering is not based on the samples in the files (i.e.
the first sample of the first file is NOT the first sample of the
dataset) because it depends on the stamps in the STC file. Usually, the
recording starts and after a few millisecond (maybe one second), the
actual acquisition starts. STC takes the offset into account. This has
the counterintuitive result that if you call read_data, the first few
hundreds samples are nan.
"""
dat = empty((len(chan), endsam - begsam))
dat.fill(NaN)
stc, all_stamp = _read_stc(self._filename.with_suffix('.stc'))
all_erd = all_stamp['segment_name'].astype('U') # convert to str
all_beg = all_stamp['start_stamp']
all_end = all_stamp['end_stamp']
try:
begrec = where((all_end >= begsam))[0][0]
endrec = where((all_beg < endsam))[0][-1]
except IndexError:
return dat
for rec in range(begrec, endrec + 1):
begpos_rec = max(begsam, all_beg[rec])
endpos_rec = min(endsam, all_end[rec] + 1) # check + 1
# this looks weird, but it takes into account whether the values
# are outside of the limits of the file
d1 = begpos_rec - begsam
d2 = endpos_rec - begsam
erd_file = (Path(self.filename) / all_erd[rec]).with_suffix('.erd')
try:
dat_rec = _read_erd(erd_file, begpos_rec, endpos_rec)
dat[:, d1:d2] = dat_rec[chan, :]
except (FileNotFoundError, PermissionError):
lg.warning('{} does not exist'.format(erd_file))
return dat | [
"def",
"return_dat",
"(",
"self",
",",
"chan",
",",
"begsam",
",",
"endsam",
")",
":",
"dat",
"=",
"empty",
"(",
"(",
"len",
"(",
"chan",
")",
",",
"endsam",
"-",
"begsam",
")",
")",
"dat",
".",
"fill",
"(",
"NaN",
")",
"stc",
",",
"all_stamp",
... | Read the data based on begsam and endsam.
Parameters
----------
chan : list of int
list of channel indeces
begsam : int
index of the first sample
endsam :
index of the last sample
Returns
-------
ndarray
2-d matrix with data (might contain NaN)
Notes
-----
The sample numbering is not based on the samples in the files (i.e.
the first sample of the first file is NOT the first sample of the
dataset) because it depends on the stamps in the STC file. Usually, the
recording starts and after a few millisecond (maybe one second), the
actual acquisition starts. STC takes the offset into account. This has
the counterintuitive result that if you call read_data, the first few
hundreds samples are nan. | [
"Read",
"the",
"data",
"based",
"on",
"begsam",
"and",
"endsam",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L895-L955 | train | 23,600 |
wonambi-python/wonambi | wonambi/ioeeg/ktlx.py | Ktlx.return_markers | def return_markers(self):
"""Reads the notes of the Ktlx recordings.
"""
ent_file = self._filename.with_suffix('.ent')
if not ent_file.exists():
ent_file = self._filename.with_suffix('.ent.old')
try:
ent_notes = _read_ent(ent_file)
except (FileNotFoundError, PermissionError):
markers = []
else:
allnote = []
for n in ent_notes:
try:
n['value'].keys()
allnote.append(n['value'])
except AttributeError:
lg.debug('Note of length {} was not '
'converted to dict'.format(n['length']))
s_freq = self._hdr['erd']['sample_freq']
pcname = '0CFEBE72-DA20-4b3a-A8AC-CDD41BFE2F0D'
note_time = []
note_name = []
note_note = []
for n in allnote:
if n['Text'] == 'Analyzed Data Note':
continue
if not n['Text']:
continue
if 'User' not in n['Data'].keys():
continue
user1 = n['Data']['User'] == 'Persyst'
user2 = False # n['Data']['User'] == 'eeg'
user3 = n['Data']['User'] == pcname
user4 = n['Data']['User'] == 'XLSpike - Intracranial'
user5 = n['Data']['User'] == 'XLEvent - Intracranial'
if user1 or user2 or user3 or user4 or user5:
continue
if len(n['Data']['User']) == 0:
note_name.append('-unknown-')
else:
note_name.append(n['Data']['User'].split()[0])
note_time.append(n['Stamp'] / s_freq)
note_note.append(n['Text'])
markers = []
for time, name, note in zip(note_time, note_name, note_note):
m = {'name': note + ' (' + name + ')',
'start': time,
'end': time,
'chan': None,
}
markers.append(m)
return markers | python | def return_markers(self):
"""Reads the notes of the Ktlx recordings.
"""
ent_file = self._filename.with_suffix('.ent')
if not ent_file.exists():
ent_file = self._filename.with_suffix('.ent.old')
try:
ent_notes = _read_ent(ent_file)
except (FileNotFoundError, PermissionError):
markers = []
else:
allnote = []
for n in ent_notes:
try:
n['value'].keys()
allnote.append(n['value'])
except AttributeError:
lg.debug('Note of length {} was not '
'converted to dict'.format(n['length']))
s_freq = self._hdr['erd']['sample_freq']
pcname = '0CFEBE72-DA20-4b3a-A8AC-CDD41BFE2F0D'
note_time = []
note_name = []
note_note = []
for n in allnote:
if n['Text'] == 'Analyzed Data Note':
continue
if not n['Text']:
continue
if 'User' not in n['Data'].keys():
continue
user1 = n['Data']['User'] == 'Persyst'
user2 = False # n['Data']['User'] == 'eeg'
user3 = n['Data']['User'] == pcname
user4 = n['Data']['User'] == 'XLSpike - Intracranial'
user5 = n['Data']['User'] == 'XLEvent - Intracranial'
if user1 or user2 or user3 or user4 or user5:
continue
if len(n['Data']['User']) == 0:
note_name.append('-unknown-')
else:
note_name.append(n['Data']['User'].split()[0])
note_time.append(n['Stamp'] / s_freq)
note_note.append(n['Text'])
markers = []
for time, name, note in zip(note_time, note_name, note_note):
m = {'name': note + ' (' + name + ')',
'start': time,
'end': time,
'chan': None,
}
markers.append(m)
return markers | [
"def",
"return_markers",
"(",
"self",
")",
":",
"ent_file",
"=",
"self",
".",
"_filename",
".",
"with_suffix",
"(",
"'.ent'",
")",
"if",
"not",
"ent_file",
".",
"exists",
"(",
")",
":",
"ent_file",
"=",
"self",
".",
"_filename",
".",
"with_suffix",
"(",
... | Reads the notes of the Ktlx recordings. | [
"Reads",
"the",
"notes",
"of",
"the",
"Ktlx",
"recordings",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/ktlx.py#L1024-L1082 | train | 23,601 |
wonambi-python/wonambi | wonambi/ioeeg/blackrock.py | BlackRock.return_markers | def return_markers(self, trigger_bits=8, trigger_zero=True):
"""We always read triggers as 16bit, but we convert them to 8 here
if requested.
"""
nev_file = splitext(self.filename)[0] + '.nev'
markers = _read_neuralev(nev_file, read_markers=True)
if trigger_bits == 8:
to8 = lambda x: str(int(x) - (256 ** 2 - 256))
for m in markers:
m['name'] = to8(m['name'])
if trigger_zero:
no_zero = (i for i, m in enumerate(markers) if m['name'] != '0')
markers_no_zero = []
for i in no_zero:
if (i + 1) < len(markers) and markers[i + 1]['name'] == '0':
markers[i]['end'] = markers[i + 1]['start']
markers_no_zero.append(markers[i])
return markers_no_zero | python | def return_markers(self, trigger_bits=8, trigger_zero=True):
"""We always read triggers as 16bit, but we convert them to 8 here
if requested.
"""
nev_file = splitext(self.filename)[0] + '.nev'
markers = _read_neuralev(nev_file, read_markers=True)
if trigger_bits == 8:
to8 = lambda x: str(int(x) - (256 ** 2 - 256))
for m in markers:
m['name'] = to8(m['name'])
if trigger_zero:
no_zero = (i for i, m in enumerate(markers) if m['name'] != '0')
markers_no_zero = []
for i in no_zero:
if (i + 1) < len(markers) and markers[i + 1]['name'] == '0':
markers[i]['end'] = markers[i + 1]['start']
markers_no_zero.append(markers[i])
return markers_no_zero | [
"def",
"return_markers",
"(",
"self",
",",
"trigger_bits",
"=",
"8",
",",
"trigger_zero",
"=",
"True",
")",
":",
"nev_file",
"=",
"splitext",
"(",
"self",
".",
"filename",
")",
"[",
"0",
"]",
"+",
"'.nev'",
"markers",
"=",
"_read_neuralev",
"(",
"nev_fil... | We always read triggers as 16bit, but we convert them to 8 here
if requested. | [
"We",
"always",
"read",
"triggers",
"as",
"16bit",
"but",
"we",
"convert",
"them",
"to",
"8",
"here",
"if",
"requested",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/blackrock.py#L144-L166 | train | 23,602 |
wonambi-python/wonambi | wonambi/trans/extern/dpss.py | tridi_inverse_iteration | def tridi_inverse_iteration(d, e, w, x0=None, rtol=1e-8):
"""Perform an inverse iteration to find the eigenvector corresponding
to the given eigenvalue in a symmetric tridiagonal system.
Parameters
----------
d : ndarray
main diagonal of the tridiagonal system
e : ndarray
offdiagonal stored in e[:-1]
w : float
eigenvalue of the eigenvector
x0 : ndarray
initial point to start the iteration
rtol : float
tolerance for the norm of the difference of iterates
Returns
-------
e : ndarray
The converged eigenvector
"""
eig_diag = d - w
if x0 is None:
x0 = np.random.randn(len(d))
x_prev = np.zeros_like(x0)
norm_x = np.linalg.norm(x0)
# the eigenvector is unique up to sign change, so iterate
# until || |x^(n)| - |x^(n-1)| ||^2 < rtol
x0 /= norm_x
while np.linalg.norm(np.abs(x0) - np.abs(x_prev)) > rtol:
x_prev = x0.copy()
tridisolve(eig_diag, e, x0)
norm_x = np.linalg.norm(x0)
x0 /= norm_x
return x0 | python | def tridi_inverse_iteration(d, e, w, x0=None, rtol=1e-8):
"""Perform an inverse iteration to find the eigenvector corresponding
to the given eigenvalue in a symmetric tridiagonal system.
Parameters
----------
d : ndarray
main diagonal of the tridiagonal system
e : ndarray
offdiagonal stored in e[:-1]
w : float
eigenvalue of the eigenvector
x0 : ndarray
initial point to start the iteration
rtol : float
tolerance for the norm of the difference of iterates
Returns
-------
e : ndarray
The converged eigenvector
"""
eig_diag = d - w
if x0 is None:
x0 = np.random.randn(len(d))
x_prev = np.zeros_like(x0)
norm_x = np.linalg.norm(x0)
# the eigenvector is unique up to sign change, so iterate
# until || |x^(n)| - |x^(n-1)| ||^2 < rtol
x0 /= norm_x
while np.linalg.norm(np.abs(x0) - np.abs(x_prev)) > rtol:
x_prev = x0.copy()
tridisolve(eig_diag, e, x0)
norm_x = np.linalg.norm(x0)
x0 /= norm_x
return x0 | [
"def",
"tridi_inverse_iteration",
"(",
"d",
",",
"e",
",",
"w",
",",
"x0",
"=",
"None",
",",
"rtol",
"=",
"1e-8",
")",
":",
"eig_diag",
"=",
"d",
"-",
"w",
"if",
"x0",
"is",
"None",
":",
"x0",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"len",... | Perform an inverse iteration to find the eigenvector corresponding
to the given eigenvalue in a symmetric tridiagonal system.
Parameters
----------
d : ndarray
main diagonal of the tridiagonal system
e : ndarray
offdiagonal stored in e[:-1]
w : float
eigenvalue of the eigenvector
x0 : ndarray
initial point to start the iteration
rtol : float
tolerance for the norm of the difference of iterates
Returns
-------
e : ndarray
The converged eigenvector | [
"Perform",
"an",
"inverse",
"iteration",
"to",
"find",
"the",
"eigenvector",
"corresponding",
"to",
"the",
"given",
"eigenvalue",
"in",
"a",
"symmetric",
"tridiagonal",
"system",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/extern/dpss.py#L136-L174 | train | 23,603 |
wonambi-python/wonambi | wonambi/trans/extern/dpss.py | tridisolve | def tridisolve(d, e, b, overwrite_b=True):
"""
Symmetric tridiagonal system solver,
from Golub and Van Loan, Matrix Computations pg 157
Parameters
----------
d : ndarray
main diagonal stored in d[:]
e : ndarray
superdiagonal stored in e[:-1]
b : ndarray
RHS vector
Returns
-------
x : ndarray
Solution to Ax = b (if overwrite_b is False). Otherwise solution is
stored in previous RHS vector b
"""
N = len(b)
# work vectors
dw = d.copy()
ew = e.copy()
if overwrite_b:
x = b
else:
x = b.copy()
for k in range(1, N):
# e^(k-1) = e(k-1) / d(k-1)
# d(k) = d(k) - e^(k-1)e(k-1) / d(k-1)
t = ew[k - 1]
ew[k - 1] = t / dw[k - 1]
dw[k] = dw[k] - t * ew[k - 1]
for k in range(1, N):
x[k] = x[k] - ew[k - 1] * x[k - 1]
x[N - 1] = x[N - 1] / dw[N - 1]
for k in range(N - 2, -1, -1):
x[k] = x[k] / dw[k] - ew[k] * x[k + 1]
if not overwrite_b:
return x | python | def tridisolve(d, e, b, overwrite_b=True):
"""
Symmetric tridiagonal system solver,
from Golub and Van Loan, Matrix Computations pg 157
Parameters
----------
d : ndarray
main diagonal stored in d[:]
e : ndarray
superdiagonal stored in e[:-1]
b : ndarray
RHS vector
Returns
-------
x : ndarray
Solution to Ax = b (if overwrite_b is False). Otherwise solution is
stored in previous RHS vector b
"""
N = len(b)
# work vectors
dw = d.copy()
ew = e.copy()
if overwrite_b:
x = b
else:
x = b.copy()
for k in range(1, N):
# e^(k-1) = e(k-1) / d(k-1)
# d(k) = d(k) - e^(k-1)e(k-1) / d(k-1)
t = ew[k - 1]
ew[k - 1] = t / dw[k - 1]
dw[k] = dw[k] - t * ew[k - 1]
for k in range(1, N):
x[k] = x[k] - ew[k - 1] * x[k - 1]
x[N - 1] = x[N - 1] / dw[N - 1]
for k in range(N - 2, -1, -1):
x[k] = x[k] / dw[k] - ew[k] * x[k + 1]
if not overwrite_b:
return x | [
"def",
"tridisolve",
"(",
"d",
",",
"e",
",",
"b",
",",
"overwrite_b",
"=",
"True",
")",
":",
"N",
"=",
"len",
"(",
"b",
")",
"# work vectors",
"dw",
"=",
"d",
".",
"copy",
"(",
")",
"ew",
"=",
"e",
".",
"copy",
"(",
")",
"if",
"overwrite_b",
... | Symmetric tridiagonal system solver,
from Golub and Van Loan, Matrix Computations pg 157
Parameters
----------
d : ndarray
main diagonal stored in d[:]
e : ndarray
superdiagonal stored in e[:-1]
b : ndarray
RHS vector
Returns
-------
x : ndarray
Solution to Ax = b (if overwrite_b is False). Otherwise solution is
stored in previous RHS vector b | [
"Symmetric",
"tridiagonal",
"system",
"solver",
"from",
"Golub",
"and",
"Van",
"Loan",
"Matrix",
"Computations",
"pg",
"157"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/extern/dpss.py#L177-L221 | train | 23,604 |
wonambi-python/wonambi | wonambi/trans/extern/dpss.py | autocov | def autocov(x, **kwargs):
"""Returns the autocovariance of signal s at all lags.
Parameters
----------
x : ndarray
axis : time axis
all_lags : {True/False}
whether to return all nonzero lags, or to clip the length of r_xy
to be the length of x and y. If False, then the zero lag correlation
is at index 0. Otherwise, it is found at (len(x) + len(y) - 1)/2
Returns
-------
cxx : ndarray
The autocovariance function
Notes
-----
Adheres to the definition
.. math::
C_{xx}[k]=E\{(X[n+k]-E\{X\})(X[n]-E\{X\})^{*}\}
where X is a discrete, stationary (ergodic) random process
"""
# only remove the mean once, if needed
debias = kwargs.pop('debias', True)
axis = kwargs.get('axis', -1)
if debias:
x = remove_bias(x, axis)
kwargs['debias'] = False
return crosscov(x, x, **kwargs) | python | def autocov(x, **kwargs):
"""Returns the autocovariance of signal s at all lags.
Parameters
----------
x : ndarray
axis : time axis
all_lags : {True/False}
whether to return all nonzero lags, or to clip the length of r_xy
to be the length of x and y. If False, then the zero lag correlation
is at index 0. Otherwise, it is found at (len(x) + len(y) - 1)/2
Returns
-------
cxx : ndarray
The autocovariance function
Notes
-----
Adheres to the definition
.. math::
C_{xx}[k]=E\{(X[n+k]-E\{X\})(X[n]-E\{X\})^{*}\}
where X is a discrete, stationary (ergodic) random process
"""
# only remove the mean once, if needed
debias = kwargs.pop('debias', True)
axis = kwargs.get('axis', -1)
if debias:
x = remove_bias(x, axis)
kwargs['debias'] = False
return crosscov(x, x, **kwargs) | [
"def",
"autocov",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
":",
"# only remove the mean once, if needed",
"debias",
"=",
"kwargs",
".",
"pop",
"(",
"'debias'",
",",
"True",
")",
"axis",
"=",
"kwargs",
".",
"get",
"(",
"'axis'",
",",
"-",
"1",
")",
"if",... | Returns the autocovariance of signal s at all lags.
Parameters
----------
x : ndarray
axis : time axis
all_lags : {True/False}
whether to return all nonzero lags, or to clip the length of r_xy
to be the length of x and y. If False, then the zero lag correlation
is at index 0. Otherwise, it is found at (len(x) + len(y) - 1)/2
Returns
-------
cxx : ndarray
The autocovariance function
Notes
-----
Adheres to the definition
.. math::
C_{xx}[k]=E\{(X[n+k]-E\{X\})(X[n]-E\{X\})^{*}\}
where X is a discrete, stationary (ergodic) random process | [
"Returns",
"the",
"autocovariance",
"of",
"signal",
"s",
"at",
"all",
"lags",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/extern/dpss.py#L255-L291 | train | 23,605 |
wonambi-python/wonambi | wonambi/trans/extern/dpss.py | fftconvolve | def fftconvolve(in1, in2, mode="full", axis=None):
""" Convolve two N-dimensional arrays using FFT. See convolve.
This is a fix of scipy.signal.fftconvolve, adding an axis argument and
importing locally the stuff only needed for this function
"""
s1 = np.array(in1.shape)
s2 = np.array(in2.shape)
complex_result = (np.issubdtype(in1.dtype, np.complexfloating) or
np.issubdtype(in2.dtype, np.complexfloating))
if axis is None:
size = s1 + s2 - 1
fslice = tuple([slice(0, int(sz)) for sz in size])
else:
equal_shapes = s1 == s2
# allow equal_shapes[axis] to be False
equal_shapes[axis] = True
assert equal_shapes.all(), 'Shape mismatch on non-convolving axes'
size = s1[axis] + s2[axis] - 1
fslice = [slice(l) for l in s1]
fslice[axis] = slice(0, int(size))
fslice = tuple(fslice)
# Always use 2**n-sized FFT
fsize = 2 ** int(np.ceil(np.log2(size)))
if axis is None:
IN1 = fftpack.fftn(in1, fsize)
IN1 *= fftpack.fftn(in2, fsize)
ret = fftpack.ifftn(IN1)[fslice].copy()
else:
IN1 = fftpack.fft(in1, fsize, axis=axis)
IN1 *= fftpack.fft(in2, fsize, axis=axis)
ret = fftpack.ifft(IN1, axis=axis)[fslice].copy()
del IN1
if not complex_result:
ret = ret.real
if mode == "full":
return ret
elif mode == "same":
if np.product(s1, axis=0) > np.product(s2, axis=0):
osize = s1
else:
osize = s2
return signaltools._centered(ret, osize)
elif mode == "valid":
return signaltools._centered(ret, abs(s2 - s1) + 1) | python | def fftconvolve(in1, in2, mode="full", axis=None):
""" Convolve two N-dimensional arrays using FFT. See convolve.
This is a fix of scipy.signal.fftconvolve, adding an axis argument and
importing locally the stuff only needed for this function
"""
s1 = np.array(in1.shape)
s2 = np.array(in2.shape)
complex_result = (np.issubdtype(in1.dtype, np.complexfloating) or
np.issubdtype(in2.dtype, np.complexfloating))
if axis is None:
size = s1 + s2 - 1
fslice = tuple([slice(0, int(sz)) for sz in size])
else:
equal_shapes = s1 == s2
# allow equal_shapes[axis] to be False
equal_shapes[axis] = True
assert equal_shapes.all(), 'Shape mismatch on non-convolving axes'
size = s1[axis] + s2[axis] - 1
fslice = [slice(l) for l in s1]
fslice[axis] = slice(0, int(size))
fslice = tuple(fslice)
# Always use 2**n-sized FFT
fsize = 2 ** int(np.ceil(np.log2(size)))
if axis is None:
IN1 = fftpack.fftn(in1, fsize)
IN1 *= fftpack.fftn(in2, fsize)
ret = fftpack.ifftn(IN1)[fslice].copy()
else:
IN1 = fftpack.fft(in1, fsize, axis=axis)
IN1 *= fftpack.fft(in2, fsize, axis=axis)
ret = fftpack.ifft(IN1, axis=axis)[fslice].copy()
del IN1
if not complex_result:
ret = ret.real
if mode == "full":
return ret
elif mode == "same":
if np.product(s1, axis=0) > np.product(s2, axis=0):
osize = s1
else:
osize = s2
return signaltools._centered(ret, osize)
elif mode == "valid":
return signaltools._centered(ret, abs(s2 - s1) + 1) | [
"def",
"fftconvolve",
"(",
"in1",
",",
"in2",
",",
"mode",
"=",
"\"full\"",
",",
"axis",
"=",
"None",
")",
":",
"s1",
"=",
"np",
".",
"array",
"(",
"in1",
".",
"shape",
")",
"s2",
"=",
"np",
".",
"array",
"(",
"in2",
".",
"shape",
")",
"complex... | Convolve two N-dimensional arrays using FFT. See convolve.
This is a fix of scipy.signal.fftconvolve, adding an axis argument and
importing locally the stuff only needed for this function | [
"Convolve",
"two",
"N",
"-",
"dimensional",
"arrays",
"using",
"FFT",
".",
"See",
"convolve",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/extern/dpss.py#L352-L399 | train | 23,606 |
wonambi-python/wonambi | wonambi/trans/frequency.py | band_power | def band_power(data, freq, scaling='power', n_fft=None, detrend=None,
array_out=False):
"""Compute power or energy acoss a frequency band, and its peak frequency.
Power is estimated using the mid-point rectangle rule. Input can be
ChanTime or ChanFreq.
Parameters
----------
data : instance of ChanTime or ChanFreq
data to be analyzed, one trial only
freq : tuple of float
Frequencies for band of interest. Power will be integrated across this
band, inclusively, and peak frequency determined within it. If a value
is None, the band is unbounded in that direction.
input_type : str
'time' or 'spectrum'
scaling : str
'power' or 'energy', only used if data is ChanTime
n_fft : int
length of FFT. if shorter than input signal, signal is truncated; if
longer, signal is zero-padded to length
array_out : bool
if True, will return two arrays instead of two dict.
Returns
-------
dict of float, or ndarray
keys are channels, values are power or energy
dict of float, or ndarray
keys are channels, values are respective peak frequency
"""
if not array_out:
power = {}
peakf = {}
else:
power = zeros((data.number_of('chan')[0], 1))
peakf = zeros((data.number_of('chan')[0], 1))
if isinstance(data, ChanFreq):
Sxx = data
elif isinstance(data, ChanTime):
Sxx = frequency(data, scaling=scaling, n_fft=n_fft, detrend=detrend)
else:
raise ValueError('Invalid data type')
if detrend is None:
if 'power' == scaling:
detrend = 'linear'
elif 'energy' == scaling:
detrend = None
sf = Sxx.axis['freq'][0]
f_res = sf[1] - sf[0] # frequency resolution
if freq[0] is not None:
idx_f1 = asarray([abs(x - freq[0]) for x in sf]).argmin()
else:
idx_f1 = 0
if freq[1] is not None:
idx_f2 = min(asarray([abs(x - freq[1]) for x in sf]).argmin() + 1,
len(sf) - 1) # inclusive, to follow convention
else:
idx_f2 = len(sf) - 1
for i, chan in enumerate(Sxx.axis['chan'][0]):
s = Sxx(chan=chan)[0]
pw = sum(s[idx_f1:idx_f2]) * f_res
idx_peak = s[idx_f1:idx_f2].argmax()
pf = sf[idx_f1:idx_f2][idx_peak]
if array_out:
power[i, 0] = pw
peakf[i, 0] = pf
else:
power[chan] = pw
peakf[chan] = pf
return power, peakf | python | def band_power(data, freq, scaling='power', n_fft=None, detrend=None,
array_out=False):
"""Compute power or energy acoss a frequency band, and its peak frequency.
Power is estimated using the mid-point rectangle rule. Input can be
ChanTime or ChanFreq.
Parameters
----------
data : instance of ChanTime or ChanFreq
data to be analyzed, one trial only
freq : tuple of float
Frequencies for band of interest. Power will be integrated across this
band, inclusively, and peak frequency determined within it. If a value
is None, the band is unbounded in that direction.
input_type : str
'time' or 'spectrum'
scaling : str
'power' or 'energy', only used if data is ChanTime
n_fft : int
length of FFT. if shorter than input signal, signal is truncated; if
longer, signal is zero-padded to length
array_out : bool
if True, will return two arrays instead of two dict.
Returns
-------
dict of float, or ndarray
keys are channels, values are power or energy
dict of float, or ndarray
keys are channels, values are respective peak frequency
"""
if not array_out:
power = {}
peakf = {}
else:
power = zeros((data.number_of('chan')[0], 1))
peakf = zeros((data.number_of('chan')[0], 1))
if isinstance(data, ChanFreq):
Sxx = data
elif isinstance(data, ChanTime):
Sxx = frequency(data, scaling=scaling, n_fft=n_fft, detrend=detrend)
else:
raise ValueError('Invalid data type')
if detrend is None:
if 'power' == scaling:
detrend = 'linear'
elif 'energy' == scaling:
detrend = None
sf = Sxx.axis['freq'][0]
f_res = sf[1] - sf[0] # frequency resolution
if freq[0] is not None:
idx_f1 = asarray([abs(x - freq[0]) for x in sf]).argmin()
else:
idx_f1 = 0
if freq[1] is not None:
idx_f2 = min(asarray([abs(x - freq[1]) for x in sf]).argmin() + 1,
len(sf) - 1) # inclusive, to follow convention
else:
idx_f2 = len(sf) - 1
for i, chan in enumerate(Sxx.axis['chan'][0]):
s = Sxx(chan=chan)[0]
pw = sum(s[idx_f1:idx_f2]) * f_res
idx_peak = s[idx_f1:idx_f2].argmax()
pf = sf[idx_f1:idx_f2][idx_peak]
if array_out:
power[i, 0] = pw
peakf[i, 0] = pf
else:
power[chan] = pw
peakf[chan] = pf
return power, peakf | [
"def",
"band_power",
"(",
"data",
",",
"freq",
",",
"scaling",
"=",
"'power'",
",",
"n_fft",
"=",
"None",
",",
"detrend",
"=",
"None",
",",
"array_out",
"=",
"False",
")",
":",
"if",
"not",
"array_out",
":",
"power",
"=",
"{",
"}",
"peakf",
"=",
"{... | Compute power or energy acoss a frequency band, and its peak frequency.
Power is estimated using the mid-point rectangle rule. Input can be
ChanTime or ChanFreq.
Parameters
----------
data : instance of ChanTime or ChanFreq
data to be analyzed, one trial only
freq : tuple of float
Frequencies for band of interest. Power will be integrated across this
band, inclusively, and peak frequency determined within it. If a value
is None, the band is unbounded in that direction.
input_type : str
'time' or 'spectrum'
scaling : str
'power' or 'energy', only used if data is ChanTime
n_fft : int
length of FFT. if shorter than input signal, signal is truncated; if
longer, signal is zero-padded to length
array_out : bool
if True, will return two arrays instead of two dict.
Returns
-------
dict of float, or ndarray
keys are channels, values are power or energy
dict of float, or ndarray
keys are channels, values are respective peak frequency | [
"Compute",
"power",
"or",
"energy",
"acoss",
"a",
"frequency",
"band",
"and",
"its",
"peak",
"frequency",
".",
"Power",
"is",
"estimated",
"using",
"the",
"mid",
"-",
"point",
"rectangle",
"rule",
".",
"Input",
"can",
"be",
"ChanTime",
"or",
"ChanFreq",
".... | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/frequency.py#L346-L424 | train | 23,607 |
wonambi-python/wonambi | wonambi/trans/frequency.py | _create_morlet | def _create_morlet(options, s_freq):
"""Create morlet wavelets, with scipy.signal doing the actual computation.
Parameters
----------
foi : ndarray or list or tuple
vector with frequency of interest
s_freq : int or float
sampling frequency of the data
options : dict
with 'M_in_s' (duration of the wavelet in seconds) and 'w' (Omega0)
Returns
-------
ndarray
nFreq X nSamples matrix containing the complex Morlet wavelets.
"""
wavelets = []
foi = options.pop('foi')
for f in foi:
wavelets.append(morlet(f, s_freq, **options))
return wavelets | python | def _create_morlet(options, s_freq):
"""Create morlet wavelets, with scipy.signal doing the actual computation.
Parameters
----------
foi : ndarray or list or tuple
vector with frequency of interest
s_freq : int or float
sampling frequency of the data
options : dict
with 'M_in_s' (duration of the wavelet in seconds) and 'w' (Omega0)
Returns
-------
ndarray
nFreq X nSamples matrix containing the complex Morlet wavelets.
"""
wavelets = []
foi = options.pop('foi')
for f in foi:
wavelets.append(morlet(f, s_freq, **options))
return wavelets | [
"def",
"_create_morlet",
"(",
"options",
",",
"s_freq",
")",
":",
"wavelets",
"=",
"[",
"]",
"foi",
"=",
"options",
".",
"pop",
"(",
"'foi'",
")",
"for",
"f",
"in",
"foi",
":",
"wavelets",
".",
"append",
"(",
"morlet",
"(",
"f",
",",
"s_freq",
",",... | Create morlet wavelets, with scipy.signal doing the actual computation.
Parameters
----------
foi : ndarray or list or tuple
vector with frequency of interest
s_freq : int or float
sampling frequency of the data
options : dict
with 'M_in_s' (duration of the wavelet in seconds) and 'w' (Omega0)
Returns
-------
ndarray
nFreq X nSamples matrix containing the complex Morlet wavelets. | [
"Create",
"morlet",
"wavelets",
"with",
"scipy",
".",
"signal",
"doing",
"the",
"actual",
"computation",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/frequency.py#L427-L450 | train | 23,608 |
wonambi-python/wonambi | wonambi/trans/frequency.py | morlet | def morlet(freq, s_freq, ratio=5, sigma_f=None, dur_in_sd=4, dur_in_s=None,
normalization='peak', zero_mean=False):
"""Create a Morlet wavelet.
Parameters
----------
freq : float
central frequency of the wavelet
s_freq : int
sampling frequency
ratio : float
ratio for a wavelet family ( = freq / sigma_f)
sigma_f : float
standard deviation of the wavelet in frequency domain
dur_in_sd : float
duration of the wavelet, given as number of the standard deviation in
the time domain, in one side.
dur_in_s : float
total duration of the wavelet, two-sided (i.e. from start to finish)
normalization : str
'area' means that energy is normalized to 1, 'peak' means that the peak
is set at 1, 'max' is a normalization used by nitime which does not
change max value of output when you change sigma_f.
zero_mean : bool
make sure that the wavelet has zero mean (only relevant if ratio < 5)
Returns
-------
ndarray
vector containing the complex Morlet wavelets
Notes
-----
'ratio' and 'sigma_f' are mutually exclusive. If you use 'sigma_f', the
standard deviation stays the same for all the frequency. It's more common
to specify a constant ratio for the wavelet family, so that the frequency
resolution changes with the frequency of interest.
'dur_in_sd' and 'dur_in_s' are mutually exclusive. 'dur_in_s' specifies the
total duration (from start to finish) of the window. 'dur_in_sd' calculates
the total duration as the length in standard deviations in the time domain:
dur_in_s = dur_in_sd * 2 * sigma_t, with sigma_t = 1 / (2 * pi * sigma_f)
"""
if sigma_f is None:
sigma_f = freq / ratio
else:
ratio = freq / sigma_f
sigma_t = 1 / (2 * pi * sigma_f)
if ratio < 5 and not zero_mean:
lg.info('The wavelet won\'t have zero mean, set zero_mean=True to '
'correct it')
if dur_in_s is None:
dur_in_s = sigma_t * dur_in_sd * 2
t = arange(-dur_in_s / 2, dur_in_s / 2, 1 / s_freq)
w = exp(1j * 2 * pi * freq * t)
if zero_mean:
w -= exp(-1 / 2 * ratio ** 2)
w *= exp(-t ** 2 / (2 * sigma_t ** 2))
if normalization == 'area':
w /= sqrt(sqrt(pi) * sigma_t * s_freq)
elif normalization == 'max':
w /= 2 * sigma_t * sqrt(2 * pi) / s_freq
elif normalization == 'peak':
pass
lg.info('At freq {0: 9.3f}Hz, sigma_f={1: 9.3f}Hz, sigma_t={2: 9.3f}s, '
'total duration={3: 9.3f}s'.format(freq, sigma_f, sigma_t,
dur_in_s))
lg.debug(' Real peak={0: 9.3f}, Mean={1: 12.6f}, '
'Energy={2: 9.3f}'.format(max(real(w)), mean(w), norm(w) ** 2))
return w | python | def morlet(freq, s_freq, ratio=5, sigma_f=None, dur_in_sd=4, dur_in_s=None,
normalization='peak', zero_mean=False):
"""Create a Morlet wavelet.
Parameters
----------
freq : float
central frequency of the wavelet
s_freq : int
sampling frequency
ratio : float
ratio for a wavelet family ( = freq / sigma_f)
sigma_f : float
standard deviation of the wavelet in frequency domain
dur_in_sd : float
duration of the wavelet, given as number of the standard deviation in
the time domain, in one side.
dur_in_s : float
total duration of the wavelet, two-sided (i.e. from start to finish)
normalization : str
'area' means that energy is normalized to 1, 'peak' means that the peak
is set at 1, 'max' is a normalization used by nitime which does not
change max value of output when you change sigma_f.
zero_mean : bool
make sure that the wavelet has zero mean (only relevant if ratio < 5)
Returns
-------
ndarray
vector containing the complex Morlet wavelets
Notes
-----
'ratio' and 'sigma_f' are mutually exclusive. If you use 'sigma_f', the
standard deviation stays the same for all the frequency. It's more common
to specify a constant ratio for the wavelet family, so that the frequency
resolution changes with the frequency of interest.
'dur_in_sd' and 'dur_in_s' are mutually exclusive. 'dur_in_s' specifies the
total duration (from start to finish) of the window. 'dur_in_sd' calculates
the total duration as the length in standard deviations in the time domain:
dur_in_s = dur_in_sd * 2 * sigma_t, with sigma_t = 1 / (2 * pi * sigma_f)
"""
if sigma_f is None:
sigma_f = freq / ratio
else:
ratio = freq / sigma_f
sigma_t = 1 / (2 * pi * sigma_f)
if ratio < 5 and not zero_mean:
lg.info('The wavelet won\'t have zero mean, set zero_mean=True to '
'correct it')
if dur_in_s is None:
dur_in_s = sigma_t * dur_in_sd * 2
t = arange(-dur_in_s / 2, dur_in_s / 2, 1 / s_freq)
w = exp(1j * 2 * pi * freq * t)
if zero_mean:
w -= exp(-1 / 2 * ratio ** 2)
w *= exp(-t ** 2 / (2 * sigma_t ** 2))
if normalization == 'area':
w /= sqrt(sqrt(pi) * sigma_t * s_freq)
elif normalization == 'max':
w /= 2 * sigma_t * sqrt(2 * pi) / s_freq
elif normalization == 'peak':
pass
lg.info('At freq {0: 9.3f}Hz, sigma_f={1: 9.3f}Hz, sigma_t={2: 9.3f}s, '
'total duration={3: 9.3f}s'.format(freq, sigma_f, sigma_t,
dur_in_s))
lg.debug(' Real peak={0: 9.3f}, Mean={1: 12.6f}, '
'Energy={2: 9.3f}'.format(max(real(w)), mean(w), norm(w) ** 2))
return w | [
"def",
"morlet",
"(",
"freq",
",",
"s_freq",
",",
"ratio",
"=",
"5",
",",
"sigma_f",
"=",
"None",
",",
"dur_in_sd",
"=",
"4",
",",
"dur_in_s",
"=",
"None",
",",
"normalization",
"=",
"'peak'",
",",
"zero_mean",
"=",
"False",
")",
":",
"if",
"sigma_f"... | Create a Morlet wavelet.
Parameters
----------
freq : float
central frequency of the wavelet
s_freq : int
sampling frequency
ratio : float
ratio for a wavelet family ( = freq / sigma_f)
sigma_f : float
standard deviation of the wavelet in frequency domain
dur_in_sd : float
duration of the wavelet, given as number of the standard deviation in
the time domain, in one side.
dur_in_s : float
total duration of the wavelet, two-sided (i.e. from start to finish)
normalization : str
'area' means that energy is normalized to 1, 'peak' means that the peak
is set at 1, 'max' is a normalization used by nitime which does not
change max value of output when you change sigma_f.
zero_mean : bool
make sure that the wavelet has zero mean (only relevant if ratio < 5)
Returns
-------
ndarray
vector containing the complex Morlet wavelets
Notes
-----
'ratio' and 'sigma_f' are mutually exclusive. If you use 'sigma_f', the
standard deviation stays the same for all the frequency. It's more common
to specify a constant ratio for the wavelet family, so that the frequency
resolution changes with the frequency of interest.
'dur_in_sd' and 'dur_in_s' are mutually exclusive. 'dur_in_s' specifies the
total duration (from start to finish) of the window. 'dur_in_sd' calculates
the total duration as the length in standard deviations in the time domain:
dur_in_s = dur_in_sd * 2 * sigma_t, with sigma_t = 1 / (2 * pi * sigma_f) | [
"Create",
"a",
"Morlet",
"wavelet",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/frequency.py#L453-L530 | train | 23,609 |
wonambi-python/wonambi | wonambi/widgets/modal_widgets.py | ChannelDialog.create_widgets | def create_widgets(self):
"""Build basic components of dialog."""
self.bbox = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.idx_ok = self.bbox.button(QDialogButtonBox.Ok)
self.idx_cancel = self.bbox.button(QDialogButtonBox.Cancel)
self.idx_group = FormMenu([gr['name'] for gr in self.groups])
chan_box = QListWidget()
self.idx_chan = chan_box
stage_box = QListWidget()
stage_box.addItems(STAGE_NAME)
stage_box.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.idx_stage = stage_box
cycle_box = QListWidget()
cycle_box.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.idx_cycle = cycle_box | python | def create_widgets(self):
"""Build basic components of dialog."""
self.bbox = QDialogButtonBox(
QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
self.idx_ok = self.bbox.button(QDialogButtonBox.Ok)
self.idx_cancel = self.bbox.button(QDialogButtonBox.Cancel)
self.idx_group = FormMenu([gr['name'] for gr in self.groups])
chan_box = QListWidget()
self.idx_chan = chan_box
stage_box = QListWidget()
stage_box.addItems(STAGE_NAME)
stage_box.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.idx_stage = stage_box
cycle_box = QListWidget()
cycle_box.setSelectionMode(QAbstractItemView.ExtendedSelection)
self.idx_cycle = cycle_box | [
"def",
"create_widgets",
"(",
"self",
")",
":",
"self",
".",
"bbox",
"=",
"QDialogButtonBox",
"(",
"QDialogButtonBox",
".",
"Ok",
"|",
"QDialogButtonBox",
".",
"Cancel",
")",
"self",
".",
"idx_ok",
"=",
"self",
".",
"bbox",
".",
"button",
"(",
"QDialogButt... | Build basic components of dialog. | [
"Build",
"basic",
"components",
"of",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/modal_widgets.py#L58-L77 | train | 23,610 |
wonambi-python/wonambi | wonambi/widgets/modal_widgets.py | ChannelDialog.update_groups | def update_groups(self):
"""Update the channel groups list when dialog is opened."""
self.groups = self.parent.channels.groups
self.idx_group.clear()
for gr in self.groups:
self.idx_group.addItem(gr['name'])
self.update_channels() | python | def update_groups(self):
"""Update the channel groups list when dialog is opened."""
self.groups = self.parent.channels.groups
self.idx_group.clear()
for gr in self.groups:
self.idx_group.addItem(gr['name'])
self.update_channels() | [
"def",
"update_groups",
"(",
"self",
")",
":",
"self",
".",
"groups",
"=",
"self",
".",
"parent",
".",
"channels",
".",
"groups",
"self",
".",
"idx_group",
".",
"clear",
"(",
")",
"for",
"gr",
"in",
"self",
".",
"groups",
":",
"self",
".",
"idx_group... | Update the channel groups list when dialog is opened. | [
"Update",
"the",
"channel",
"groups",
"list",
"when",
"dialog",
"is",
"opened",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/modal_widgets.py#L79-L86 | train | 23,611 |
wonambi-python/wonambi | wonambi/widgets/modal_widgets.py | ChannelDialog.update_channels | def update_channels(self):
"""Update the channels list when a new group is selected."""
group_dict = {k['name']: i for i, k in enumerate(self.groups)}
group_index = group_dict[self.idx_group.currentText()]
self.one_grp = self.groups[group_index]
self.idx_chan.clear()
self.idx_chan.setSelectionMode(QAbstractItemView.ExtendedSelection)
for chan in self.one_grp['chan_to_plot']:
name = chan + '—(' + '+'.join(self.one_grp['ref_chan']) + ')'
item = QListWidgetItem(name)
self.idx_chan.addItem(item) | python | def update_channels(self):
"""Update the channels list when a new group is selected."""
group_dict = {k['name']: i for i, k in enumerate(self.groups)}
group_index = group_dict[self.idx_group.currentText()]
self.one_grp = self.groups[group_index]
self.idx_chan.clear()
self.idx_chan.setSelectionMode(QAbstractItemView.ExtendedSelection)
for chan in self.one_grp['chan_to_plot']:
name = chan + '—(' + '+'.join(self.one_grp['ref_chan']) + ')'
item = QListWidgetItem(name)
self.idx_chan.addItem(item) | [
"def",
"update_channels",
"(",
"self",
")",
":",
"group_dict",
"=",
"{",
"k",
"[",
"'name'",
"]",
":",
"i",
"for",
"i",
",",
"k",
"in",
"enumerate",
"(",
"self",
".",
"groups",
")",
"}",
"group_index",
"=",
"group_dict",
"[",
"self",
".",
"idx_group"... | Update the channels list when a new group is selected. | [
"Update",
"the",
"channels",
"list",
"when",
"a",
"new",
"group",
"is",
"selected",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/modal_widgets.py#L88-L100 | train | 23,612 |
wonambi-python/wonambi | wonambi/widgets/modal_widgets.py | ChannelDialog.update_cycles | def update_cycles(self):
"""Enable cycles checkbox only if there are cycles marked, with no
errors."""
self.idx_cycle.clear()
try:
self.cycles = self.parent.notes.annot.get_cycles()
except ValueError as err:
self.idx_cycle.setEnabled(False)
msg = 'There is a problem with the cycle markers: ' + str(err)
self.parent.statusBar().showMessage(msg)
else:
if self.cycles is None:
self.idx_cycle.setEnabled(False)
else:
self.idx_cycle.setEnabled(True)
for i in range(len(self.cycles)):
self.idx_cycle.addItem(str(i+1)) | python | def update_cycles(self):
"""Enable cycles checkbox only if there are cycles marked, with no
errors."""
self.idx_cycle.clear()
try:
self.cycles = self.parent.notes.annot.get_cycles()
except ValueError as err:
self.idx_cycle.setEnabled(False)
msg = 'There is a problem with the cycle markers: ' + str(err)
self.parent.statusBar().showMessage(msg)
else:
if self.cycles is None:
self.idx_cycle.setEnabled(False)
else:
self.idx_cycle.setEnabled(True)
for i in range(len(self.cycles)):
self.idx_cycle.addItem(str(i+1)) | [
"def",
"update_cycles",
"(",
"self",
")",
":",
"self",
".",
"idx_cycle",
".",
"clear",
"(",
")",
"try",
":",
"self",
".",
"cycles",
"=",
"self",
".",
"parent",
".",
"notes",
".",
"annot",
".",
"get_cycles",
"(",
")",
"except",
"ValueError",
"as",
"er... | Enable cycles checkbox only if there are cycles marked, with no
errors. | [
"Enable",
"cycles",
"checkbox",
"only",
"if",
"there",
"are",
"cycles",
"marked",
"with",
"no",
"errors",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/modal_widgets.py#L102-L121 | train | 23,613 |
wonambi-python/wonambi | wonambi/widgets/traces.py | _create_data_to_plot | def _create_data_to_plot(data, chan_groups):
"""Create data after montage and filtering.
Parameters
----------
data : instance of ChanTime
the raw data
chan_groups : list of dict
information about channels to plot, to use as reference and about
filtering etc.
Returns
-------
instance of ChanTime
data ready to be plotted.
"""
# chan_to_plot only gives the number of channels to plot, for prealloc
chan_to_plot = [one_chan for one_grp in chan_groups
for one_chan in one_grp['chan_to_plot']]
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(chan_to_plot), data.number_of('time')[0]),
dtype='f')
all_chan_grp_name = []
i_ch = 0
for one_grp in chan_groups:
sel_data = _select_channels(data,
one_grp['chan_to_plot'] +
one_grp['ref_chan'])
data1 = montage(sel_data, ref_chan=one_grp['ref_chan'])
data1.data[0] = nan_to_num(data1.data[0])
if one_grp['hp'] is not None:
data1 = filter_(data1, low_cut=one_grp['hp'])
if one_grp['lp'] is not None:
data1 = filter_(data1, high_cut=one_grp['lp'])
for chan in one_grp['chan_to_plot']:
chan_grp_name = chan + ' (' + one_grp['name'] + ')'
all_chan_grp_name.append(chan_grp_name)
dat = data1(chan=chan, trial=0)
dat = dat - nanmean(dat)
output.data[0][i_ch, :] = dat * one_grp['scale']
i_ch += 1
output.axis['chan'][0] = asarray(all_chan_grp_name, dtype='U')
return output | python | def _create_data_to_plot(data, chan_groups):
"""Create data after montage and filtering.
Parameters
----------
data : instance of ChanTime
the raw data
chan_groups : list of dict
information about channels to plot, to use as reference and about
filtering etc.
Returns
-------
instance of ChanTime
data ready to be plotted.
"""
# chan_to_plot only gives the number of channels to plot, for prealloc
chan_to_plot = [one_chan for one_grp in chan_groups
for one_chan in one_grp['chan_to_plot']]
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(chan_to_plot), data.number_of('time')[0]),
dtype='f')
all_chan_grp_name = []
i_ch = 0
for one_grp in chan_groups:
sel_data = _select_channels(data,
one_grp['chan_to_plot'] +
one_grp['ref_chan'])
data1 = montage(sel_data, ref_chan=one_grp['ref_chan'])
data1.data[0] = nan_to_num(data1.data[0])
if one_grp['hp'] is not None:
data1 = filter_(data1, low_cut=one_grp['hp'])
if one_grp['lp'] is not None:
data1 = filter_(data1, high_cut=one_grp['lp'])
for chan in one_grp['chan_to_plot']:
chan_grp_name = chan + ' (' + one_grp['name'] + ')'
all_chan_grp_name.append(chan_grp_name)
dat = data1(chan=chan, trial=0)
dat = dat - nanmean(dat)
output.data[0][i_ch, :] = dat * one_grp['scale']
i_ch += 1
output.axis['chan'][0] = asarray(all_chan_grp_name, dtype='U')
return output | [
"def",
"_create_data_to_plot",
"(",
"data",
",",
"chan_groups",
")",
":",
"# chan_to_plot only gives the number of channels to plot, for prealloc",
"chan_to_plot",
"=",
"[",
"one_chan",
"for",
"one_grp",
"in",
"chan_groups",
"for",
"one_chan",
"in",
"one_grp",
"[",
"'chan... | Create data after montage and filtering.
Parameters
----------
data : instance of ChanTime
the raw data
chan_groups : list of dict
information about channels to plot, to use as reference and about
filtering etc.
Returns
-------
instance of ChanTime
data ready to be plotted. | [
"Create",
"data",
"after",
"montage",
"and",
"filtering",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L1173-L1231 | train | 23,614 |
wonambi-python/wonambi | wonambi/widgets/traces.py | _convert_timestr_to_seconds | def _convert_timestr_to_seconds(time_str, rec_start):
"""Convert input from user about time string to an absolute time for
the recordings.
Parameters
----------
time_str : str
time information as '123' or '22:30' or '22:30:22'
rec_start: instance of datetime
absolute start time of the recordings.
Returns
-------
int
start time of the window, in s, from the start of the recordings
Raises
------
ValueError
if it cannot convert the string
"""
if not CHECK_TIME_STR.match(time_str):
raise ValueError('Input can only contain digits and colons')
if ':' in time_str:
time_split = [int(x) for x in time_str.split(':')]
# if it's in 'HH:MM' format, add ':SS'
if len(time_split) == 2:
time_split.append(0)
clock_time = time(*time_split)
chosen_start = datetime.combine(rec_start.date(), clock_time)
# if the clock time is after start of the recordings, assume it's the next day
if clock_time < rec_start.time():
chosen_start += timedelta(days=1)
window_start = int((chosen_start - rec_start).total_seconds())
else:
window_start = int(time_str)
return window_start | python | def _convert_timestr_to_seconds(time_str, rec_start):
"""Convert input from user about time string to an absolute time for
the recordings.
Parameters
----------
time_str : str
time information as '123' or '22:30' or '22:30:22'
rec_start: instance of datetime
absolute start time of the recordings.
Returns
-------
int
start time of the window, in s, from the start of the recordings
Raises
------
ValueError
if it cannot convert the string
"""
if not CHECK_TIME_STR.match(time_str):
raise ValueError('Input can only contain digits and colons')
if ':' in time_str:
time_split = [int(x) for x in time_str.split(':')]
# if it's in 'HH:MM' format, add ':SS'
if len(time_split) == 2:
time_split.append(0)
clock_time = time(*time_split)
chosen_start = datetime.combine(rec_start.date(), clock_time)
# if the clock time is after start of the recordings, assume it's the next day
if clock_time < rec_start.time():
chosen_start += timedelta(days=1)
window_start = int((chosen_start - rec_start).total_seconds())
else:
window_start = int(time_str)
return window_start | [
"def",
"_convert_timestr_to_seconds",
"(",
"time_str",
",",
"rec_start",
")",
":",
"if",
"not",
"CHECK_TIME_STR",
".",
"match",
"(",
"time_str",
")",
":",
"raise",
"ValueError",
"(",
"'Input can only contain digits and colons'",
")",
"if",
"':'",
"in",
"time_str",
... | Convert input from user about time string to an absolute time for
the recordings.
Parameters
----------
time_str : str
time information as '123' or '22:30' or '22:30:22'
rec_start: instance of datetime
absolute start time of the recordings.
Returns
-------
int
start time of the window, in s, from the start of the recordings
Raises
------
ValueError
if it cannot convert the string | [
"Convert",
"input",
"from",
"user",
"about",
"time",
"string",
"to",
"an",
"absolute",
"time",
"for",
"the",
"recordings",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L1234-L1275 | train | 23,615 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.read_data | def read_data(self):
"""Read the data to plot."""
window_start = self.parent.value('window_start')
window_end = window_start + self.parent.value('window_length')
dataset = self.parent.info.dataset
groups = self.parent.channels.groups
chan_to_read = []
for one_grp in groups:
chan_to_read.extend(one_grp['chan_to_plot'] + one_grp['ref_chan'])
if not chan_to_read:
return
data = dataset.read_data(chan=chan_to_read,
begtime=window_start,
endtime=window_end)
max_s_freq = self.parent.value('max_s_freq')
if data.s_freq > max_s_freq:
q = int(data.s_freq / max_s_freq)
lg.debug('Decimate (no low-pass filter) at ' + str(q))
data.data[0] = data.data[0][:, slice(None, None, q)]
data.axis['time'][0] = data.axis['time'][0][slice(None, None, q)]
data.s_freq = int(data.s_freq / q)
self.data = _create_data_to_plot(data, self.parent.channels.groups) | python | def read_data(self):
"""Read the data to plot."""
window_start = self.parent.value('window_start')
window_end = window_start + self.parent.value('window_length')
dataset = self.parent.info.dataset
groups = self.parent.channels.groups
chan_to_read = []
for one_grp in groups:
chan_to_read.extend(one_grp['chan_to_plot'] + one_grp['ref_chan'])
if not chan_to_read:
return
data = dataset.read_data(chan=chan_to_read,
begtime=window_start,
endtime=window_end)
max_s_freq = self.parent.value('max_s_freq')
if data.s_freq > max_s_freq:
q = int(data.s_freq / max_s_freq)
lg.debug('Decimate (no low-pass filter) at ' + str(q))
data.data[0] = data.data[0][:, slice(None, None, q)]
data.axis['time'][0] = data.axis['time'][0][slice(None, None, q)]
data.s_freq = int(data.s_freq / q)
self.data = _create_data_to_plot(data, self.parent.channels.groups) | [
"def",
"read_data",
"(",
"self",
")",
":",
"window_start",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"window_end",
"=",
"window_start",
"+",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"dataset",
"=",
"self... | Read the data to plot. | [
"Read",
"the",
"data",
"to",
"plot",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L329-L355 | train | 23,616 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.display | def display(self):
"""Display the recordings."""
if self.data is None:
return
if self.scene is not None:
self.y_scrollbar_value = self.verticalScrollBar().value()
self.scene.clear()
self.create_chan_labels()
self.create_time_labels()
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
time_height = max([x.boundingRect().height() for x in self.idx_time])
label_width = window_length * self.parent.value('label_ratio')
scene_height = (len(self.idx_label) * self.parent.value('y_distance') +
time_height)
self.scene = QGraphicsScene(window_start - label_width,
0,
window_length + label_width,
scene_height)
self.setScene(self.scene)
self.idx_markers = []
self.idx_annot = []
self.idx_annot_labels = []
self.add_chan_labels()
self.add_time_labels()
self.add_traces()
self.display_grid()
self.display_markers()
self.display_annotations()
self.resizeEvent(None)
self.verticalScrollBar().setValue(self.y_scrollbar_value)
self.parent.info.display_view()
self.parent.overview.display_current() | python | def display(self):
"""Display the recordings."""
if self.data is None:
return
if self.scene is not None:
self.y_scrollbar_value = self.verticalScrollBar().value()
self.scene.clear()
self.create_chan_labels()
self.create_time_labels()
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
time_height = max([x.boundingRect().height() for x in self.idx_time])
label_width = window_length * self.parent.value('label_ratio')
scene_height = (len(self.idx_label) * self.parent.value('y_distance') +
time_height)
self.scene = QGraphicsScene(window_start - label_width,
0,
window_length + label_width,
scene_height)
self.setScene(self.scene)
self.idx_markers = []
self.idx_annot = []
self.idx_annot_labels = []
self.add_chan_labels()
self.add_time_labels()
self.add_traces()
self.display_grid()
self.display_markers()
self.display_annotations()
self.resizeEvent(None)
self.verticalScrollBar().setValue(self.y_scrollbar_value)
self.parent.info.display_view()
self.parent.overview.display_current() | [
"def",
"display",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
"is",
"None",
":",
"return",
"if",
"self",
".",
"scene",
"is",
"not",
"None",
":",
"self",
".",
"y_scrollbar_value",
"=",
"self",
".",
"verticalScrollBar",
"(",
")",
".",
"value",
"(... | Display the recordings. | [
"Display",
"the",
"recordings",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L358-L398 | train | 23,617 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.create_chan_labels | def create_chan_labels(self):
"""Create the channel labels, but don't plot them yet.
Notes
-----
It's necessary to have the width of the labels, so that we can adjust
the main scene.
"""
self.idx_label = []
for one_grp in self.parent.channels.groups:
for one_label in one_grp['chan_to_plot']:
item = QGraphicsSimpleTextItem(one_label)
item.setBrush(QBrush(QColor(one_grp['color'])))
item.setFlag(QGraphicsItem.ItemIgnoresTransformations)
self.idx_label.append(item) | python | def create_chan_labels(self):
"""Create the channel labels, but don't plot them yet.
Notes
-----
It's necessary to have the width of the labels, so that we can adjust
the main scene.
"""
self.idx_label = []
for one_grp in self.parent.channels.groups:
for one_label in one_grp['chan_to_plot']:
item = QGraphicsSimpleTextItem(one_label)
item.setBrush(QBrush(QColor(one_grp['color'])))
item.setFlag(QGraphicsItem.ItemIgnoresTransformations)
self.idx_label.append(item) | [
"def",
"create_chan_labels",
"(",
"self",
")",
":",
"self",
".",
"idx_label",
"=",
"[",
"]",
"for",
"one_grp",
"in",
"self",
".",
"parent",
".",
"channels",
".",
"groups",
":",
"for",
"one_label",
"in",
"one_grp",
"[",
"'chan_to_plot'",
"]",
":",
"item",... | Create the channel labels, but don't plot them yet.
Notes
-----
It's necessary to have the width of the labels, so that we can adjust
the main scene. | [
"Create",
"the",
"channel",
"labels",
"but",
"don",
"t",
"plot",
"them",
"yet",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L400-L414 | train | 23,618 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.create_time_labels | def create_time_labels(self):
"""Create the time labels, but don't plot them yet.
Notes
-----
It's necessary to have the height of the time labels, so that we can
adjust the main scene.
Not very robust, because it uses seconds as integers.
"""
min_time = int(floor(min(self.data.axis['time'][0])))
max_time = int(ceil(max(self.data.axis['time'][0])))
n_time_labels = self.parent.value('n_time_labels')
self.idx_time = []
self.time_pos = []
for one_time in linspace(min_time, max_time, n_time_labels):
x_label = (self.data.start_time +
timedelta(seconds=one_time)).strftime('%H:%M:%S')
item = QGraphicsSimpleTextItem(x_label)
item.setFlag(QGraphicsItem.ItemIgnoresTransformations)
self.idx_time.append(item)
self.time_pos.append(QPointF(one_time,
len(self.idx_label) *
self.parent.value('y_distance'))) | python | def create_time_labels(self):
"""Create the time labels, but don't plot them yet.
Notes
-----
It's necessary to have the height of the time labels, so that we can
adjust the main scene.
Not very robust, because it uses seconds as integers.
"""
min_time = int(floor(min(self.data.axis['time'][0])))
max_time = int(ceil(max(self.data.axis['time'][0])))
n_time_labels = self.parent.value('n_time_labels')
self.idx_time = []
self.time_pos = []
for one_time in linspace(min_time, max_time, n_time_labels):
x_label = (self.data.start_time +
timedelta(seconds=one_time)).strftime('%H:%M:%S')
item = QGraphicsSimpleTextItem(x_label)
item.setFlag(QGraphicsItem.ItemIgnoresTransformations)
self.idx_time.append(item)
self.time_pos.append(QPointF(one_time,
len(self.idx_label) *
self.parent.value('y_distance'))) | [
"def",
"create_time_labels",
"(",
"self",
")",
":",
"min_time",
"=",
"int",
"(",
"floor",
"(",
"min",
"(",
"self",
".",
"data",
".",
"axis",
"[",
"'time'",
"]",
"[",
"0",
"]",
")",
")",
")",
"max_time",
"=",
"int",
"(",
"ceil",
"(",
"max",
"(",
... | Create the time labels, but don't plot them yet.
Notes
-----
It's necessary to have the height of the time labels, so that we can
adjust the main scene.
Not very robust, because it uses seconds as integers. | [
"Create",
"the",
"time",
"labels",
"but",
"don",
"t",
"plot",
"them",
"yet",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L416-L440 | train | 23,619 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.add_chan_labels | def add_chan_labels(self):
"""Add channel labels on the left."""
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
label_width = window_length * self.parent.value('label_ratio')
for row, one_label_item in enumerate(self.idx_label):
self.scene.addItem(one_label_item)
one_label_item.setPos(window_start - label_width,
self.parent.value('y_distance') * row +
self.parent.value('y_distance') / 2) | python | def add_chan_labels(self):
"""Add channel labels on the left."""
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
label_width = window_length * self.parent.value('label_ratio')
for row, one_label_item in enumerate(self.idx_label):
self.scene.addItem(one_label_item)
one_label_item.setPos(window_start - label_width,
self.parent.value('y_distance') * row +
self.parent.value('y_distance') / 2) | [
"def",
"add_chan_labels",
"(",
"self",
")",
":",
"window_start",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"window_length",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"label_width",
"=",
"window_length",
... | Add channel labels on the left. | [
"Add",
"channel",
"labels",
"on",
"the",
"left",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L442-L452 | train | 23,620 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.add_time_labels | def add_time_labels(self):
"""Add time labels at the bottom."""
for text, pos in zip(self.idx_time, self.time_pos):
self.scene.addItem(text)
text.setPos(pos) | python | def add_time_labels(self):
"""Add time labels at the bottom."""
for text, pos in zip(self.idx_time, self.time_pos):
self.scene.addItem(text)
text.setPos(pos) | [
"def",
"add_time_labels",
"(",
"self",
")",
":",
"for",
"text",
",",
"pos",
"in",
"zip",
"(",
"self",
".",
"idx_time",
",",
"self",
".",
"time_pos",
")",
":",
"self",
".",
"scene",
".",
"addItem",
"(",
"text",
")",
"text",
".",
"setPos",
"(",
"pos"... | Add time labels at the bottom. | [
"Add",
"time",
"labels",
"at",
"the",
"bottom",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L454-L458 | train | 23,621 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.add_traces | def add_traces(self):
"""Add traces based on self.data."""
y_distance = self.parent.value('y_distance')
self.chan = []
self.chan_pos = []
self.chan_scale = []
row = 0
for one_grp in self.parent.channels.groups:
for one_chan in one_grp['chan_to_plot']:
# channel name
chan_name = one_chan + ' (' + one_grp['name'] + ')'
# trace
dat = (self.data(trial=0, chan=chan_name) *
self.parent.value('y_scale'))
dat *= -1 # flip data, upside down
path = self.scene.addPath(Path(self.data.axis['time'][0],
dat))
path.setPen(QPen(QColor(one_grp['color']), LINE_WIDTH))
# adjust position
chan_pos = y_distance * row + y_distance / 2
path.setPos(0, chan_pos)
row += 1
self.chan.append(chan_name)
self.chan_scale.append(one_grp['scale'])
self.chan_pos.append(chan_pos) | python | def add_traces(self):
"""Add traces based on self.data."""
y_distance = self.parent.value('y_distance')
self.chan = []
self.chan_pos = []
self.chan_scale = []
row = 0
for one_grp in self.parent.channels.groups:
for one_chan in one_grp['chan_to_plot']:
# channel name
chan_name = one_chan + ' (' + one_grp['name'] + ')'
# trace
dat = (self.data(trial=0, chan=chan_name) *
self.parent.value('y_scale'))
dat *= -1 # flip data, upside down
path = self.scene.addPath(Path(self.data.axis['time'][0],
dat))
path.setPen(QPen(QColor(one_grp['color']), LINE_WIDTH))
# adjust position
chan_pos = y_distance * row + y_distance / 2
path.setPos(0, chan_pos)
row += 1
self.chan.append(chan_name)
self.chan_scale.append(one_grp['scale'])
self.chan_pos.append(chan_pos) | [
"def",
"add_traces",
"(",
"self",
")",
":",
"y_distance",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'y_distance'",
")",
"self",
".",
"chan",
"=",
"[",
"]",
"self",
".",
"chan_pos",
"=",
"[",
"]",
"self",
".",
"chan_scale",
"=",
"[",
"]",
"row... | Add traces based on self.data. | [
"Add",
"traces",
"based",
"on",
"self",
".",
"data",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L460-L489 | train | 23,622 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.display_grid | def display_grid(self):
"""Display grid on x-axis and y-axis."""
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
window_end = window_start + window_length
if self.parent.value('grid_x'):
x_tick = self.parent.value('grid_xtick')
x_ticks = arange(window_start, window_end + x_tick, x_tick)
for x in x_ticks:
x_pos = [x, x]
y_pos = [0,
self.parent.value('y_distance') * len(self.idx_label)]
path = self.scene.addPath(Path(x_pos, y_pos))
path.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine))
if self.parent.value('grid_y'):
y_tick = (self.parent.value('grid_ytick') *
self.parent.value('y_scale'))
for one_label_item in self.idx_label:
x_pos = [window_start, window_end]
y = one_label_item.y()
y_pos_0 = [y, y]
path_0 = self.scene.addPath(Path(x_pos, y_pos_0))
path_0.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine))
y_up = one_label_item.y() + y_tick
y_pos_up = [y_up, y_up]
path_up = self.scene.addPath(Path(x_pos, y_pos_up))
path_up.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine))
y_down = one_label_item.y() - y_tick
y_pos_down = [y_down, y_down]
path_down = self.scene.addPath(Path(x_pos, y_pos_down))
path_down.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine)) | python | def display_grid(self):
"""Display grid on x-axis and y-axis."""
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
window_end = window_start + window_length
if self.parent.value('grid_x'):
x_tick = self.parent.value('grid_xtick')
x_ticks = arange(window_start, window_end + x_tick, x_tick)
for x in x_ticks:
x_pos = [x, x]
y_pos = [0,
self.parent.value('y_distance') * len(self.idx_label)]
path = self.scene.addPath(Path(x_pos, y_pos))
path.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine))
if self.parent.value('grid_y'):
y_tick = (self.parent.value('grid_ytick') *
self.parent.value('y_scale'))
for one_label_item in self.idx_label:
x_pos = [window_start, window_end]
y = one_label_item.y()
y_pos_0 = [y, y]
path_0 = self.scene.addPath(Path(x_pos, y_pos_0))
path_0.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine))
y_up = one_label_item.y() + y_tick
y_pos_up = [y_up, y_up]
path_up = self.scene.addPath(Path(x_pos, y_pos_up))
path_up.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine))
y_down = one_label_item.y() - y_tick
y_pos_down = [y_down, y_down]
path_down = self.scene.addPath(Path(x_pos, y_pos_down))
path_down.setPen(QPen(QColor(LINE_COLOR), LINE_WIDTH,
Qt.DotLine)) | [
"def",
"display_grid",
"(",
"self",
")",
":",
"window_start",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"window_length",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"window_end",
"=",
"window_start",
"+"... | Display grid on x-axis and y-axis. | [
"Display",
"grid",
"on",
"x",
"-",
"axis",
"and",
"y",
"-",
"axis",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L491-L530 | train | 23,623 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.display_markers | def display_markers(self):
"""Add markers on top of first plot."""
for item in self.idx_markers:
self.scene.removeItem(item)
self.idx_markers = []
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
window_end = window_start + window_length
y_distance = self.parent.value('y_distance')
markers = []
if self.parent.info.markers is not None:
if self.parent.value('marker_show'):
markers = self.parent.info.markers
for mrk in markers:
if window_start <= mrk['end'] and window_end >= mrk['start']:
mrk_start = max((mrk['start'], window_start))
mrk_end = min((mrk['end'], window_end))
color = QColor(self.parent.value('marker_color'))
item = QGraphicsRectItem(mrk_start, 0,
mrk_end - mrk_start,
len(self.idx_label) * y_distance)
item.setPen(color)
item.setBrush(color)
item.setZValue(-9)
self.scene.addItem(item)
item = TextItem_with_BG(color.darker(200))
item.setText(mrk['name'])
item.setPos(mrk['start'],
len(self.idx_label) *
self.parent.value('y_distance'))
item.setFlag(QGraphicsItem.ItemIgnoresTransformations)
item.setRotation(-90)
self.scene.addItem(item)
self.idx_markers.append(item) | python | def display_markers(self):
"""Add markers on top of first plot."""
for item in self.idx_markers:
self.scene.removeItem(item)
self.idx_markers = []
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
window_end = window_start + window_length
y_distance = self.parent.value('y_distance')
markers = []
if self.parent.info.markers is not None:
if self.parent.value('marker_show'):
markers = self.parent.info.markers
for mrk in markers:
if window_start <= mrk['end'] and window_end >= mrk['start']:
mrk_start = max((mrk['start'], window_start))
mrk_end = min((mrk['end'], window_end))
color = QColor(self.parent.value('marker_color'))
item = QGraphicsRectItem(mrk_start, 0,
mrk_end - mrk_start,
len(self.idx_label) * y_distance)
item.setPen(color)
item.setBrush(color)
item.setZValue(-9)
self.scene.addItem(item)
item = TextItem_with_BG(color.darker(200))
item.setText(mrk['name'])
item.setPos(mrk['start'],
len(self.idx_label) *
self.parent.value('y_distance'))
item.setFlag(QGraphicsItem.ItemIgnoresTransformations)
item.setRotation(-90)
self.scene.addItem(item)
self.idx_markers.append(item) | [
"def",
"display_markers",
"(",
"self",
")",
":",
"for",
"item",
"in",
"self",
".",
"idx_markers",
":",
"self",
".",
"scene",
".",
"removeItem",
"(",
"item",
")",
"self",
".",
"idx_markers",
"=",
"[",
"]",
"window_start",
"=",
"self",
".",
"parent",
"."... | Add markers on top of first plot. | [
"Add",
"markers",
"on",
"top",
"of",
"first",
"plot",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L532-L571 | train | 23,624 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.step_prev | def step_prev(self):
"""Go to the previous step."""
window_start = around(self.parent.value('window_start') -
self.parent.value('window_length') /
self.parent.value('window_step'), 2)
if window_start < 0:
return
self.parent.overview.update_position(window_start) | python | def step_prev(self):
"""Go to the previous step."""
window_start = around(self.parent.value('window_start') -
self.parent.value('window_length') /
self.parent.value('window_step'), 2)
if window_start < 0:
return
self.parent.overview.update_position(window_start) | [
"def",
"step_prev",
"(",
"self",
")",
":",
"window_start",
"=",
"around",
"(",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"-",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"/",
"self",
".",
"parent",
".",
"val... | Go to the previous step. | [
"Go",
"to",
"the",
"previous",
"step",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L645-L652 | train | 23,625 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.step_next | def step_next(self):
"""Go to the next step."""
window_start = around(self.parent.value('window_start') +
self.parent.value('window_length') /
self.parent.value('window_step'), 2)
self.parent.overview.update_position(window_start) | python | def step_next(self):
"""Go to the next step."""
window_start = around(self.parent.value('window_start') +
self.parent.value('window_length') /
self.parent.value('window_step'), 2)
self.parent.overview.update_position(window_start) | [
"def",
"step_next",
"(",
"self",
")",
":",
"window_start",
"=",
"around",
"(",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"+",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"/",
"self",
".",
"parent",
".",
"val... | Go to the next step. | [
"Go",
"to",
"the",
"next",
"step",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L654-L660 | train | 23,626 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.page_prev | def page_prev(self):
"""Go to the previous page."""
window_start = (self.parent.value('window_start') -
self.parent.value('window_length'))
if window_start < 0:
return
self.parent.overview.update_position(window_start) | python | def page_prev(self):
"""Go to the previous page."""
window_start = (self.parent.value('window_start') -
self.parent.value('window_length'))
if window_start < 0:
return
self.parent.overview.update_position(window_start) | [
"def",
"page_prev",
"(",
"self",
")",
":",
"window_start",
"=",
"(",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"-",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
")",
"if",
"window_start",
"<",
"0",
":",
"retu... | Go to the previous page. | [
"Go",
"to",
"the",
"previous",
"page",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L662-L668 | train | 23,627 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.page_next | def page_next(self):
"""Go to the next page."""
window_start = (self.parent.value('window_start') +
self.parent.value('window_length'))
self.parent.overview.update_position(window_start) | python | def page_next(self):
"""Go to the next page."""
window_start = (self.parent.value('window_start') +
self.parent.value('window_length'))
self.parent.overview.update_position(window_start) | [
"def",
"page_next",
"(",
"self",
")",
":",
"window_start",
"=",
"(",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"+",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
")",
"self",
".",
"parent",
".",
"overview",
".... | Go to the next page. | [
"Go",
"to",
"the",
"next",
"page",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L670-L674 | train | 23,628 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.go_to_epoch | def go_to_epoch(self, checked=False, test_text_str=None):
"""Go to any window"""
if test_text_str is not None:
time_str = test_text_str
ok = True
else:
time_str, ok = QInputDialog.getText(self,
'Go To Epoch',
'Enter start time of the '
'epoch,\nin seconds ("1560") '
'or\nas absolute time '
'("22:30")')
if not ok:
return
try:
rec_start_time = self.parent.info.dataset.header['start_time']
window_start = _convert_timestr_to_seconds(time_str, rec_start_time)
except ValueError as err:
error_dialog = QErrorMessage()
error_dialog.setWindowTitle('Error moving to epoch')
error_dialog.showMessage(str(err))
if test_text_str is None:
error_dialog.exec()
self.parent.statusBar().showMessage(str(err))
return
self.parent.overview.update_position(window_start) | python | def go_to_epoch(self, checked=False, test_text_str=None):
"""Go to any window"""
if test_text_str is not None:
time_str = test_text_str
ok = True
else:
time_str, ok = QInputDialog.getText(self,
'Go To Epoch',
'Enter start time of the '
'epoch,\nin seconds ("1560") '
'or\nas absolute time '
'("22:30")')
if not ok:
return
try:
rec_start_time = self.parent.info.dataset.header['start_time']
window_start = _convert_timestr_to_seconds(time_str, rec_start_time)
except ValueError as err:
error_dialog = QErrorMessage()
error_dialog.setWindowTitle('Error moving to epoch')
error_dialog.showMessage(str(err))
if test_text_str is None:
error_dialog.exec()
self.parent.statusBar().showMessage(str(err))
return
self.parent.overview.update_position(window_start) | [
"def",
"go_to_epoch",
"(",
"self",
",",
"checked",
"=",
"False",
",",
"test_text_str",
"=",
"None",
")",
":",
"if",
"test_text_str",
"is",
"not",
"None",
":",
"time_str",
"=",
"test_text_str",
"ok",
"=",
"True",
"else",
":",
"time_str",
",",
"ok",
"=",
... | Go to any window | [
"Go",
"to",
"any",
"window"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L676-L704 | train | 23,629 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.line_up_with_epoch | def line_up_with_epoch(self):
"""Go to the start of the present epoch."""
if self.parent.notes.annot is None: # TODO: remove if buttons are disabled
error_dialog = QErrorMessage()
error_dialog.setWindowTitle('Error moving to epoch')
error_dialog.showMessage('No score file loaded')
error_dialog.exec()
return
new_window_start = self.parent.notes.annot.get_epoch_start(
self.parent.value('window_start'))
self.parent.overview.update_position(new_window_start) | python | def line_up_with_epoch(self):
"""Go to the start of the present epoch."""
if self.parent.notes.annot is None: # TODO: remove if buttons are disabled
error_dialog = QErrorMessage()
error_dialog.setWindowTitle('Error moving to epoch')
error_dialog.showMessage('No score file loaded')
error_dialog.exec()
return
new_window_start = self.parent.notes.annot.get_epoch_start(
self.parent.value('window_start'))
self.parent.overview.update_position(new_window_start) | [
"def",
"line_up_with_epoch",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"notes",
".",
"annot",
"is",
"None",
":",
"# TODO: remove if buttons are disabled",
"error_dialog",
"=",
"QErrorMessage",
"(",
")",
"error_dialog",
".",
"setWindowTitle",
"(",
... | Go to the start of the present epoch. | [
"Go",
"to",
"the",
"start",
"of",
"the",
"present",
"epoch",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L706-L718 | train | 23,630 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.add_time | def add_time(self, extra_time):
"""Go to the predefined time forward."""
window_start = self.parent.value('window_start') + extra_time
self.parent.overview.update_position(window_start) | python | def add_time(self, extra_time):
"""Go to the predefined time forward."""
window_start = self.parent.value('window_start') + extra_time
self.parent.overview.update_position(window_start) | [
"def",
"add_time",
"(",
"self",
",",
"extra_time",
")",
":",
"window_start",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"+",
"extra_time",
"self",
".",
"parent",
".",
"overview",
".",
"update_position",
"(",
"window_start",
")"
] | Go to the predefined time forward. | [
"Go",
"to",
"the",
"predefined",
"time",
"forward",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L720-L723 | train | 23,631 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.X_more | def X_more(self):
"""Zoom in on the x-axis."""
if self.parent.value('window_length') < 0.3:
return
self.parent.value('window_length',
self.parent.value('window_length') * 2)
self.parent.overview.update_position() | python | def X_more(self):
"""Zoom in on the x-axis."""
if self.parent.value('window_length') < 0.3:
return
self.parent.value('window_length',
self.parent.value('window_length') * 2)
self.parent.overview.update_position() | [
"def",
"X_more",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"<",
"0.3",
":",
"return",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'w... | Zoom in on the x-axis. | [
"Zoom",
"in",
"on",
"the",
"x",
"-",
"axis",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L725-L731 | train | 23,632 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.X_less | def X_less(self):
"""Zoom out on the x-axis."""
self.parent.value('window_length',
self.parent.value('window_length') / 2)
self.parent.overview.update_position() | python | def X_less(self):
"""Zoom out on the x-axis."""
self.parent.value('window_length',
self.parent.value('window_length') / 2)
self.parent.overview.update_position() | [
"def",
"X_less",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"/",
"2",
")",
"self",
".",
"parent",
".",
"overview",
".",
"update_position",
"... | Zoom out on the x-axis. | [
"Zoom",
"out",
"on",
"the",
"x",
"-",
"axis",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L733-L737 | train | 23,633 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.X_length | def X_length(self, new_window_length):
"""Use presets for length of the window."""
self.parent.value('window_length', new_window_length)
self.parent.overview.update_position() | python | def X_length(self, new_window_length):
"""Use presets for length of the window."""
self.parent.value('window_length', new_window_length)
self.parent.overview.update_position() | [
"def",
"X_length",
"(",
"self",
",",
"new_window_length",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
",",
"new_window_length",
")",
"self",
".",
"parent",
".",
"overview",
".",
"update_position",
"(",
")"
] | Use presets for length of the window. | [
"Use",
"presets",
"for",
"length",
"of",
"the",
"window",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L739-L742 | train | 23,634 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.Y_more | def Y_more(self):
"""Increase the scaling."""
self.parent.value('y_scale', self.parent.value('y_scale') * 2)
self.parent.traces.display() | python | def Y_more(self):
"""Increase the scaling."""
self.parent.value('y_scale', self.parent.value('y_scale') * 2)
self.parent.traces.display() | [
"def",
"Y_more",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'y_scale'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'y_scale'",
")",
"*",
"2",
")",
"self",
".",
"parent",
".",
"traces",
".",
"display",
"(",
")"
] | Increase the scaling. | [
"Increase",
"the",
"scaling",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L744-L747 | train | 23,635 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.Y_less | def Y_less(self):
"""Decrease the scaling."""
self.parent.value('y_scale', self.parent.value('y_scale') / 2)
self.parent.traces.display() | python | def Y_less(self):
"""Decrease the scaling."""
self.parent.value('y_scale', self.parent.value('y_scale') / 2)
self.parent.traces.display() | [
"def",
"Y_less",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'y_scale'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'y_scale'",
")",
"/",
"2",
")",
"self",
".",
"parent",
".",
"traces",
".",
"display",
"(",
")"
] | Decrease the scaling. | [
"Decrease",
"the",
"scaling",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L749-L752 | train | 23,636 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.Y_ampl | def Y_ampl(self, new_y_scale):
"""Make scaling on Y axis using predefined values"""
self.parent.value('y_scale', new_y_scale)
self.parent.traces.display() | python | def Y_ampl(self, new_y_scale):
"""Make scaling on Y axis using predefined values"""
self.parent.value('y_scale', new_y_scale)
self.parent.traces.display() | [
"def",
"Y_ampl",
"(",
"self",
",",
"new_y_scale",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'y_scale'",
",",
"new_y_scale",
")",
"self",
".",
"parent",
".",
"traces",
".",
"display",
"(",
")"
] | Make scaling on Y axis using predefined values | [
"Make",
"scaling",
"on",
"Y",
"axis",
"using",
"predefined",
"values"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L754-L757 | train | 23,637 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.Y_wider | def Y_wider(self):
"""Increase the distance of the lines."""
self.parent.value('y_distance', self.parent.value('y_distance') * 1.4)
self.parent.traces.display() | python | def Y_wider(self):
"""Increase the distance of the lines."""
self.parent.value('y_distance', self.parent.value('y_distance') * 1.4)
self.parent.traces.display() | [
"def",
"Y_wider",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'y_distance'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'y_distance'",
")",
"*",
"1.4",
")",
"self",
".",
"parent",
".",
"traces",
".",
"display",
"(",
")"
] | Increase the distance of the lines. | [
"Increase",
"the",
"distance",
"of",
"the",
"lines",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L759-L762 | train | 23,638 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.Y_tighter | def Y_tighter(self):
"""Decrease the distance of the lines."""
self.parent.value('y_distance', self.parent.value('y_distance') / 1.4)
self.parent.traces.display() | python | def Y_tighter(self):
"""Decrease the distance of the lines."""
self.parent.value('y_distance', self.parent.value('y_distance') / 1.4)
self.parent.traces.display() | [
"def",
"Y_tighter",
"(",
"self",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'y_distance'",
",",
"self",
".",
"parent",
".",
"value",
"(",
"'y_distance'",
")",
"/",
"1.4",
")",
"self",
".",
"parent",
".",
"traces",
".",
"display",
"(",
")"
] | Decrease the distance of the lines. | [
"Decrease",
"the",
"distance",
"of",
"the",
"lines",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L764-L767 | train | 23,639 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.Y_dist | def Y_dist(self, new_y_distance):
"""Use preset values for the distance between lines."""
self.parent.value('y_distance', new_y_distance)
self.parent.traces.display() | python | def Y_dist(self, new_y_distance):
"""Use preset values for the distance between lines."""
self.parent.value('y_distance', new_y_distance)
self.parent.traces.display() | [
"def",
"Y_dist",
"(",
"self",
",",
"new_y_distance",
")",
":",
"self",
".",
"parent",
".",
"value",
"(",
"'y_distance'",
",",
"new_y_distance",
")",
"self",
".",
"parent",
".",
"traces",
".",
"display",
"(",
")"
] | Use preset values for the distance between lines. | [
"Use",
"preset",
"values",
"for",
"the",
"distance",
"between",
"lines",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L769-L772 | train | 23,640 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.mousePressEvent | def mousePressEvent(self, event):
"""Create a marker or start selection
Parameters
----------
event : instance of QtCore.QEvent
it contains the position that was clicked.
"""
if not self.scene:
return
if self.event_sel or self.current_event:
self.parent.notes.idx_eventtype.setCurrentText(self.current_etype)
self.current_etype = None
self.current_event = None
self.deselect = True
self.event_sel = None
self.current_event_row = None
self.scene.removeItem(self.highlight)
self.highlight = None
self.parent.statusBar().showMessage('')
return
self.ready = False
self.event_sel = None
xy_scene = self.mapToScene(event.pos())
chan_idx = argmin(abs(asarray(self.chan_pos) - xy_scene.y()))
self.sel_chan = chan_idx
self.sel_xy = (xy_scene.x(), xy_scene.y())
chk_marker = self.parent.notes.action['new_bookmark'].isChecked()
chk_event = self.parent.notes.action['new_event'].isChecked()
if not (chk_marker or chk_event):
channame = self.chan[self.sel_chan] + ' in selected window'
self.parent.spectrum.show_channame(channame)
# Make annotations clickable
else:
for annot in self.idx_annot:
if annot.contains(xy_scene):
self.highlight_event(annot)
if chk_event:
row = self.parent.notes.find_row(annot.marker.x(),
annot.marker.x() + annot.marker.width())
self.parent.notes.idx_annot_list.setCurrentCell(row, 0)
break
self.ready = True | python | def mousePressEvent(self, event):
"""Create a marker or start selection
Parameters
----------
event : instance of QtCore.QEvent
it contains the position that was clicked.
"""
if not self.scene:
return
if self.event_sel or self.current_event:
self.parent.notes.idx_eventtype.setCurrentText(self.current_etype)
self.current_etype = None
self.current_event = None
self.deselect = True
self.event_sel = None
self.current_event_row = None
self.scene.removeItem(self.highlight)
self.highlight = None
self.parent.statusBar().showMessage('')
return
self.ready = False
self.event_sel = None
xy_scene = self.mapToScene(event.pos())
chan_idx = argmin(abs(asarray(self.chan_pos) - xy_scene.y()))
self.sel_chan = chan_idx
self.sel_xy = (xy_scene.x(), xy_scene.y())
chk_marker = self.parent.notes.action['new_bookmark'].isChecked()
chk_event = self.parent.notes.action['new_event'].isChecked()
if not (chk_marker or chk_event):
channame = self.chan[self.sel_chan] + ' in selected window'
self.parent.spectrum.show_channame(channame)
# Make annotations clickable
else:
for annot in self.idx_annot:
if annot.contains(xy_scene):
self.highlight_event(annot)
if chk_event:
row = self.parent.notes.find_row(annot.marker.x(),
annot.marker.x() + annot.marker.width())
self.parent.notes.idx_annot_list.setCurrentCell(row, 0)
break
self.ready = True | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"scene",
":",
"return",
"if",
"self",
".",
"event_sel",
"or",
"self",
".",
"current_event",
":",
"self",
".",
"parent",
".",
"notes",
".",
"idx_eventtype",
".",
"s... | Create a marker or start selection
Parameters
----------
event : instance of QtCore.QEvent
it contains the position that was clicked. | [
"Create",
"a",
"marker",
"or",
"start",
"selection"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L774-L823 | train | 23,641 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.mouseReleaseEvent | def mouseReleaseEvent(self, event):
"""Create a new event or marker, or show the previous power spectrum
"""
if not self.scene:
return
if self.event_sel:
return
if self.deselect:
self.deselect = False
return
if not self.ready:
return
chk_marker = self.parent.notes.action['new_bookmark'].isChecked()
chk_event = self.parent.notes.action['new_event'].isChecked()
y_distance = self.parent.value('y_distance')
if chk_marker or chk_event:
x_in_scene = self.mapToScene(event.pos()).x()
y_in_scene = self.mapToScene(event.pos()).y()
# it can happen that selection is empty (f.e. double-click)
if self.sel_xy[0] is not None:
# max resolution = sampling frequency
# in case there is no data
s_freq = self.parent.info.dataset.header['s_freq']
at_s_freq = lambda x: round(x * s_freq) / s_freq
start = at_s_freq(self.sel_xy[0])
end = at_s_freq(x_in_scene)
if abs(end - start) < self.parent.value('min_marker_dur'):
end = start
if start <= end:
time = (start, end)
else:
time = (end, start)
if chk_marker:
self.parent.notes.add_bookmark(time)
elif chk_event and start != end:
eventtype = self.parent.notes.idx_eventtype.currentText()
# if dragged across > 1.5 chan, event is marked on all chan
if abs(y_in_scene - self.sel_xy[1]) > 1.5 * y_distance:
chan = ''
else:
chan_idx = int(floor(self.sel_xy[1] / y_distance))
chan = self.chan[chan_idx]
self.parent.notes.add_event(eventtype, time, chan)
else: # normal selection
if self.idx_info in self.scene.items():
self.scene.removeItem(self.idx_info)
self.idx_info = None
# restore spectrum
self.parent.spectrum.update()
self.parent.spectrum.display_window()
# general garbage collection
self.sel_chan = None
self.sel_xy = (None, None)
if self.idx_sel in self.scene.items():
self.scene.removeItem(self.idx_sel)
self.idx_sel = None | python | def mouseReleaseEvent(self, event):
"""Create a new event or marker, or show the previous power spectrum
"""
if not self.scene:
return
if self.event_sel:
return
if self.deselect:
self.deselect = False
return
if not self.ready:
return
chk_marker = self.parent.notes.action['new_bookmark'].isChecked()
chk_event = self.parent.notes.action['new_event'].isChecked()
y_distance = self.parent.value('y_distance')
if chk_marker or chk_event:
x_in_scene = self.mapToScene(event.pos()).x()
y_in_scene = self.mapToScene(event.pos()).y()
# it can happen that selection is empty (f.e. double-click)
if self.sel_xy[0] is not None:
# max resolution = sampling frequency
# in case there is no data
s_freq = self.parent.info.dataset.header['s_freq']
at_s_freq = lambda x: round(x * s_freq) / s_freq
start = at_s_freq(self.sel_xy[0])
end = at_s_freq(x_in_scene)
if abs(end - start) < self.parent.value('min_marker_dur'):
end = start
if start <= end:
time = (start, end)
else:
time = (end, start)
if chk_marker:
self.parent.notes.add_bookmark(time)
elif chk_event and start != end:
eventtype = self.parent.notes.idx_eventtype.currentText()
# if dragged across > 1.5 chan, event is marked on all chan
if abs(y_in_scene - self.sel_xy[1]) > 1.5 * y_distance:
chan = ''
else:
chan_idx = int(floor(self.sel_xy[1] / y_distance))
chan = self.chan[chan_idx]
self.parent.notes.add_event(eventtype, time, chan)
else: # normal selection
if self.idx_info in self.scene.items():
self.scene.removeItem(self.idx_info)
self.idx_info = None
# restore spectrum
self.parent.spectrum.update()
self.parent.spectrum.display_window()
# general garbage collection
self.sel_chan = None
self.sel_xy = (None, None)
if self.idx_sel in self.scene.items():
self.scene.removeItem(self.idx_sel)
self.idx_sel = None | [
"def",
"mouseReleaseEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"scene",
":",
"return",
"if",
"self",
".",
"event_sel",
":",
"return",
"if",
"self",
".",
"deselect",
":",
"self",
".",
"deselect",
"=",
"False",
"return",
"if",... | Create a new event or marker, or show the previous power spectrum | [
"Create",
"a",
"new",
"event",
"or",
"marker",
"or",
"show",
"the",
"previous",
"power",
"spectrum"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L907-L980 | train | 23,642 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.next_event | def next_event(self, delete=False):
"""Go to next event."""
if delete:
msg = "Delete this event? This cannot be undone."
msgbox = QMessageBox(QMessageBox.Question, 'Delete event', msg)
msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgbox.setDefaultButton(QMessageBox.Yes)
response = msgbox.exec_()
if response == QMessageBox.No:
return
event_sel = self.event_sel
if event_sel is None:
return
notes = self.parent.notes
if not self.current_event_row:
row = notes.find_row(event_sel.marker.x(),
event_sel.marker.x() + event_sel.marker.width())
else:
row = self.current_event_row
same_type = self.action['next_of_same_type'].isChecked()
if same_type:
target = notes.idx_annot_list.item(row, 2).text()
if delete:
notes.delete_row()
msg = 'Deleted event from {} to {}.'.format(event_sel.marker.x(),
event_sel.marker.x() + event_sel.marker.width())
self.parent.statusBar().showMessage(msg)
row -= 1
if row + 1 == notes.idx_annot_list.rowCount():
return
if not same_type:
next_row = row + 1
else:
next_row = None
types = notes.idx_annot_list.property('name')[row + 1:]
for i, ty in enumerate(types):
if ty == target:
next_row = row + 1 + i
break
if next_row is None:
return
self.current_event_row = next_row
notes.go_to_marker(next_row, 0, 'annot')
notes.idx_annot_list.setCurrentCell(next_row, 0) | python | def next_event(self, delete=False):
"""Go to next event."""
if delete:
msg = "Delete this event? This cannot be undone."
msgbox = QMessageBox(QMessageBox.Question, 'Delete event', msg)
msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
msgbox.setDefaultButton(QMessageBox.Yes)
response = msgbox.exec_()
if response == QMessageBox.No:
return
event_sel = self.event_sel
if event_sel is None:
return
notes = self.parent.notes
if not self.current_event_row:
row = notes.find_row(event_sel.marker.x(),
event_sel.marker.x() + event_sel.marker.width())
else:
row = self.current_event_row
same_type = self.action['next_of_same_type'].isChecked()
if same_type:
target = notes.idx_annot_list.item(row, 2).text()
if delete:
notes.delete_row()
msg = 'Deleted event from {} to {}.'.format(event_sel.marker.x(),
event_sel.marker.x() + event_sel.marker.width())
self.parent.statusBar().showMessage(msg)
row -= 1
if row + 1 == notes.idx_annot_list.rowCount():
return
if not same_type:
next_row = row + 1
else:
next_row = None
types = notes.idx_annot_list.property('name')[row + 1:]
for i, ty in enumerate(types):
if ty == target:
next_row = row + 1 + i
break
if next_row is None:
return
self.current_event_row = next_row
notes.go_to_marker(next_row, 0, 'annot')
notes.idx_annot_list.setCurrentCell(next_row, 0) | [
"def",
"next_event",
"(",
"self",
",",
"delete",
"=",
"False",
")",
":",
"if",
"delete",
":",
"msg",
"=",
"\"Delete this event? This cannot be undone.\"",
"msgbox",
"=",
"QMessageBox",
"(",
"QMessageBox",
".",
"Question",
",",
"'Delete event'",
",",
"msg",
")",
... | Go to next event. | [
"Go",
"to",
"next",
"event",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L1048-L1101 | train | 23,643 |
wonambi-python/wonambi | wonambi/widgets/traces.py | Traces.resizeEvent | def resizeEvent(self, event):
"""Resize scene so that it fits the whole widget.
Parameters
----------
event : instance of QtCore.QEvent
not important
Notes
-----
This function overwrites Qt function, therefore the non-standard
name. Argument also depends on Qt.
The function is used to change the scale of view, so that the scene
fits the whole scene. There are two problems that I could not fix: 1)
how to give the width of the label in absolute width, 2) how to strech
scene just enough that it doesn't trigger a scrollbar. However, it's
pretty good as it is now.
"""
if self.scene is not None:
ratio = self.width() / (self.scene.width() * 1.1)
self.resetTransform()
self.scale(ratio, 1) | python | def resizeEvent(self, event):
"""Resize scene so that it fits the whole widget.
Parameters
----------
event : instance of QtCore.QEvent
not important
Notes
-----
This function overwrites Qt function, therefore the non-standard
name. Argument also depends on Qt.
The function is used to change the scale of view, so that the scene
fits the whole scene. There are two problems that I could not fix: 1)
how to give the width of the label in absolute width, 2) how to strech
scene just enough that it doesn't trigger a scrollbar. However, it's
pretty good as it is now.
"""
if self.scene is not None:
ratio = self.width() / (self.scene.width() * 1.1)
self.resetTransform()
self.scale(ratio, 1) | [
"def",
"resizeEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"self",
".",
"scene",
"is",
"not",
"None",
":",
"ratio",
"=",
"self",
".",
"width",
"(",
")",
"/",
"(",
"self",
".",
"scene",
".",
"width",
"(",
")",
"*",
"1.1",
")",
"self",
".",... | Resize scene so that it fits the whole widget.
Parameters
----------
event : instance of QtCore.QEvent
not important
Notes
-----
This function overwrites Qt function, therefore the non-standard
name. Argument also depends on Qt.
The function is used to change the scale of view, so that the scene
fits the whole scene. There are two problems that I could not fix: 1)
how to give the width of the label in absolute width, 2) how to strech
scene just enough that it doesn't trigger a scrollbar. However, it's
pretty good as it is now. | [
"Resize",
"scene",
"so",
"that",
"it",
"fits",
"the",
"whole",
"widget",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/traces.py#L1130-L1152 | train | 23,644 |
wonambi-python/wonambi | wonambi/ioeeg/edf.py | Edf.return_dat | def return_dat(self, chan, begsam, endsam):
"""Read data from an EDF file.
Reads channel by channel, and adjusts the values by calibration.
Parameters
----------
chan : list of int
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.ndarray
A 2d matrix, where the first dimension is the channels and the
second dimension are the samples.
"""
assert begsam < endsam
dat = empty((len(chan), endsam - begsam))
dat.fill(NaN)
with self.filename.open('rb') as f:
for i_dat, blk, i_blk in _select_blocks(self.blocks, begsam, endsam):
dat_in_rec = self._read_record(f, blk, chan)
dat[:, i_dat[0]:i_dat[1]] = dat_in_rec[:, i_blk[0]:i_blk[1]]
# calibration
dat = ((dat.astype('float64') - self.dig_min[chan, newaxis]) *
self.gain[chan, newaxis] + self.phys_min[chan, newaxis])
return dat | python | def return_dat(self, chan, begsam, endsam):
"""Read data from an EDF file.
Reads channel by channel, and adjusts the values by calibration.
Parameters
----------
chan : list of int
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.ndarray
A 2d matrix, where the first dimension is the channels and the
second dimension are the samples.
"""
assert begsam < endsam
dat = empty((len(chan), endsam - begsam))
dat.fill(NaN)
with self.filename.open('rb') as f:
for i_dat, blk, i_blk in _select_blocks(self.blocks, begsam, endsam):
dat_in_rec = self._read_record(f, blk, chan)
dat[:, i_dat[0]:i_dat[1]] = dat_in_rec[:, i_blk[0]:i_blk[1]]
# calibration
dat = ((dat.astype('float64') - self.dig_min[chan, newaxis]) *
self.gain[chan, newaxis] + self.phys_min[chan, newaxis])
return dat | [
"def",
"return_dat",
"(",
"self",
",",
"chan",
",",
"begsam",
",",
"endsam",
")",
":",
"assert",
"begsam",
"<",
"endsam",
"dat",
"=",
"empty",
"(",
"(",
"len",
"(",
"chan",
")",
",",
"endsam",
"-",
"begsam",
")",
")",
"dat",
".",
"fill",
"(",
"Na... | Read data from an EDF file.
Reads channel by channel, and adjusts the values by calibration.
Parameters
----------
chan : list of int
index (indices) of the channels to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.ndarray
A 2d matrix, where the first dimension is the channels and the
second dimension are the samples. | [
"Read",
"data",
"from",
"an",
"EDF",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/edf.py#L177-L212 | train | 23,645 |
wonambi-python/wonambi | wonambi/ioeeg/edf.py | Edf._read_record | def _read_record(self, f, blk, chans):
"""Read raw data from a single EDF channel.
Parameters
----------
i_chan : int
index of the channel to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.ndarray
A vector with the data as written on file, in 16-bit precision
"""
dat_in_rec = empty((len(chans), self.max_smp))
i_ch_in_dat = 0
for i_ch in chans:
offset, n_smp_per_chan = self._offset(blk, i_ch)
f.seek(offset)
x = fromfile(f, count=n_smp_per_chan, dtype=EDF_FORMAT)
ratio = int(self.max_smp / n_smp_per_chan)
dat_in_rec[i_ch_in_dat, :] = repeat(x, ratio)
i_ch_in_dat += 1
return dat_in_rec | python | def _read_record(self, f, blk, chans):
"""Read raw data from a single EDF channel.
Parameters
----------
i_chan : int
index of the channel to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.ndarray
A vector with the data as written on file, in 16-bit precision
"""
dat_in_rec = empty((len(chans), self.max_smp))
i_ch_in_dat = 0
for i_ch in chans:
offset, n_smp_per_chan = self._offset(blk, i_ch)
f.seek(offset)
x = fromfile(f, count=n_smp_per_chan, dtype=EDF_FORMAT)
ratio = int(self.max_smp / n_smp_per_chan)
dat_in_rec[i_ch_in_dat, :] = repeat(x, ratio)
i_ch_in_dat += 1
return dat_in_rec | [
"def",
"_read_record",
"(",
"self",
",",
"f",
",",
"blk",
",",
"chans",
")",
":",
"dat_in_rec",
"=",
"empty",
"(",
"(",
"len",
"(",
"chans",
")",
",",
"self",
".",
"max_smp",
")",
")",
"i_ch_in_dat",
"=",
"0",
"for",
"i_ch",
"in",
"chans",
":",
"... | Read raw data from a single EDF channel.
Parameters
----------
i_chan : int
index of the channel to read
begsam : int
index of the first sample
endsam : int
index of the last sample
Returns
-------
numpy.ndarray
A vector with the data as written on file, in 16-bit precision | [
"Read",
"raw",
"data",
"from",
"a",
"single",
"EDF",
"channel",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/edf.py#L214-L244 | train | 23,646 |
wonambi-python/wonambi | wonambi/ioeeg/brainvision.py | write_brainvision | def write_brainvision(data, filename, markers=None):
"""Export data in BrainVision format
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (use '.vhdr' as extension)
"""
filename = Path(filename).resolve().with_suffix('.vhdr')
if markers is None:
markers = []
with filename.open('w') as f:
f.write(_write_vhdr(data, filename))
with filename.with_suffix('.vmrk').open('w') as f:
f.write(_write_vmrk(data, filename, markers))
_write_eeg(data, filename) | python | def write_brainvision(data, filename, markers=None):
"""Export data in BrainVision format
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (use '.vhdr' as extension)
"""
filename = Path(filename).resolve().with_suffix('.vhdr')
if markers is None:
markers = []
with filename.open('w') as f:
f.write(_write_vhdr(data, filename))
with filename.with_suffix('.vmrk').open('w') as f:
f.write(_write_vmrk(data, filename, markers))
_write_eeg(data, filename) | [
"def",
"write_brainvision",
"(",
"data",
",",
"filename",
",",
"markers",
"=",
"None",
")",
":",
"filename",
"=",
"Path",
"(",
"filename",
")",
".",
"resolve",
"(",
")",
".",
"with_suffix",
"(",
"'.vhdr'",
")",
"if",
"markers",
"is",
"None",
":",
"mark... | Export data in BrainVision format
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (use '.vhdr' as extension) | [
"Export",
"data",
"in",
"BrainVision",
"format"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/brainvision.py#L226-L246 | train | 23,647 |
wonambi-python/wonambi | wonambi/source/linear.py | calc_xyz2surf | def calc_xyz2surf(surf, xyz, threshold=20, exponent=None, std=None):
"""Calculate transformation matrix from xyz values to vertices.
Parameters
----------
surf : instance of wonambi.attr.Surf
the surface of only one hemisphere.
xyz : numpy.ndarray
nChan x 3 matrix, with the locations in x, y, z.
std : float
distance in mm of the Gaussian kernel
exponent : int
inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube)
threshold : float
distance in mm for a vertex to pick up electrode activity (if distance
is above the threshold, one electrode does not affect a vertex).
Returns
-------
numpy.ndarray
nVertices X xyz.shape[0] matrix
Notes
-----
This function is a helper when plotting onto brain surface, by creating a
transformation matrix from the values in space (f.e. at each electrode) to
the position of the vertices (used to show the brain surface).
There are many ways to move from values to vertices. The crucial parameter
is the function at which activity decreases in respect to the distance. You
can have an inverse relationship by specifying 'exponent'. If 'exponent' is
2, then the activity will decrease as inverse square of the distance. The
function can be a Gaussian. With std, you specify the width of the gaussian
kernel in mm.
For each vertex, it uses a threshold based on the distance ('threshold'
value, in mm). Finally, it normalizes the contribution of all the channels
to 1, so that the sum of the coefficients for each vertex is 1.
You can also create your own matrix (and skip calc_xyz2surf altogether) and
pass it as attribute to the main figure.
Because it's a loop over all the vertices, this function is pretty slow,
but if you calculate it once, you can reuse it.
We take advantage of multiprocessing, which speeds it up considerably.
"""
if exponent is None and std is None:
exponent = 1
if exponent is not None:
lg.debug('Vertex values based on inverse-law, with exponent ' +
str(exponent))
funct = partial(calc_one_vert_inverse, xyz=xyz, exponent=exponent)
elif std is not None:
lg.debug('Vertex values based on gaussian, with s.d. ' + str(std))
funct = partial(calc_one_vert_gauss, xyz=xyz, std=std)
with Pool() as p:
xyz2surf = p.map(funct, surf.vert)
xyz2surf = asarray(xyz2surf)
if exponent is not None:
threshold_value = (1 / (threshold ** exponent))
external_threshold_value = threshold_value
elif std is not None:
threshold_value = gauss(threshold, std)
external_threshold_value = gauss(std, std) # this is around 0.607
lg.debug('Values thresholded at ' + str(threshold_value))
xyz2surf[xyz2surf < threshold_value] = NaN
# here we deal with vertices that are within the threshold value but far
# from a single electrodes, so those remain empty
sumval = nansum(xyz2surf, axis=1)
sumval[sumval < external_threshold_value] = NaN
# normalize by the number of electrodes
xyz2surf /= atleast_2d(sumval).T
xyz2surf[isnan(xyz2surf)] = 0
return xyz2surf | python | def calc_xyz2surf(surf, xyz, threshold=20, exponent=None, std=None):
"""Calculate transformation matrix from xyz values to vertices.
Parameters
----------
surf : instance of wonambi.attr.Surf
the surface of only one hemisphere.
xyz : numpy.ndarray
nChan x 3 matrix, with the locations in x, y, z.
std : float
distance in mm of the Gaussian kernel
exponent : int
inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube)
threshold : float
distance in mm for a vertex to pick up electrode activity (if distance
is above the threshold, one electrode does not affect a vertex).
Returns
-------
numpy.ndarray
nVertices X xyz.shape[0] matrix
Notes
-----
This function is a helper when plotting onto brain surface, by creating a
transformation matrix from the values in space (f.e. at each electrode) to
the position of the vertices (used to show the brain surface).
There are many ways to move from values to vertices. The crucial parameter
is the function at which activity decreases in respect to the distance. You
can have an inverse relationship by specifying 'exponent'. If 'exponent' is
2, then the activity will decrease as inverse square of the distance. The
function can be a Gaussian. With std, you specify the width of the gaussian
kernel in mm.
For each vertex, it uses a threshold based on the distance ('threshold'
value, in mm). Finally, it normalizes the contribution of all the channels
to 1, so that the sum of the coefficients for each vertex is 1.
You can also create your own matrix (and skip calc_xyz2surf altogether) and
pass it as attribute to the main figure.
Because it's a loop over all the vertices, this function is pretty slow,
but if you calculate it once, you can reuse it.
We take advantage of multiprocessing, which speeds it up considerably.
"""
if exponent is None and std is None:
exponent = 1
if exponent is not None:
lg.debug('Vertex values based on inverse-law, with exponent ' +
str(exponent))
funct = partial(calc_one_vert_inverse, xyz=xyz, exponent=exponent)
elif std is not None:
lg.debug('Vertex values based on gaussian, with s.d. ' + str(std))
funct = partial(calc_one_vert_gauss, xyz=xyz, std=std)
with Pool() as p:
xyz2surf = p.map(funct, surf.vert)
xyz2surf = asarray(xyz2surf)
if exponent is not None:
threshold_value = (1 / (threshold ** exponent))
external_threshold_value = threshold_value
elif std is not None:
threshold_value = gauss(threshold, std)
external_threshold_value = gauss(std, std) # this is around 0.607
lg.debug('Values thresholded at ' + str(threshold_value))
xyz2surf[xyz2surf < threshold_value] = NaN
# here we deal with vertices that are within the threshold value but far
# from a single electrodes, so those remain empty
sumval = nansum(xyz2surf, axis=1)
sumval[sumval < external_threshold_value] = NaN
# normalize by the number of electrodes
xyz2surf /= atleast_2d(sumval).T
xyz2surf[isnan(xyz2surf)] = 0
return xyz2surf | [
"def",
"calc_xyz2surf",
"(",
"surf",
",",
"xyz",
",",
"threshold",
"=",
"20",
",",
"exponent",
"=",
"None",
",",
"std",
"=",
"None",
")",
":",
"if",
"exponent",
"is",
"None",
"and",
"std",
"is",
"None",
":",
"exponent",
"=",
"1",
"if",
"exponent",
... | Calculate transformation matrix from xyz values to vertices.
Parameters
----------
surf : instance of wonambi.attr.Surf
the surface of only one hemisphere.
xyz : numpy.ndarray
nChan x 3 matrix, with the locations in x, y, z.
std : float
distance in mm of the Gaussian kernel
exponent : int
inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube)
threshold : float
distance in mm for a vertex to pick up electrode activity (if distance
is above the threshold, one electrode does not affect a vertex).
Returns
-------
numpy.ndarray
nVertices X xyz.shape[0] matrix
Notes
-----
This function is a helper when plotting onto brain surface, by creating a
transformation matrix from the values in space (f.e. at each electrode) to
the position of the vertices (used to show the brain surface).
There are many ways to move from values to vertices. The crucial parameter
is the function at which activity decreases in respect to the distance. You
can have an inverse relationship by specifying 'exponent'. If 'exponent' is
2, then the activity will decrease as inverse square of the distance. The
function can be a Gaussian. With std, you specify the width of the gaussian
kernel in mm.
For each vertex, it uses a threshold based on the distance ('threshold'
value, in mm). Finally, it normalizes the contribution of all the channels
to 1, so that the sum of the coefficients for each vertex is 1.
You can also create your own matrix (and skip calc_xyz2surf altogether) and
pass it as attribute to the main figure.
Because it's a loop over all the vertices, this function is pretty slow,
but if you calculate it once, you can reuse it.
We take advantage of multiprocessing, which speeds it up considerably. | [
"Calculate",
"transformation",
"matrix",
"from",
"xyz",
"values",
"to",
"vertices",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/source/linear.py#L57-L136 | train | 23,648 |
wonambi-python/wonambi | wonambi/source/linear.py | calc_one_vert_inverse | def calc_one_vert_inverse(one_vert, xyz=None, exponent=None):
"""Calculate how many electrodes influence one vertex, using the inverse
function.
Parameters
----------
one_vert : ndarray
vector of xyz position of a vertex
xyz : ndarray
nChan X 3 with the position of all the channels
exponent : int
inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube)
Returns
-------
ndarray
one vector with values for one vertex
"""
trans = empty(xyz.shape[0])
for i, one_xyz in enumerate(xyz):
trans[i] = 1 / (norm(one_vert - one_xyz) ** exponent)
return trans | python | def calc_one_vert_inverse(one_vert, xyz=None, exponent=None):
"""Calculate how many electrodes influence one vertex, using the inverse
function.
Parameters
----------
one_vert : ndarray
vector of xyz position of a vertex
xyz : ndarray
nChan X 3 with the position of all the channels
exponent : int
inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube)
Returns
-------
ndarray
one vector with values for one vertex
"""
trans = empty(xyz.shape[0])
for i, one_xyz in enumerate(xyz):
trans[i] = 1 / (norm(one_vert - one_xyz) ** exponent)
return trans | [
"def",
"calc_one_vert_inverse",
"(",
"one_vert",
",",
"xyz",
"=",
"None",
",",
"exponent",
"=",
"None",
")",
":",
"trans",
"=",
"empty",
"(",
"xyz",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
",",
"one_xyz",
"in",
"enumerate",
"(",
"xyz",
")",
"... | Calculate how many electrodes influence one vertex, using the inverse
function.
Parameters
----------
one_vert : ndarray
vector of xyz position of a vertex
xyz : ndarray
nChan X 3 with the position of all the channels
exponent : int
inverse law (1-> direct inverse, 2-> inverse square, 3-> inverse cube)
Returns
-------
ndarray
one vector with values for one vertex | [
"Calculate",
"how",
"many",
"electrodes",
"influence",
"one",
"vertex",
"using",
"the",
"inverse",
"function",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/source/linear.py#L139-L160 | train | 23,649 |
wonambi-python/wonambi | wonambi/source/linear.py | calc_one_vert_gauss | def calc_one_vert_gauss(one_vert, xyz=None, std=None):
"""Calculate how many electrodes influence one vertex, using a Gaussian
function.
Parameters
----------
one_vert : ndarray
vector of xyz position of a vertex
xyz : ndarray
nChan X 3 with the position of all the channels
std : float
distance in mm of the Gaussian kernel
Returns
-------
ndarray
one vector with values for one vertex
"""
trans = empty(xyz.shape[0])
for i, one_xyz in enumerate(xyz):
trans[i] = gauss(norm(one_vert - one_xyz), std)
return trans | python | def calc_one_vert_gauss(one_vert, xyz=None, std=None):
"""Calculate how many electrodes influence one vertex, using a Gaussian
function.
Parameters
----------
one_vert : ndarray
vector of xyz position of a vertex
xyz : ndarray
nChan X 3 with the position of all the channels
std : float
distance in mm of the Gaussian kernel
Returns
-------
ndarray
one vector with values for one vertex
"""
trans = empty(xyz.shape[0])
for i, one_xyz in enumerate(xyz):
trans[i] = gauss(norm(one_vert - one_xyz), std)
return trans | [
"def",
"calc_one_vert_gauss",
"(",
"one_vert",
",",
"xyz",
"=",
"None",
",",
"std",
"=",
"None",
")",
":",
"trans",
"=",
"empty",
"(",
"xyz",
".",
"shape",
"[",
"0",
"]",
")",
"for",
"i",
",",
"one_xyz",
"in",
"enumerate",
"(",
"xyz",
")",
":",
"... | Calculate how many electrodes influence one vertex, using a Gaussian
function.
Parameters
----------
one_vert : ndarray
vector of xyz position of a vertex
xyz : ndarray
nChan X 3 with the position of all the channels
std : float
distance in mm of the Gaussian kernel
Returns
-------
ndarray
one vector with values for one vertex | [
"Calculate",
"how",
"many",
"electrodes",
"influence",
"one",
"vertex",
"using",
"a",
"Gaussian",
"function",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/source/linear.py#L163-L184 | train | 23,650 |
wonambi-python/wonambi | wonambi/ioeeg/micromed.py | _read_history | def _read_history(f, zone):
"""This matches the Matlab reader from Matlab Exchange but doesn't seem
correct.
"""
pos, length = zone
f.seek(pos, SEEK_SET)
histories = []
while f.tell() < (pos + length):
history = {
'nSample': unpack(MAX_SAMPLE * 'I', f.read(MAX_SAMPLE * 4)),
'lines': unpack('H', f.read(2)),
'sectors': unpack('H', f.read(2)),
'base_time': unpack('H', f.read(2)),
'notch': unpack('H', f.read(2)),
'colour': unpack(MAX_CAN_VIEW * 'B', f.read(MAX_CAN_VIEW)),
'selection': unpack(MAX_CAN_VIEW * 'B', f.read(MAX_CAN_VIEW)),
'description': f.read(64).strip(b'\x01\x00'),
'inputsNonInv': unpack(MAX_CAN_VIEW * 'H', f.read(MAX_CAN_VIEW * 2)), # NonInv : non inverting input
'inputsInv': unpack(MAX_CAN_VIEW * 'H', f.read(MAX_CAN_VIEW * 2)), # Inv : inverting input
'HiPass_Filter': unpack(MAX_CAN_VIEW * 'I', f.read(MAX_CAN_VIEW * 4)),
'LowPass_Filter': unpack(MAX_CAN_VIEW * 'I', f.read(MAX_CAN_VIEW * 4)),
'reference': unpack(MAX_CAN_VIEW * 'I', f.read(MAX_CAN_VIEW * 4)),
'free': f.read(1720).strip(b'\x01\x00'),
}
histories.append(history)
return histories | python | def _read_history(f, zone):
"""This matches the Matlab reader from Matlab Exchange but doesn't seem
correct.
"""
pos, length = zone
f.seek(pos, SEEK_SET)
histories = []
while f.tell() < (pos + length):
history = {
'nSample': unpack(MAX_SAMPLE * 'I', f.read(MAX_SAMPLE * 4)),
'lines': unpack('H', f.read(2)),
'sectors': unpack('H', f.read(2)),
'base_time': unpack('H', f.read(2)),
'notch': unpack('H', f.read(2)),
'colour': unpack(MAX_CAN_VIEW * 'B', f.read(MAX_CAN_VIEW)),
'selection': unpack(MAX_CAN_VIEW * 'B', f.read(MAX_CAN_VIEW)),
'description': f.read(64).strip(b'\x01\x00'),
'inputsNonInv': unpack(MAX_CAN_VIEW * 'H', f.read(MAX_CAN_VIEW * 2)), # NonInv : non inverting input
'inputsInv': unpack(MAX_CAN_VIEW * 'H', f.read(MAX_CAN_VIEW * 2)), # Inv : inverting input
'HiPass_Filter': unpack(MAX_CAN_VIEW * 'I', f.read(MAX_CAN_VIEW * 4)),
'LowPass_Filter': unpack(MAX_CAN_VIEW * 'I', f.read(MAX_CAN_VIEW * 4)),
'reference': unpack(MAX_CAN_VIEW * 'I', f.read(MAX_CAN_VIEW * 4)),
'free': f.read(1720).strip(b'\x01\x00'),
}
histories.append(history)
return histories | [
"def",
"_read_history",
"(",
"f",
",",
"zone",
")",
":",
"pos",
",",
"length",
"=",
"zone",
"f",
".",
"seek",
"(",
"pos",
",",
"SEEK_SET",
")",
"histories",
"=",
"[",
"]",
"while",
"f",
".",
"tell",
"(",
")",
"<",
"(",
"pos",
"+",
"length",
")"... | This matches the Matlab reader from Matlab Exchange but doesn't seem
correct. | [
"This",
"matches",
"the",
"Matlab",
"reader",
"from",
"Matlab",
"Exchange",
"but",
"doesn",
"t",
"seem",
"correct",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/micromed.py#L458-L486 | train | 23,651 |
wonambi-python/wonambi | wonambi/widgets/video.py | Video.create_video | def create_video(self):
"""Create video widget."""
self.instance = vlc.Instance()
video_widget = QFrame()
self.mediaplayer = self.instance.media_player_new()
if system() == 'Linux':
self.mediaplayer.set_xwindow(video_widget.winId())
elif system() == 'Windows':
self.mediaplayer.set_hwnd(video_widget.winId())
elif system() == 'darwin': # to test
self.mediaplayer.set_nsobject(video_widget.winId())
else:
lg.warning('unsupported system for video widget')
return
self.medialistplayer = vlc.MediaListPlayer()
self.medialistplayer.set_media_player(self.mediaplayer)
event_manager = self.medialistplayer.event_manager()
event_manager.event_attach(vlc.EventType.MediaListPlayerNextItemSet,
self.next_video)
self.idx_button = QPushButton()
self.idx_button.setText('Start')
self.idx_button.clicked.connect(self.start_stop_video)
layout = QVBoxLayout()
layout.addWidget(video_widget)
layout.addWidget(self.idx_button)
self.setLayout(layout) | python | def create_video(self):
"""Create video widget."""
self.instance = vlc.Instance()
video_widget = QFrame()
self.mediaplayer = self.instance.media_player_new()
if system() == 'Linux':
self.mediaplayer.set_xwindow(video_widget.winId())
elif system() == 'Windows':
self.mediaplayer.set_hwnd(video_widget.winId())
elif system() == 'darwin': # to test
self.mediaplayer.set_nsobject(video_widget.winId())
else:
lg.warning('unsupported system for video widget')
return
self.medialistplayer = vlc.MediaListPlayer()
self.medialistplayer.set_media_player(self.mediaplayer)
event_manager = self.medialistplayer.event_manager()
event_manager.event_attach(vlc.EventType.MediaListPlayerNextItemSet,
self.next_video)
self.idx_button = QPushButton()
self.idx_button.setText('Start')
self.idx_button.clicked.connect(self.start_stop_video)
layout = QVBoxLayout()
layout.addWidget(video_widget)
layout.addWidget(self.idx_button)
self.setLayout(layout) | [
"def",
"create_video",
"(",
"self",
")",
":",
"self",
".",
"instance",
"=",
"vlc",
".",
"Instance",
"(",
")",
"video_widget",
"=",
"QFrame",
"(",
")",
"self",
".",
"mediaplayer",
"=",
"self",
".",
"instance",
".",
"media_player_new",
"(",
")",
"if",
"s... | Create video widget. | [
"Create",
"video",
"widget",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L74-L104 | train | 23,652 |
wonambi-python/wonambi | wonambi/widgets/video.py | Video.stop_video | def stop_video(self, tick):
"""Stop video if tick is more than the end, only for last file.
Parameters
----------
tick : int
time in ms from the beginning of the file
useless?
"""
if self.cnt_video == self.n_video:
if tick >= self.end_diff:
self.idx_button.setText('Start')
self.video.stop() | python | def stop_video(self, tick):
"""Stop video if tick is more than the end, only for last file.
Parameters
----------
tick : int
time in ms from the beginning of the file
useless?
"""
if self.cnt_video == self.n_video:
if tick >= self.end_diff:
self.idx_button.setText('Start')
self.video.stop() | [
"def",
"stop_video",
"(",
"self",
",",
"tick",
")",
":",
"if",
"self",
".",
"cnt_video",
"==",
"self",
".",
"n_video",
":",
"if",
"tick",
">=",
"self",
".",
"end_diff",
":",
"self",
".",
"idx_button",
".",
"setText",
"(",
"'Start'",
")",
"self",
".",... | Stop video if tick is more than the end, only for last file.
Parameters
----------
tick : int
time in ms from the beginning of the file
useless? | [
"Stop",
"video",
"if",
"tick",
"is",
"more",
"than",
"the",
"end",
"only",
"for",
"last",
"file",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L106-L119 | train | 23,653 |
wonambi-python/wonambi | wonambi/widgets/video.py | Video.next_video | def next_video(self, _):
"""Also runs when file is loaded, so index starts at 2."""
self.cnt_video += 1
lg.info('Update video to ' + str(self.cnt_video)) | python | def next_video(self, _):
"""Also runs when file is loaded, so index starts at 2."""
self.cnt_video += 1
lg.info('Update video to ' + str(self.cnt_video)) | [
"def",
"next_video",
"(",
"self",
",",
"_",
")",
":",
"self",
".",
"cnt_video",
"+=",
"1",
"lg",
".",
"info",
"(",
"'Update video to '",
"+",
"str",
"(",
"self",
".",
"cnt_video",
")",
")"
] | Also runs when file is loaded, so index starts at 2. | [
"Also",
"runs",
"when",
"file",
"is",
"loaded",
"so",
"index",
"starts",
"at",
"2",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L128-L131 | train | 23,654 |
wonambi-python/wonambi | wonambi/widgets/video.py | Video.start_stop_video | def start_stop_video(self):
"""Start and stop the video, and change the button.
"""
if self.parent.info.dataset is None:
self.parent.statusBar().showMessage('No Dataset Loaded')
return
# & is added automatically by PyQt, it seems
if 'Start' in self.idx_button.text().replace('&', ''):
try:
self.update_video()
except IndexError as er:
lg.debug(er)
self.idx_button.setText('Not Available / Start')
return
except OSError as er:
lg.debug(er)
self.idx_button.setText('NO VIDEO for this dataset')
return
self.idx_button.setText('Stop')
elif 'Stop' in self.idx_button.text():
self.idx_button.setText('Start')
self.medialistplayer.stop()
self.t.stop() | python | def start_stop_video(self):
"""Start and stop the video, and change the button.
"""
if self.parent.info.dataset is None:
self.parent.statusBar().showMessage('No Dataset Loaded')
return
# & is added automatically by PyQt, it seems
if 'Start' in self.idx_button.text().replace('&', ''):
try:
self.update_video()
except IndexError as er:
lg.debug(er)
self.idx_button.setText('Not Available / Start')
return
except OSError as er:
lg.debug(er)
self.idx_button.setText('NO VIDEO for this dataset')
return
self.idx_button.setText('Stop')
elif 'Stop' in self.idx_button.text():
self.idx_button.setText('Start')
self.medialistplayer.stop()
self.t.stop() | [
"def",
"start_stop_video",
"(",
"self",
")",
":",
"if",
"self",
".",
"parent",
".",
"info",
".",
"dataset",
"is",
"None",
":",
"self",
".",
"parent",
".",
"statusBar",
"(",
")",
".",
"showMessage",
"(",
"'No Dataset Loaded'",
")",
"return",
"# & is added a... | Start and stop the video, and change the button. | [
"Start",
"and",
"stop",
"the",
"video",
"and",
"change",
"the",
"button",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L133-L158 | train | 23,655 |
wonambi-python/wonambi | wonambi/widgets/video.py | Video.update_video | def update_video(self):
"""Read list of files, convert to video time, and add video to queue.
"""
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
d = self.parent.info.dataset
videos, begsec, endsec = d.read_videos(window_start,
window_start + window_length)
lg.debug(f'Video: {begsec} - {endsec}')
self.endsec = endsec
videos = [str(v) for v in videos] # make sure it's a str (not path)
medialist = vlc.MediaList(videos)
self.medialistplayer.set_media_list(medialist)
self.cnt_video = 0
self.n_video = len(videos)
self.t = QTimer()
self.t.timeout.connect(self.check_if_finished)
self.t.start(100)
self.medialistplayer.play()
self.mediaplayer.set_time(int(begsec * 1000)) | python | def update_video(self):
"""Read list of files, convert to video time, and add video to queue.
"""
window_start = self.parent.value('window_start')
window_length = self.parent.value('window_length')
d = self.parent.info.dataset
videos, begsec, endsec = d.read_videos(window_start,
window_start + window_length)
lg.debug(f'Video: {begsec} - {endsec}')
self.endsec = endsec
videos = [str(v) for v in videos] # make sure it's a str (not path)
medialist = vlc.MediaList(videos)
self.medialistplayer.set_media_list(medialist)
self.cnt_video = 0
self.n_video = len(videos)
self.t = QTimer()
self.t.timeout.connect(self.check_if_finished)
self.t.start(100)
self.medialistplayer.play()
self.mediaplayer.set_time(int(begsec * 1000)) | [
"def",
"update_video",
"(",
"self",
")",
":",
"window_start",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_start'",
")",
"window_length",
"=",
"self",
".",
"parent",
".",
"value",
"(",
"'window_length'",
")",
"d",
"=",
"self",
".",
"parent",
"... | Read list of files, convert to video time, and add video to queue. | [
"Read",
"list",
"of",
"files",
"convert",
"to",
"video",
"time",
"and",
"add",
"video",
"to",
"queue",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/video.py#L160-L184 | train | 23,656 |
wonambi-python/wonambi | wonambi/trans/montage.py | montage | def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None,
method='average'):
"""Apply linear transformation to the channels.
Parameters
----------
data : instance of DataRaw
the data to filter
ref_chan : list of str
list of channels used as reference
ref_to_avg : bool
if re-reference to average or not
bipolar : float
distance in mm to consider two channels as neighbors and then compute
the bipolar montage between them.
method : str
'average' or 'regression'. 'average' takes the
average across the channels selected as reference (it can be all) and
subtract it from each channel. 'regression' keeps the residuals after
regressing out the mean across channels.
Returns
-------
filtered_data : instance of DataRaw
filtered data
Notes
-----
If you don't change anything, it returns the same instance of data.
"""
if ref_to_avg and ref_chan is not None:
raise TypeError('You cannot specify reference to the average and '
'the channels to use as reference')
if ref_chan is not None:
if (not isinstance(ref_chan, (list, tuple)) or
not all(isinstance(x, str) for x in ref_chan)):
raise TypeError('chan should be a list of strings')
if ref_chan is None:
ref_chan = [] # TODO: check bool for ref_chan
if bipolar:
if not data.attr['chan']:
raise ValueError('Data should have Chan information in attr')
_assert_equal_channels(data.axis['chan'])
chan_in_data = data.axis['chan'][0]
chan = data.attr['chan']
chan = chan(lambda x: x.label in chan_in_data)
chan, trans = create_bipolar_chan(chan, bipolar)
data.attr['chan'] = chan
if ref_to_avg or ref_chan or bipolar:
mdata = data._copy()
idx_chan = mdata.index_of('chan')
for i in range(mdata.number_of('trial')):
if ref_to_avg or ref_chan:
if ref_to_avg:
ref_chan = data.axis['chan'][i]
ref_data = data(trial=i, chan=ref_chan)
if method == 'average':
mdata.data[i] = (data(trial=i) - mean(ref_data, axis=idx_chan))
elif method == 'regression':
mdata.data[i] = compute_average_regress(data(trial=i), idx_chan)
elif bipolar:
if not data.index_of('chan') == 0:
raise ValueError('For matrix multiplication to work, '
'the first dimension should be chan')
mdata.data[i] = dot(trans, data(trial=i))
mdata.axis['chan'][i] = asarray(chan.return_label(),
dtype='U')
else:
mdata = data
return mdata | python | def montage(data, ref_chan=None, ref_to_avg=False, bipolar=None,
method='average'):
"""Apply linear transformation to the channels.
Parameters
----------
data : instance of DataRaw
the data to filter
ref_chan : list of str
list of channels used as reference
ref_to_avg : bool
if re-reference to average or not
bipolar : float
distance in mm to consider two channels as neighbors and then compute
the bipolar montage between them.
method : str
'average' or 'regression'. 'average' takes the
average across the channels selected as reference (it can be all) and
subtract it from each channel. 'regression' keeps the residuals after
regressing out the mean across channels.
Returns
-------
filtered_data : instance of DataRaw
filtered data
Notes
-----
If you don't change anything, it returns the same instance of data.
"""
if ref_to_avg and ref_chan is not None:
raise TypeError('You cannot specify reference to the average and '
'the channels to use as reference')
if ref_chan is not None:
if (not isinstance(ref_chan, (list, tuple)) or
not all(isinstance(x, str) for x in ref_chan)):
raise TypeError('chan should be a list of strings')
if ref_chan is None:
ref_chan = [] # TODO: check bool for ref_chan
if bipolar:
if not data.attr['chan']:
raise ValueError('Data should have Chan information in attr')
_assert_equal_channels(data.axis['chan'])
chan_in_data = data.axis['chan'][0]
chan = data.attr['chan']
chan = chan(lambda x: x.label in chan_in_data)
chan, trans = create_bipolar_chan(chan, bipolar)
data.attr['chan'] = chan
if ref_to_avg or ref_chan or bipolar:
mdata = data._copy()
idx_chan = mdata.index_of('chan')
for i in range(mdata.number_of('trial')):
if ref_to_avg or ref_chan:
if ref_to_avg:
ref_chan = data.axis['chan'][i]
ref_data = data(trial=i, chan=ref_chan)
if method == 'average':
mdata.data[i] = (data(trial=i) - mean(ref_data, axis=idx_chan))
elif method == 'regression':
mdata.data[i] = compute_average_regress(data(trial=i), idx_chan)
elif bipolar:
if not data.index_of('chan') == 0:
raise ValueError('For matrix multiplication to work, '
'the first dimension should be chan')
mdata.data[i] = dot(trans, data(trial=i))
mdata.axis['chan'][i] = asarray(chan.return_label(),
dtype='U')
else:
mdata = data
return mdata | [
"def",
"montage",
"(",
"data",
",",
"ref_chan",
"=",
"None",
",",
"ref_to_avg",
"=",
"False",
",",
"bipolar",
"=",
"None",
",",
"method",
"=",
"'average'",
")",
":",
"if",
"ref_to_avg",
"and",
"ref_chan",
"is",
"not",
"None",
":",
"raise",
"TypeError",
... | Apply linear transformation to the channels.
Parameters
----------
data : instance of DataRaw
the data to filter
ref_chan : list of str
list of channels used as reference
ref_to_avg : bool
if re-reference to average or not
bipolar : float
distance in mm to consider two channels as neighbors and then compute
the bipolar montage between them.
method : str
'average' or 'regression'. 'average' takes the
average across the channels selected as reference (it can be all) and
subtract it from each channel. 'regression' keeps the residuals after
regressing out the mean across channels.
Returns
-------
filtered_data : instance of DataRaw
filtered data
Notes
-----
If you don't change anything, it returns the same instance of data. | [
"Apply",
"linear",
"transformation",
"to",
"the",
"channels",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/montage.py#L18-L99 | train | 23,657 |
wonambi-python/wonambi | wonambi/trans/montage.py | _assert_equal_channels | def _assert_equal_channels(axis):
"""check that all the trials have the same channels, in the same order.
Parameters
----------
axis : ndarray of ndarray
one of the data axis
Raises
------
"""
for i0 in axis:
for i1 in axis:
if not all(i0 == i1):
raise ValueError('The channels for all the trials should have '
'the same labels, in the same order.') | python | def _assert_equal_channels(axis):
"""check that all the trials have the same channels, in the same order.
Parameters
----------
axis : ndarray of ndarray
one of the data axis
Raises
------
"""
for i0 in axis:
for i1 in axis:
if not all(i0 == i1):
raise ValueError('The channels for all the trials should have '
'the same labels, in the same order.') | [
"def",
"_assert_equal_channels",
"(",
"axis",
")",
":",
"for",
"i0",
"in",
"axis",
":",
"for",
"i1",
"in",
"axis",
":",
"if",
"not",
"all",
"(",
"i0",
"==",
"i1",
")",
":",
"raise",
"ValueError",
"(",
"'The channels for all the trials should have '",
"'the s... | check that all the trials have the same channels, in the same order.
Parameters
----------
axis : ndarray of ndarray
one of the data axis
Raises
------ | [
"check",
"that",
"all",
"the",
"trials",
"have",
"the",
"same",
"channels",
"in",
"the",
"same",
"order",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/montage.py#L102-L118 | train | 23,658 |
wonambi-python/wonambi | wonambi/trans/montage.py | compute_average_regress | def compute_average_regress(x, idx_chan):
"""Take the mean across channels and regress out the mean from each channel
Parameters
----------
x : ndarray
2d array with channels on one dimension
idx_chan:
which axis contains channels
Returns
-------
ndarray
same as x, but with the mean being regressed out
"""
if x.ndim != 2:
raise ValueError(f'The number of dimensions must be 2, not {x.ndim}')
x = moveaxis(x, idx_chan, 0) # move axis to the front
avg = mean(x, axis=0)
x_o = []
for i in range(x.shape[0]):
r = lstsq(avg[:, None], x[i, :][:, None], rcond=0)[0]
x_o.append(
x[i, :] - r[0, 0] * avg
)
return moveaxis(asarray(x_o), 0, idx_chan) | python | def compute_average_regress(x, idx_chan):
"""Take the mean across channels and regress out the mean from each channel
Parameters
----------
x : ndarray
2d array with channels on one dimension
idx_chan:
which axis contains channels
Returns
-------
ndarray
same as x, but with the mean being regressed out
"""
if x.ndim != 2:
raise ValueError(f'The number of dimensions must be 2, not {x.ndim}')
x = moveaxis(x, idx_chan, 0) # move axis to the front
avg = mean(x, axis=0)
x_o = []
for i in range(x.shape[0]):
r = lstsq(avg[:, None], x[i, :][:, None], rcond=0)[0]
x_o.append(
x[i, :] - r[0, 0] * avg
)
return moveaxis(asarray(x_o), 0, idx_chan) | [
"def",
"compute_average_regress",
"(",
"x",
",",
"idx_chan",
")",
":",
"if",
"x",
".",
"ndim",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"f'The number of dimensions must be 2, not {x.ndim}'",
")",
"x",
"=",
"moveaxis",
"(",
"x",
",",
"idx_chan",
",",
"0",
... | Take the mean across channels and regress out the mean from each channel
Parameters
----------
x : ndarray
2d array with channels on one dimension
idx_chan:
which axis contains channels
Returns
-------
ndarray
same as x, but with the mean being regressed out | [
"Take",
"the",
"mean",
"across",
"channels",
"and",
"regress",
"out",
"the",
"mean",
"from",
"each",
"channel"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/montage.py#L155-L182 | train | 23,659 |
wonambi-python/wonambi | wonambi/widgets/utils.py | keep_recent_datasets | def keep_recent_datasets(max_dataset_history, info=None):
"""Keep track of the most recent recordings.
Parameters
----------
max_dataset_history : int
maximum number of datasets to remember
info : str, optional TODO
path to file
Returns
-------
list of str
paths to most recent datasets (only if you don't specify
new_dataset)
"""
history = settings.value('recent_recordings', [])
if isinstance(history, str):
history = [history]
if info is not None and info.filename is not None:
new_dataset = info.filename
if new_dataset in history:
lg.debug(new_dataset + ' already present, will be replaced')
history.remove(new_dataset)
if len(history) > max_dataset_history:
lg.debug('Removing last dataset ' + history[-1])
history.pop()
lg.debug('Adding ' + new_dataset + ' to list of recent datasets')
history.insert(0, new_dataset)
settings.setValue('recent_recordings', history)
return None
else:
return history | python | def keep_recent_datasets(max_dataset_history, info=None):
"""Keep track of the most recent recordings.
Parameters
----------
max_dataset_history : int
maximum number of datasets to remember
info : str, optional TODO
path to file
Returns
-------
list of str
paths to most recent datasets (only if you don't specify
new_dataset)
"""
history = settings.value('recent_recordings', [])
if isinstance(history, str):
history = [history]
if info is not None and info.filename is not None:
new_dataset = info.filename
if new_dataset in history:
lg.debug(new_dataset + ' already present, will be replaced')
history.remove(new_dataset)
if len(history) > max_dataset_history:
lg.debug('Removing last dataset ' + history[-1])
history.pop()
lg.debug('Adding ' + new_dataset + ' to list of recent datasets')
history.insert(0, new_dataset)
settings.setValue('recent_recordings', history)
return None
else:
return history | [
"def",
"keep_recent_datasets",
"(",
"max_dataset_history",
",",
"info",
"=",
"None",
")",
":",
"history",
"=",
"settings",
".",
"value",
"(",
"'recent_recordings'",
",",
"[",
"]",
")",
"if",
"isinstance",
"(",
"history",
",",
"str",
")",
":",
"history",
"=... | Keep track of the most recent recordings.
Parameters
----------
max_dataset_history : int
maximum number of datasets to remember
info : str, optional TODO
path to file
Returns
-------
list of str
paths to most recent datasets (only if you don't specify
new_dataset) | [
"Keep",
"track",
"of",
"the",
"most",
"recent",
"recordings",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L687-L723 | train | 23,660 |
wonambi-python/wonambi | wonambi/widgets/utils.py | choose_file_or_dir | def choose_file_or_dir():
"""Create a simple message box to see if the user wants to open dir or file
Returns
-------
str
'dir' or 'file' or 'abort'
"""
question = QMessageBox(QMessageBox.Information, 'Open Dataset',
'Do you want to open a file or a directory?')
dir_button = question.addButton('Directory', QMessageBox.YesRole)
file_button = question.addButton('File', QMessageBox.NoRole)
question.addButton(QMessageBox.Cancel)
question.exec_()
response = question.clickedButton()
if response == dir_button:
return 'dir'
elif response == file_button:
return 'file'
else:
return 'abort' | python | def choose_file_or_dir():
"""Create a simple message box to see if the user wants to open dir or file
Returns
-------
str
'dir' or 'file' or 'abort'
"""
question = QMessageBox(QMessageBox.Information, 'Open Dataset',
'Do you want to open a file or a directory?')
dir_button = question.addButton('Directory', QMessageBox.YesRole)
file_button = question.addButton('File', QMessageBox.NoRole)
question.addButton(QMessageBox.Cancel)
question.exec_()
response = question.clickedButton()
if response == dir_button:
return 'dir'
elif response == file_button:
return 'file'
else:
return 'abort' | [
"def",
"choose_file_or_dir",
"(",
")",
":",
"question",
"=",
"QMessageBox",
"(",
"QMessageBox",
".",
"Information",
",",
"'Open Dataset'",
",",
"'Do you want to open a file or a directory?'",
")",
"dir_button",
"=",
"question",
".",
"addButton",
"(",
"'Directory'",
",... | Create a simple message box to see if the user wants to open dir or file
Returns
-------
str
'dir' or 'file' or 'abort' | [
"Create",
"a",
"simple",
"message",
"box",
"to",
"see",
"if",
"the",
"user",
"wants",
"to",
"open",
"dir",
"or",
"file"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L726-L748 | train | 23,661 |
wonambi-python/wonambi | wonambi/widgets/utils.py | convert_name_to_color | def convert_name_to_color(s):
"""Convert any string to an RGB color.
Parameters
----------
s : str
string to convert
selection : bool, optional
if an event is being selected, it's lighter
Returns
-------
instance of QColor
one of the possible color
Notes
-----
It takes any string and converts it to RGB color. The same string always
returns the same color. The numbers are a bit arbitrary but not completely.
h is the baseline color (keep it high to have brighter colors). Make sure
that the max module + h is less than 256 (RGB limit).
The number you multiply ord for is necessary to differentiate the letters
(otherwise 'r' and 's' are too close to each other).
"""
h = 100
v = [5 * ord(x) for x in s]
sum_mod = lambda x: sum(x) % 100
color = QColor(sum_mod(v[::3]) + h, sum_mod(v[1::3]) + h,
sum_mod(v[2::3]) + h)
return color | python | def convert_name_to_color(s):
"""Convert any string to an RGB color.
Parameters
----------
s : str
string to convert
selection : bool, optional
if an event is being selected, it's lighter
Returns
-------
instance of QColor
one of the possible color
Notes
-----
It takes any string and converts it to RGB color. The same string always
returns the same color. The numbers are a bit arbitrary but not completely.
h is the baseline color (keep it high to have brighter colors). Make sure
that the max module + h is less than 256 (RGB limit).
The number you multiply ord for is necessary to differentiate the letters
(otherwise 'r' and 's' are too close to each other).
"""
h = 100
v = [5 * ord(x) for x in s]
sum_mod = lambda x: sum(x) % 100
color = QColor(sum_mod(v[::3]) + h, sum_mod(v[1::3]) + h,
sum_mod(v[2::3]) + h)
return color | [
"def",
"convert_name_to_color",
"(",
"s",
")",
":",
"h",
"=",
"100",
"v",
"=",
"[",
"5",
"*",
"ord",
"(",
"x",
")",
"for",
"x",
"in",
"s",
"]",
"sum_mod",
"=",
"lambda",
"x",
":",
"sum",
"(",
"x",
")",
"%",
"100",
"color",
"=",
"QColor",
"(",... | Convert any string to an RGB color.
Parameters
----------
s : str
string to convert
selection : bool, optional
if an event is being selected, it's lighter
Returns
-------
instance of QColor
one of the possible color
Notes
-----
It takes any string and converts it to RGB color. The same string always
returns the same color. The numbers are a bit arbitrary but not completely.
h is the baseline color (keep it high to have brighter colors). Make sure
that the max module + h is less than 256 (RGB limit).
The number you multiply ord for is necessary to differentiate the letters
(otherwise 'r' and 's' are too close to each other). | [
"Convert",
"any",
"string",
"to",
"an",
"RGB",
"color",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L760-L790 | train | 23,662 |
wonambi-python/wonambi | wonambi/widgets/utils.py | freq_from_str | def freq_from_str(freq_str):
"""Obtain frequency ranges from input string, either as list or dynamic
notation.
Parameters
----------
freq_str : str
String with frequency ranges, either as a list:
e.g. [[1-3], [3-5], [5-8]];
or with a dynamic definition: (start, stop, width, step).
Returns
-------
list of tuple of float or None
Every tuple of float represents a frequency band. If input is invalid,
returns None.
"""
freq = []
as_list = freq_str[1:-1].replace(' ', '').split(',')
try:
if freq_str[0] == '[' and freq_str[-1] == ']':
for i in as_list:
one_band = i[1:-1].split('-')
one_band = float(one_band[0]), float(one_band[1])
freq.append(one_band)
elif freq_str[0] == '(' and freq_str[-1] == ')':
if len(as_list) == 4:
start = float(as_list[0])
stop = float(as_list[1])
halfwidth = float(as_list[2]) / 2
step = float(as_list[3])
centres = arange(start, stop, step)
for i in centres:
freq.append((i - halfwidth, i + halfwidth))
else:
return None
else:
return None
except:
return None
return freq | python | def freq_from_str(freq_str):
"""Obtain frequency ranges from input string, either as list or dynamic
notation.
Parameters
----------
freq_str : str
String with frequency ranges, either as a list:
e.g. [[1-3], [3-5], [5-8]];
or with a dynamic definition: (start, stop, width, step).
Returns
-------
list of tuple of float or None
Every tuple of float represents a frequency band. If input is invalid,
returns None.
"""
freq = []
as_list = freq_str[1:-1].replace(' ', '').split(',')
try:
if freq_str[0] == '[' and freq_str[-1] == ']':
for i in as_list:
one_band = i[1:-1].split('-')
one_band = float(one_band[0]), float(one_band[1])
freq.append(one_band)
elif freq_str[0] == '(' and freq_str[-1] == ')':
if len(as_list) == 4:
start = float(as_list[0])
stop = float(as_list[1])
halfwidth = float(as_list[2]) / 2
step = float(as_list[3])
centres = arange(start, stop, step)
for i in centres:
freq.append((i - halfwidth, i + halfwidth))
else:
return None
else:
return None
except:
return None
return freq | [
"def",
"freq_from_str",
"(",
"freq_str",
")",
":",
"freq",
"=",
"[",
"]",
"as_list",
"=",
"freq_str",
"[",
"1",
":",
"-",
"1",
"]",
".",
"replace",
"(",
"' '",
",",
"''",
")",
".",
"split",
"(",
"','",
")",
"try",
":",
"if",
"freq_str",
"[",
"0... | Obtain frequency ranges from input string, either as list or dynamic
notation.
Parameters
----------
freq_str : str
String with frequency ranges, either as a list:
e.g. [[1-3], [3-5], [5-8]];
or with a dynamic definition: (start, stop, width, step).
Returns
-------
list of tuple of float or None
Every tuple of float represents a frequency band. If input is invalid,
returns None. | [
"Obtain",
"frequency",
"ranges",
"from",
"input",
"string",
"either",
"as",
"list",
"or",
"dynamic",
"notation",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L793-L838 | train | 23,663 |
wonambi-python/wonambi | wonambi/widgets/utils.py | export_graphics_to_svg | def export_graphics_to_svg(widget, filename):
"""Export graphics to svg
Parameters
----------
widget : instance of QGraphicsView
traces or overview
filename : str
path to save svg
"""
generator = QSvgGenerator()
generator.setFileName(filename)
generator.setSize(widget.size())
generator.setViewBox(widget.rect())
painter = QPainter()
painter.begin(generator)
widget.render(painter)
painter.end() | python | def export_graphics_to_svg(widget, filename):
"""Export graphics to svg
Parameters
----------
widget : instance of QGraphicsView
traces or overview
filename : str
path to save svg
"""
generator = QSvgGenerator()
generator.setFileName(filename)
generator.setSize(widget.size())
generator.setViewBox(widget.rect())
painter = QPainter()
painter.begin(generator)
widget.render(painter)
painter.end() | [
"def",
"export_graphics_to_svg",
"(",
"widget",
",",
"filename",
")",
":",
"generator",
"=",
"QSvgGenerator",
"(",
")",
"generator",
".",
"setFileName",
"(",
"filename",
")",
"generator",
".",
"setSize",
"(",
"widget",
".",
"size",
"(",
")",
")",
"generator"... | Export graphics to svg
Parameters
----------
widget : instance of QGraphicsView
traces or overview
filename : str
path to save svg | [
"Export",
"graphics",
"to",
"svg"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L869-L887 | train | 23,664 |
wonambi-python/wonambi | wonambi/widgets/utils.py | FormList.get_value | def get_value(self, default=None):
"""Get int from widget.
Parameters
----------
default : list
list with widgets
Returns
-------
list
list that might contain int or str or float etc
"""
if default is None:
default = []
try:
text = literal_eval(self.text())
if not isinstance(text, list):
pass
# raise ValueError
except ValueError:
lg.debug('Cannot convert "' + str(text) + '" to list. ' +
'Using default ' + str(default))
text = default
self.set_value(text)
return text | python | def get_value(self, default=None):
"""Get int from widget.
Parameters
----------
default : list
list with widgets
Returns
-------
list
list that might contain int or str or float etc
"""
if default is None:
default = []
try:
text = literal_eval(self.text())
if not isinstance(text, list):
pass
# raise ValueError
except ValueError:
lg.debug('Cannot convert "' + str(text) + '" to list. ' +
'Using default ' + str(default))
text = default
self.set_value(text)
return text | [
"def",
"get_value",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"[",
"]",
"try",
":",
"text",
"=",
"literal_eval",
"(",
"self",
".",
"text",
"(",
")",
")",
"if",
"not",
"isinstance",
"(",
... | Get int from widget.
Parameters
----------
default : list
list with widgets
Returns
-------
list
list that might contain int or str or float etc | [
"Get",
"int",
"from",
"widget",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L390-L419 | train | 23,665 |
wonambi-python/wonambi | wonambi/widgets/utils.py | FormDir.connect | def connect(self, funct):
"""Call funct when the text was changed.
Parameters
----------
funct : function
function that broadcasts a change.
Notes
-----
There is something wrong here. When you run this function, it calls
for opening a directory three or four times. This is obviously wrong
but I don't understand why this happens three times. Traceback did not
help.
"""
def get_directory():
rec = QFileDialog.getExistingDirectory(self,
'Path to Recording'
' Directory')
if rec == '':
return
self.setText(rec)
funct()
self.clicked.connect(get_directory) | python | def connect(self, funct):
"""Call funct when the text was changed.
Parameters
----------
funct : function
function that broadcasts a change.
Notes
-----
There is something wrong here. When you run this function, it calls
for opening a directory three or four times. This is obviously wrong
but I don't understand why this happens three times. Traceback did not
help.
"""
def get_directory():
rec = QFileDialog.getExistingDirectory(self,
'Path to Recording'
' Directory')
if rec == '':
return
self.setText(rec)
funct()
self.clicked.connect(get_directory) | [
"def",
"connect",
"(",
"self",
",",
"funct",
")",
":",
"def",
"get_directory",
"(",
")",
":",
"rec",
"=",
"QFileDialog",
".",
"getExistingDirectory",
"(",
"self",
",",
"'Path to Recording'",
"' Directory'",
")",
"if",
"rec",
"==",
"''",
":",
"return",
"sel... | Call funct when the text was changed.
Parameters
----------
funct : function
function that broadcasts a change.
Notes
-----
There is something wrong here. When you run this function, it calls
for opening a directory three or four times. This is obviously wrong
but I don't understand why this happens three times. Traceback did not
help. | [
"Call",
"funct",
"when",
"the",
"text",
"was",
"changed",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L528-L554 | train | 23,666 |
wonambi-python/wonambi | wonambi/widgets/utils.py | FormMenu.get_value | def get_value(self, default=None):
"""Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox
"""
if default is None:
default = ''
try:
text = self.currentText()
except ValueError:
lg.debug('Cannot convert "' + str(text) + '" to list. ' +
'Using default ' + str(default))
text = default
self.set_value(text)
return text | python | def get_value(self, default=None):
"""Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox
"""
if default is None:
default = ''
try:
text = self.currentText()
except ValueError:
lg.debug('Cannot convert "' + str(text) + '" to list. ' +
'Using default ' + str(default))
text = default
self.set_value(text)
return text | [
"def",
"get_value",
"(",
"self",
",",
"default",
"=",
"None",
")",
":",
"if",
"default",
"is",
"None",
":",
"default",
"=",
"''",
"try",
":",
"text",
"=",
"self",
".",
"currentText",
"(",
")",
"except",
"ValueError",
":",
"lg",
".",
"debug",
"(",
"... | Get selection from widget.
Parameters
----------
default : str
str for use by widget
Returns
-------
str
selected item from the combobox | [
"Get",
"selection",
"from",
"widget",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/widgets/utils.py#L572-L598 | train | 23,667 |
wonambi-python/wonambi | wonambi/ioeeg/bids.py | _write_ieeg_json | def _write_ieeg_json(output_file):
"""Use only required fields
"""
dataset_info = {
"TaskName": "unknown",
"Manufacturer": "n/a",
"PowerLineFrequency": 50,
"iEEGReference": "n/a",
}
with output_file.open('w') as f:
dump(dataset_info, f, indent=' ') | python | def _write_ieeg_json(output_file):
"""Use only required fields
"""
dataset_info = {
"TaskName": "unknown",
"Manufacturer": "n/a",
"PowerLineFrequency": 50,
"iEEGReference": "n/a",
}
with output_file.open('w') as f:
dump(dataset_info, f, indent=' ') | [
"def",
"_write_ieeg_json",
"(",
"output_file",
")",
":",
"dataset_info",
"=",
"{",
"\"TaskName\"",
":",
"\"unknown\"",
",",
"\"Manufacturer\"",
":",
"\"n/a\"",
",",
"\"PowerLineFrequency\"",
":",
"50",
",",
"\"iEEGReference\"",
":",
"\"n/a\"",
",",
"}",
"with",
... | Use only required fields | [
"Use",
"only",
"required",
"fields"
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/bids.py#L115-L126 | train | 23,668 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.value | def value(self, parameter, new_value=None):
"""This function is a shortcut for any parameter. Instead of calling
the widget, its config and its values, you can call directly the
parameter.
Parameters
----------
parameter : str
name of the parameter of interest
new_value : str or float, optional
new value for the parameter
Returns
-------
str or float
if you didn't specify new_value, it returns the current value.
Notes
-----
It's important to maintain an organized dict in DEFAULTS which has to
correspond to the values in the widgets, also the name of the widget.
DEFAULTS is used like a look-up table.
"""
for widget_name, values in DEFAULTS.items():
if parameter in values.keys():
widget = getattr(self, widget_name)
if new_value is None:
return widget.config.value[parameter]
else:
lg.debug('setting value {0} of {1} to {2}'
''.format(parameter, widget_name, new_value))
widget.config.value[parameter] = new_value | python | def value(self, parameter, new_value=None):
"""This function is a shortcut for any parameter. Instead of calling
the widget, its config and its values, you can call directly the
parameter.
Parameters
----------
parameter : str
name of the parameter of interest
new_value : str or float, optional
new value for the parameter
Returns
-------
str or float
if you didn't specify new_value, it returns the current value.
Notes
-----
It's important to maintain an organized dict in DEFAULTS which has to
correspond to the values in the widgets, also the name of the widget.
DEFAULTS is used like a look-up table.
"""
for widget_name, values in DEFAULTS.items():
if parameter in values.keys():
widget = getattr(self, widget_name)
if new_value is None:
return widget.config.value[parameter]
else:
lg.debug('setting value {0} of {1} to {2}'
''.format(parameter, widget_name, new_value))
widget.config.value[parameter] = new_value | [
"def",
"value",
"(",
"self",
",",
"parameter",
",",
"new_value",
"=",
"None",
")",
":",
"for",
"widget_name",
",",
"values",
"in",
"DEFAULTS",
".",
"items",
"(",
")",
":",
"if",
"parameter",
"in",
"values",
".",
"keys",
"(",
")",
":",
"widget",
"=",
... | This function is a shortcut for any parameter. Instead of calling
the widget, its config and its values, you can call directly the
parameter.
Parameters
----------
parameter : str
name of the parameter of interest
new_value : str or float, optional
new value for the parameter
Returns
-------
str or float
if you didn't specify new_value, it returns the current value.
Notes
-----
It's important to maintain an organized dict in DEFAULTS which has to
correspond to the values in the widgets, also the name of the widget.
DEFAULTS is used like a look-up table. | [
"This",
"function",
"is",
"a",
"shortcut",
"for",
"any",
"parameter",
".",
"Instead",
"of",
"calling",
"the",
"widget",
"its",
"config",
"and",
"its",
"values",
"you",
"can",
"call",
"directly",
"the",
"parameter",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L88-L119 | train | 23,669 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.update | def update(self):
"""Once you open a dataset, it activates all the widgets.
"""
self.info.display_dataset()
self.overview.update()
self.labels.update(labels=self.info.dataset.header['chan_name'])
self.channels.update()
try:
self.info.markers = self.info.dataset.read_markers()
except FileNotFoundError:
lg.info('No notes/markers present in the header of the file')
else:
self.notes.update_dataset_marker() | python | def update(self):
"""Once you open a dataset, it activates all the widgets.
"""
self.info.display_dataset()
self.overview.update()
self.labels.update(labels=self.info.dataset.header['chan_name'])
self.channels.update()
try:
self.info.markers = self.info.dataset.read_markers()
except FileNotFoundError:
lg.info('No notes/markers present in the header of the file')
else:
self.notes.update_dataset_marker() | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"info",
".",
"display_dataset",
"(",
")",
"self",
".",
"overview",
".",
"update",
"(",
")",
"self",
".",
"labels",
".",
"update",
"(",
"labels",
"=",
"self",
".",
"info",
".",
"dataset",
".",
"he... | Once you open a dataset, it activates all the widgets. | [
"Once",
"you",
"open",
"a",
"dataset",
"it",
"activates",
"all",
"the",
"widgets",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L121-L134 | train | 23,670 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.reset | def reset(self):
"""Remove all the information from previous dataset before loading a
new dataset.
"""
# store current dataset
max_dataset_history = self.value('max_dataset_history')
keep_recent_datasets(max_dataset_history, self.info)
# reset all the widgets
self.labels.reset()
self.channels.reset()
self.info.reset()
self.notes.reset()
self.overview.reset()
self.spectrum.reset()
self.traces.reset() | python | def reset(self):
"""Remove all the information from previous dataset before loading a
new dataset.
"""
# store current dataset
max_dataset_history = self.value('max_dataset_history')
keep_recent_datasets(max_dataset_history, self.info)
# reset all the widgets
self.labels.reset()
self.channels.reset()
self.info.reset()
self.notes.reset()
self.overview.reset()
self.spectrum.reset()
self.traces.reset() | [
"def",
"reset",
"(",
"self",
")",
":",
"# store current dataset",
"max_dataset_history",
"=",
"self",
".",
"value",
"(",
"'max_dataset_history'",
")",
"keep_recent_datasets",
"(",
"max_dataset_history",
",",
"self",
".",
"info",
")",
"# reset all the widgets",
"self",... | Remove all the information from previous dataset before loading a
new dataset. | [
"Remove",
"all",
"the",
"information",
"from",
"previous",
"dataset",
"before",
"loading",
"a",
"new",
"dataset",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L136-L152 | train | 23,671 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.show_settings | def show_settings(self):
"""Open the Setting windows, after updating the values in GUI. """
self.notes.config.put_values()
self.overview.config.put_values()
self.settings.config.put_values()
self.spectrum.config.put_values()
self.traces.config.put_values()
self.video.config.put_values()
self.settings.show() | python | def show_settings(self):
"""Open the Setting windows, after updating the values in GUI. """
self.notes.config.put_values()
self.overview.config.put_values()
self.settings.config.put_values()
self.spectrum.config.put_values()
self.traces.config.put_values()
self.video.config.put_values()
self.settings.show() | [
"def",
"show_settings",
"(",
"self",
")",
":",
"self",
".",
"notes",
".",
"config",
".",
"put_values",
"(",
")",
"self",
".",
"overview",
".",
"config",
".",
"put_values",
"(",
")",
"self",
".",
"settings",
".",
"config",
".",
"put_values",
"(",
")",
... | Open the Setting windows, after updating the values in GUI. | [
"Open",
"the",
"Setting",
"windows",
"after",
"updating",
"the",
"values",
"in",
"GUI",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L154-L163 | train | 23,672 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.show_spindle_dialog | def show_spindle_dialog(self):
"""Create the spindle detection dialog."""
self.spindle_dialog.update_groups()
self.spindle_dialog.update_cycles()
self.spindle_dialog.show() | python | def show_spindle_dialog(self):
"""Create the spindle detection dialog."""
self.spindle_dialog.update_groups()
self.spindle_dialog.update_cycles()
self.spindle_dialog.show() | [
"def",
"show_spindle_dialog",
"(",
"self",
")",
":",
"self",
".",
"spindle_dialog",
".",
"update_groups",
"(",
")",
"self",
".",
"spindle_dialog",
".",
"update_cycles",
"(",
")",
"self",
".",
"spindle_dialog",
".",
"show",
"(",
")"
] | Create the spindle detection dialog. | [
"Create",
"the",
"spindle",
"detection",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L180-L184 | train | 23,673 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.show_slow_wave_dialog | def show_slow_wave_dialog(self):
"""Create the SW detection dialog."""
self.slow_wave_dialog.update_groups()
self.slow_wave_dialog.update_cycles()
self.slow_wave_dialog.show() | python | def show_slow_wave_dialog(self):
"""Create the SW detection dialog."""
self.slow_wave_dialog.update_groups()
self.slow_wave_dialog.update_cycles()
self.slow_wave_dialog.show() | [
"def",
"show_slow_wave_dialog",
"(",
"self",
")",
":",
"self",
".",
"slow_wave_dialog",
".",
"update_groups",
"(",
")",
"self",
".",
"slow_wave_dialog",
".",
"update_cycles",
"(",
")",
"self",
".",
"slow_wave_dialog",
".",
"show",
"(",
")"
] | Create the SW detection dialog. | [
"Create",
"the",
"SW",
"detection",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L186-L190 | train | 23,674 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.show_event_analysis_dialog | def show_event_analysis_dialog(self):
"""Create the event analysis dialog."""
self.event_analysis_dialog.update_types()
self.event_analysis_dialog.update_groups()
self.event_analysis_dialog.update_cycles()
self.event_analysis_dialog.show() | python | def show_event_analysis_dialog(self):
"""Create the event analysis dialog."""
self.event_analysis_dialog.update_types()
self.event_analysis_dialog.update_groups()
self.event_analysis_dialog.update_cycles()
self.event_analysis_dialog.show() | [
"def",
"show_event_analysis_dialog",
"(",
"self",
")",
":",
"self",
".",
"event_analysis_dialog",
".",
"update_types",
"(",
")",
"self",
".",
"event_analysis_dialog",
".",
"update_groups",
"(",
")",
"self",
".",
"event_analysis_dialog",
".",
"update_cycles",
"(",
... | Create the event analysis dialog. | [
"Create",
"the",
"event",
"analysis",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L192-L197 | train | 23,675 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.show_analysis_dialog | def show_analysis_dialog(self):
"""Create the analysis dialog."""
self.analysis_dialog.update_evt_types()
self.analysis_dialog.update_groups()
self.analysis_dialog.update_cycles()
self.analysis_dialog.show() | python | def show_analysis_dialog(self):
"""Create the analysis dialog."""
self.analysis_dialog.update_evt_types()
self.analysis_dialog.update_groups()
self.analysis_dialog.update_cycles()
self.analysis_dialog.show() | [
"def",
"show_analysis_dialog",
"(",
"self",
")",
":",
"self",
".",
"analysis_dialog",
".",
"update_evt_types",
"(",
")",
"self",
".",
"analysis_dialog",
".",
"update_groups",
"(",
")",
"self",
".",
"analysis_dialog",
".",
"update_cycles",
"(",
")",
"self",
"."... | Create the analysis dialog. | [
"Create",
"the",
"analysis",
"dialog",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L199-L204 | train | 23,676 |
wonambi-python/wonambi | wonambi/scroll_data.py | MainWindow.closeEvent | def closeEvent(self, event):
"""save the name of the last open dataset."""
max_dataset_history = self.value('max_dataset_history')
keep_recent_datasets(max_dataset_history, self.info)
settings.setValue('window/geometry', self.saveGeometry())
settings.setValue('window/state', self.saveState())
event.accept() | python | def closeEvent(self, event):
"""save the name of the last open dataset."""
max_dataset_history = self.value('max_dataset_history')
keep_recent_datasets(max_dataset_history, self.info)
settings.setValue('window/geometry', self.saveGeometry())
settings.setValue('window/state', self.saveState())
event.accept() | [
"def",
"closeEvent",
"(",
"self",
",",
"event",
")",
":",
"max_dataset_history",
"=",
"self",
".",
"value",
"(",
"'max_dataset_history'",
")",
"keep_recent_datasets",
"(",
"max_dataset_history",
",",
"self",
".",
"info",
")",
"settings",
".",
"setValue",
"(",
... | save the name of the last open dataset. | [
"save",
"the",
"name",
"of",
"the",
"last",
"open",
"dataset",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/scroll_data.py#L243-L251 | train | 23,677 |
wonambi-python/wonambi | wonambi/ioeeg/bci2000.py | _read_header | def _read_header(filename):
"""It's a pain to parse the header. It might be better to use the cpp code
but I would need to include it here.
"""
header = _read_header_text(filename)
first_row = header[0]
EXTRA_ROWS = 3 # drop DefaultValue1 LowRange1 HighRange1
hdr = {}
for group in finditer('(\w*)= ([\w.]*)', first_row):
hdr[group.group(1)] = group.group(2)
if first_row.startswith('BCI2000V'):
VERSION = hdr['BCI2000V']
else:
VERSION = '1'
hdr['DataFormat'] = 'int16'
for row in header[1:]:
if row.startswith('['): # remove '[ ... Definition ]'
section = row[2:-14].replace(' ', '')
if section == 'StateVector':
hdr[section] = []
else:
hdr[section] = {} # defaultdict(dict)
continue
if row == '':
continue
elif section == 'StateVector':
statevector = {key: value for key, value in list(zip(STATEVECTOR, row.split(' ')))}
hdr[section].append(statevector)
else:
group = match('(?P<subsection>[\w:%]*) (?P<format>\w*) (?P<key>\w*)= (?P<value>.*) // ', row)
onerow = group.groupdict()
values = onerow['value'].split(' ')
if len(values) > EXTRA_ROWS:
value = ' '.join(onerow['value'].split(' ')[:-EXTRA_ROWS])
else:
value = ' '.join(values)
hdr[section][onerow['key']] = value # similar to matlab's output
return hdr | python | def _read_header(filename):
"""It's a pain to parse the header. It might be better to use the cpp code
but I would need to include it here.
"""
header = _read_header_text(filename)
first_row = header[0]
EXTRA_ROWS = 3 # drop DefaultValue1 LowRange1 HighRange1
hdr = {}
for group in finditer('(\w*)= ([\w.]*)', first_row):
hdr[group.group(1)] = group.group(2)
if first_row.startswith('BCI2000V'):
VERSION = hdr['BCI2000V']
else:
VERSION = '1'
hdr['DataFormat'] = 'int16'
for row in header[1:]:
if row.startswith('['): # remove '[ ... Definition ]'
section = row[2:-14].replace(' ', '')
if section == 'StateVector':
hdr[section] = []
else:
hdr[section] = {} # defaultdict(dict)
continue
if row == '':
continue
elif section == 'StateVector':
statevector = {key: value for key, value in list(zip(STATEVECTOR, row.split(' ')))}
hdr[section].append(statevector)
else:
group = match('(?P<subsection>[\w:%]*) (?P<format>\w*) (?P<key>\w*)= (?P<value>.*) // ', row)
onerow = group.groupdict()
values = onerow['value'].split(' ')
if len(values) > EXTRA_ROWS:
value = ' '.join(onerow['value'].split(' ')[:-EXTRA_ROWS])
else:
value = ' '.join(values)
hdr[section][onerow['key']] = value # similar to matlab's output
return hdr | [
"def",
"_read_header",
"(",
"filename",
")",
":",
"header",
"=",
"_read_header_text",
"(",
"filename",
")",
"first_row",
"=",
"header",
"[",
"0",
"]",
"EXTRA_ROWS",
"=",
"3",
"# drop DefaultValue1 LowRange1 HighRange1",
"hdr",
"=",
"{",
"}",
"for",
"group",
"i... | It's a pain to parse the header. It might be better to use the cpp code
but I would need to include it here. | [
"It",
"s",
"a",
"pain",
"to",
"parse",
"the",
"header",
".",
"It",
"might",
"be",
"better",
"to",
"use",
"the",
"cpp",
"code",
"but",
"I",
"would",
"need",
"to",
"include",
"it",
"here",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/ioeeg/bci2000.py#L212-L260 | train | 23,678 |
wonambi-python/wonambi | wonambi/trans/reject.py | remove_artf_evts | def remove_artf_evts(times, annot, chan=None, min_dur=0.1):
"""Correct times to remove events marked 'Artefact'.
Parameters
----------
times : list of tuple of float
the start and end times of each segment
annot : instance of Annotations
the annotation file containing events and epochs
chan : str, optional
full name of channel on which artefacts were marked. Channel format is
'chan_name (group_name)'. If None, artefacts from any channel will be
removed.
min_dur : float
resulting segments, after concatenation, are rejected if shorter than
this duration
Returns
-------
list of tuple of float
the new start and end times of each segment, with artefact periods
taken out
"""
new_times = times
beg = times[0][0]
end = times[-1][-1]
chan = (chan, '') if chan else None # '' is for channel-global artefacts
artefact = annot.get_events(name='Artefact', time=(beg, end), chan=chan,
qual='Good')
if artefact:
new_times = []
for seg in times:
reject = False
new_seg = True
while new_seg is not False:
if type(new_seg) is tuple:
seg = new_seg
end = seg[1]
for artf in artefact:
if artf['start'] <= seg[0] and seg[1] <= artf['end']:
reject = True
new_seg = False
break
a_starts_in_s = seg[0] <= artf['start'] <= seg[1]
a_ends_in_s = seg[0] <= artf['end'] <= seg[1]
if a_ends_in_s and not a_starts_in_s:
seg = artf['end'], seg[1]
elif a_starts_in_s:
seg = seg[0], artf['start']
if a_ends_in_s:
new_seg = artf['end'], end
else:
new_seg = False
break
new_seg = False
if reject is False and seg[1] - seg[0] >= min_dur:
new_times.append(seg)
return new_times | python | def remove_artf_evts(times, annot, chan=None, min_dur=0.1):
"""Correct times to remove events marked 'Artefact'.
Parameters
----------
times : list of tuple of float
the start and end times of each segment
annot : instance of Annotations
the annotation file containing events and epochs
chan : str, optional
full name of channel on which artefacts were marked. Channel format is
'chan_name (group_name)'. If None, artefacts from any channel will be
removed.
min_dur : float
resulting segments, after concatenation, are rejected if shorter than
this duration
Returns
-------
list of tuple of float
the new start and end times of each segment, with artefact periods
taken out
"""
new_times = times
beg = times[0][0]
end = times[-1][-1]
chan = (chan, '') if chan else None # '' is for channel-global artefacts
artefact = annot.get_events(name='Artefact', time=(beg, end), chan=chan,
qual='Good')
if artefact:
new_times = []
for seg in times:
reject = False
new_seg = True
while new_seg is not False:
if type(new_seg) is tuple:
seg = new_seg
end = seg[1]
for artf in artefact:
if artf['start'] <= seg[0] and seg[1] <= artf['end']:
reject = True
new_seg = False
break
a_starts_in_s = seg[0] <= artf['start'] <= seg[1]
a_ends_in_s = seg[0] <= artf['end'] <= seg[1]
if a_ends_in_s and not a_starts_in_s:
seg = artf['end'], seg[1]
elif a_starts_in_s:
seg = seg[0], artf['start']
if a_ends_in_s:
new_seg = artf['end'], end
else:
new_seg = False
break
new_seg = False
if reject is False and seg[1] - seg[0] >= min_dur:
new_times.append(seg)
return new_times | [
"def",
"remove_artf_evts",
"(",
"times",
",",
"annot",
",",
"chan",
"=",
"None",
",",
"min_dur",
"=",
"0.1",
")",
":",
"new_times",
"=",
"times",
"beg",
"=",
"times",
"[",
"0",
"]",
"[",
"0",
"]",
"end",
"=",
"times",
"[",
"-",
"1",
"]",
"[",
"... | Correct times to remove events marked 'Artefact'.
Parameters
----------
times : list of tuple of float
the start and end times of each segment
annot : instance of Annotations
the annotation file containing events and epochs
chan : str, optional
full name of channel on which artefacts were marked. Channel format is
'chan_name (group_name)'. If None, artefacts from any channel will be
removed.
min_dur : float
resulting segments, after concatenation, are rejected if shorter than
this duration
Returns
-------
list of tuple of float
the new start and end times of each segment, with artefact periods
taken out | [
"Correct",
"times",
"to",
"remove",
"events",
"marked",
"Artefact",
"."
] | 1d8e3d7e53df8017c199f703bcab582914676e76 | https://github.com/wonambi-python/wonambi/blob/1d8e3d7e53df8017c199f703bcab582914676e76/wonambi/trans/reject.py#L13-L83 | train | 23,679 |
SuLab/WikidataIntegrator | wikidataintegrator/wdi_core.py | WDBaseDataType.statement_ref_mode | def statement_ref_mode(self, value):
"""Set the reference mode for a statement, always overrides the global reference state."""
valid_values = ['STRICT_KEEP', 'STRICT_KEEP_APPEND', 'STRICT_OVERWRITE', 'KEEP_GOOD', 'CUSTOM']
if value not in valid_values:
raise ValueError('Not an allowed reference mode, allowed values {}'.format(' '.join(valid_values)))
self._statement_ref_mode = value | python | def statement_ref_mode(self, value):
"""Set the reference mode for a statement, always overrides the global reference state."""
valid_values = ['STRICT_KEEP', 'STRICT_KEEP_APPEND', 'STRICT_OVERWRITE', 'KEEP_GOOD', 'CUSTOM']
if value not in valid_values:
raise ValueError('Not an allowed reference mode, allowed values {}'.format(' '.join(valid_values)))
self._statement_ref_mode = value | [
"def",
"statement_ref_mode",
"(",
"self",
",",
"value",
")",
":",
"valid_values",
"=",
"[",
"'STRICT_KEEP'",
",",
"'STRICT_KEEP_APPEND'",
",",
"'STRICT_OVERWRITE'",
",",
"'KEEP_GOOD'",
",",
"'CUSTOM'",
"]",
"if",
"value",
"not",
"in",
"valid_values",
":",
"raise... | Set the reference mode for a statement, always overrides the global reference state. | [
"Set",
"the",
"reference",
"mode",
"for",
"a",
"statement",
"always",
"overrides",
"the",
"global",
"reference",
"state",
"."
] | 8ceb2ed1c08fec070ec9edfcf7db7b8691481b62 | https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_core.py#L1641-L1647 | train | 23,680 |
SuLab/WikidataIntegrator | wikidataintegrator/wdi_core.py | WDBaseDataType.equals | def equals(self, that, include_ref=False, fref=None):
"""
Tests for equality of two statements.
If comparing references, the order of the arguments matters!!!
self is the current statement, the next argument is the new statement.
Allows passing in a function to use to compare the references 'fref'. Default is equality.
fref accepts two arguments 'oldrefs' and 'newrefs', each of which are a list of references,
where each reference is a list of statements
"""
if not include_ref:
# return the result of WDBaseDataType.__eq__, which is testing for equality of value and qualifiers
return self == that
if include_ref and self != that:
return False
if include_ref and fref is None:
fref = WDBaseDataType.refs_equal
return fref(self, that) | python | def equals(self, that, include_ref=False, fref=None):
"""
Tests for equality of two statements.
If comparing references, the order of the arguments matters!!!
self is the current statement, the next argument is the new statement.
Allows passing in a function to use to compare the references 'fref'. Default is equality.
fref accepts two arguments 'oldrefs' and 'newrefs', each of which are a list of references,
where each reference is a list of statements
"""
if not include_ref:
# return the result of WDBaseDataType.__eq__, which is testing for equality of value and qualifiers
return self == that
if include_ref and self != that:
return False
if include_ref and fref is None:
fref = WDBaseDataType.refs_equal
return fref(self, that) | [
"def",
"equals",
"(",
"self",
",",
"that",
",",
"include_ref",
"=",
"False",
",",
"fref",
"=",
"None",
")",
":",
"if",
"not",
"include_ref",
":",
"# return the result of WDBaseDataType.__eq__, which is testing for equality of value and qualifiers",
"return",
"self",
"==... | Tests for equality of two statements.
If comparing references, the order of the arguments matters!!!
self is the current statement, the next argument is the new statement.
Allows passing in a function to use to compare the references 'fref'. Default is equality.
fref accepts two arguments 'oldrefs' and 'newrefs', each of which are a list of references,
where each reference is a list of statements | [
"Tests",
"for",
"equality",
"of",
"two",
"statements",
".",
"If",
"comparing",
"references",
"the",
"order",
"of",
"the",
"arguments",
"matters!!!",
"self",
"is",
"the",
"current",
"statement",
"the",
"next",
"argument",
"is",
"the",
"new",
"statement",
".",
... | 8ceb2ed1c08fec070ec9edfcf7db7b8691481b62 | https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_core.py#L1798-L1814 | train | 23,681 |
SuLab/WikidataIntegrator | wikidataintegrator/wdi_core.py | WDBaseDataType.refs_equal | def refs_equal(olditem, newitem):
"""
tests for exactly identical references
"""
oldrefs = olditem.references
newrefs = newitem.references
ref_equal = lambda oldref, newref: True if (len(oldref) == len(newref)) and all(
x in oldref for x in newref) else False
if len(oldrefs) == len(newrefs) and all(
any(ref_equal(oldref, newref) for oldref in oldrefs) for newref in newrefs):
return True
else:
return False | python | def refs_equal(olditem, newitem):
"""
tests for exactly identical references
"""
oldrefs = olditem.references
newrefs = newitem.references
ref_equal = lambda oldref, newref: True if (len(oldref) == len(newref)) and all(
x in oldref for x in newref) else False
if len(oldrefs) == len(newrefs) and all(
any(ref_equal(oldref, newref) for oldref in oldrefs) for newref in newrefs):
return True
else:
return False | [
"def",
"refs_equal",
"(",
"olditem",
",",
"newitem",
")",
":",
"oldrefs",
"=",
"olditem",
".",
"references",
"newrefs",
"=",
"newitem",
".",
"references",
"ref_equal",
"=",
"lambda",
"oldref",
",",
"newref",
":",
"True",
"if",
"(",
"len",
"(",
"oldref",
... | tests for exactly identical references | [
"tests",
"for",
"exactly",
"identical",
"references"
] | 8ceb2ed1c08fec070ec9edfcf7db7b8691481b62 | https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_core.py#L1817-L1830 | train | 23,682 |
SuLab/WikidataIntegrator | wikidataintegrator/wdi_helpers/__init__.py | try_write | def try_write(wd_item, record_id, record_prop, login, edit_summary='', write=True):
"""
Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An external identifier, to be used for logging
:type record_id: str
:param record_prop: Property of the external identifier
:type record_prop: str
:param login: PBB_core login instance
:type login: PBB_login.WDLogin
:param edit_summary: passed directly to wd_item.write
:type edit_summary: str
:param write: If `False`, do not actually perform write. Action will be logged as if write had occured
:type write: bool
:return: True if write did not throw an exception, returns the exception otherwise
"""
if wd_item.require_write:
if wd_item.create_new_item:
msg = "CREATE"
else:
msg = "UPDATE"
else:
msg = "SKIP"
try:
if write:
wd_item.write(login=login, edit_summary=edit_summary)
wdi_core.WDItemEngine.log("INFO", format_msg(record_id, record_prop, wd_item.wd_item_id, msg) + ";" + str(
wd_item.lastrevid))
except wdi_core.WDApiError as e:
print(e)
wdi_core.WDItemEngine.log("ERROR",
format_msg(record_id, record_prop, wd_item.wd_item_id, json.dumps(e.wd_error_msg),
type(e)))
return e
except Exception as e:
print(e)
wdi_core.WDItemEngine.log("ERROR", format_msg(record_id, record_prop, wd_item.wd_item_id, str(e), type(e)))
return e
return True | python | def try_write(wd_item, record_id, record_prop, login, edit_summary='', write=True):
"""
Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An external identifier, to be used for logging
:type record_id: str
:param record_prop: Property of the external identifier
:type record_prop: str
:param login: PBB_core login instance
:type login: PBB_login.WDLogin
:param edit_summary: passed directly to wd_item.write
:type edit_summary: str
:param write: If `False`, do not actually perform write. Action will be logged as if write had occured
:type write: bool
:return: True if write did not throw an exception, returns the exception otherwise
"""
if wd_item.require_write:
if wd_item.create_new_item:
msg = "CREATE"
else:
msg = "UPDATE"
else:
msg = "SKIP"
try:
if write:
wd_item.write(login=login, edit_summary=edit_summary)
wdi_core.WDItemEngine.log("INFO", format_msg(record_id, record_prop, wd_item.wd_item_id, msg) + ";" + str(
wd_item.lastrevid))
except wdi_core.WDApiError as e:
print(e)
wdi_core.WDItemEngine.log("ERROR",
format_msg(record_id, record_prop, wd_item.wd_item_id, json.dumps(e.wd_error_msg),
type(e)))
return e
except Exception as e:
print(e)
wdi_core.WDItemEngine.log("ERROR", format_msg(record_id, record_prop, wd_item.wd_item_id, str(e), type(e)))
return e
return True | [
"def",
"try_write",
"(",
"wd_item",
",",
"record_id",
",",
"record_prop",
",",
"login",
",",
"edit_summary",
"=",
"''",
",",
"write",
"=",
"True",
")",
":",
"if",
"wd_item",
".",
"require_write",
":",
"if",
"wd_item",
".",
"create_new_item",
":",
"msg",
... | Write a PBB_core item. Log if item was created, updated, or skipped.
Catch and log all errors.
:param wd_item: A wikidata item that will be written
:type wd_item: PBB_Core.WDItemEngine
:param record_id: An external identifier, to be used for logging
:type record_id: str
:param record_prop: Property of the external identifier
:type record_prop: str
:param login: PBB_core login instance
:type login: PBB_login.WDLogin
:param edit_summary: passed directly to wd_item.write
:type edit_summary: str
:param write: If `False`, do not actually perform write. Action will be logged as if write had occured
:type write: bool
:return: True if write did not throw an exception, returns the exception otherwise | [
"Write",
"a",
"PBB_core",
"item",
".",
"Log",
"if",
"item",
"was",
"created",
"updated",
"or",
"skipped",
".",
"Catch",
"and",
"log",
"all",
"errors",
"."
] | 8ceb2ed1c08fec070ec9edfcf7db7b8691481b62 | https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_helpers/__init__.py#L58-L101 | train | 23,683 |
maykinmedia/django-admin-index | django_admin_index/compat/django18.py | _build_app_dict | def _build_app_dict(site, request, label=None):
"""
Builds the app dictionary. Takes an optional label parameters to filter
models of a specific app.
"""
app_dict = {}
if label:
models = {
m: m_a for m, m_a in site._registry.items()
if m._meta.app_label == label
}
else:
models = site._registry
for model, model_admin in models.items():
app_label = model._meta.app_label
has_module_perms = model_admin.has_module_permission(request)
if not has_module_perms:
continue
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True not in perms.values():
continue
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change'):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=site.name)
except NoReverseMatch:
pass
if perms.get('add'):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=site.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': apps.get_app_config(app_label).verbose_name,
'app_label': app_label,
'app_url': reverse(
'admin:app_list',
kwargs={'app_label': app_label},
current_app=site.name,
),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if label:
return app_dict.get(label)
return app_dict | python | def _build_app_dict(site, request, label=None):
"""
Builds the app dictionary. Takes an optional label parameters to filter
models of a specific app.
"""
app_dict = {}
if label:
models = {
m: m_a for m, m_a in site._registry.items()
if m._meta.app_label == label
}
else:
models = site._registry
for model, model_admin in models.items():
app_label = model._meta.app_label
has_module_perms = model_admin.has_module_permission(request)
if not has_module_perms:
continue
perms = model_admin.get_model_perms(request)
# Check whether user has any perm for this module.
# If so, add the module to the model_list.
if True not in perms.values():
continue
info = (app_label, model._meta.model_name)
model_dict = {
'name': capfirst(model._meta.verbose_name_plural),
'object_name': model._meta.object_name,
'perms': perms,
}
if perms.get('change'):
try:
model_dict['admin_url'] = reverse('admin:%s_%s_changelist' % info, current_app=site.name)
except NoReverseMatch:
pass
if perms.get('add'):
try:
model_dict['add_url'] = reverse('admin:%s_%s_add' % info, current_app=site.name)
except NoReverseMatch:
pass
if app_label in app_dict:
app_dict[app_label]['models'].append(model_dict)
else:
app_dict[app_label] = {
'name': apps.get_app_config(app_label).verbose_name,
'app_label': app_label,
'app_url': reverse(
'admin:app_list',
kwargs={'app_label': app_label},
current_app=site.name,
),
'has_module_perms': has_module_perms,
'models': [model_dict],
}
if label:
return app_dict.get(label)
return app_dict | [
"def",
"_build_app_dict",
"(",
"site",
",",
"request",
",",
"label",
"=",
"None",
")",
":",
"app_dict",
"=",
"{",
"}",
"if",
"label",
":",
"models",
"=",
"{",
"m",
":",
"m_a",
"for",
"m",
",",
"m_a",
"in",
"site",
".",
"_registry",
".",
"items",
... | Builds the app dictionary. Takes an optional label parameters to filter
models of a specific app. | [
"Builds",
"the",
"app",
"dictionary",
".",
"Takes",
"an",
"optional",
"label",
"parameters",
"to",
"filter",
"models",
"of",
"a",
"specific",
"app",
"."
] | 5bfd90e6945775865d722e0f5058824769f68f04 | https://github.com/maykinmedia/django-admin-index/blob/5bfd90e6945775865d722e0f5058824769f68f04/django_admin_index/compat/django18.py#L13-L76 | train | 23,684 |
maykinmedia/django-admin-index | django_admin_index/compat/django18.py | get_app_list | def get_app_list(site, request):
"""
Returns a sorted list of all the installed apps that have been
registered in this site.
"""
app_dict = _build_app_dict(site, request)
# Sort the apps alphabetically.
app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
return app_list | python | def get_app_list(site, request):
"""
Returns a sorted list of all the installed apps that have been
registered in this site.
"""
app_dict = _build_app_dict(site, request)
# Sort the apps alphabetically.
app_list = sorted(app_dict.values(), key=lambda x: x['name'].lower())
# Sort the models alphabetically within each app.
for app in app_list:
app['models'].sort(key=lambda x: x['name'])
return app_list | [
"def",
"get_app_list",
"(",
"site",
",",
"request",
")",
":",
"app_dict",
"=",
"_build_app_dict",
"(",
"site",
",",
"request",
")",
"# Sort the apps alphabetically.",
"app_list",
"=",
"sorted",
"(",
"app_dict",
".",
"values",
"(",
")",
",",
"key",
"=",
"lamb... | Returns a sorted list of all the installed apps that have been
registered in this site. | [
"Returns",
"a",
"sorted",
"list",
"of",
"all",
"the",
"installed",
"apps",
"that",
"have",
"been",
"registered",
"in",
"this",
"site",
"."
] | 5bfd90e6945775865d722e0f5058824769f68f04 | https://github.com/maykinmedia/django-admin-index/blob/5bfd90e6945775865d722e0f5058824769f68f04/django_admin_index/compat/django18.py#L79-L93 | train | 23,685 |
SuLab/WikidataIntegrator | wikidataintegrator/wdi_fastrun.py | FastRunContainer.format_query_results | def format_query_results(self, r, prop_nr):
"""
`r` is the results of the sparql query in _query_data and is modified in place
`prop_nr` is needed to get the property datatype to determine how to format the value
`r` is a list of dicts. The keys are:
item: the subject. the item this statement is on
v: the object. The value for this statement
sid: statement ID
pq: qualifier property
qval: qualifier value
ref: reference ID
pr: reference property
rval: reference value
"""
prop_dt = self.get_prop_datatype(prop_nr)
for i in r:
for value in {'item', 'sid', 'pq', 'pr', 'ref'}:
if value in i:
# these are always URIs for the local wikibase
i[value] = i[value]['value'].split('/')[-1]
# make sure datetimes are formatted correctly.
# the correct format is '+%Y-%m-%dT%H:%M:%SZ', but is sometimes missing the plus??
# some difference between RDF and xsd:dateTime that I don't understand
for value in {'v', 'qval', 'rval'}:
if value in i:
if i[value].get("datatype") == 'http://www.w3.org/2001/XMLSchema#dateTime' and not \
i[value]['value'][0] in '+-':
# if it is a dateTime and doesn't start with plus or minus, add a plus
i[value]['value'] = '+' + i[value]['value']
# these three ({'v', 'qval', 'rval'}) are values that can be any data type
# strip off the URI if they are wikibase-items
if 'v' in i:
if i['v']['type'] == 'uri' and prop_dt == 'wikibase-item':
i['v'] = i['v']['value'].split('/')[-1]
else:
i['v'] = i['v']['value']
# Note: no-value and some-value don't actually show up in the results here
# see for example: select * where { wd:Q7207 p:P40 ?c . ?c ?d ?e }
if type(i['v']) is not dict:
self.rev_lookup[i['v']].add(i['item'])
# handle qualifier value
if 'qval' in i:
qual_prop_dt = self.get_prop_datatype(prop_nr=i['pq'])
if i['qval']['type'] == 'uri' and qual_prop_dt == 'wikibase-item':
i['qval'] = i['qval']['value'].split('/')[-1]
else:
i['qval'] = i['qval']['value']
# handle reference value
if 'rval' in i:
ref_prop_dt = self.get_prop_datatype(prop_nr=i['pr'])
if i['rval']['type'] == 'uri' and ref_prop_dt == 'wikibase-item':
i['rval'] = i['rval']['value'].split('/')[-1]
else:
i['rval'] = i['rval']['value'] | python | def format_query_results(self, r, prop_nr):
"""
`r` is the results of the sparql query in _query_data and is modified in place
`prop_nr` is needed to get the property datatype to determine how to format the value
`r` is a list of dicts. The keys are:
item: the subject. the item this statement is on
v: the object. The value for this statement
sid: statement ID
pq: qualifier property
qval: qualifier value
ref: reference ID
pr: reference property
rval: reference value
"""
prop_dt = self.get_prop_datatype(prop_nr)
for i in r:
for value in {'item', 'sid', 'pq', 'pr', 'ref'}:
if value in i:
# these are always URIs for the local wikibase
i[value] = i[value]['value'].split('/')[-1]
# make sure datetimes are formatted correctly.
# the correct format is '+%Y-%m-%dT%H:%M:%SZ', but is sometimes missing the plus??
# some difference between RDF and xsd:dateTime that I don't understand
for value in {'v', 'qval', 'rval'}:
if value in i:
if i[value].get("datatype") == 'http://www.w3.org/2001/XMLSchema#dateTime' and not \
i[value]['value'][0] in '+-':
# if it is a dateTime and doesn't start with plus or minus, add a plus
i[value]['value'] = '+' + i[value]['value']
# these three ({'v', 'qval', 'rval'}) are values that can be any data type
# strip off the URI if they are wikibase-items
if 'v' in i:
if i['v']['type'] == 'uri' and prop_dt == 'wikibase-item':
i['v'] = i['v']['value'].split('/')[-1]
else:
i['v'] = i['v']['value']
# Note: no-value and some-value don't actually show up in the results here
# see for example: select * where { wd:Q7207 p:P40 ?c . ?c ?d ?e }
if type(i['v']) is not dict:
self.rev_lookup[i['v']].add(i['item'])
# handle qualifier value
if 'qval' in i:
qual_prop_dt = self.get_prop_datatype(prop_nr=i['pq'])
if i['qval']['type'] == 'uri' and qual_prop_dt == 'wikibase-item':
i['qval'] = i['qval']['value'].split('/')[-1]
else:
i['qval'] = i['qval']['value']
# handle reference value
if 'rval' in i:
ref_prop_dt = self.get_prop_datatype(prop_nr=i['pr'])
if i['rval']['type'] == 'uri' and ref_prop_dt == 'wikibase-item':
i['rval'] = i['rval']['value'].split('/')[-1]
else:
i['rval'] = i['rval']['value'] | [
"def",
"format_query_results",
"(",
"self",
",",
"r",
",",
"prop_nr",
")",
":",
"prop_dt",
"=",
"self",
".",
"get_prop_datatype",
"(",
"prop_nr",
")",
"for",
"i",
"in",
"r",
":",
"for",
"value",
"in",
"{",
"'item'",
",",
"'sid'",
",",
"'pq'",
",",
"'... | `r` is the results of the sparql query in _query_data and is modified in place
`prop_nr` is needed to get the property datatype to determine how to format the value
`r` is a list of dicts. The keys are:
item: the subject. the item this statement is on
v: the object. The value for this statement
sid: statement ID
pq: qualifier property
qval: qualifier value
ref: reference ID
pr: reference property
rval: reference value | [
"r",
"is",
"the",
"results",
"of",
"the",
"sparql",
"query",
"in",
"_query_data",
"and",
"is",
"modified",
"in",
"place",
"prop_nr",
"is",
"needed",
"to",
"get",
"the",
"property",
"datatype",
"to",
"determine",
"how",
"to",
"format",
"the",
"value"
] | 8ceb2ed1c08fec070ec9edfcf7db7b8691481b62 | https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_fastrun.py#L299-L358 | train | 23,686 |
SuLab/WikidataIntegrator | wikidataintegrator/wdi_fastrun.py | FastRunContainer.clear | def clear(self):
"""
convinience function to empty this fastrun container
"""
self.prop_dt_map = dict()
self.prop_data = dict()
self.rev_lookup = defaultdict(set) | python | def clear(self):
"""
convinience function to empty this fastrun container
"""
self.prop_dt_map = dict()
self.prop_data = dict()
self.rev_lookup = defaultdict(set) | [
"def",
"clear",
"(",
"self",
")",
":",
"self",
".",
"prop_dt_map",
"=",
"dict",
"(",
")",
"self",
".",
"prop_data",
"=",
"dict",
"(",
")",
"self",
".",
"rev_lookup",
"=",
"defaultdict",
"(",
"set",
")"
] | convinience function to empty this fastrun container | [
"convinience",
"function",
"to",
"empty",
"this",
"fastrun",
"container"
] | 8ceb2ed1c08fec070ec9edfcf7db7b8691481b62 | https://github.com/SuLab/WikidataIntegrator/blob/8ceb2ed1c08fec070ec9edfcf7db7b8691481b62/wikidataintegrator/wdi_fastrun.py#L504-L510 | train | 23,687 |
sighingnow/parsec.py | src/parsec/__init__.py | times | def times(p, mint, maxt=None):
'''Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN.
Return a list of values.'''
maxt = maxt if maxt else mint
@Parser
def times_parser(text, index):
cnt, values, res = 0, Value.success(index, []), None
while cnt < maxt:
res = p(text, index)
if res.status:
values = values.aggregate(
Value.success(res.index, [res.value]))
index, cnt = res.index, cnt + 1
else:
if cnt >= mint:
break
else:
return res # failed, throw exception.
if cnt >= maxt: # finish.
break
# If we don't have any remaining text to start next loop, we need break.
#
# We cannot put the `index < len(text)` in where because some parser can
# success even when we have no any text. We also need to detect if the
# parser consume no text.
#
# See: #28
if index >= len(text):
if cnt >= mint:
break # we already have decent result to return
else:
r = p(text, index)
if index != r.index: # report error when the parser cannot success with no text
return Value.failure(index, "already meets the end, no enough text")
return values
return times_parser | python | def times(p, mint, maxt=None):
'''Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN.
Return a list of values.'''
maxt = maxt if maxt else mint
@Parser
def times_parser(text, index):
cnt, values, res = 0, Value.success(index, []), None
while cnt < maxt:
res = p(text, index)
if res.status:
values = values.aggregate(
Value.success(res.index, [res.value]))
index, cnt = res.index, cnt + 1
else:
if cnt >= mint:
break
else:
return res # failed, throw exception.
if cnt >= maxt: # finish.
break
# If we don't have any remaining text to start next loop, we need break.
#
# We cannot put the `index < len(text)` in where because some parser can
# success even when we have no any text. We also need to detect if the
# parser consume no text.
#
# See: #28
if index >= len(text):
if cnt >= mint:
break # we already have decent result to return
else:
r = p(text, index)
if index != r.index: # report error when the parser cannot success with no text
return Value.failure(index, "already meets the end, no enough text")
return values
return times_parser | [
"def",
"times",
"(",
"p",
",",
"mint",
",",
"maxt",
"=",
"None",
")",
":",
"maxt",
"=",
"maxt",
"if",
"maxt",
"else",
"mint",
"@",
"Parser",
"def",
"times_parser",
"(",
"text",
",",
"index",
")",
":",
"cnt",
",",
"values",
",",
"res",
"=",
"0",
... | Repeat a parser between `mint` and `maxt` times. DO AS MUCH MATCH AS IT CAN.
Return a list of values. | [
"Repeat",
"a",
"parser",
"between",
"mint",
"and",
"maxt",
"times",
".",
"DO",
"AS",
"MUCH",
"MATCH",
"AS",
"IT",
"CAN",
".",
"Return",
"a",
"list",
"of",
"values",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L405-L441 | train | 23,688 |
sighingnow/parsec.py | src/parsec/__init__.py | optional | def optional(p, default_value=None):
'''`Make a parser as optional. If success, return the result, otherwise return
default_value silently, without raising any exception. If default_value is not
provided None is returned instead.
'''
@Parser
def optional_parser(text, index):
res = p(text, index)
if res.status:
return Value.success(res.index, res.value)
else:
# Return the maybe existing default value without doing anything.
return Value.success(res.index, default_value)
return optional_parser | python | def optional(p, default_value=None):
'''`Make a parser as optional. If success, return the result, otherwise return
default_value silently, without raising any exception. If default_value is not
provided None is returned instead.
'''
@Parser
def optional_parser(text, index):
res = p(text, index)
if res.status:
return Value.success(res.index, res.value)
else:
# Return the maybe existing default value without doing anything.
return Value.success(res.index, default_value)
return optional_parser | [
"def",
"optional",
"(",
"p",
",",
"default_value",
"=",
"None",
")",
":",
"@",
"Parser",
"def",
"optional_parser",
"(",
"text",
",",
"index",
")",
":",
"res",
"=",
"p",
"(",
"text",
",",
"index",
")",
"if",
"res",
".",
"status",
":",
"return",
"Val... | `Make a parser as optional. If success, return the result, otherwise return
default_value silently, without raising any exception. If default_value is not
provided None is returned instead. | [
"Make",
"a",
"parser",
"as",
"optional",
".",
"If",
"success",
"return",
"the",
"result",
"otherwise",
"return",
"default_value",
"silently",
"without",
"raising",
"any",
"exception",
".",
"If",
"default_value",
"is",
"not",
"provided",
"None",
"is",
"returned",... | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L450-L463 | train | 23,689 |
sighingnow/parsec.py | src/parsec/__init__.py | separated | def separated(p, sep, mint, maxt=None, end=None):
'''Repeat a parser `p` separated by `s` between `mint` and `maxt` times.
When `end` is None, a trailing separator is optional.
When `end` is True, a trailing separator is required.
When `end` is False, a trailing separator is not allowed.
MATCHES AS MUCH AS POSSIBLE.
Return list of values returned by `p`.'''
maxt = maxt if maxt else mint
@Parser
def sep_parser(text, index):
cnt, values, res = 0, Value.success(index, []), None
while cnt < maxt:
if end in [False, None] and cnt > 0:
res = sep(text, index)
if res.status: # `sep` found, consume it (advance index)
index, values = res.index, Value.success(
res.index, values.value)
elif cnt < mint:
return res # error: need more elemnts, but no `sep` found.
else:
break
res = p(text, index)
if res.status:
values = values.aggregate(
Value.success(res.index, [res.value]))
index, cnt = res.index, cnt + 1
elif cnt >= mint:
break
else:
return res # error: need more elements, but no `p` found.
if end is True:
res = sep(text, index)
if res.status:
index, values = res.index, Value.success(
res.index, values.value)
else:
return res # error: trailing `sep` not found
if cnt >= maxt:
break
return values
return sep_parser | python | def separated(p, sep, mint, maxt=None, end=None):
'''Repeat a parser `p` separated by `s` between `mint` and `maxt` times.
When `end` is None, a trailing separator is optional.
When `end` is True, a trailing separator is required.
When `end` is False, a trailing separator is not allowed.
MATCHES AS MUCH AS POSSIBLE.
Return list of values returned by `p`.'''
maxt = maxt if maxt else mint
@Parser
def sep_parser(text, index):
cnt, values, res = 0, Value.success(index, []), None
while cnt < maxt:
if end in [False, None] and cnt > 0:
res = sep(text, index)
if res.status: # `sep` found, consume it (advance index)
index, values = res.index, Value.success(
res.index, values.value)
elif cnt < mint:
return res # error: need more elemnts, but no `sep` found.
else:
break
res = p(text, index)
if res.status:
values = values.aggregate(
Value.success(res.index, [res.value]))
index, cnt = res.index, cnt + 1
elif cnt >= mint:
break
else:
return res # error: need more elements, but no `p` found.
if end is True:
res = sep(text, index)
if res.status:
index, values = res.index, Value.success(
res.index, values.value)
else:
return res # error: trailing `sep` not found
if cnt >= maxt:
break
return values
return sep_parser | [
"def",
"separated",
"(",
"p",
",",
"sep",
",",
"mint",
",",
"maxt",
"=",
"None",
",",
"end",
"=",
"None",
")",
":",
"maxt",
"=",
"maxt",
"if",
"maxt",
"else",
"mint",
"@",
"Parser",
"def",
"sep_parser",
"(",
"text",
",",
"index",
")",
":",
"cnt",... | Repeat a parser `p` separated by `s` between `mint` and `maxt` times.
When `end` is None, a trailing separator is optional.
When `end` is True, a trailing separator is required.
When `end` is False, a trailing separator is not allowed.
MATCHES AS MUCH AS POSSIBLE.
Return list of values returned by `p`. | [
"Repeat",
"a",
"parser",
"p",
"separated",
"by",
"s",
"between",
"mint",
"and",
"maxt",
"times",
".",
"When",
"end",
"is",
"None",
"a",
"trailing",
"separator",
"is",
"optional",
".",
"When",
"end",
"is",
"True",
"a",
"trailing",
"separator",
"is",
"requ... | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L478-L522 | train | 23,690 |
sighingnow/parsec.py | src/parsec/__init__.py | one_of | def one_of(s):
'''Parser a char from specified string.'''
@Parser
def one_of_parser(text, index=0):
if index < len(text) and text[index] in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'one of {}'.format(s))
return one_of_parser | python | def one_of(s):
'''Parser a char from specified string.'''
@Parser
def one_of_parser(text, index=0):
if index < len(text) and text[index] in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'one of {}'.format(s))
return one_of_parser | [
"def",
"one_of",
"(",
"s",
")",
":",
"@",
"Parser",
"def",
"one_of_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"if",
"index",
"<",
"len",
"(",
"text",
")",
"and",
"text",
"[",
"index",
"]",
"in",
"s",
":",
"return",
"Value",
".",
"s... | Parser a char from specified string. | [
"Parser",
"a",
"char",
"from",
"specified",
"string",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L567-L575 | train | 23,691 |
sighingnow/parsec.py | src/parsec/__init__.py | none_of | def none_of(s):
'''Parser a char NOT from specified string.'''
@Parser
def none_of_parser(text, index=0):
if index < len(text) and text[index] not in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'none of {}'.format(s))
return none_of_parser | python | def none_of(s):
'''Parser a char NOT from specified string.'''
@Parser
def none_of_parser(text, index=0):
if index < len(text) and text[index] not in s:
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'none of {}'.format(s))
return none_of_parser | [
"def",
"none_of",
"(",
"s",
")",
":",
"@",
"Parser",
"def",
"none_of_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"if",
"index",
"<",
"len",
"(",
"text",
")",
"and",
"text",
"[",
"index",
"]",
"not",
"in",
"s",
":",
"return",
"Value",
... | Parser a char NOT from specified string. | [
"Parser",
"a",
"char",
"NOT",
"from",
"specified",
"string",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L578-L586 | train | 23,692 |
sighingnow/parsec.py | src/parsec/__init__.py | space | def space():
'''Parser a whitespace character.'''
@Parser
def space_parser(text, index=0):
if index < len(text) and text[index].isspace():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'one space')
return space_parser | python | def space():
'''Parser a whitespace character.'''
@Parser
def space_parser(text, index=0):
if index < len(text) and text[index].isspace():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'one space')
return space_parser | [
"def",
"space",
"(",
")",
":",
"@",
"Parser",
"def",
"space_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"if",
"index",
"<",
"len",
"(",
"text",
")",
"and",
"text",
"[",
"index",
"]",
".",
"isspace",
"(",
")",
":",
"return",
"Value",
... | Parser a whitespace character. | [
"Parser",
"a",
"whitespace",
"character",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L589-L597 | train | 23,693 |
sighingnow/parsec.py | src/parsec/__init__.py | letter | def letter():
'''Parse a letter in alphabet.'''
@Parser
def letter_parser(text, index=0):
if index < len(text) and text[index].isalpha():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'a letter')
return letter_parser | python | def letter():
'''Parse a letter in alphabet.'''
@Parser
def letter_parser(text, index=0):
if index < len(text) and text[index].isalpha():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'a letter')
return letter_parser | [
"def",
"letter",
"(",
")",
":",
"@",
"Parser",
"def",
"letter_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"if",
"index",
"<",
"len",
"(",
"text",
")",
"and",
"text",
"[",
"index",
"]",
".",
"isalpha",
"(",
")",
":",
"return",
"Value",... | Parse a letter in alphabet. | [
"Parse",
"a",
"letter",
"in",
"alphabet",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L605-L613 | train | 23,694 |
sighingnow/parsec.py | src/parsec/__init__.py | digit | def digit():
'''Parse a digit character.'''
@Parser
def digit_parser(text, index=0):
if index < len(text) and text[index].isdigit():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'a digit')
return digit_parser | python | def digit():
'''Parse a digit character.'''
@Parser
def digit_parser(text, index=0):
if index < len(text) and text[index].isdigit():
return Value.success(index + 1, text[index])
else:
return Value.failure(index, 'a digit')
return digit_parser | [
"def",
"digit",
"(",
")",
":",
"@",
"Parser",
"def",
"digit_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"if",
"index",
"<",
"len",
"(",
"text",
")",
"and",
"text",
"[",
"index",
"]",
".",
"isdigit",
"(",
")",
":",
"return",
"Value",
... | Parse a digit character. | [
"Parse",
"a",
"digit",
"character",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L616-L624 | train | 23,695 |
sighingnow/parsec.py | src/parsec/__init__.py | eof | def eof():
'''Parser EOF flag of a string.'''
@Parser
def eof_parser(text, index=0):
if index >= len(text):
return Value.success(index, None)
else:
return Value.failure(index, 'EOF')
return eof_parser | python | def eof():
'''Parser EOF flag of a string.'''
@Parser
def eof_parser(text, index=0):
if index >= len(text):
return Value.success(index, None)
else:
return Value.failure(index, 'EOF')
return eof_parser | [
"def",
"eof",
"(",
")",
":",
"@",
"Parser",
"def",
"eof_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"if",
"index",
">=",
"len",
"(",
"text",
")",
":",
"return",
"Value",
".",
"success",
"(",
"index",
",",
"None",
")",
"else",
":",
"... | Parser EOF flag of a string. | [
"Parser",
"EOF",
"flag",
"of",
"a",
"string",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L627-L635 | train | 23,696 |
sighingnow/parsec.py | src/parsec/__init__.py | string | def string(s):
'''Parser a string.'''
@Parser
def string_parser(text, index=0):
slen, tlen = len(s), len(text)
if text[index:index + slen] == s:
return Value.success(index + slen, s)
else:
matched = 0
while matched < slen and index + matched < tlen and text[index + matched] == s[matched]:
matched = matched + 1
return Value.failure(index + matched, s)
return string_parser | python | def string(s):
'''Parser a string.'''
@Parser
def string_parser(text, index=0):
slen, tlen = len(s), len(text)
if text[index:index + slen] == s:
return Value.success(index + slen, s)
else:
matched = 0
while matched < slen and index + matched < tlen and text[index + matched] == s[matched]:
matched = matched + 1
return Value.failure(index + matched, s)
return string_parser | [
"def",
"string",
"(",
"s",
")",
":",
"@",
"Parser",
"def",
"string_parser",
"(",
"text",
",",
"index",
"=",
"0",
")",
":",
"slen",
",",
"tlen",
"=",
"len",
"(",
"s",
")",
",",
"len",
"(",
"text",
")",
"if",
"text",
"[",
"index",
":",
"index",
... | Parser a string. | [
"Parser",
"a",
"string",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L638-L650 | train | 23,697 |
sighingnow/parsec.py | src/parsec/__init__.py | ParseError.loc_info | def loc_info(text, index):
'''Location of `index` in source code `text`.'''
if index > len(text):
raise ValueError('Invalid index.')
line, last_ln = text.count('\n', 0, index), text.rfind('\n', 0, index)
col = index - (last_ln + 1)
return (line, col) | python | def loc_info(text, index):
'''Location of `index` in source code `text`.'''
if index > len(text):
raise ValueError('Invalid index.')
line, last_ln = text.count('\n', 0, index), text.rfind('\n', 0, index)
col = index - (last_ln + 1)
return (line, col) | [
"def",
"loc_info",
"(",
"text",
",",
"index",
")",
":",
"if",
"index",
">",
"len",
"(",
"text",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid index.'",
")",
"line",
",",
"last_ln",
"=",
"text",
".",
"count",
"(",
"'\\n'",
",",
"0",
",",
"index",
... | Location of `index` in source code `text`. | [
"Location",
"of",
"index",
"in",
"source",
"code",
"text",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L29-L35 | train | 23,698 |
sighingnow/parsec.py | src/parsec/__init__.py | ParseError.loc | def loc(self):
'''Locate the error position in the source code text.'''
try:
return '{}:{}'.format(*ParseError.loc_info(self.text, self.index))
except ValueError:
return '<out of bounds index {!r}>'.format(self.index) | python | def loc(self):
'''Locate the error position in the source code text.'''
try:
return '{}:{}'.format(*ParseError.loc_info(self.text, self.index))
except ValueError:
return '<out of bounds index {!r}>'.format(self.index) | [
"def",
"loc",
"(",
"self",
")",
":",
"try",
":",
"return",
"'{}:{}'",
".",
"format",
"(",
"*",
"ParseError",
".",
"loc_info",
"(",
"self",
".",
"text",
",",
"self",
".",
"index",
")",
")",
"except",
"ValueError",
":",
"return",
"'<out of bounds index {!r... | Locate the error position in the source code text. | [
"Locate",
"the",
"error",
"position",
"in",
"the",
"source",
"code",
"text",
"."
] | ed50e1e259142757470b925f8d20dfe5ad223af0 | https://github.com/sighingnow/parsec.py/blob/ed50e1e259142757470b925f8d20dfe5ad223af0/src/parsec/__init__.py#L37-L42 | train | 23,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.