Ejemplo n.º 1
0
 def test_create_epochs(self):
     signal = [0] * 30 + [1] * 5 + [0] * 30 + [1] * 5 + [0] * 30
     events = nk.find_events(np.array(signal))
     data = nk.create_epochs(pd.DataFrame({"Signal": signal}),
                             events_onsets=events["onsets"],
                             duration=5)
     self.assertEqual(len(data), 2)
Ejemplo n.º 2
0
def analyzeSCR(event_file, acq_file):
    import neurokit as nk
    import pandas as pd
    import numpy as np
    import seaborn as sns
    ## loading acq file
    df, sampling_rate = nk.read_acqknowledge(acq_file,
                                             return_sampling_rate=True)
    bio = nk.bio_process(eda=df["GSR100C"],
                         add=df["Script"],
                         sampling_rate=sampling_rate)

    # adding conditions
    events = pd.read_csv(event_file, sep=r'\s+')
    condition_list = events['trial_type']
    events = {
        'onset': np.array(events["onset"] * 1000),
        'duration': np.array(events["duration"] * 1000)
    }
    epochs = nk.create_epochs(
        bio["df"], events["onset"], duration=120000,
        onset=0)  # create epoch file with 120sec duration and -1sec begins

    data = {}  # Initialize an empty dict
    for epoch_index in epochs:
        data[epoch_index] = {
        }  # Initialize an empty dict for the current epoch
        epoch = epochs[epoch_index]

        # ECG
        #    baseline = epoch["ECG_RR_Interval"].ix[-100:0].mean()  # Baseline
        #    rr_max = epoch["ECG_RR_Interval"].ix[0:400].max()  # Maximum RR interval
        #    data[epoch_index]["HRV_MaxRR"] = rr_max - baseline  # Corrected for baseline

        # EDA - SCR
        scr_max = epoch["SCR_Peaks"].ix[100:15000].max(
        )  # Maximum SCR peak - now its 30sec after initiation of script
        if np.isnan(scr_max):
            scr_max = 0  # If no SCR, consider the magnitude, i.e.  that the value is 0
        data[epoch_index]["SCR_Magnitude"] = scr_max

    data = pd.DataFrame.from_dict(data,
                                  orient="index")  # Convert to a dataframe
    data["Condition"] = condition_list  # Add the conditions
    data  # Print
    return data
Ejemplo n.º 3
0
def test_create_epochs(df):
    df = pd.DataFrame({
        "Trigger":
        pd.Series(
            scipy.signal.square(1 * np.pi * 5 *
                                np.linspace(0, 1, 2000, endpoint=False))),
        "Signal":
        pd.Series(np.sin(20 * np.pi * np.linspace(0, 1, 2000, endpoint=False)))
        * np.random.normal(0, 1, 2000),
        "Signal2":
        pd.Series(np.sin(60 * np.pi * np.linspace(0, 1, 2000, endpoint=False)))
        * np.random.normal(0, 2, 2000)
    })
    df.plot()
    events = nk.find_events(df["Trigger"], cut="lower")
    assert len(events) == 2

    fig = nk.plot_events_in_signal(df, events["onsets"])

    epochs = nk.create_epochs(df, events["onsets"], duration=0.1)
    assert len(epochs) == 2
Ejemplo n.º 4
0
nk.z_score(bio["df"][["ECG_Filtered", "RSP_Filtered",
                      "RSA"]])[1000:2500].plot()
plt.title('RSA algorithm')
plt.savefig('graphs/rsaalg')

#define condition list
condition_list = ["Negative", "Neutral", "Neutral", "Negative"]

#dict containing onsets and durations of each event --> should be 1
events = nk.find_events(df["Photosensor"], cut="lower")
print("event finding")
print(events)

#create_epoch --> epochs of data corresponding to each event (since is 1 event, is the epoch[0])
epochs = nk.create_epochs(bio["df"],
                          events["onsets"],
                          duration=700,
                          onset=-100)
nk.z_score(epochs[0][["ECG_Filtered", "EDA_Filtered", "Photosensor"]]).plot()
plt.title('Epoch')
plt.savefig('graphs/epoch')

# itereate through the epochs and store the interesting results in a new dict that will be, at the end, converted to a dataframe
data = {}  # Initialize an empty dict
for epoch_index in epochs:
    data[epoch_index] = {}  # Initialize an empty dict for the current epoch
    epoch = epochs[epoch_index]

    # ECG
    baseline = epoch["ECG_RR_Interval"].loc[-100:0].mean()  # Baseline
    rr_max = epoch["ECG_RR_Interval"].loc[0:400].max()  # Maximum RR interval
    data[epoch_index][
Ejemplo n.º 5
0
import neurokit as nk
import pandas as pd
import numpy as np
import scipy

df = pd.read_csv("EDA_RSP_Artifacts.csv")  # Sampled at 100Hz
conditions = pd.Series.from_csv("events.csv")

# Preprocessing
df = nk.bio_process(eda=df["EDA"], rsp=df["RSP"], add=df["Photosensor"], sampling_rate=100, scr_min_amplitude=0.02)
df = df["df"]


events = nk.find_events(df["Photosensor"], cut="lower")
epochs = nk.create_epochs(df, events["onsets"], duration=events["durations"]+800, onset=-400)


#==============================================================================
#
#==============================================================================
def eda_ERP(epoch, event_length, sampling_rate=1000, window_post=4):
    """
    Extract event-related EDA and Skin Conductance Response (SCR).

    Parameters
    ----------
    epoch : pandas.DataFrame
        An epoch contains in the epochs dict returned by :function:`nk.create_epochs()` on dataframe returned by :function:`nk.bio_process()`. Index must range from -4s to +4s (relatively to event onset and end).
    event_length : int
        In seconds.
    sampling_rate : int
Ejemplo n.º 6
0
import neurokit as nk

df = nk.read_acqknowledge("abnormal_ECG.acq")

events = nk.find_events(df["Photosensor"], cut="lower")
df = nk.create_epochs(df, events["onsets"], duration=events["durations"])[0]

#df["Photosensor"].plot()
df = nk.ecg_process(df['ECG, X, RSPEC-R'])
ecg = df["ECG"]
df = df["df"]
#rpeaks = nk.ecg_find_peaks(df['ECG_Filtered'])
nk.plot_events_in_signal(df['ECG_Filtered'], ecg["R_Peaks"])
#df['ECG, X, RSPEC-R'].iloc[104000:140000].plot()