signature
stringlengths
8
3.44k
body
stringlengths
0
1.41M
docstring
stringlengths
1
122k
id
stringlengths
5
17
def cvxEDA(eda, sampling_rate=<NUM_LIT:1000>, tau0=<NUM_LIT>, tau1=<NUM_LIT>, delta_knot=<NUM_LIT>, alpha=<NUM_LIT>, gamma=<NUM_LIT>, solver=None, verbose=False, options={'<STR_LIT>':<NUM_LIT>}):
frequency = <NUM_LIT:1>/sampling_rate<EOL>eda = z_score(eda)<EOL>eda = np.array(eda)[:,<NUM_LIT:0>]<EOL>n = len(eda)<EOL>eda = eda.astype('<STR_LIT>')<EOL>eda = cv.matrix(eda)<EOL>a1 = <NUM_LIT:1.>/min(tau1, tau0) <EOL>a0 = <NUM_LIT:1.>/max(tau1, tau0)<EOL>ar = np.array([(a1*frequency + <NUM_LIT>) * (a0*frequency + <NU...
A convex optimization approach to electrodermal activity processing (CVXEDA). This function implements the cvxEDA algorithm described in "cvxEDA: a Convex Optimization Approach to Electrodermal Activity Processing" (Greco et al., 2015). Parameters ---------- eda : list or array raw EDA signal array. samp...
f10896:m1
def eda_scr(signal, sampling_rate=<NUM_LIT:1000>, treshold=<NUM_LIT:0.1>, method="<STR_LIT>"):
<EOL>if method == "<STR_LIT>":<EOL><INDENT>gradient = np.gradient(signal)<EOL>size = int(<NUM_LIT:0.1> * sampling_rate)<EOL>smooth, _ = biosppy.tools.smoother(signal=gradient, kernel='<STR_LIT>', size=size, mirror=True)<EOL>zeros, = biosppy.tools.zero_cross(signal=smooth, detrend=True)<EOL>onsets = []<EOL>peaks = []<EO...
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" or "slow". Either use a gradient-based ...
f10896:m2
def eda_EventRelated(epoch, event_length, window_post=<NUM_LIT:4>):
<EOL>EDA_Response = {}<EOL>window_end = event_length + window_post<EOL>if epoch.index[-<NUM_LIT:1>]-event_length < <NUM_LIT:1>:<EOL><INDENT>print("<STR_LIT>" %(epoch.index[-<NUM_LIT:1>]-event_length))<EOL><DEDENT>if "<STR_LIT>" in epoch.columns:<EOL><INDENT>baseline = epoch["<STR_LIT>"][<NUM_LIT:0>:<NUM_LIT:1>].min()<E...
Extract event-related EDA and Skin Conductance Response (SCR). Parameters ---------- epoch : pandas.DataFrame An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :function:`neurokit.bio_process()`. Index must range from -4s to +4s (relatively to event onse...
f10896:m3
def emg_process(emg, sampling_rate=<NUM_LIT:1000>, emg_names=None, envelope_freqs=[<NUM_LIT:10>, <NUM_LIT>], envelope_lfreq=<NUM_LIT:4>, activation_treshold="<STR_LIT:default>", activation_n_above=<NUM_LIT>, activation_n_below=<NUM_LIT:1>):
if emg_names is None:<EOL><INDENT>if isinstance(emg, pd.DataFrame):<EOL><INDENT>emg_names = emg.columns.values<EOL><DEDENT><DEDENT>emg = np.array(emg)<EOL>if len(np.shape(emg)) == <NUM_LIT:1>:<EOL><INDENT>emg = np.array(pd.DataFrame(emg))<EOL><DEDENT>if emg_names is None:<EOL><INDENT>if np.shape(emg)[<NUM_LIT:1>]><NUM_...
Automated processing of EMG signal. Parameters ---------- emg : list, array or DataFrame EMG signal array. Can include multiple channels. sampling_rate : int Sampling rate (samples/second). emg_names : list List of EMG channel names. envelope_freqs : list [fc_h, fc_l], optional cutoff frequencies ...
f10897:m0
def emg_tkeo(emg):
emg = np.asarray(emg)<EOL>tkeo = np.copy(emg)<EOL>tkeo[<NUM_LIT:1>:-<NUM_LIT:1>] = emg[<NUM_LIT:1>:-<NUM_LIT:1>]*emg[<NUM_LIT:1>:-<NUM_LIT:1>] - emg[:-<NUM_LIT:2>]*emg[<NUM_LIT:2>:]<EOL>tkeo[<NUM_LIT:0>], tkeo[-<NUM_LIT:1>] = tkeo[<NUM_LIT:1>], tkeo[-<NUM_LIT:2>]<EOL>return(tkeo)<EOL>
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 notebook [1]_. References ---------- .. [1] https://gith...
f10897:m1
def emg_linear_envelope(emg, sampling_rate=<NUM_LIT:1000>, freqs=[<NUM_LIT:10>, <NUM_LIT>], lfreq=<NUM_LIT:4>):
emg = emg_tkeo(emg)<EOL>if np.size(freqs) == <NUM_LIT:2>:<EOL><INDENT>b, a = scipy.signal.butter(<NUM_LIT:2>, np.array(freqs)/(sampling_rate/<NUM_LIT>), btype = '<STR_LIT>')<EOL>emg = scipy.signal.filtfilt(b, a, emg)<EOL><DEDENT>if np.size(lfreq) == <NUM_LIT:1>:<EOL><INDENT>envelope = abs(emg)<EOL>b, a = scipy.signal.b...
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 ...
f10897:m2
def emg_find_activation(envelope, sampling_rate=<NUM_LIT:1000>, threshold=<NUM_LIT:0>, n_above=<NUM_LIT>, n_below=<NUM_LIT:1>):
n_above = n_above*sampling_rate<EOL>n_below = n_below*sampling_rate<EOL>envelope = np.atleast_1d(envelope).astype('<STR_LIT>')<EOL>envelope[np.isnan(envelope)] = -np.inf<EOL>inds = np.nonzero(envelope >= threshold)[<NUM_LIT:0>]<EOL>if inds.size:<EOL><INDENT>inds = np.vstack((inds[np.diff(np.hstack((-np.inf, inds))) > n...
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 ...
f10897:m3
def ecg_process(ecg, rsp=None, sampling_rate=<NUM_LIT:1000>, filter_type="<STR_LIT>", filter_band="<STR_LIT>", filter_frequency=[<NUM_LIT:3>, <NUM_LIT>], segmenter="<STR_LIT>", quality_model="<STR_LIT:default>", hrv_features=["<STR_LIT:time>", "<STR_LIT>"], age=None, sex=None, position=None):
<EOL>processed_ecg = ecg_preprocess(ecg,<EOL>sampling_rate=sampling_rate,<EOL>filter_type=filter_type,<EOL>filter_band=filter_band,<EOL>filter_frequency=filter_frequency,<EOL>segmenter=segmenter)<EOL>if quality_model is not None:<EOL><INDENT>quality = ecg_signal_quality(cardiac_cycles=processed_ecg["<STR_LIT>"]["<STR_L...
Automated processing of ECG and RSP signals. Parameters ---------- ecg : list or ndarray ECG signal array. rsp : list or ndarray Respiratory (RSP) signal array. sampling_rate : int Sampling rate (samples/second). filter_type : str Can be Finite Impulse Response filter ("FIR"), Butterworth filter ("butt...
f10898:m0
def ecg_rsa(rpeaks, rsp, sampling_rate=<NUM_LIT:1000>):
<EOL>rsp_cycles = rsp_find_cycles(rsp)<EOL>rsp_onsets = rsp_cycles["<STR_LIT>"]<EOL>rsp_cycle_center = rsp_cycles["<STR_LIT>"]<EOL>rsp_cycle_center = np.array(rsp_cycle_center)[rsp_cycle_center > rsp_onsets[<NUM_LIT:0>]]<EOL>if len(rsp_cycle_center) - len(rsp_onsets) == <NUM_LIT:0>:<EOL><INDENT>rsp_cycle_center = rsp_c...
Returns Respiratory Sinus Arrhythmia (RSA) features. Only the Peak-to-trough (P2T) algorithm is currently implemented (see details). Parameters ---------- rpeaks : list or ndarray List of R peaks indices. rsp : list or ndarray Filtered RSP signal. sampling_rate : int Sampling rate (samples/second). Retur...
f10898:m1
def ecg_signal_quality(cardiac_cycles, sampling_rate, rpeaks=None, quality_model="<STR_LIT:default>"):
if len(cardiac_cycles) > <NUM_LIT:200>:<EOL><INDENT>cardiac_cycles = cardiac_cycles.rolling(<NUM_LIT:20>).mean().resample("<STR_LIT>").pad()<EOL><DEDENT>if len(cardiac_cycles) < <NUM_LIT:200>:<EOL><INDENT>cardiac_cycles = cardiac_cycles.resample("<STR_LIT>").pad()<EOL>cardiac_cycles = cardiac_cycles.rolling(<NUM_LIT:20...
Attempt to find the recording lead and the overall and individual quality of heartbeats signal. Although used as a routine, this feature is experimental. Parameters ---------- cardiac_cycles : pd.DataFrame DataFrame containing heartbeats. Computed by :function:`neurokit.ecg_process`. sampling_rate : int Sampli...
f10898:m2
def ecg_hrv(rpeaks=None, rri=None, sampling_rate=<NUM_LIT:1000>, hrv_features=["<STR_LIT:time>", "<STR_LIT>", "<STR_LIT>"]):
<EOL>if rpeaks is None and rri is None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>if rpeaks is not None and rri is not None:<EOL><INDENT>raise ValueError("<STR_LIT>")<EOL><DEDENT>hrv = {}<EOL>if rpeaks is not None:<EOL><INDENT>RRis = np.diff(rpeaks)<EOL><DEDENT>else:<EOL><INDENT>RRis = rri<EOL><DEDENT>RRis ...
Computes the Heart-Rate Variability (HRV). Shamelessly stolen from the `hrv <https://github.com/rhenanbartels/hrv/blob/develop/hrv>`_ package by Rhenan Bartels. All credits go to him. Parameters ---------- rpeaks : list or ndarray R-peak location indices. rri: list or ndarray RR intervals in the signal. If thi...
f10898:m3
def ecg_hrv_assessment(hrv, age=None, sex=None, position=None):
hrv_adjusted = {}<EOL>if position == "<STR_LIT>":<EOL><INDENT>if sex == "<STR_LIT:m>":<EOL><INDENT>if age <= <NUM_LIT>:<EOL><INDENT>hrv_adjusted["<STR_LIT>"] = (hrv["<STR_LIT>"]-<NUM_LIT>)/<NUM_LIT><EOL>hrv_adjusted["<STR_LIT>"] = (hrv["<STR_LIT>"]-<NUM_LIT>)/<NUM_LIT><EOL>hrv_adjusted["<STR_LIT>"] = (hrv["<STR_LIT>"]-...
Correct HRV features based on normative data from Voss et al. (2015). Parameters ---------- hrv : dict HRV features obtained by :function:`neurokit.ecg_hrv`. age : float Subject's age. sex : str Subject's gender ("m" or "f"). position : str Recording position. To compare with data from Voss et al. (201...
f10898:m4
def ecg_EventRelated(epoch, event_length=<NUM_LIT:1>, window_post=<NUM_LIT:0>, features=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]):
def compute_features(variable, prefix, response):<EOL><INDENT>"""<STR_LIT>"""<EOL>response[prefix + "<STR_LIT>"] = epoch[variable][<NUM_LIT:0>]<EOL>response[prefix + "<STR_LIT>"] = epoch[variable][<NUM_LIT:0>:window_end].min()<EOL>response[prefix + "<STR_LIT>"] = response[prefix + "<STR_LIT>"] - response[prefix + "<STR...
Extract event-related ECG changes. Parameters ---------- epoch : pandas.DataFrame An epoch contained in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :function:`neurokit.bio_process()`. Index should range from -4s to +4s (relatively to event onset and end). event_length ...
f10898:m5
def ecg_simulate(duration=<NUM_LIT:10>, sampling_rate=<NUM_LIT:1000>, bpm=<NUM_LIT>, noise=<NUM_LIT>):
<EOL>cardiac = scipy.signal.wavelets.daub(<NUM_LIT:10>)<EOL>cardiac = np.concatenate([cardiac, np.zeros(<NUM_LIT:10>)])<EOL>num_heart_beats = int(duration * bpm / <NUM_LIT>)<EOL>ecg = np.tile(cardiac , num_heart_beats)<EOL>noise = np.random.normal(<NUM_LIT:0>, noise, len(ecg))<EOL>ecg = noise + ecg<EOL>ecg = scipy.sign...
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 Event-related ECG response features. Example ------...
f10898:m6
def read_acqknowledge(filename, path="<STR_LIT>", index="<STR_LIT>", sampling_rate="<STR_LIT>", resampling_method="<STR_LIT>", fill_interruptions=True, return_sampling_rate=True):
<EOL>file = path + filename<EOL>if "<STR_LIT>" not in file:<EOL><INDENT>file += "<STR_LIT>"<EOL><DEDENT>if os.path.exists(file) is False:<EOL><INDENT>print("<STR_LIT>" + filename)<EOL>return()<EOL><DEDENT>creation_date = find_creation_date(file)<EOL>creation_date = datetime.datetime.fromtimestamp(creation_date)<EOL>fil...
Read and Format a BIOPAC's AcqKnowledge file into a pandas' dataframe. Parameters ---------- filename : str Filename (with or without the extension) of a BIOPAC's AcqKnowledge file. path : str Data directory. index : str How to index the dataframe. "datetime" for aproximate datetime (based on the file cre...
f10899:m0
def rsp_process(rsp, sampling_rate=<NUM_LIT:1000>):
processed_rsp = {"<STR_LIT>": pd.DataFrame({"<STR_LIT>": np.array(rsp)})}<EOL>biosppy_rsp = dict(biosppy.signals.resp.resp(rsp, sampling_rate=sampling_rate, show=False))<EOL>processed_rsp["<STR_LIT>"]["<STR_LIT>"] = biosppy_rsp["<STR_LIT>"]<EOL>RSP Rate<EOL>============<EOL>rsp_rate = biosppy_rsp["<STR_LIT>"]*<NUM_LIT>...
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 RSP raw signal, the filtered signal, the resp...
f10900:m0
def rsp_find_cycles(signal):
<EOL>gradient = np.gradient(signal)<EOL>zeros, = biosppy.tools.zero_cross(signal=gradient, detrend=True)<EOL>phases_indices = []<EOL>for i in zeros:<EOL><INDENT>if gradient[i+<NUM_LIT:1>] > gradient[i-<NUM_LIT:1>]:<EOL><INDENT>phases_indices.append("<STR_LIT>")<EOL><DEDENT>else:<EOL><INDENT>phases_indices.append("<STR_...
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_cycles = nk.rsp_find_cycles(signal) Notes -------...
f10900:m1
def rsp_EventRelated(epoch, event_length, window_post=<NUM_LIT:4>):
<EOL>RSP_Response = {}<EOL>window_end = event_length + window_post<EOL>if "<STR_LIT>" in epoch.columns:<EOL><INDENT>RSP_Response["<STR_LIT>"] = epoch["<STR_LIT>"].ix[<NUM_LIT:0>]<EOL>RSP_Response["<STR_LIT>"] = epoch["<STR_LIT>"].ix[<NUM_LIT:0>:window_end].min()<EOL>RSP_Response["<STR_LIT>"] = RSP_Response["<STR_LIT>"]...
Extract event-related respiratory (RSP) changes. Parameters ---------- epoch : pandas.DataFrame An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :function:`neurokit.bio_process()`. event_length : int In seconds. sampling_rate : int Sampling rate...
f10900:m2
def bio_process(ecg=None, rsp=None, eda=None, emg=None, add=None, sampling_rate=<NUM_LIT:1000>, age=None, sex=None, position=None, ecg_filter_type="<STR_LIT>", ecg_filter_band="<STR_LIT>", ecg_filter_frequency=[<NUM_LIT:3>, <NUM_LIT>], ecg_segmenter="<STR_LIT>", ecg_quality_model="<STR_LIT:default>", ecg_hrv_features=[...
processed_bio = {}<EOL>bio_df = pd.DataFrame({})<EOL>if ecg is not None:<EOL><INDENT>ecg = ecg_process(ecg=ecg, rsp=rsp, sampling_rate=sampling_rate, filter_type=ecg_filter_type, filter_band=ecg_filter_band, filter_frequency=ecg_filter_frequency, segmenter=ecg_segmenter, quality_model=ecg_quality_model, hrv_features=ec...
Automated processing of bio signals. Wrapper for other bio processing functions. Parameters ---------- ecg : list or array ECG signal array. rsp : list or array Respiratory signal array. eda : list or array EDA signal array. emg : list, array or DataFrame EMG signal array. Can include multiple channe...
f10901:m0
def bio_EventRelated(epoch, event_length, window_post_ecg=<NUM_LIT:0>, window_post_rsp=<NUM_LIT:4>, window_post_eda=<NUM_LIT:4>, ecg_features=["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]):
bio_response = {}<EOL>ECG_Response = ecg_EventRelated(epoch, event_length, window_post=window_post_ecg, features=ecg_features)<EOL>bio_response.update(ECG_Response)<EOL>RSP_Response = rsp_EventRelated(epoch, event_length, window_post=window_post_rsp)<EOL>bio_response.update(RSP_Response)<EOL>EDA_Response = eda_EventRel...
Extract event-related bio (EDA, ECG and RSP) changes. Parameters ---------- epoch : pandas.DataFrame An epoch contains in the epochs dict returned by :function:`neurokit.create_epochs()` on dataframe returned by :function:`neurokit.bio_process()`. event_length : int In seconds. sampling_rate : int Sampling...
f10901:m1
def ecg_preprocess(ecg, sampling_rate=<NUM_LIT:1000>, filter_type="<STR_LIT>", filter_band="<STR_LIT>", filter_frequency=[<NUM_LIT:3>, <NUM_LIT>], filter_order=<NUM_LIT>, segmenter="<STR_LIT>"):
<EOL>ecg = np.array(ecg)<EOL>if filter_type in ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]:<EOL><INDENT>order = int(filter_order * sampling_rate)<EOL>filtered, _, _ = biosppy.tools.filter_signal(signal=ecg,<EOL>ftype=filter_type,<EOL>band=filter_band,<EOL>order=order,<EOL>frequency=fi...
ECG signal preprocessing. Parameters ---------- ecg : list or ndarray ECG signal array. sampling_rate : int Sampling rate (samples/second). filter_type : str or None Can be Finite Impulse Response filter ("FIR"), Butterworth filter ("butter"), Chebyshev filters ("cheby1" and "cheby2"), Elliptic filter ("el...
f10903:m0
def ecg_find_peaks(signal, sampling_rate=<NUM_LIT:1000>):
rpeaks, = biosppy.ecg.hamilton_segmenter(np.array(signal), sampling_rate=sampling_rate)<EOL>rpeaks, = biosppy.ecg.correct_rpeaks(signal=np.array(signal), rpeaks=rpeaks, sampling_rate=sampling_rate, tol=<NUM_LIT>)<EOL>return(rpeaks)<EOL>
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 ---------- >>> import neurokit as nk >>> Rpeaks = nk.ec...
f10903:m1
def ecg_wave_detector(ecg, rpeaks):
q_waves = []<EOL>p_waves = []<EOL>q_waves_starts = []<EOL>s_waves = []<EOL>t_waves = []<EOL>t_waves_starts = []<EOL>t_waves_ends = []<EOL>for index, rpeak in enumerate(rpeaks[:-<NUM_LIT:3>]):<EOL><INDENT>try:<EOL><INDENT>epoch_before = np.array(ecg)[int(rpeaks[index-<NUM_LIT:1>]):int(rpeak)]<EOL>epoch_before = epoch_be...
Returns the localization of the P, Q, T waves. This function needs massive help! Parameters ---------- ecg : list or ndarray ECG signal (preferably filtered). rpeaks : list or ndarray R peaks localization. Returns ---------- ecg_waves : dict Contains wave peaks location indices. Example ---------- >>> im...
f10903:m2
def ecg_systole(ecg, rpeaks, t_waves_ends):
waves = np.array(["<STR_LIT>"]*len(ecg))<EOL>waves[rpeaks] = "<STR_LIT:R>"<EOL>waves[t_waves_ends] = "<STR_LIT:T>"<EOL>systole = [<NUM_LIT:0>]<EOL>current = <NUM_LIT:0><EOL>for index, value in enumerate(waves[<NUM_LIT:1>:]):<EOL><INDENT>if waves[index-<NUM_LIT:1>] == "<STR_LIT:R>":<EOL><INDENT>current = <NUM_LIT:1><EOL...
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 : ndarray Array indicating where systole (1) ...
f10903:m3
def segmenter_pekkanen(ecg, sampling_rate, window_size=<NUM_LIT>, lfreq=<NUM_LIT>, hfreq=<NUM_LIT>):
window_size = int(window_size*sampling_rate)<EOL>lowpass = scipy.signal.butter(<NUM_LIT:1>, hfreq/(sampling_rate/<NUM_LIT>), '<STR_LIT>')<EOL>highpass = scipy.signal.butter(<NUM_LIT:1>, lfreq/(sampling_rate/<NUM_LIT>), '<STR_LIT>')<EOL>ecg_low = scipy.signal.filtfilt(*lowpass, x=ecg)<EOL>ecg_band = scipy.signal.filtfil...
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 : int Sampling ra...
f10903:m4
def mad(var, constant=<NUM_LIT:1>):
median = np.median(var)<EOL>mad = np.median(np.abs(var - median))<EOL>mad = mad*constant<EOL>return(mad)<EOL>
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 ---------- >>> import neurokit as nk >>> hrv = nk.mad([...
f10904:m0
def z_score(raw_scores, center=True, scale=True):
df = pd.DataFrame(raw_scores)<EOL>mean = df.mean(axis=<NUM_LIT:0>)<EOL>sd = df.std(axis=<NUM_LIT:0>)<EOL>z_scores = (df - mean)/sd<EOL>return(z_scores)<EOL>
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 ---------- z_scores : pandas.DataFrame The norm...
f10904:m1
def find_outliers(data, treshold=<NUM_LIT>):
outliers = []<EOL>mean = np.mean(data)<EOL>std = np.std(data)<EOL>for i in data:<EOL><INDENT>if abs(i - mean)/std < treshold:<EOL><INDENT>outliers.append(False)<EOL><DEDENT>else:<EOL><INDENT>outliers.append(True)<EOL><DEDENT><DEDENT>outliers = np.array(outliers)<EOL>return (outliers)<EOL>
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% and 1.28 = rejecting 10%. ...
f10904:m2
def normal_range(mean, sd, treshold=<NUM_LIT>):
bottom = mean - sd*treshold<EOL>top = mean + sd*treshold<EOL>return(bottom, top)<EOL>
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%. Returns ---------- ...
f10904:m3
def find_following_duplicates(array):
array = array[:]<EOL>uniques = []<EOL>for i in range(len(array)):<EOL><INDENT>if i == <NUM_LIT:0>:<EOL><INDENT>uniques.append(True)<EOL><DEDENT>else:<EOL><INDENT>if array[i] == array[i-<NUM_LIT:1>]:<EOL><INDENT>uniques.append(False)<EOL><DEDENT>else:<EOL><INDENT>uniques.append(True)<EOL><DEDENT><DEDENT><DEDENT>return(u...
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 ---------- >>> import neurokit as nk >>> mylist = ["a","a","b","...
f10904:m4
def find_closest_in_list(number, array, direction="<STR_LIT>", strictly=False):
if direction == "<STR_LIT>":<EOL><INDENT>closest = min(array, key=lambda x:abs(x-number))<EOL><DEDENT>if direction == "<STR_LIT>":<EOL><INDENT>if strictly is True:<EOL><INDENT>closest = max(x for x in array if x < number)<EOL><DEDENT>else:<EOL><INDENT>closest = max(x for x in array if x <= number)<EOL><DEDENT><DEDENT>i...
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 False for stricly superior or inferior...
f10904:m5
def plot_polarbar(scores, labels=None, labels_size=<NUM_LIT:15>, colors="<STR_LIT:default>", distribution_means=None, distribution_sds=None, treshold=<NUM_LIT>, fig_size=(<NUM_LIT:15>, <NUM_LIT:15>)):
<EOL>if isinstance(scores, dict):<EOL><INDENT>if labels is None:<EOL><INDENT>labels = list(scores.keys())<EOL><DEDENT>try:<EOL><INDENT>scores = [scores[key] for key in labels]<EOL><DEDENT>except KeyError:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT>if colors == "<STR_LIT:default>":<EOL><INDENT>if len(scores) < <...
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 means to add a range ribbon. distribution_sds : ...
f10905:m0
def compute_dprime(n_Hit=None, n_Miss=None, n_FA=None, n_CR=None):
<EOL>hit_rate = n_Hit/(n_Hit + n_Miss)<EOL>fa_rate = n_FA/(n_FA + n_CR)<EOL>hit_rate_adjusted = (n_Hit+ <NUM_LIT:0.5>)/((n_Hit+ <NUM_LIT:0.5>) + n_Miss + <NUM_LIT:1>)<EOL>fa_rate_adjusted = (n_FA+ <NUM_LIT:0.5>)/((n_FA+ <NUM_LIT:0.5>) + n_CR + <NUM_LIT:1>)<EOL>dprime = scipy.stats.norm.ppf(hit_rate_adjusted) - scipy.st...
Computes the d', beta, aprime, b''d and c parameters based on the signal detection theory (SDT). **Feel free to help me expand the documentation of this function with details and interpretation guides.** Parameters ---------- n_Hit : int Number of hits. n_Miss : int Number of misses. n_FA : int Number of f...
f10907:m0
def compute_BMI(height, weight, age, sex):
<EOL>height = height/<NUM_LIT:100><EOL>bmi = {}<EOL>bmi["<STR_LIT>"] = weight/(height**<NUM_LIT:2>)<EOL>bmi["<STR_LIT>"] = <NUM_LIT>*weight/height**<NUM_LIT><EOL>if bmi["<STR_LIT>"] < <NUM_LIT:15>:<EOL><INDENT>bmi["<STR_LIT>"] = "<STR_LIT>"<EOL><DEDENT>if <NUM_LIT:15> < bmi["<STR_LIT>"] < <NUM_LIT:16>:<EOL><INDENT>bmi[...
Returns the traditional BMI, the 'new' Body Mass Index and estimates the Body Fat Percentage (BFP; Deurenberg et al., 1991). Parameters ---------- height : float Height in cm. weight : float Weight in kg. age : float Age in years. sex : str "m" or "f". Returns ---------- bmi : dict dict containing...
f10907:m1
def compute_interoceptive_accuracy(nbeats_real, nbeats_reported):
<EOL>if isinstance(nbeats_real, list):<EOL><INDENT>nbeats_real = np.array(nbeats_real)<EOL>nbeats_reported = np.array(nbeats_reported)<EOL><DEDENT>accuracy = <NUM_LIT:1> - (abs(nbeats_real-nbeats_reported))/((nbeats_real+nbeats_reported)/<NUM_LIT:2>)<EOL>return(accuracy)<EOL>
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 accuracy in detecting internal bodily sensati...
f10907:m2
def __init__(self, signal=[<NUM_LIT:0>, <NUM_LIT:100>], treshold=<NUM_LIT>, burn=<NUM_LIT:5>, stop_n_inversions=False, prior_signal=[], prior_response=[]):
self.treshold = treshold<EOL>self.signal_min = np.min(signal)<EOL>self.signal_max = np.max(signal)<EOL>self.signal_range = self.signal_max - self.signal_min<EOL>if len(signal) == <NUM_LIT:2>:<EOL><INDENT>self.signal = pd.DataFrame({"<STR_LIT>":np.linspace(self.signal_min, self.signal_max, <NUM_LIT:1000>)})<EOL><DEDENT>...
Staircase procedure handler to find a treshold. For now, using a GLM - likelihood method. Parameters ---------- signal : list Either list with min or max or range of possible signal values. treshold : int or list Treshold (between 0 and 1) to look for. burn : int or list Signal values to try at the beginni...
f10907:c0:m0
def add_response(self, response, value):
if value != "<STR_LIT>":<EOL><INDENT>self.X = pd.concat([self.X, pd.DataFrame({"<STR_LIT>":[value]})])<EOL>self.y = np.array(list(self.y) + [response])<EOL>if len(set(list(self.y))) > <NUM_LIT:1>:<EOL><INDENT>self.model = self.fit_model(self.X , self.y)<EOL><DEDENT><DEDENT>
Add response to staircase. Parameters ---------- response : int or bool 0 or 1. value : int or float Signal corresponding to response.
f10907:c0:m3
def save_nk_object(obj, filename="<STR_LIT:file>", path="<STR_LIT>", extension="<STR_LIT>", compress=False, compatibility=-<NUM_LIT:1>):
if compress is True:<EOL><INDENT>with gzip.open(path + filename + "<STR_LIT:.>" + extension, '<STR_LIT:wb>') as name:<EOL><INDENT>pickle.dump(obj, name, protocol=compatibility)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>with open(path + filename + "<STR_LIT:.>" + extension, '<STR_LIT:wb>') as name:<EOL><INDENT>pickle.dump(o...
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 Enable compression using gzip. compatibi...
f10908:m0
def read_nk_object(filename, path="<STR_LIT>"):
filename = path + filename<EOL>try:<EOL><INDENT>with open(filename, '<STR_LIT:rb>') as name:<EOL><INDENT>file = pickle.load(name)<EOL><DEDENT><DEDENT>except pickle.UnpicklingError:<EOL><INDENT>with gzip.open(filename, '<STR_LIT:rb>') as name:<EOL><INDENT>file = pickle.load(name)<EOL><DEDENT><DEDENT>except ModuleNotFoun...
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("myobject.nk") Notes ---------- *Authors* - `D...
f10908:m1
def find_creation_date(path):
if platform.system() == '<STR_LIT>':<EOL><INDENT>return(os.path.getctime(path))<EOL><DEDENT>else:<EOL><INDENT>stat = os.stat(path)<EOL>try:<EOL><INDENT>return(stat.st_birthtime)<EOL><DEDENT>except AttributeError:<EOL><INDENT>print("<STR_LIT>")<EOL>return(stat.st_mtime)<EOL><DEDENT><DEDENT>
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 >>> import datetime >>> >>> creation_date = n...
f10908:m2
def reset(self):
self.clock = builtin_time.clock()<EOL>
Reset the clock of the Time object. Parameters ---------- None Returns ---------- None Example ---------- >>> import neurokit as nk >>> time_passed_since_neuropsydia_loading = nk.time.get() >>> nk.time.reset() >>> time_passed_since_reset = nk.time.get() Notes ---------- *Authors* - `Dominique Makowski <https://dom...
f10910:c0:m1
def get(self, reset=True):
t = (builtin_time.clock()-self.clock)*<NUM_LIT:1000><EOL>if reset is True:<EOL><INDENT>self.reset()<EOL><DEDENT>return(t)<EOL>
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 neurokit as nk >>> time_passed_since_neurobox_loading = nk.time.get() >>> nk.time.reset(...
f10910:c0:m2
def eeg_add_channel(raw, channel, sync_index_eeg=<NUM_LIT:0>, sync_index_channel=<NUM_LIT:0>, channel_type=None, channel_name=None):
if channel_name is None:<EOL><INDENT>if isinstance(channel, pd.core.series.Series):<EOL><INDENT>if channel.name is not None:<EOL><INDENT>channel_name = channel.name<EOL><DEDENT>else:<EOL><INDENT>channel_name = "<STR_LIT>"<EOL><DEDENT><DEDENT>else:<EOL><INDENT>channel_name = "<STR_LIT>"<EOL><DEDENT><DEDENT>diff = sync_i...
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 An index, in the raw data, by ...
f10912:m0
def eeg_select_channels(raw, channel_names):
if isinstance(channel_names, list) is False:<EOL><INDENT>channel_names = [channel_names]<EOL><DEDENT>channels, time_index = raw.copy().pick_channels(channel_names)[:]<EOL>if len(channel_names) > <NUM_LIT:1>:<EOL><INDENT>channels = pd.DataFrame(channels.T, columns=channel_names)<EOL><DEDENT>else:<EOL><INDENT>channels = ...
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 neurokit as nk >>> raw = nk.eeg_select_channel(raw,...
f10912:m1
def eeg_select_electrodes(eeg, include="<STR_LIT:all>", exclude=None, hemisphere="<STR_LIT>", central=True):
<EOL>eeg = eeg.copy().pick_types(meg=False, eeg=True)<EOL>channel_list = eeg.ch_names<EOL>if include == "<STR_LIT:all>":<EOL><INDENT>electrodes = channel_list<EOL><DEDENT>elif isinstance(include, str):<EOL><INDENT>electrodes = [s for s in channel_list if include in s]<EOL><DEDENT>elif isinstance(include, list):<EOL><IN...
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 Select both hemispheres? "both", "left...
f10912:m2
def eeg_create_mne_events(onsets, conditions=None):
event_id = {}<EOL>if conditions is None:<EOL><INDENT>conditions = ["<STR_LIT>"] * len(onsets)<EOL><DEDENT>if len(conditions) != len(onsets):<EOL><INDENT>print("<STR_LIT>")<EOL>return()<EOL><DEDENT>event_names = list(set(conditions))<EOL><INDENT>event_index = [<NUM_LIT:1>, <NUM_LIT:2>, <NUM_LIT:3>, <NUM_LIT:4>, <NUM_LIT...
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's names. Example ---------- >>> import...
f10912:m3
def eeg_add_events(raw, events_channel, conditions=None, treshold="<STR_LIT>", cut="<STR_LIT>", time_index=None, number="<STR_LIT:all>", after=<NUM_LIT:0>, before=None, min_duration=<NUM_LIT:1>):
<EOL>if isinstance(events_channel, str):<EOL><INDENT>try:<EOL><INDENT>events_channel = eeg_select_channels(raw, events_channel)<EOL><DEDENT>except:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT><DEDENT>events = find_events(events_channel, treshold=treshold, cut=cut, time_index=time_index, number=number, after=after, befor...
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. conditions : list List containin...
f10912:m4
def eeg_to_all_evokeds(all_epochs, conditions=None):
if conditions is None:<EOL><INDENT>conditions = {}<EOL>for participant, epochs in all_epochs.items():<EOL><INDENT>conditions.update(epochs.event_id)<EOL><DEDENT><DEDENT>all_evokeds = {}<EOL>for participant, epochs in all_epochs.items():<EOL><INDENT>evokeds = {}<EOL>for cond in conditions:<EOL><INDENT>try:<EOL><INDENT>e...
Convert all_epochs to all_evokeds. DOCS INCOMPLETE :(
f10912:m5
def eeg_to_df(eeg, index=None, include="<STR_LIT:all>", exclude=None, hemisphere="<STR_LIT>", central=True):
if isinstance(eeg, mne.Epochs):<EOL><INDENT>data = {}<EOL>if index is None:<EOL><INDENT>index = range(len(eeg))<EOL><DEDENT>for epoch_index, epoch in zip(index, eeg.get_data()):<EOL><INDENT>epoch = pd.DataFrame(epoch.T)<EOL>epoch.columns = eeg.ch_names<EOL>epoch.index = eeg.times<EOL>selection = eeg_select_electrodes(e...
Convert mne Raw or Epochs object to dataframe or dict of dataframes. DOCS INCOMPLETE :(
f10912:m6
def eeg_erp(eeg, times=None, index=None, include="<STR_LIT:all>", exclude=None, hemisphere="<STR_LIT>", central=True, verbose=True, names="<STR_LIT>", method="<STR_LIT>"):
erp = {}<EOL>data = eeg_to_df(eeg, index=index, include=include, exclude=exclude, hemisphere=hemisphere, central=central)<EOL>for epoch_index, epoch in data.items():<EOL><INDENT>if isinstance(times, list):<EOL><INDENT>if isinstance(times[<NUM_LIT:0>], list):<EOL><INDENT>values = {}<EOL>for window_index, window in enume...
DOCS INCOMPLETE :(
f10914:m0
def plot_eeg_erp(all_epochs, conditions=None, times=None, include="<STR_LIT:all>", exclude=None, hemisphere="<STR_LIT>", central=True, name=None, colors=None, gfp=False, ci=<NUM_LIT>, ci_alpha=<NUM_LIT>, invert_y=False, linewidth=<NUM_LIT:1>, linestyle="<STR_LIT:->", filter_hfreq=None):
<EOL>all_epochs_current = all_epochs.copy()<EOL>if (filter_hfreq is not None) and (isinstance(filter_hfreq, int)):<EOL><INDENT>for participant, epochs in all_epochs_current.items():<EOL><INDENT>all_epochs_current[participant] = epochs.savgol_filter(filter_hfreq, copy=True)<EOL><DEDENT><DEDENT>if isinstance(times, list)...
DOCS INCOMPLETE :(
f10914:m1
def plot_eeg_erp_topo(all_epochs, colors=None):
all_evokeds = eeg_to_all_evokeds(all_epochs)<EOL>data = {}<EOL>for participant, epochs in all_evokeds.items():<EOL><INDENT>for cond, epoch in epochs.items():<EOL><INDENT>data[cond] = []<EOL><DEDENT><DEDENT>for participant, epochs in all_evokeds.items():<EOL><INDENT>for cond, epoch in epochs.items():<EOL><INDENT>data[co...
Plot butterfly plot. DOCS INCOMPLETE :(
f10914:m2
def eeg_complexity(eeg, sampling_rate, times=None, index=None, include="<STR_LIT:all>", exclude=None, hemisphere="<STR_LIT>", 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, ...
data = eeg_to_df(eeg, index=index, include=include, exclude=exclude, hemisphere=hemisphere, central=central)<EOL>if isinstance(data, dict) is False:<EOL><INDENT>data = {<NUM_LIT:0>: data}<EOL><DEDENT>if isinstance(times, tuple):<EOL><INDENT>times = list(times)<EOL><DEDENT>if isinstance(times, list):<EOL><INDENT>if isin...
Compute complexity indices of epochs or raw object. DOCS INCOMPLETE :(
f10915:m0
def eeg_name_frequencies(freqs):
freqs = list(freqs)<EOL>freqs_names = []<EOL>for freq in freqs:<EOL><INDENT>if freq < <NUM_LIT:1>:<EOL><INDENT>freqs_names.append("<STR_LIT>")<EOL><DEDENT>elif freq <= <NUM_LIT:3>:<EOL><INDENT>freqs_names.append("<STR_LIT>")<EOL><DEDENT>elif freq <= <NUM_LIT:7>:<EOL><INDENT>freqs_names.append("<STR_LIT>")<EOL><DEDENT>e...
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 >>> >>> nk.eeg_name_frequencies([0.5, 1.5, 3, 5, 7,...
f10917:m0
def eeg_psd(raw, sensors_include="<STR_LIT:all>", sensors_exclude=None, fmin=<NUM_LIT>, fmax=<NUM_LIT>, method="<STR_LIT>", proj=False):
picks = mne.pick_types(raw.info, include=eeg_select_electrodes(include=sensors_include, exclude=sensors_exclude), exclude="<STR_LIT>")<EOL>if method == "<STR_LIT>":<EOL><INDENT>psds, freqs = mne.time_frequency.psd_multitaper(raw,<EOL>fmin=fmin,<EOL>fmax=fmax,<EOL>low_bias=True,<EOL>proj=proj,<EOL>picks=picks)<EOL><DEDE...
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()`. fmin : float Min frequency of inte...
f10917:m1
def eeg_create_frequency_bands(bands="<STR_LIT:all>", step=<NUM_LIT:1>):
if bands == "<STR_LIT:all>" or bands == "<STR_LIT>":<EOL><INDENT>bands = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in bands:<EOL><INDENT>bands.remove("<STR_LIT>")<EOL>bands += ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>if "<STR_LIT>" in bands:<EOL><INDENT>band...
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
f10917:m2
def eeg_gfp_peaks(data, gflp_method='<STR_LIT>', smoothing=False, smoothing_window=<NUM_LIT:100>, peak_method="<STR_LIT>", normalize=False):
ntf = data.shape[<NUM_LIT:0>]<EOL>gfp_curve = np.zeros((ntf, ))<EOL>if gflp_method == '<STR_LIT>':<EOL><INDENT>for i in range(ntf):<EOL><INDENT>x = data[i,:]<EOL>gfp_curve[i] = np.sqrt(np.sum((x - x.mean())**<NUM_LIT:2> / len(x) ))<EOL><DEDENT><DEDENT>elif gflp_method == '<STR_LIT>':<EOL><INDENT>for i in range(ntf):<EO...
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...
f10918:m0
def eeg_gfp(raws, gflp_method="<STR_LIT>", scale=True, normalize=True, smoothing=None):
<EOL><INDENT>if isinstance(raws, str):<EOL><INDENT>raws = load_object(filename=raws)<EOL><DEDENT><DEDENT>gfp = {}<EOL>for participant in raws:<EOL><INDENT>gfp[participant] = {}<EOL>for run in raws[participant]:<EOL><INDENT>gfp[participant][run] = {}<EOL>raw = raws[participant][run].copy()<EOL>if True in set(["<STR_LIT>...
Run the GFP analysis.
f10918:m1
def eeg_microstates_clustering(data, n_microstates=<NUM_LIT:4>, clustering_method="<STR_LIT>", n_jobs=<NUM_LIT:1>, n_init=<NUM_LIT>, occurence_rejection_treshold=<NUM_LIT>, max_refitting=<NUM_LIT:5>, verbose=True):
<EOL>training_set = data.copy()<EOL>if verbose is True:<EOL><INDENT>print("<STR_LIT>")<EOL><DEDENT>if clustering_method == "<STR_LIT>":<EOL><INDENT>algorithm = sklearn.cluster.KMeans(init='<STR_LIT>', n_clusters=n_microstates, n_init=n_init, n_jobs=n_jobs)<EOL><DEDENT>elif clustering_method == "<STR_LIT>":<EOL><INDENT>...
Fit the clustering algorithm.
f10918:m2
def eeg_microstates_features(results, method, ecg=True, nonlinearity=True, verbose=True):
for participant in results:<EOL><INDENT>for run in results[participant]:<EOL><INDENT>if verbose is True:<EOL><INDENT>print("<STR_LIT>" + participant)<EOL><DEDENT>occurences = dict(collections.Counter(results[participant][run]["<STR_LIT>"]))<EOL>if nonlinearity is True:<EOL><INDENT>results[participant][run]["<STR_LIT>"]...
Compute statistics and features for/of the microstates.
f10918:m3
def eeg_microstates(gfp, n_microstates=<NUM_LIT:4>, clustering_method="<STR_LIT>", n_jobs=<NUM_LIT:1>, n_init=<NUM_LIT>, occurence_rejection_treshold=<NUM_LIT>, max_refitting=<NUM_LIT:5>, clustering_metrics=True, good_fit_treshold=<NUM_LIT:0>, feature_reduction_method="<STR_LIT>", n_features=<NUM_LIT:32>, nonlinearity=...
<EOL><INDENT>if verbose is True:<EOL><INDENT>print("""<STR_LIT>""")<EOL><DEDENT>method = {}<EOL>data_all = []<EOL>for participant in results:<EOL><INDENT>for run in results[participant]:<EOL><INDENT>data_all.append(results[participant][run]["<STR_LIT:data>"])<EOL>method["<STR_LIT>"] = results[participant][run]["<STR_LI...
Run the full microstates analysis. Parameters ---------- raws = dict Two levels dictionary containing the participants, within which the run(s), associated with an mne.io.Raw class object. method ({'GFPL1', 'GFPL2'}): `GFPL1` : use L1-Norm to compute GFP peaks `GFPL2` : use L2-Norm to compute GFP peaks smo...
f10918:m4
def eeg_microstates_plot(method, path="<STR_LIT>", extension="<STR_LIT>", show_sensors_position=False, show_sensors_name=False, plot=True, save=True, dpi=<NUM_LIT>, contours=<NUM_LIT:0>, colorbar=False, separate=False):
<EOL>figures = []<EOL>names = []<EOL>try:<EOL><INDENT>microstates = method["<STR_LIT>"]<EOL><DEDENT>except KeyError:<EOL><INDENT>microstates = method["<STR_LIT>"]<EOL><DEDENT>for microstate in set(microstates):<EOL><INDENT>if microstate != "<STR_LIT>":<EOL><INDENT>values = np.mean(method["<STR_LIT:data>"][np.where(micr...
Plot the microstates.
f10918:m5
def eeg_microstates_relabel(method, results, microstates_labels, reverse_microstates=None):
microstates = list(method['<STR_LIT>'])<EOL>for index, microstate in enumerate(method['<STR_LIT>']):<EOL><INDENT>if microstate in list(reverse_microstates.keys()):<EOL><INDENT>microstates[index] = reverse_microstates[microstate]<EOL>method["<STR_LIT:data>"][index] = -<NUM_LIT:1>*method["<STR_LIT:data>"][index]<EOL><DED...
Relabel the microstates.
f10918:m6
def feature_reduction(data, method, n_features):
if method == "<STR_LIT>":<EOL><INDENT>feature_red_method = sklearn.decomposition.PCA(n_components=n_features)<EOL>data_processed = feature_red_method.fit_transform(data)<EOL><DEDENT>elif method == "<STR_LIT>":<EOL><INDENT>feature_red_method = sklearn.cluster.FeatureAgglomeration(n_clusters=n_features)<EOL>data_processe...
Feature reduction. Parameters ---------- NA Returns ---------- NA Example ---------- NA Authors ---------- Dominique Makowski Dependencies ---------- - sklearn
f10919:m0
def __aiter__(self):
return self<EOL>
We are our own iterator.
f10931:c0:m1
@asyncio.coroutine<EOL><INDENT>def __anext__(self):<DEDENT>
line = yield from self.readline()<EOL>if line:<EOL><INDENT>return line<EOL><DEDENT>else:<EOL><INDENT>raise StopAsyncIteration<EOL><DEDENT>
Simulate normal file iteration.
f10931:c0:m2
@asyncio.coroutine<EOL>def _open(file, mode='<STR_LIT:r>', buffering=-<NUM_LIT:1>, encoding=None, errors=None, newline=None,<EOL>closefd=True, opener=None, *, loop=None, executor=None):
if loop is None:<EOL><INDENT>loop = asyncio.get_event_loop()<EOL><DEDENT>cb = partial(sync_open, file, mode=mode, buffering=buffering,<EOL>encoding=encoding, errors=errors, newline=newline,<EOL>closefd=closefd, opener=opener)<EOL>f = yield from loop.run_in_executor(executor, cb)<EOL>return wrap(f, loop=loop, executor=e...
Open an asyncio file.
f10934:m1
def price_str(raw_price, default=_not_defined, dec_point='<STR_LIT:.>'):
def _error_or_default(err_msg):<EOL><INDENT>if default == _not_defined:<EOL><INDENT>raise ValueError(err_msg)<EOL><DEDENT>return default<EOL><DEDENT>if not isinstance(raw_price, str):<EOL><INDENT>return _error_or_default(<EOL>'<STR_LIT>'<EOL>'<STR_LIT>'.format(price_type=type(raw_price)))<EOL><DEDENT>price = re.sub('<S...
Search and clean price value. Convert raw price string presented in any localization as a valid number string with an optional decimal point. If raw price does not contain valid price value or contains more than one price value, then return default value. If default value not set, then raise Value...
f10939:m0
def price_dec(raw_price, default=_not_defined):
try:<EOL><INDENT>price = price_str(raw_price)<EOL>return decimal.Decimal(price)<EOL><DEDENT>except ValueError as err:<EOL><INDENT>if default == _not_defined:<EOL><INDENT>raise err<EOL><DEDENT><DEDENT>return default<EOL>
Price decimal value from raw string. Extract price value from input raw string and present as Decimal number. If raw price does not contain valid price value or contains more than one price value, then return default value. If default value not set, then raise ValueError. :param str raw_price...
f10939:m1
def __init__(self, wd_item_id='<STR_LIT>', new_item=False, data=None,<EOL>mediawiki_api_url='<STR_LIT>',<EOL>sparql_endpoint_url='<STR_LIT>',<EOL>append_value=None, fast_run=False, fast_run_base_filter=None, fast_run_use_refs=False,<EOL>ref_handler=None, global_ref_mode='<STR_LIT>', good_refs=None, keep_good_ref_statem...
self.core_prop_match_thresh = core_prop_match_thresh<EOL>self.wd_item_id = wd_item_id<EOL>self.new_item = new_item<EOL>self.mediawiki_api_url = mediawiki_api_url<EOL>self.sparql_endpoint_url = sparql_endpoint_url<EOL>self.data = [] if data is None else data<EOL>self.append_value = [] if append_value is None else append...
constructor :param wd_item_id: Wikidata item id :param new_item: This parameter lets the user indicate if a new item should be created :type new_item: True or False :param data: a dictionary with WD property strings as keys and the data which should be written to a WD item as the property values :type data: List[WD...
f10941:c0:m0
@classmethod<EOL><INDENT>def get_distinct_value_props(cls, sparql_endpoint_url='<STR_LIT>'):<DEDENT>
pcpid = config['<STR_LIT>']<EOL>dvcqid = config['<STR_LIT>']<EOL>try:<EOL><INDENT>h = WikibaseHelper(sparql_endpoint_url)<EOL>pcpid = h.get_pid(pcpid)<EOL>dvcqid = h.get_qid(dvcqid)<EOL><DEDENT>except Exception:<EOL><INDENT>warnings.warn("<STR_LIT>" +<EOL>"<STR_LIT>" +<EOL>"<STR_LIT>")<EOL>cls.DISTINCT_VALUE_PROPS[spar...
On wikidata, the default core IDs will be the properties with a distinct values constraint select ?p where {?p wdt:P2302 wd:Q21502410} See: https://www.wikidata.org/wiki/Help:Property_constraints_portal https://www.wikidata.org/wiki/Help:Property_constraints_portal/Unique_value
f10941:c0:m1
def get_wd_entity(self):
params = {<EOL>'<STR_LIT:action>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': self.wd_item_id,<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>headers = {<EOL>'<STR_LIT>': self.user_agent<EOL>}<EOL>json_data = self.mediawiki_api_call("<STR_LIT:GET>", self.mediawiki_api_url, params=params, headers=headers)<EOL>r...
retrieve a WD item in json representation from Wikidata :rtype: dict :return: python complex dictionary represenation of a json
f10941:c0:m4
def parse_wd_json(self, wd_json):
wd_data = {x: wd_json[x] for x in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>') if x in wd_json}<EOL>wd_data['<STR_LIT>'] = dict()<EOL>self.entity_metadata = {x: wd_json[x] for x in wd_json if x not in<EOL>('<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>')}<EOL>self.sitelinks = wd_json.get('<STR_L...
Parses a WD entity json and generates the datatype objects, sets self.wd_json_representation :param wd_json: the json of a WD entity :type wd_json: A Python Json representation of a WD item :return: returns the json representation containing 'labels', 'descriptions', 'claims', 'aliases', 'sitelinks'.
f10941:c0:m5
@staticmethod<EOL><INDENT>def get_wd_search_results(search_string='<STR_LIT>', mediawiki_api_url='<STR_LIT>',<EOL>user_agent=config['<STR_LIT>'],<EOL>max_results=<NUM_LIT>, language='<STR_LIT>'):<DEDENT>
params = {<EOL>'<STR_LIT:action>': '<STR_LIT>',<EOL>'<STR_LIT>': language,<EOL>'<STR_LIT>': search_string,<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': <NUM_LIT:50><EOL>}<EOL>headers = {<EOL>'<STR_LIT>': user_agent<EOL>}<EOL>cont_count = <NUM_LIT:1><EOL>id_list = []<EOL>id_labels = []<EOL>while cont_count > <NUM_LIT:...
Performs a search in WD for a certain WD search string :param search_string: a string which should be searched for in WD :type search_string: str :param mediawiki_api_url: Specify the mediawiki_api_url. :type mediawiki_api_url: str :param user_agent: The user agent string transmitted in the http header :type user_agent...
f10941:c0:m6
def get_property_list(self):
property_list = set()<EOL>for x in self.statements:<EOL><INDENT>property_list.add(x.get_prop_nr())<EOL><DEDENT>return list(property_list)<EOL>
List of properties on the current item :return: a list of WD property ID strings (Pxxxx).
f10941:c0:m7
def __select_wd_item(self):
qid_list = set()<EOL>conflict_source = {}<EOL>if self.mrh:<EOL><INDENT>exact_qid = self.mrh.mrt_qids['<STR_LIT>']<EOL>mrt_pid = self.mrh.mrt_pid<EOL><DEDENT>else:<EOL><INDENT>exact_qid = "<STR_LIT>"<EOL>mrt_pid = "<STR_LIT>"<EOL><DEDENT>for statement in self.data:<EOL><INDENT>wd_property = statement.get_prop_nr()<EOL>m...
The most likely WD item QID should be returned, after querying WDQ for all values in core_id properties :return: Either a single WD QID is returned, or an empty string if no suitable item in WD
f10941:c0:m8
def __construct_claim_json(self):
def handle_qualifiers(old_item, new_item):<EOL><INDENT>if not new_item.check_qualifier_equality:<EOL><INDENT>old_item.set_qualifiers(new_item.get_qualifiers())<EOL><DEDENT><DEDENT>def is_good_ref(ref_block):<EOL><INDENT>if len(WDItemEngine.databases) == <NUM_LIT:0>:<EOL><INDENT>WDItemEngine._init_ref_system()<EOL><DEDE...
Writes the properties from self.data to a new or existing json in self.wd_json_representation :return: None
f10941:c0:m9
def update(self, data, append_value=None):
assert type(data) == list<EOL>if append_value:<EOL><INDENT>assert type(append_value) == list<EOL>self.append_value.extend(append_value)<EOL><DEDENT>self.data.extend(data)<EOL>self.statements = copy.deepcopy(self.original_statements)<EOL>if not __debug__:<EOL><INDENT>print(self.data)<EOL><DEDENT>if self.fast_run:<EOL><I...
This method takes data, and modifies the Wikidata item. This works together with the data already provided via the constructor or if the constructor is being instantiated with search_only=True. In the latter case, this allows for checking the item data before deciding which new data should be written to the Wikidata it...
f10941:c0:m10
def get_wd_json_representation(self):
return self.wd_json_representation<EOL>
A method to access the internal json representation of the WD item, mainly for testing :return: returns a Python json representation object of the WD item at the current state of the instance
f10941:c0:m11
def __check_integrity(self):
<EOL>wdi_core_props = self.core_props<EOL>cp_statements = [x for x in self.statements if x.get_prop_nr() in wdi_core_props]<EOL>item_core_props = set(x.get_prop_nr() for x in cp_statements)<EOL>cp_data = [x for x in self.data if x.get_prop_nr() in wdi_core_props]<EOL>count_existing_ids = len([x for x in self.data if x....
A method to check if when invoking __select_wd_item() and the WD item does not exist yet, but another item has a property of the current domain with a value like submitted in the data dict, this item does not get selected but a ManualInterventionReqException() is raised. This check is dependent on the core identifiers ...
f10941:c0:m12
def get_label(self, lang='<STR_LIT>'):
if self.fast_run:<EOL><INDENT>return list(self.fast_run_container.get_language_data(self.wd_item_id, lang, '<STR_LIT:label>'))[<NUM_LIT:0>]<EOL><DEDENT>try:<EOL><INDENT>return self.wd_json_representation['<STR_LIT>'][lang]['<STR_LIT:value>']<EOL><DEDENT>except KeyError:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>
Returns the label for a certain language :param lang: :type lang: str :return: returns the label in the specified language, an empty string if the label does not exist
f10941:c0:m13
def set_label(self, label, lang='<STR_LIT>'):
if self.fast_run and not self.require_write:<EOL><INDENT>self.require_write = self.fast_run_container.check_language_data(qid=self.wd_item_id,<EOL>lang_data=[label], lang=lang,<EOL>lang_data_type='<STR_LIT:label>')<EOL>if self.require_write:<EOL><INDENT>self.init_data_load()<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DE...
Set the label for a WD item in a certain language :param label: The description of the item in a certain language :type label: str :param lang: The language a label should be set for. :type lang: str :return: None
f10941:c0:m14
def get_aliases(self, lang='<STR_LIT>'):
if self.fast_run:<EOL><INDENT>return list(self.fast_run_container.get_language_data(self.wd_item_id, lang, '<STR_LIT>'))<EOL><DEDENT>alias_list = []<EOL>if '<STR_LIT>' in self.wd_json_representation and lang in self.wd_json_representation['<STR_LIT>']:<EOL><INDENT>for alias in self.wd_json_representation['<STR_LIT>'][l...
Retrieve the aliases in a certain language :param lang: The Wikidata language the description should be retrieved for :return: Returns a list of aliases, an empty list if none exist for the specified language
f10941:c0:m15
def set_aliases(self, aliases, lang='<STR_LIT>', append=True):
if self.fast_run and not self.require_write:<EOL><INDENT>self.require_write = self.fast_run_container.check_language_data(qid=self.wd_item_id,<EOL>lang_data=aliases, lang=lang,<EOL>lang_data_type='<STR_LIT>')<EOL>if self.require_write:<EOL><INDENT>self.init_data_load()<EOL><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT><...
set the aliases for a WD item :param aliases: a list of strings representing the aliases of a WD item :param lang: The language a description should be set for :param append: If true, append a new alias to the list of existing aliases, else, overwrite. Default: True :return: None
f10941:c0:m16
def get_description(self, lang='<STR_LIT>'):
if self.fast_run:<EOL><INDENT>return list(self.fast_run_container.get_language_data(self.wd_item_id, lang, '<STR_LIT:description>'))[<NUM_LIT:0>]<EOL><DEDENT>if '<STR_LIT>' not in self.wd_json_representation or lang not in self.wd_json_representation['<STR_LIT>']:<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT>else:<EOL><I...
Retrieve the description in a certain language :param lang: The Wikidata language the description should be retrieved for :return: Returns the description string
f10941:c0:m17
def set_description(self, description, lang='<STR_LIT>'):
if self.fast_run and not self.require_write:<EOL><INDENT>self.require_write = self.fast_run_container.check_language_data(qid=self.wd_item_id,<EOL>lang_data=[description], lang=lang,<EOL>lang_data_type='<STR_LIT:description>')<EOL>if self.require_write:<EOL><INDENT>self.init_data_load()<EOL><DEDENT>else:<EOL><INDENT>re...
Set the description for a WD item in a certain language :param description: The description of the item in a certain language :type description: str :param lang: The language a description should be set for. :type lang: str :return: None
f10941:c0:m18
def set_sitelink(self, site, title, badges=()):
sitelink = {<EOL>'<STR_LIT>': site,<EOL>'<STR_LIT:title>': title,<EOL>'<STR_LIT>': badges<EOL>}<EOL>self.wd_json_representation['<STR_LIT>'][site] = sitelink<EOL>self.sitelinks[site] = sitelink<EOL>
Set sitelinks to corresponding Wikipedia pages :param site: The Wikipedia page a sitelink is directed to (e.g. 'enwiki') :param title: The title of the Wikipedia page the sitelink is directed to :param badges: An iterable containing Wikipedia badge strings. :return:
f10941:c0:m19
def get_sitelink(self, site):
if site in self.sitelinks:<EOL><INDENT>return self.sitelinks[site]<EOL><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>
A method to access the interwiki links in the json.model :param site: The Wikipedia site the interwiki/sitelink should be returned for :return: The interwiki/sitelink string for the specified Wikipedia will be returned.
f10941:c0:m20
def write(self, login, bot_account=True, edit_summary='<STR_LIT>', entity_type='<STR_LIT>', property_datatype='<STR_LIT:string>',<EOL>max_retries=<NUM_LIT:10>, retry_after=<NUM_LIT:30>):
if not self.require_write:<EOL><INDENT>return self.wd_item_id<EOL><DEDENT>if entity_type == '<STR_LIT>':<EOL><INDENT>self.wd_json_representation['<STR_LIT>'] = property_datatype<EOL>if '<STR_LIT>' in self.wd_json_representation:<EOL><INDENT>del self.wd_json_representation['<STR_LIT>']<EOL><DEDENT><DEDENT>payload = {<EO...
Writes the WD item Json to WD and after successful write, updates the object with new ids and hashes generated by WD. For new items, also returns the new QIDs. :param login: a instance of the class PBB_login which provides edit-cookies and edit-tokens :param bot_account: Tell the Wikidata API whether the script should ...
f10941:c0:m21
@staticmethod<EOL><INDENT>def mediawiki_api_call(method, mediawiki_api_url='<STR_LIT>',<EOL>session=None, max_retries=<NUM_LIT:10>, retry_after=<NUM_LIT:30>, **kwargs):<DEDENT>
response = None<EOL>session = session if session else requests.session()<EOL>for n in range(max_retries):<EOL><INDENT>try:<EOL><INDENT>response = session.request(method, mediawiki_api_url, **kwargs)<EOL><DEDENT>except requests.exceptions.ConnectionError as e:<EOL><INDENT>print("<STR_LIT>".format(e, retry_after))<EOL>ti...
:param method: 'GET' or 'POST' :param mediawiki_api_url: :param session: If a session is passed, it will be used. Otherwise a new requests session is created :param max_retries: If api request fails due to rate limiting, maxlag, or readonly mode, retry up to `max_retries` times :type max_retries: int :param retry_after...
f10941:c0:m22
@classmethod<EOL><INDENT>def setup_logging(cls, log_dir="<STR_LIT>", log_name=None, header=None, names=None,<EOL>delimiter="<STR_LIT:;>", logger_name='<STR_LIT>'):<DEDENT>
names = ["<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>", "<STR_LIT>",<EOL>"<STR_LIT>"] if names is None else names<EOL>if not os.path.exists(log_dir):<EOL><INDENT>os.makedirs(log_dir)<EOL><DEDENT>if not log_name:<EOL><INDENT>run_id = time.strftime('<STR_LIT>', time.localtime())<EOL>log_nam...
A static method which initiates log files compatible to .csv format, allowing for easy further analysis. :param log_dir: allows for setting relative or absolute path for logging, default is ./logs. :type log_dir: str :param log_name: File name of log file to be written. e.g. "WD_bot_run-20160204.log". Default is "WD_bo...
f10941:c0:m23
@classmethod<EOL><INDENT>def log(cls, level, message):<DEDENT>
if cls.logger is None:<EOL><INDENT>cls.setup_logging()<EOL><DEDENT>log_levels = {'<STR_LIT>': logging.DEBUG, '<STR_LIT>': logging.ERROR, '<STR_LIT>': logging.INFO, '<STR_LIT>': logging.WARNING,<EOL>'<STR_LIT>': logging.CRITICAL}<EOL>cls.logger.log(level=log_levels[level], msg=message)<EOL>
:param level: The log level as in the Python logging documentation, 5 different possible values with increasing severity :type level: String of value 'DEBUG', 'INFO', 'WARNING', 'ERROR' or 'CRITICAL'. :param message: The logging data which should be written to the log file. In order to achieve a csv-file compatible f...
f10941:c0:m24
@classmethod<EOL><INDENT>def generate_item_instances(cls, items, mediawiki_api_url='<STR_LIT>', login=None,<EOL>user_agent=config['<STR_LIT>']):<DEDENT>
assert type(items) == list<EOL>url = mediawiki_api_url<EOL>params = {<EOL>'<STR_LIT:action>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:|>'.join(items),<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>headers = {<EOL>'<STR_LIT>': user_agent<EOL>}<EOL>if login:<EOL><INDENT>reply = login.get_session().get(url, params=params, header...
A method which allows for retrieval of a list of Wikidata items or properties. The method generates a list of tuples where the first value in the tuple is the QID or property ID, whereas the second is the new instance of WDItemEngine containing all the data of the item. This is most useful for mass retrieval of WD item...
f10941:c0:m25
@staticmethod<EOL><INDENT>@wdi_backoff()<EOL>def execute_sparql_query(query, prefix=None, endpoint='<STR_LIT>',<EOL>user_agent=config['<STR_LIT>'], as_dataframe=False):<DEDENT>
if not endpoint:<EOL><INDENT>endpoint = '<STR_LIT>'<EOL><DEDENT>if prefix:<EOL><INDENT>query = prefix + '<STR_LIT:\n>' + query<EOL><DEDENT>params = {<EOL>'<STR_LIT>': '<STR_LIT>' + query,<EOL>'<STR_LIT>': '<STR_LIT>'<EOL>}<EOL>headers = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': user_agent<EOL>}<EOL>response = re...
Static method which can be used to execute any SPARQL query :param prefix: The URI prefixes required for an endpoint, default is the Wikidata specific prefixes :param query: The actual SPARQL query string :param endpoint: The URL string for the SPARQL endpoint. Default is the URL for the Wikidata SPARQL endpoint :param...
f10941:c0:m26
@staticmethod<EOL><INDENT>def run_shex_manifest(manifest_url, index=<NUM_LIT:0>, debug=False):<DEDENT>
manifest = json.loads(manifest_url, debug=False)<EOL>manifest_results = dict()<EOL>for case in manifest[index]:<EOL><INDENT>if case.data.startswith("<STR_LIT>"):<EOL><INDENT>sparql_endpoint = case.data.replace("<STR_LIT>", "<STR_LIT>")<EOL>schema = requests.get(case.schemaURL).text<EOL>shex = ShExC(schema).schema<EOL>e...
:param manifest: A url to a manifest that contains all the ingredients to run a shex conformance test :param index: Manifests are stored in lists. This method only handles one manifest, hence by default the first manifest is going to be selected :return:
f10941:c0:m29
@staticmethod<EOL><INDENT>def merge_items(from_id, to_id, login_obj, mediawiki_api_url='<STR_LIT>',<EOL>ignore_conflicts='<STR_LIT>', user_agent=config['<STR_LIT>']):<DEDENT>
url = mediawiki_api_url<EOL>headers = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:utf-8>',<EOL>'<STR_LIT>': user_agent<EOL>}<EOL>params = {<EOL>'<STR_LIT:action>': '<STR_LIT>',<EOL>'<STR_LIT>': from_id,<EOL>'<STR_LIT>': to_id,<EOL>'<STR_LIT>': login_obj.get_edit_token(),<EOL>'<STR_LIT>': '<STR_LIT>',<EOL...
A static method to merge two Wikidata items :param from_id: The QID which should be merged into another item :type from_id: string with 'Q' prefix :param to_id: The QID into which another item should be merged :type to_id: string with 'Q' prefix :param login_obj: The object containing the login credentials and cookies ...
f10941:c0:m30
@staticmethod<EOL><INDENT>def delete_items(item_list, reason, login, mediawiki_api_url='<STR_LIT>',<EOL>user_agent=config['<STR_LIT>']):<DEDENT>
url = mediawiki_api_url<EOL>bulk_deletion_string = '<STR_LIT>'<EOL>bulk_deletion_string += '<STR_LIT>'.format('<STR_LIT>'.join(item_list), reason)<EOL>params = {<EOL>'<STR_LIT:action>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT:content>',<EOL>'<STR_LIT>': '<STR_...
Takes a list of items and posts them for deletion by Wikidata moderators, appends at the end of the deletion request page. :param item_list: a list of QIDs which should be deleted :type item_list: list :param reason: short text about the reason for the deletion request :type reason: str :param login: A WDI login object...
f10941:c0:m32
@classmethod<EOL><INDENT>def wikibase_item_engine_factory(cls, mediawiki_api_url, sparql_endpoint_url, name='<STR_LIT>'):<DEDENT>
class SubCls(cls):<EOL><INDENT>def __init__(self, *args, **kwargs):<EOL><INDENT>kwargs['<STR_LIT>'] = mediawiki_api_url<EOL>kwargs['<STR_LIT>'] = sparql_endpoint_url<EOL>super(SubCls, self).__init__(*args, **kwargs)<EOL><DEDENT><DEDENT>SubCls.__name__ = name<EOL>return SubCls<EOL>
Helper function for creating a WDItemEngine class with arguments set for a different Wikibase instance than Wikidata. :param mediawiki_api_url: Mediawiki api url. For wikidata, this is: 'https://www.wikidata.org/w/api.php' :param sparql_endpoint_url: sparql endpoint url. For wikidata, this is: 'https://query.wikidata.o...
f10941:c0:m33
def __init__(self, value, snak_type, data_type, is_reference, is_qualifier, references, qualifiers, rank, prop_nr,<EOL>check_qualifier_equality):
self.value = value<EOL>self.snak_type = snak_type<EOL>self.data_type = data_type<EOL>if not references:<EOL><INDENT>self.references = []<EOL><DEDENT>else:<EOL><INDENT>self.references = references<EOL><DEDENT>self.qualifiers = qualifiers<EOL>self.is_reference = is_reference<EOL>self.is_qualifier = is_qualifier<EOL>self....
Constructor, will be called by all data types. :param value: Data value of the WD data snak :type value: str or int or tuple :param snak_type: The snak type of the WD data snak, three values possible, depending if the value is a known (value), not existent (novalue) or unknown (somevalue). See WD do...
f10941:c2:m0
@statement_ref_mode.setter<EOL><INDENT>def statement_ref_mode(self, value):<DEDENT>
valid_values = ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>']<EOL>if value not in valid_values:<EOL><INDENT>raise ValueError('<STR_LIT>'.format('<STR_LIT:U+0020>'.join(valid_values)))<EOL><DEDENT>self._statement_ref_mode = value<EOL>
Set the reference mode for a statement, always overrides the global reference state.
f10941:c2:m7