How to use the neurokit2.misc.as_vector function in neurokit2

To help you get started, we’ve selected a few neurokit2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github neuropsychology / NeuroKit / neurokit2 / eda / eda_clean.py View on Github external
See Also
    --------
    eda_simulate, eda_findpeaks, eda_process, eda_plot

    Examples
    --------
    >>> import pandas as pd
    >>> import neurokit2 as nk
    >>>
    >>> eda = nk.eda_simulate(duration=30, sampling_rate=100, scr_number=10, noise=0.01, drift=0.02)
    >>> signals = pd.DataFrame({ "EDA_Raw": eda, "EDA_BioSPPy": nk.eda_clean(eda, sampling_rate=100, method='biosppy'), "EDA_NeuroKit": nk.eda_clean(eda, sampling_rate=100, method='neurokit')})
    >>> fig = signals.plot()
    >>> fig #doctest: +SKIP

    """
    eda_signal = as_vector(eda_signal)

    method = method.lower()  # remove capitalised letters
    if method == "biosppy":
        clean = _eda_clean_biosppy(eda_signal, sampling_rate)
    elif method in ["default", "neurokit", "nk"]:
        clean = _eda_clean_neurokit(eda_signal, sampling_rate)
    else:
        raise ValueError("NeuroKit error: eda_clean(): 'method' should be one of 'biosppy'.")

    return clean
github neuropsychology / NeuroKit / neurokit2 / eog / eog_clean.py View on Github external
...                     "agarwal2019": agarwal2019,
    ...                     "MNE": mne}).plot() #doctest: +ELLIPSIS
    


    References
    ----------
    - Agarwal, M., & Sivakumar, R. (2019). Blink: A Fully Automated Unsupervised Algorithm for
    Eye-Blink Detection in EEG Signals. In 2019 57th Annual Allerton Conference on Communication,
    Control, and Computing (Allerton) (pp. 1113-1121). IEEE.
    - Kong, X., & Wilson, G. F. (1998). A new EOG-based eyeblink detection algorithm.
    Behavior Research Methods, Instruments, & Computers, 30(4), 713-719.

    """
    # Sanitize input
    eog_signal = as_vector(eog_signal)

    # Apply method
    method = method.lower()
    if method in ["agarwal", "agarwal2019"]:
        clean = _eog_clean_agarwal2019(eog_signal, sampling_rate=sampling_rate)
    elif method in ["brainstorm"]:
        clean = _eog_clean_brainstorm(eog_signal, sampling_rate=sampling_rate)
    elif method in ["mne"]:
        clean = _eog_clean_mne(eog_signal, sampling_rate=sampling_rate)
    elif method in ["kong1998", "kong"]:
        clean = _eog_clean_kong1998(eog_signal, sampling_rate=sampling_rate)
    else:
        raise ValueError(
            "NeuroKit error: eog_clean(): 'method' should be " "one of 'agarwal2019', 'brainstorm', 'mne', 'kong1998'."
        )
github neuropsychology / NeuroKit / neurokit2 / bio / bio_process.py View on Github external
else:
                ecg = None
            if "EOG" in data.keys():
                eog = data["EOG"]
            else:
                eog = None
            cols = ["ECG", "EKG", "RSP", "EDA", "EMG", "EOG"]
            keep_keys = [key for key in data.keys() if key not in cols]
            if len(keep_keys) != 0:
                keep = data[keep_keys]
            else:
                keep = None

    # ECG
    if ecg is not None:
        ecg = as_vector(ecg)
        ecg_signals, ecg_info = ecg_process(ecg, sampling_rate=sampling_rate)
        bio_info.update(ecg_info)
        bio_df = pd.concat([bio_df, ecg_signals], axis=1)

    # RSP
    if rsp is not None:
        rsp = as_vector(rsp)
        rsp_signals, rsp_info = rsp_process(rsp, sampling_rate=sampling_rate)
        bio_info.update(rsp_info)
        bio_df = pd.concat([bio_df, rsp_signals], axis=1)

    # EDA
    if eda is not None:
        eda = as_vector(eda)
        eda_signals, eda_info = eda_process(eda, sampling_rate=sampling_rate)
        bio_info.update(eda_info)
github neuropsychology / NeuroKit / neurokit2 / signal / signal_findpeaks.py View on Github external
def _signal_findpeaks_findbase(peaks, signal, what="onset"):
    if what == "onset":
        direction = "smaller"
    else:
        direction = "greater"

    troughs, _ = scipy.signal.find_peaks(-1 * signal)

    bases = find_closest(peaks, troughs, direction=direction, strictly=True)
    bases = as_vector(bases)

    return bases
github neuropsychology / NeuroKit / neurokit2 / ppg / ppg_clean.py View on Github external
ppg_simulate, ppg_findpeaks

    Examples
    --------
    >>> import neurokit2 as nk
    >>> import matplotlib.pyplot as plt
    >>>
    >>> ppg = nk.ppg_simulate(heart_rate=75, duration=30)
    >>> ppg_clean = nk.ppg_clean(ppg)
    >>>
    >>> plt.plot(ppg, label="raw PPG") #doctest: +SKIP
    >>> plt.plot(ppg_clean, label="clean PPG") #doctest: +SKIP
    >>> plt.legend() #doctest: +SKIP

    """
    ppg_signal = as_vector(ppg_signal)

    method = method.lower()
    if method in ["elgendi"]:
        clean = _ppg_clean_elgendi(ppg_signal, sampling_rate)
    else:
        raise ValueError("Neurokit error: Please use one of the following methods: 'elgendi'.")

    return clean
github neuropsychology / NeuroKit / neurokit2 / emg / emg_activation.py View on Github external
References
    ----------
    - BioSPPy: https://github.com/PIA-Group/BioSPPy/blob/master/biosppy/signals/emg.py

    - Modified emg.py for BioSPPy: https://gist.github.com/tostasmistas/747f4585198411c8c4bda5f312f27dfb

    - Silva H, Scherer R, Sousa J, Londral A , "Towards improving the ssability of
    electromyographic interfacess", Journal of Oral Rehabilitation, pp. 1–2, 2012.

    """
    # Sanity checks.
    if emg_amplitude is not None:
        emg_amplitude = as_vector(emg_amplitude)
    if emg_cleaned is not None:
        emg_cleaned = as_vector(emg_cleaned)
        if emg_amplitude is None:
            emg_amplitude = as_vector(emg_cleaned)

    if duration_min == "default":
        duration_min = int(0.05 * sampling_rate)

    # Find offsets and onsets.
    method = method.lower()  # remove capitalised letters
    if method == "threshold":
        if emg_amplitude is None:
            raise ValueError(
                "NeuroKit error: emg_activation(): 'threshold' method needs 'emg_amplitude' signal to be passed."
            )
        activity = _emg_activation_threshold(emg_amplitude, threshold=threshold)

    elif method == "mixture":
github neuropsychology / NeuroKit / neurokit2 / microstates / microstates_static.py View on Github external
Values of microstates proportion, lifetime distribution and duration (median, mean, and their averages).

    Examples
    --------
    >>> import neurokit2 as nk
    >>>
    >>> microstates = [0, 0, 0, 1, 1, 2, 2, 2, 2, 1, 0, 0]
    >>> nk.microstates_static(microstates, sampling_rate=100)  #doctest: +ELLIPSIS
      Microstate_0_Proportion  ...  Microstate_Average_DurationMedian
    0 ...                      ...  ...

    [1 rows x 14 columns]

    """
    out = {}
    microstates = as_vector(microstates)

    out, lifetimes = _microstates_prevalence(microstates, out=out)
    out, durations, types = _microstates_duration(microstates, sampling_rate=sampling_rate, out=out)

    if show is True:
        fig = plt.figure(constrained_layout=False)
        spec = matplotlib.gridspec.GridSpec(ncols=2, nrows=2, height_ratios=[1, 1], width_ratios=[1, 1])

        ax0 = fig.add_subplot(spec[1, :])
        ax1 = fig.add_subplot(spec[0, :-1])
        ax2 = fig.add_subplot(spec[0, 1])

        _microstates_duration_plot(durations, types, ax=ax0)
        _microstates_prevalence_plot(microstates, lifetimes, out, ax_prop=ax1, ax_distrib=ax2)

    df = pd.DataFrame.from_dict(out, orient="index").T.add_prefix("Microstate_")
github neuropsychology / NeuroKit / neurokit2 / rsp / rsp_clean.py View on Github external
Examples
    --------
    >>> import pandas as pd
    >>> import neurokit2 as nk
    >>>
    >>> rsp = nk.rsp_simulate(duration=30, sampling_rate=50, noise=0.01)
    >>> signals = pd.DataFrame({ "RSP_Raw": rsp, "RSP_Khodadad2018": nk.rsp_clean(rsp, sampling_rate=50, method="khodadad2018"), "RSP_BioSPPy": nk.rsp_clean(rsp, sampling_rate=50, method="biosppy")})
    >>> fig = signals.plot()
    >>> fig #doctest: +SKIP

    References
    ----------
    - `Khodadad et al. (2018) `_

    """
    rsp_signal = as_vector(rsp_signal)

    method = method.lower()  # remove capitalised letters
    if method in ["khodadad", "khodadad2018"]:
        clean = _rsp_clean_khodadad2018(rsp_signal, sampling_rate)
    elif method == "biosppy":
        clean = _rsp_clean_biosppy(rsp_signal, sampling_rate)
    else:
        raise ValueError("NeuroKit error: rsp_clean(): 'method' should be one of 'khodadad2018' or 'biosppy'.")

    return clean
github neuropsychology / NeuroKit / neurokit2 / bio / bio_process.py View on Github external
if eda is not None:
        eda = as_vector(eda)
        eda_signals, eda_info = eda_process(eda, sampling_rate=sampling_rate)
        bio_info.update(eda_info)
        bio_df = pd.concat([bio_df, eda_signals], axis=1)

    # EMG
    if emg is not None:
        emg = as_vector(emg)
        emg_signals, emg_info = emg_process(emg, sampling_rate=sampling_rate)
        bio_info.update(emg_info)
        bio_df = pd.concat([bio_df, emg_signals], axis=1)

    # EOG
    if eog is not None:
        eog = as_vector(eog)
        eog_signals, eog_info = eog_process(eog, sampling_rate=sampling_rate)
        bio_info.update(eog_info)
        bio_df = pd.concat([bio_df, eog_signals], axis=1)

    # Additional channels to keep
    if keep is not None:
        keep = keep.reset_index(drop=True)
        bio_df = pd.concat([bio_df, keep], axis=1)

    # RSA
    if ecg is not None and rsp is not None:
        rsa = ecg_rsa(ecg_signals, rsp_signals, rpeaks=None, sampling_rate=sampling_rate, continuous=True)
        bio_df = pd.concat([bio_df, rsa], axis=1)

    return bio_df, bio_info
github neuropsychology / NeuroKit / neurokit2 / ppg / ppg_process.py View on Github external
See Also
    --------
    ppg_clean, ppg_findpeaks

    Examples
    --------
    >>> import neurokit2 as nk
    >>>
    >>> ppg = nk.ppg_simulate(duration=10, sampling_rate=1000, heart_rate=70)
    >>> signals, info = nk.ppg_process(ppg, sampling_rate=1000)
    >>> fig = nk.ppg_plot(signals)
    >>> fig #doctest: +SKIP

    """
    # Sanitize input
    ppg_signal = as_vector(ppg_signal)

    # Clean signal
    ppg_cleaned = ppg_clean(ppg_signal, sampling_rate=sampling_rate)

    # Find peaks
    info = ppg_findpeaks(ppg_cleaned, sampling_rate=sampling_rate, **kwargs)

    # Mark peaks
    peaks_signal = _signal_from_indices(info["PPG_Peaks"], desired_length=len(ppg_cleaned))

    # Rate computation
    rate = signal_rate(info["PPG_Peaks"], sampling_rate=sampling_rate, desired_length=len(ppg_cleaned))

    # Prepare output
    signals = pd.DataFrame(
        {"PPG_Raw": ppg_signal, "PPG_Clean": ppg_cleaned, "PPG_Rate": rate, "PPG_Peaks": peaks_signal}