code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
default_normcase = getattr(pattern, 'normcase', self.module.normcase) normcase = normcase or default_normcase name = normcase(self.name) pattern = normcase(pattern) return fnmatch.fnmatchcase(name, pattern)
def fnmatch(self, pattern, normcase=None)
Return ``True`` if `self.name` matches the given `pattern`. `pattern` - A filename pattern with wildcards, for example ``'*.py'``. If the pattern contains a `normcase` attribute, it is applied to the name and path prior to comparison. `normcase` - (optional) A function used to ...
3.060301
3.325897
0.920143
cls = self._next_class return [cls(s) for s in glob.glob(self / pattern)]
def glob(self, pattern)
Return a list of Path objects that match the pattern. `pattern` - a path relative to this directory, with wildcards. For example, ``Path('/users').glob('*/bin/*')`` returns a list of all the files users have in their :file:`bin` directories. .. seealso:: :func:`glob.glob` .. ...
9.422841
14.352796
0.656516
with self.open(*args, **kwargs) as f: for chunk in iter(lambda: f.read(size) or None, None): yield chunk
def chunks(self, size, *args, **kwargs)
Returns a generator yielding chunks of the file, so it can be read piece by piece with a simple for loop. Any argument you pass after `size` will be passed to :meth:`open`. :example: >>> hash = hashlib.md5() >>> for chunk in Path("CHANGES.rst").chunks(8...
3.096494
4.537555
0.682415
if append: mode = 'ab' else: mode = 'wb' with self.open(mode) as f: f.write(bytes)
def write_bytes(self, bytes, append=False)
Open this file and write the given bytes to it. Default behavior is to overwrite any existing file. Call ``p.write_bytes(bytes, append=True)`` to append instead.
2.378758
2.385145
0.997322
r with self.open(mode='r', encoding=encoding, errors=errors) as f: return U_NEWLINE.sub('\n', f.read())
def text(self, encoding=None, errors='strict')
r""" Open this file, read it in, return the content as a string. All newline sequences are converted to ``'\n'``. Keyword arguments will be passed to :meth:`open`. .. seealso:: :meth:`lines`
6.448951
8.945302
0.720932
r return self.text(encoding, errors).splitlines(retain)
def lines(self, encoding=None, errors='strict', retain=True)
r""" Open this file, read all lines, return them in a list. Optional arguments: `encoding` - The Unicode encoding (or character set) of the file. The default is ``None``, meaning the content of the file is read as 8-bit characters and returned as a l...
13.886086
21.870743
0.634916
r with self.open('ab' if append else 'wb') as f: for line in lines: isUnicode = isinstance(line, str) if linesep is not None: pattern = U_NL_END if isUnicode else NL_END line = pattern.sub('', line) + linesep ...
def write_lines(self, lines, encoding=None, errors='strict', linesep=os.linesep, append=False)
r""" Write the given lines of text to this file. By default this overwrites any existing file at this path. This puts a platform-specific newline sequence on every line. See `linesep` below. `lines` - A list of strings. `encoding` - A Unicode encoding to use. This ap...
4.24346
4.555377
0.931528
m = hashlib.new(hash_name) for chunk in self.chunks(8192, mode="rb"): m.update(chunk) return m
def _hash(self, hash_name)
Returns a hash object for the file at the current path. `hash_name` should be a hash algo name (such as ``'md5'`` or ``'sha1'``) that's available in the :mod:`hashlib` module.
3.737727
3.54959
1.053002
if not hasattr(self.module, 'samefile'): other = Path(other).realpath().normpath().normcase() return self.realpath().normpath().normcase() == other return self.module.samefile(self, other)
def samefile(self, other)
.. seealso:: :func:`os.path.samefile`
4.178071
3.851081
1.084909
desc = win32security.GetFileSecurity( self, win32security.OWNER_SECURITY_INFORMATION) sid = desc.GetSecurityDescriptorOwner() account, domain, typecode = win32security.LookupAccountSid(None, sid) return domain + '\\' + account
def __get_owner_windows(self)
Return the name of the owner of this file or directory. Follow symbolic links. Return a name of the form ``r'DOMAIN\\User Name'``; may be a group. .. seealso:: :attr:`owner`
3.481206
3.991841
0.87208
st = self.stat() return pwd.getpwuid(st.st_uid).pw_name
def __get_owner_unix(self)
Return the name of the owner of this file or directory. Follow symbolic links. .. seealso:: :attr:`owner`
4.692205
5.171494
0.907321
if isinstance(mode, str): mask = _multi_permission_mask(mode) mode = mask(self.stat().st_mode) os.chmod(self, mode) return self
def chmod(self, mode)
Set the mode. May be the new mode (os.chmod behavior) or a `symbolic mode <http://en.wikipedia.org/wiki/Chmod#Symbolic_modes>`_. .. seealso:: :func:`os.chmod`
5.693782
6.846197
0.831671
if hasattr(os, 'chown'): if 'pwd' in globals() and isinstance(uid, str): uid = pwd.getpwnam(uid).pw_uid if 'grp' in globals() and isinstance(gid, str): gid = grp.getgrnam(gid).gr_gid os.chown(self, uid, gid) else: m...
def chown(self, uid=-1, gid=-1)
Change the owner and group by names rather than the uid or gid numbers. .. seealso:: :func:`os.chown`
2.4876
2.61359
0.951794
os.rename(self, new) return self._next_class(new)
def rename(self, new)
.. seealso:: :func:`os.rename`
14.375381
12.398713
1.159425
os.renames(self, new) return self._next_class(new)
def renames(self, new)
.. seealso:: :func:`os.renames`
13.556458
10.835893
1.25107
with contextlib.suppress(FileExistsError): self.mkdir(mode) return self
def mkdir_p(self, mode=0o777)
Like :meth:`mkdir`, but does not raise an exception if the directory already exists.
5.04991
4.824485
1.046725
with contextlib.suppress(FileExistsError): self.makedirs(mode) return self
def makedirs_p(self, mode=0o777)
Like :meth:`makedirs`, but does not raise an exception if the directory already exists.
5.094604
4.922205
1.035025
suppressed = FileNotFoundError, FileExistsError, DirectoryNotEmpty with contextlib.suppress(suppressed): with DirectoryNotEmpty.translate(): self.rmdir() return self
def rmdir_p(self)
Like :meth:`rmdir`, but does not raise an exception if the directory is not empty or does not exist.
13.657041
11.063432
1.234431
with contextlib.suppress(FileExistsError, DirectoryNotEmpty): with DirectoryNotEmpty.translate(): self.removedirs() return self
def removedirs_p(self)
Like :meth:`removedirs`, but does not raise an exception if the directory is not empty or does not exist.
13.618075
11.707793
1.163163
fd = os.open(self, os.O_WRONLY | os.O_CREAT, 0o666) os.close(fd) os.utime(self, None) return self
def touch(self)
Set the access/modified times of this file to the current time. Create the file if it does not exist.
2.459563
2.169063
1.133929
dst = self._next_class(dst) dst.makedirs_p() if update: warnings.warn( "Update is deprecated; " "use copy_function=only_newer(shutil.copy2)", DeprecationWarning, stacklevel=2, ) copy_fun...
def merge_tree( self, dst, symlinks=False, *, update=False, copy_function=shutil.copy2, ignore=lambda dir, contents: [])
Copy entire contents of self to dst, overwriting existing contents in dst with those in self. Pass ``symlinks=True`` to copy symbolic links as links. Accepts a ``copy_function``, similar to copytree. To avoid overwriting newer files, supply a copy function wrapped in ``only_ne...
2.831203
2.871249
0.986053
import io if set(mode).intersection('wa+'): raise ValueError('Only read-only file modes can be used') # move existing file to backup, create new file with same permissions # borrowed extensively from the fileinput module backup_fn = self + (backup_extension...
def in_place( self, mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None, )
A context in which a file may be re-written in-place with new content. Yields a tuple of :samp:`({readable}, {writable})` file objects, where `writable` replaces `readable`. If an exception occurs, the old file is restored, removing the written data. Mode *must not* us...
2.545183
2.408268
1.056852
prop_name = '{scope}_{class_}_dir'.format(**locals()) value = getattr(self.wrapper, prop_name) MultiPath = Multi.for_class(self.path_class) return MultiPath.detect(value)
def get_dir(self, scope, class_)
Return the callable function from appdirs, but with the result wrapped in self.path_class
9.954431
8.208616
1.212681
return next( class_ for class_ in cls.__mro__ if not issubclass(class_, Multi) )
def _next_class(cls)
Multi-subclasses should use the parent class
6.261824
4.427125
1.414422
s = s.replace("&", "&amp;") # Must be done first! s = s.replace("<", "&lt;") s = s.replace(">", "&gt;") if quote: s = s.replace('"', "&quot;") s = s.replace('\'', "&#x27;") return s
def escape(s, quote=True)
Replace special characters "&", "<" and ">" to HTML-safe sequences. If the optional flag quote is true (the default), the quotation mark characters, both double quote (") and single quote (') characters are also translated.
1.604297
1.620358
0.990088
if token.content.startswith('$$'): return self.render_raw_text(token) return '${}$'.format(self.render_raw_text(token))
def render_math(self, token)
Ensure Math tokens are all enclosed in two dollar signs.
3.857963
3.422787
1.127141
with renderer() as renderer: return renderer.render(Document(iterable))
def markdown(iterable, renderer=HTMLRenderer)
Output HTML with default settings. Enables inline and block-level HTML tags.
8.058025
9.227479
0.873264
node = {} # Python 3.6 uses [ordered dicts] [1]. # Put in 'type' entry first to make the final tree format somewhat # similar to [MDAST] [2]. # # [1]: https://docs.python.org/3/whatsnew/3.6.html # [2]: https://github.com/syntax-tree/mdast node['type'] = token.__class__.__name__ ...
def get_ast(token)
Recursively unrolls token attributes into dictionaries (token.children into lists). Returns: a dictionary of token's attributes.
3.837146
3.967348
0.967182
lines = FileWrapper(iterable) parse_buffer = ParseBuffer() line = lines.peek() while line is not None: for token_type in token_types: if token_type.start(line): result = token_type.read(lines) if result is not None: parse_buffe...
def tokenize_block(iterable, token_types)
Returns a list of pairs (token_type, read_result). Footnotes are parsed here, but span-level parsing has not started yet.
3.556809
3.615641
0.983728
tokens = [] for token_type, result in parse_buffer: token = token_type(result) if token is not None: tokens.append(token) return tokens
def make_tokens(parse_buffer)
Takes a list of pairs (token_type, read_result) and applies token_type(read_result). Footnotes are already parsed before this point, and span-level parsing is started here.
2.754689
2.361387
1.166555
try: with open(filename, 'r') as fin: rendered = mistletoe.markdown(fin, renderer) print(rendered, end='') except OSError: sys.exit('Cannot open file "{}".'.format(filename))
def convert_file(filename, renderer)
Parse a Markdown file and dump the output to stdout.
3.727717
3.212982
1.160205
_import_readline() _print_heading(renderer) contents = [] more = False while True: try: prompt, more = ('... ', True) if more else ('>>> ', True) contents.append(input(prompt) + '\n') except EOFError: print('\n' + mistletoe.markdown(contents, ...
def interactive(renderer)
Parse user input, dump to stdout, rinse and repeat. Python REPL style.
5.080054
5.057237
1.004512
from mistletoe.block_token import List def get_indent(level): if self.omit_title: level -= 1 return ' ' * 4 * (level - 1) def build_list_item(heading): level, content = heading template = '{indent}- {content}\n' ...
def toc(self)
Returns table of contents as a block_token.List instance.
4.165408
3.496042
1.191464
rendered = super().render_heading(token) content = self.parse_rendered_heading(rendered) if not (self.omit_title and token.level == 1 or token.level > self.depth or any(cond(content) for cond in self.filter_conds)): self._headings.append((toke...
def render_heading(self, token)
Overrides super().render_heading; stores rendered heading first, then returns it.
5.303463
4.961745
1.068871
match_obj = cls.pattern.match(line) if match_obj is None: return None # no valid leader leader = match_obj.group(1) content = match_obj.group(0).replace(leader+'\t', leader+' ', 1) # reassign prepend and leader prepend = len(content) ...
def parse_marker(cls, line)
Returns a pair (prepend, leader) iff the line has a valid leader.
4.122799
3.292499
1.252179
rendered = [self.render(child) for child in token.children] return ''.join(rendered)
def render_inner(self, token)
Recursively renders child tokens. Joins the rendered strings with no space in between. If newlines / spaces are needed between tokens, add them in their respective templates, or override this function in the renderer subclass, so that whitespace won't seem to appear magically fo...
4.518612
5.217847
0.865992
# Check if string if not isinstance(signal, str): signal = list(signal) signal = np.array(signal) # Create a frequency data data_set = list(set(signal)) freq_list = [] for entry in data_set: counter = 0. for i in signal: if i == entry: ...
def complexity_entropy_shannon(signal)
Computes the shannon entropy. Copied from the `pyEntropy <https://github.com/nikdon/pyEntropy>`_ repo by tjugo. Parameters ---------- signal : list or array List or array of values. Returns ---------- shannon_entropy : float The Shannon Entropy as float value. Example ...
2.768691
3.128997
0.884849
signal = np.array(signal) L = [] x = [] N = signal.size km_idxs = np.triu_indices(k_max - 1) km_idxs = k_max - np.flipud(np.column_stack(km_idxs)) -1 km_idxs[:,1] -= 1 for k in range(1, k_max): Lk = 0 for m in range(0, k): #we pregenerate all idxs ...
def complexity_fd_higushi(signal, k_max)
Computes Higuchi Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. k_max : int The maximal value of k. The point at which the FD plateaus is conside...
4.840194
5.079452
0.952897
psd = np.abs(np.fft.rfft(signal))**2 psd /= np.sum(psd) # psd as a pdf (normalised to one) if bands is None: power_per_band= psd[psd>0] else: freqs = np.fft.rfftfreq(signal.size, 1/float(sampling_rate)) bands = np.asarray(bands) freq_limits_low = np.concatenate([[...
def complexity_entropy_spectral(signal, sampling_rate, bands=None)
Computes Spectral Entropy of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. The power spectrum is computed through fft. Then, it is normalised and assimilated to a probability density function. Parameters ---------- signal : list or array List or a...
2.639214
2.885669
0.914594
mat = _embed_seq(signal, tau, emb_dim) W = np.linalg.svd(mat, compute_uv = False) W /= sum(W) # normalize singular values entropy_svd = -1*sum(W * np.log2(W)) return(entropy_svd)
def complexity_entropy_svd(signal, tau=1, emb_dim=2)
Computes the Singular Value Decomposition (SVD) entropy of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. tau : int The delay emb_dim : int The embedding ...
3.989843
4.903371
0.813694
diff = np.diff(signal) # x[i] * x[i-1] for i in t0 -> tmax prod = diff[1:-1] * diff[0:-2] # Number of sign changes in derivative of the signal N_delta = np.sum(prod < 0) n = len(signal) fd_petrosian = np.log(n)/(np.log(n)+np.log(n/(n+0.4*N_delta))) return(fd_petrosian)
def complexity_fd_petrosian(signal)
Computes the Petrosian Fractal Dimension of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. Returns ---------- fd_petrosian : float The Petrosian FD as float ...
5.2371
6.330368
0.827298
mat = _embed_seq(signal, tau, emb_dim) W = np.linalg.svd(mat, compute_uv = False) W /= sum(W) # normalize singular values FI_v = (W[1:] - W[:-1]) **2 / W[:-1] fisher_info = np.sum(FI_v) return(fisher_info)
def complexity_fisher_info(signal, tau=1, emb_dim=2)
Computes the Fisher information of a signal. Based on the `pyrem <https://github.com/gilestrolab/pyrem>`_ repo by Quentin Geissmann. Parameters ---------- signal : list or array List or array of values. tau : int The delay emb_dim : int The embedding dimension (*m*, the leng...
4.767083
6.040404
0.789199
ntf = data.shape[0] gfp_curve = np.zeros((ntf, )) if gflp_method == 'GFPL2': for i in range(ntf): x = data[i,:] gfp_curve[i] = np.sqrt(np.sum((x - x.mean())**2 / len(x) )) elif gflp_method == 'GFPL1': for i in range(ntf): x = data[i,:] ...
def eeg_gfp_peaks(data, gflp_method='GFPL1', smoothing=False, smoothing_window=100, peak_method="wavelet", normalize=False)
The Global Field Power (GFP) is a scalar measure of the strength of the scalp potential field and is calculated as the standard deviation of all electrodes at a given time point (Lehmann and Skrandies, 1980; Michel et al., 1993; Murray et al., 2008; Brunet et al., 2011). Between two GFP troughs, the strength of the pot...
2.207358
2.171219
1.016644
# Load data if necessary # if isinstance(raws, str): # raws = load_object(filename=raws) # Initialize empty dict gfp = {} for participant in raws: gfp[participant] = {} for run in raws[participant]: # Generate empty dic gfp[participant][run] = {...
def eeg_gfp(raws, gflp_method="GFPL1", scale=True, normalize=True, smoothing=None)
Run the GFP analysis.
2.952041
2.963998
0.995966
# Create training set training_set = data.copy() if verbose is True: print("- Initializing the clustering algorithm...") if clustering_method == "kmeans": algorithm = sklearn.cluster.KMeans(init='k-means++', n_clusters=n_microstates, n_init=n_init, n_jobs=n_jobs) elif clusterin...
def eeg_microstates_clustering(data, n_microstates=4, clustering_method="kmeans", n_jobs=1, n_init=25, occurence_rejection_treshold=0.05, max_refitting=5, verbose=True)
Fit the clustering algorithm.
2.666384
2.672182
0.99783
for participant in results: for run in results[participant]: if verbose is True: print("- " + participant) # Frequencies of each microstate occurences = dict(collections.Counter(results[participant][run]["microstates"])) # Compute compl...
def eeg_microstates_features(results, method, ecg=True, nonlinearity=True, verbose=True)
Compute statistics and features for/of the microstates.
2.879456
2.879443
1.000004
# Generate and store figures figures = [] names = [] # Check if microstates metrics available try: microstates = method["microstates_good_fit"] except KeyError: microstates = method["microstates"] # Create individual plot for each microstate for microstate in set(m...
def eeg_microstates_plot(method, path="", extension=".png", show_sensors_position=False, show_sensors_name=False, plot=True, save=True, dpi=150, contours=0, colorbar=False, separate=False)
Plot the microstates.
3.157339
3.16104
0.998829
microstates = list(method['microstates']) for index, microstate in enumerate(method['microstates']): if microstate in list(reverse_microstates.keys()): microstates[index] = reverse_microstates[microstate] method["data"][index] = -1*method["data"][index] if micros...
def eeg_microstates_relabel(method, results, microstates_labels, reverse_microstates=None)
Relabel the microstates.
2.546372
2.512145
1.013625
''' This function computes the wavelet coefficients INPUT: data: DataFrame, index is a list of timestamps at 8Hz, columns include EDA, filtered_eda OUTPUT: wave1Second: DateFrame, index is a list of timestamps at 1Hz, columns include OneSecond_feature1, OneSecond_feature2, O...
def getWaveletData(eda)
This function computes the wavelet coefficients INPUT: data: DataFrame, index is a list of timestamps at 8Hz, columns include EDA, filtered_eda OUTPUT: wave1Second: DateFrame, index is a list of timestamps at 1Hz, columns include OneSecond_feature1, OneSecond_feature2, OneSecond_fea...
2.922885
1.985086
1.472422
# The "Daubechies" wavelet is a rough approximation to a real, single, cardiac cycle cardiac = scipy.signal.wavelets.daub(10) # Add the gap after the pqrst when the heart is resting. cardiac = np.concatenate([cardiac, np.zeros(10)]) # Caculate the number of beats in capture time period num...
def ecg_simulate(duration=10, sampling_rate=1000, bpm=60, noise=0.01)
Simulates an ECG signal. Parameters ---------- duration : int Desired recording length. sampling_rate : int Desired sampling rate. bpm : int Desired simulated heart rate. noise : float Desired noise level. Returns ---------- ECG_Response : dict ...
5.615109
6.815954
0.823818
processed_rsp = {"df": pd.DataFrame({"RSP_Raw": np.array(rsp)})} biosppy_rsp = dict(biosppy.signals.resp.resp(rsp, sampling_rate=sampling_rate, show=False)) processed_rsp["df"]["RSP_Filtered"] = biosppy_rsp["filtered"] # RSP Rate # ============ rsp_rate = biosppy_rsp["resp_rate"]*60 # Get R...
def rsp_process(rsp, sampling_rate=1000)
Automated processing of RSP signals. Parameters ---------- rsp : list or array Respiratory (RSP) signal array. sampling_rate : int Sampling rate (samples/second). Returns ---------- processed_rsp : dict Dict containing processed RSP features. Contains the R...
2.873058
2.842538
1.010737
# Compute gradient (sort of derivative) gradient = np.gradient(signal) # Find zero-crossings zeros, = biosppy.tools.zero_cross(signal=gradient, detrend=True) # Find respiratory phases phases_indices = [] for i in zeros: if gradient[i+1] > gradient[i-1]: phases_indic...
def rsp_find_cycles(signal)
Find Respiratory cycles onsets, durations and phases. Parameters ---------- signal : list or array Respiratory (RSP) signal (preferably filtered). Returns ---------- rsp_cycles : dict RSP cycles features. Example ---------- >>> import neurokit as nk >>> rsp_cy...
2.802252
2.747124
1.020067
if channel_name is None: if isinstance(channel, pd.core.series.Series): if channel.name is not None: channel_name = channel.name else: channel_name = "Added_Channel" else: channel_name = "Added_Channel" # Compute the dista...
def eeg_add_channel(raw, channel, sync_index_eeg=0, sync_index_channel=0, channel_type=None, channel_name=None)
Add a channel to a mne's Raw m/eeg file. It will basically synchronize the channel to the eeg data following a particular index and add it. Parameters ---------- raw : mne.io.Raw Raw EEG data. channel : list or numpy.array The channel to be added. sync_index_eeg : int or list ...
2.571243
2.917006
0.881466
if isinstance(channel_names, list) is False: channel_names = [channel_names] channels, time_index = raw.copy().pick_channels(channel_names)[:] if len(channel_names) > 1: channels = pd.DataFrame(channels.T, columns=channel_names) else: channels = pd.Series(channels[0]) ...
def eeg_select_channels(raw, channel_names)
Select one or several channels by name and returns them in a dataframe. Parameters ---------- raw : mne.io.Raw Raw EEG data. channel_names : str or list Channel's name(s). Returns ---------- channels : pd.DataFrame Channel. Example ---------- >>> import...
2.802296
3.269725
0.857043
# Get all channel names eeg = eeg.copy().pick_types(meg=False, eeg=True) channel_list = eeg.ch_names # Include if include == "all": electrodes = channel_list elif isinstance(include, str): electrodes = [s for s in channel_list if include in s] elif isinstance(include, l...
def eeg_select_electrodes(eeg, include="all", exclude=None, hemisphere="both", central=True)
Returns electrodes/sensors names of selected region (according to a 10-20 EEG montage). Parameters ---------- eeg : mne.Raw or mne.Epochs EEG data. include : str ot list Sensor area to include. exclude : str or list or None Sensor area to exclude. hemisphere : str ...
1.649186
1.664476
0.990814
event_id = {} if conditions is None: conditions = ["Event"] * len(onsets) # Sanity check if len(conditions) != len(onsets): print("NeuroKit Warning: eeg_create_events(): conditions parameter of different length than onsets. Aborting.") return() event_names = list(se...
def eeg_create_mne_events(onsets, conditions=None)
Create MNE compatible events. Parameters ---------- onsets : list or array Events onsets. conditions : list A list of equal length containing the stimuli types/conditions. Returns ---------- (events, event_id) : tuple MNE-formated events and a dictionary with event...
3.056284
3.471577
0.880373
# Extract the events_channel from raw if needed if isinstance(events_channel, str): try: events_channel = eeg_select_channels(raw, events_channel) except: print("NeuroKit error: eeg_add_events(): Wrong events_channel name provided.") # Find event onsets even...
def eeg_add_events(raw, events_channel, conditions=None, treshold="auto", cut="higher", time_index=None, number="all", after=0, before=None, min_duration=1)
Find events on a channel, convert them into an MNE compatible format, and add them to the raw data. Parameters ---------- raw : mne.io.Raw Raw EEG data. events_channel : str or array Name of the trigger channel if in the raw, or array of equal length if externally supplied. conditio...
2.982738
3.11047
0.958935
if conditions is None: # Get event_id conditions = {} for participant, epochs in all_epochs.items(): conditions.update(epochs.event_id) all_evokeds = {} for participant, epochs in all_epochs.items(): evokeds = {} for cond in conditions: t...
def eeg_to_all_evokeds(all_epochs, conditions=None)
Convert all_epochs to all_evokeds. DOCS INCOMPLETE :(
2.227897
2.25433
0.988274
if isinstance(eeg, mne.Epochs): data = {} if index is None: index = range(len(eeg)) for epoch_index, epoch in zip(index, eeg.get_data()): epoch = pd.DataFrame(epoch.T) epoch.columns = eeg.ch_names epoch.index = eeg.times se...
def eeg_to_df(eeg, index=None, include="all", exclude=None, hemisphere="both", central=True)
Convert mne Raw or Epochs object to dataframe or dict of dataframes. DOCS INCOMPLETE :(
2.420004
2.328477
1.039308
# Sanity check if isinstance(scores, dict): if labels is None: labels = list(scores.keys()) try: scores = [scores[key] for key in labels] except KeyError: print("NeuroKit Error: plot_polarbar(): labels and scores keys not matching. Recheck them....
def plot_polarbar(scores, labels=None, labels_size=15, colors="default", distribution_means=None, distribution_sds=None, treshold=1.28, fig_size=(15, 15))
Polar bar chart. Parameters ---------- scores : list or dict Scores to plot. labels : list List of labels to be used for ticks. labels_size : int Label's size. colors : list or str List of colors or "default". distribution_means : int or list List of ...
2.340759
2.320334
1.008803
if method == "PCA": feature_red_method = sklearn.decomposition.PCA(n_components=n_features) data_processed = feature_red_method.fit_transform(data) elif method == "agglom": feature_red_method = sklearn.cluster.FeatureAgglomeration(n_clusters=n_features) data_processed = fea...
def feature_reduction(data, method, n_features)
Feature reduction. Parameters ---------- NA Returns ---------- NA Example ---------- NA Authors ---------- Dominique Makowski Dependencies ---------- - sklearn
1.440405
1.472418
0.978258
if treshold == "auto": treshold = (np.max(np.array(signal)) - np.min(np.array(signal)))/2 signal = list(signal) binary_signal = [] for i in range(len(signal)): if cut == "higher": if signal[i] > treshold: binary_signal.append(1) else: ...
def binarize_signal(signal, treshold="auto", cut="higher")
Binarize a channel based on a continuous channel. Parameters ---------- signal = array or list The signal channel. treshold = float The treshold value by which to select the events. If "auto", takes the value between the max and the min. cut = str "higher" or "lower", define...
1.550149
1.79863
0.86185
events_channel = binarize_signal(events_channel, treshold=treshold, cut=cut) events = {"onsets":[], "durations":[]} if time_index is not None: events["onsets_time"] = [] index = 0 for key, g in (groupby(events_channel)): duration = len(list(g)) if key == 1: ...
def localize_events(events_channel, treshold="auto", cut="higher", time_index=None)
Find the onsets of all events based on a continuous signal. Parameters ---------- events_channel = array or list The trigger channel. treshold = float The treshold value by which to select the events. If "auto", takes the value between the max and the min. cut = str "higher"...
2.838361
3.405151
0.833549
events = localize_events(events_channel, treshold=treshold, cut=cut, time_index=time_index) # Warning when no events detected if len(events["onsets"]) == 0: print("NeuroKit warning: find_events(): No events found. Check your events_channel or adjust trehsold.") return() # Remove l...
def find_events(events_channel, treshold="auto", cut="higher", time_index=None, number="all", after=0, before=None, min_duration=1)
Find and select events based on a continuous signal. Parameters ---------- events_channel : array or list The trigger channel. treshold : float The treshold value by which to select the events. If "auto", takes the value between the max and the min. cut : str "higher" or "lo...
1.754806
1.796226
0.976941
df = pd.DataFrame(signal) ax = df.plot() def plotOnSignal(x, color, marker=None): if (marker is None): plt.axvline(x=event, color=color) else: plt.plot(x, signal[x], marker, color=color) events_onsets = np.array(events_onsets) try: len(events_...
def plot_events_in_signal(signal, events_onsets, color="red", marker=None)
Plot events in signal. Parameters ---------- signal : array or DataFrame Signal array (can be a dataframe with many signals). events_onsets : list or ndarray Events location. color : int or list Marker color. marker : marker or list of markers (for possible marker values...
2.306681
2.55929
0.901297
# Processing # =========== if method == "slow": # Compute gradient (sort of derivative) gradient = np.gradient(signal) # Smoothing size = int(0.1 * sampling_rate) smooth, _ = biosppy.tools.smoother(signal=gradient, kernel='bartlett', size=size, mirror=True) ...
def eda_scr(signal, sampling_rate=1000, treshold=0.1, method="fast")
Skin-Conductance Responses extraction algorithm. Parameters ---------- signal : list or array EDA signal array. sampling_rate : int Sampling rate (samples/second). treshold : float SCR minimum treshold (in terms of signal standart deviation). method : str "fast"...
3.081832
2.925802
1.053329
data = eeg_to_df(eeg, index=index, include=include, exclude=exclude, hemisphere=hemisphere, central=central) # if data was Raw, make as if it was an Epoch so the following routine is only written once if isinstance(data, dict) is False: data = {0: data} # Create time windows if isin...
def eeg_complexity(eeg, sampling_rate, times=None, index=None, include="all", exclude=None, hemisphere="both", central=True, verbose=True, shannon=True, sampen=True, multiscale=True, spectral=True, svd=True, correlation=True, higushi=True, petrosian=True, fisher=True, hurst=True, dfa=True, lyap_r=False, lyap_e=False, n...
Compute complexity indices of epochs or raw object. DOCS INCOMPLETE :(
2.295137
2.301192
0.997369
# Convert to array if list if isinstance(nbeats_real, list): nbeats_real = np.array(nbeats_real) nbeats_reported = np.array(nbeats_reported) # Compute accuracy accuracy = 1 - (abs(nbeats_real-nbeats_reported))/((nbeats_real+nbeats_reported)/2) return(accuracy)
def compute_interoceptive_accuracy(nbeats_real, nbeats_reported)
Computes interoceptive accuracy according to Garfinkel et al., (2015). Parameters ---------- nbeats_real : int or list Real number of heartbeats. nbeats_reported : int or list Reported number of heartbeats. Returns ---------- accuracy : float or list Objective accur...
2.408398
2.796996
0.861066
if value != "stop": self.X = pd.concat([self.X, pd.DataFrame({"Signal":[value]})]) self.y = np.array(list(self.y) + [response]) if len(set(list(self.y))) > 1: self.model = self.fit_model(self.X , self.y)
def add_response(self, response, value)
Add response to staircase. Parameters ---------- response : int or bool 0 or 1. value : int or float Signal corresponding to response.
4.473969
4.404713
1.015723
t = (builtin_time.clock()-self.clock)*1000 if reset is True: self.reset() return(t)
def get(self, reset=True)
Get time since last initialisation / reset. Parameters ---------- reset = bool, optional Should the clock be reset after returning time? Returns ---------- float Time passed in milliseconds. Example ---------- >>> import ...
9.253175
13.77929
0.671528
# Convert ints to arrays if needed if isinstance(duration, list) or isinstance(duration, np.ndarray): duration = np.array(duration) else: duration = np.array([duration]*len(events_onsets)) if isinstance(onset, list) or isinstance(onset, np.ndarray): onset = np.array(onset) ...
def create_epochs(data, events_onsets, sampling_rate=1000, duration=1, onset=0, index=None)
Epoching a dataframe. Parameters ---------- data : pandas.DataFrame Data*time. events_onsets : list A list of event onsets indices. sampling_rate : int Sampling rate (samples/second). duration : int or list Duration(s) of each epoch(s) (in seconds). onset : i...
2.287446
2.220774
1.030022
# values=RRis.copy() # value_times=beats_times.copy() # Preprocessing initial_index = value_times[0] value_times = np.array(value_times) - initial_index # fit a 3rd degree spline on the data. spline = scipy.interpolate.splrep(x=value_times, y=values, k=3, s=0) # s=0 guarantees that it w...
def interpolate(values, value_times, sampling_rate=1000)
3rd order spline interpolation. Parameters ---------- values : dataframe Values. value_times : list Time indices of values. sampling_rate : int Sampling rate (samples/second). Returns ---------- signal : pd.Series An array containing the values indexed b...
4.659616
4.613018
1.010101
derivative = np.gradient(signal, 2) peaks = np.where(np.diff(np.sign(derivative)))[0] return(peaks)
def find_peaks(signal)
Locate peaks based on derivative. Parameters ---------- signal : list or array Signal. Returns ---------- peaks : array An array containing the peak indices. Example ---------- >>> signal = np.sin(np.arange(0, np.pi*10, 0.05)) >>> peaks = nk.find_peaks(signal) ...
3.213131
5.256818
0.611231
freqs = list(freqs) freqs_names = [] for freq in freqs: if freq < 1: freqs_names.append("UltraLow") elif freq <= 3: freqs_names.append("Delta") elif freq <= 7: freqs_names.append("Theta") elif freq <= 9: freqs_names.append(...
def eeg_name_frequencies(freqs)
Name frequencies according to standart classifications. Parameters ---------- freqs : list or numpy.array list of floats containing frequencies to classify. Returns ---------- freqs_names : list Named frequencies Example ---------- >>> import neurokit as nk >>>...
1.839735
1.621692
1.134454
picks = mne.pick_types(raw.info, include=eeg_select_electrodes(include=sensors_include, exclude=sensors_exclude), exclude="bads") if method == "multitaper": psds, freqs = mne.time_frequency.psd_multitaper(raw, fmin=fmin, ...
def eeg_psd(raw, sensors_include="all", sensors_exclude=None, fmin=0.016, fmax=60, method="multitaper", proj=False)
Compute Power-Spectral Density (PSD). Parameters ---------- raw : mne.io.Raw Raw EEG data. sensors_include : str Sensor area to include. See :func:`neurokit.eeg_select_sensors()`. sensors_exclude : str Sensor area to exclude. See :func:`neurokit.eeg_select_sensors()`. fm...
2.397727
2.454231
0.976977
if bands == "all" or bands == "All": bands = ["Delta", "Theta", "Alpha", "Beta", "Gamma", "Mu"] if "Alpha" in bands: bands.remove("Alpha") bands += ["Alpha1", "Alpha2"] if "Beta" in bands: bands.remove("Beta") bands += ["Beta1", "Beta2"] if "Gamma" in bands: ...
def eeg_create_frequency_bands(bands="all", step=1)
Delta: 1-3Hz Theta: 4-7Hz Alpha1: 8-9Hz Alpha2: 10-12Hz Beta1: 13-17Hz Beta2: 18-30Hz Gamma1: 31-40Hz Gamma2: 41-50Hz Mu: 8-13Hz
1.492875
1.27191
1.173727
median = np.median(var) mad = np.median(np.abs(var - median)) mad = mad*constant return(mad)
def mad(var, constant=1)
Median Absolute Deviation: a "robust" version of standard deviation. Parameters ---------- var : list or ndarray Value array. constant : float Scale factor. Use 1.4826 for results similar to default R. Returns ---------- mad : float The MAD. Example -------...
2.778168
5.134145
0.541116
df = pd.DataFrame(raw_scores) mean = df.mean(axis=0) sd = df.std(axis=0) z_scores = (df - mean)/sd return(z_scores)
def z_score(raw_scores, center=True, scale=True)
Transform an array, serie or list into Z scores (scaled and centered scores). Parameters ---------- raw_scores : list, ndarray or pandas.Series ECG signal array. centered : bool Center the array (mean = 0). scale : bool scale the array (sd = 1). Returns ---------- ...
2.533976
3.839158
0.660034
outliers = [] mean = np.mean(data) std = np.std(data) for i in data: if abs(i - mean)/std < treshold: outliers.append(False) else: outliers.append(True) outliers = np.array(outliers) return (outliers)
def find_outliers(data, treshold=2.58)
Identify outliers (abnormal values) using the standart deviation. Parameters ---------- data : list or ndarray Data array treshold : float Maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2.58 = rejecting 1%, 2.33 = rejecting 2%, 1.96 = 5% an...
2.025037
2.613572
0.774816
bottom = mean - sd*treshold top = mean + sd*treshold return(bottom, top)
def normal_range(mean, sd, treshold=1.28)
Returns a bottom and a top limit on a normal distribution portion based on a treshold. Parameters ---------- treshold : float maximum deviation (in terms of standart deviation). Rule of thumb of a gaussian distribution: 2.58 = keeping 99%, 2.33 = keeping 98%, 1.96 = 95% and 1.28 = keeping 90%. ...
3.66599
7.137011
0.513659
array = array[:] uniques = [] for i in range(len(array)): if i == 0: uniques.append(True) else: if array[i] == array[i-1]: uniques.append(False) else: uniques.append(True) return(uniques)
def find_following_duplicates(array)
Find the duplicates that are following themselves. Parameters ---------- array : list or ndarray A list containing duplicates. Returns ---------- uniques : list A list containing True for each unique and False for following duplicates. Example ---------- >>> impor...
2.296646
2.940961
0.780917
if direction == "both": closest = min(array, key=lambda x:abs(x-number)) if direction == "smaller": if strictly is True: closest = max(x for x in array if x < number) else: closest = max(x for x in array if x <= number) if direction == "greater": ...
def find_closest_in_list(number, array, direction="both", strictly=False)
Find the closest number in the array from x. Parameters ---------- number : float The number. array : list The list to look in. direction : str "both" for smaller or greater, "greater" for only greater numbers and "smaller" for the closest smaller. strictly : bool ...
2.003633
2.544549
0.787422
emg = np.asarray(emg) tkeo = np.copy(emg) # Teager–Kaiser Energy operator tkeo[1:-1] = emg[1:-1]*emg[1:-1] - emg[:-2]*emg[2:] # correct the data in the extremities tkeo[0], tkeo[-1] = tkeo[1], tkeo[-2] return(tkeo)
def emg_tkeo(emg)
Calculates the Teager–Kaiser Energy operator. Parameters ---------- emg : array raw EMG signal. Returns ------- tkeo : 1D array_like signal processed by the Teager–Kaiser Energy operator. Notes ----- *Authors* - Marcos Duarte *See Also* See this n...
3.566987
2.918266
1.222296
r emg = emg_tkeo(emg) if np.size(freqs) == 2: # band-pass filter b, a = scipy.signal.butter(2, np.array(freqs)/(sampling_rate/2.), btype = 'bandpass') emg = scipy.signal.filtfilt(b, a, emg) if np.size(lfreq) == 1: # full-wave rectification envelope = abs(emg) ...
def emg_linear_envelope(emg, sampling_rate=1000, freqs=[10, 400], lfreq=4)
r"""Calculate the linear envelope of a signal. Parameters ---------- emg : array raw EMG signal. sampling_rate : int Sampling rate (samples/second). freqs : list [fc_h, fc_l], optional cutoff frequencies for the band-pass filter (in Hz). lfreq : number, optional ...
2.881984
2.963137
0.972612
n_above = n_above*sampling_rate n_below = n_below*sampling_rate envelope = np.atleast_1d(envelope).astype('float64') # deal with NaN's (by definition, NaN's are not greater than threshold) envelope[np.isnan(envelope)] = -np.inf # indices of data greater than or equal to threshold inds...
def emg_find_activation(envelope, sampling_rate=1000, threshold=0, n_above=0.25, n_below=1)
Detects onset in data based on amplitude threshold. Parameters ---------- envelope : array Linear envelope of EMG signal. sampling_rate : int Sampling rate (samples/second). threshold : float minimum amplitude of `x` to detect. n_above : float minimum continuous ...
3.535918
3.683752
0.959869
rpeaks, = biosppy.ecg.hamilton_segmenter(np.array(signal), sampling_rate=sampling_rate) rpeaks, = biosppy.ecg.correct_rpeaks(signal=np.array(signal), rpeaks=rpeaks, sampling_rate=sampling_rate, tol=0.05) return(rpeaks)
def ecg_find_peaks(signal, sampling_rate=1000)
Find R peaks indices on the ECG channel. Parameters ---------- signal : list or ndarray ECG signal (preferably filtered). sampling_rate : int Sampling rate (samples/second). Returns ---------- rpeaks : list List of R-peaks location indices. Example -------...
3.404642
3.985469
0.854264
waves = np.array([""]*len(ecg)) waves[rpeaks] = "R" waves[t_waves_ends] = "T" systole = [0] current = 0 for index, value in enumerate(waves[1:]): if waves[index-1] == "R": current = 1 if waves[index-1] == "T": current = 0 systole.append(curre...
def ecg_systole(ecg, rpeaks, t_waves_ends)
Returns the localization of systoles and diastoles. Parameters ---------- ecg : list or ndarray ECG signal (preferably filtered). rpeaks : list or ndarray R peaks localization. t_waves_ends : list or ndarray T waves localization. Returns ---------- systole : nda...
2.863225
3.473675
0.824264
window_size = int(window_size*sampling_rate) lowpass = scipy.signal.butter(1, hfreq/(sampling_rate/2.0), 'low') highpass = scipy.signal.butter(1, lfreq/(sampling_rate/2.0), 'high') # TODO: Could use an actual bandpass filter ecg_low = scipy.signal.filtfilt(*lowpass, x=ecg) ecg_band = sci...
def segmenter_pekkanen(ecg, sampling_rate, window_size=5.0, lfreq=5.0, hfreq=15.0)
ECG R peak detection based on `Kathirvel et al. (2001) <http://link.springer.com/article/10.1007/s13239-011-0065-3/fulltext.html>`_ with some tweaks (mainly robust estimation of the rectified signal cutoff threshold). Parameters ---------- ecg : list or ndarray ECG signal array. sampling_rate :...
2.565333
2.671913
0.960111
erp = {} data = eeg_to_df(eeg, index=index, include=include, exclude=exclude, hemisphere=hemisphere, central=central) for epoch_index, epoch in data.items(): # Segment according to window if isinstance(times, list): if isinstance(times[0], list): values = {...
def eeg_erp(eeg, times=None, index=None, include="all", exclude=None, hemisphere="both", central=True, verbose=True, names="ERP", method="mean")
DOCS INCOMPLETE :(
1.929082
1.926727
1.001222
# Preserve original all_epochs_current = all_epochs.copy() # Filter using Savitzky-Golay polynomial method if (filter_hfreq is not None) and (isinstance(filter_hfreq, int)): for participant, epochs in all_epochs_current.items(): all_epochs_current[participant] = epochs.savgol_f...
def plot_eeg_erp(all_epochs, conditions=None, times=None, include="all", exclude=None, hemisphere="both", central=True, name=None, colors=None, gfp=False, ci=0.95, ci_alpha=0.333, invert_y=False, linewidth=1, linestyle="-", filter_hfreq=None)
DOCS INCOMPLETE :(
2.206293
2.199164
1.003242
all_evokeds = eeg_to_all_evokeds(all_epochs) data = {} for participant, epochs in all_evokeds.items(): for cond, epoch in epochs.items(): data[cond] = [] for participant, epochs in all_evokeds.items(): for cond, epoch in epochs.items(): data[cond].append(epo...
def plot_eeg_erp_topo(all_epochs, colors=None)
Plot butterfly plot. DOCS INCOMPLETE :(
2.57373
2.553671
1.007855
if compress is True: with gzip.open(path + filename + "." + extension, 'wb') as name: pickle.dump(obj, name, protocol=compatibility) else: with open(path + filename + "." + extension, 'wb') as name: pickle.dump(obj, name, protocol=compatibility)
def save_nk_object(obj, filename="file", path="", extension="nk", compress=False, compatibility=-1)
Save whatever python object to a pickled file. Parameters ---------- file : object Whatever python thing (list, dict, ...). filename : str File's name. path : str File's path. extension : str File's extension. Default "nk" but can be whatever. compress: bool ...
1.91628
2.296419
0.834464
filename = path + filename try: with open(filename, 'rb') as name: file = pickle.load(name) except pickle.UnpicklingError: with gzip.open(filename, 'rb') as name: file = pickle.load(name) except ModuleNotFoundError: # In case you're trying to unpickle a...
def read_nk_object(filename, path="")
Read a pickled file. Parameters ---------- filename : str Full file's name (with extension). path : str File's path. Example ---------- >>> import neurokit as nk >>> obj = [1, 2] >>> nk.save_nk_object(obj, filename="myobject") >>> loaded_obj = nk.read_nk_object(...
3.70378
4.568792
0.810669
if platform.system() == 'Windows': return(os.path.getctime(path)) else: stat = os.stat(path) try: return(stat.st_birthtime) except AttributeError: print("Neuropsydia error: get_creation_date(): We're probably on Linux. No easy way to get creation date...
def find_creation_date(path)
Try to get the date that a file was created, falling back to when it was last modified if that's not possible. Parameters ---------- path : str File's path. Returns ---------- creation_date : str Time of file creation. Example ---------- >>> import neurokit as nk ...
3.797024
3.628842
1.046346
from . import __version__ d = OrderedDict() d['Version'] = '%s' % __version__ for key, val in PyVisaLibrary.get_session_classes().items(): key_name = '%s %s' % (key[0].name.upper(), key[1]) try: d[key_name] = getattr(val, 'session_issue')...
def get_debug_info()
Return a list of lines with backend info.
5.355957
5.166027
1.036765
session = None while session is None or session in self.sessions: session = random.randint(1000000, 9999999) self.sessions[session] = obj return session
def _register(self, obj)
Creates a random but unique session handle for a session object, register it in the sessions dictionary and return the value :param obj: a session object. :return: session handle :rtype: int
3.349382
2.740734
1.222075
logger.debug('%s%s -> %r', func.__name__, _args_to_str(arguments), ret_value, extra=self._logging_extra) try: ret_value = StatusCode(ret_value) except ValueError: pass self._last_status = ret_value # T...
def _return_handler(self, ret_value, func, arguments)
Check return values for errors and warnings. TODO: THIS IS JUST COPIED PASTED FROM NIVisaLibrary. Needs to be adapted.
4.210368
3.999854
1.05263
try: sess = self.sessions[session] except KeyError: return constants.StatusCode.error_invalid_object return sess.clear()
def clear(self, session)
Clears a device. Corresponds to viClear function of the VISA library. :param session: Unique logical identifier to a session. :return: return value of the library call. :rtype: :class:`pyvisa.constants.StatusCode`
9.11718
6.331506
1.43997
try: return self.sessions[session].gpib_command(command_byte) except KeyError: return constants.StatusCode.error_invalid_object
def gpib_command(self, session, command_byte)
Write GPIB command byte on the bus. Corresponds to viGpibCommand function of the VISA library. See: https://linux-gpib.sourceforge.io/doc_html/gpib-protocol.html#REFERENCE-COMMAND-BYTES :param command_byte: command byte to send :type command_byte: int, must be [0 255] :return: ...
6.69687
6.352597
1.054194
try: return self.sessions[session].assert_trigger(protocol) except KeyError: return constants.StatusCode.error_invalid_object
def assert_trigger(self, session, protocol)
Asserts software or hardware trigger. Corresponds to viAssertTrigger function of the VISA library. :param session: Unique logical identifier to a session. :param protocol: Trigger protocol to use during assertion. (Constants.PROT*) :return: return value of the library call. :rt...
10.127504
6.620013
1.529831