コード例 #1
0
ファイル: utils.py プロジェクト: kaushil24/IoT-AI
    def GSRfeatures(self, df, sampling_rate=31):
        drivers = df['Driver'].value_counts().index
        df['foot meanGSR'] = [0 for _ in range(len(df))]
        df['hand meanGSR'] = [0 for _ in range(len(df))]
        df['foot meanSCR'] = [0 for _ in range(len(df))]
        df['hand meanSCR'] = [0 for _ in range(len(df))]
        df['foot maxSCR'] = [0 for _ in range(len(df))]
        df['hand maxSCR'] = [0 for _ in range(len(df))]
        df['foot meanSCL'] = [0 for _ in range(len(df))]
        df['hand slopeSCL'] = [0 for _ in range(len(df))]
        for dr in drivers:
            for var in ['foot', 'hand']:
                temp = df.loc[df['Driver'] == dr, var + ' GSR']
                meanGSR = temp.mean()
                df.loc[temp.index, var + ' meanGSR'] = meanGSR
                processed_GSR = nk.eda_process(temp,
                                               sampling_rate=sampling_rate)
                meanSCL = processed_GSR['df']['EDA_Tonic'].mean()
                df.loc[temp.index, var + ' meanSCL'] = meanSCL
                slopeSCL = max(processed_GSR['df']['EDA_Tonic']) - min(
                    processed_GSR['df']['EDA_Tonic'])
                df.loc[temp.index, var + ' slopeSCL'] = slopeSCL
                meanSCR = processed_GSR['df']['EDA_Phasic'].mean()
                df.loc[temp.index, var + ' meanSCR'] = meanSCR
                maxSCR = max(processed_GSR['df']['EDA_Phasic'])
                df.loc[temp.index, var + ' maxSCR'] = maxSCR

        print(
            'Finished extracting foot and hand GSR features: meanGSR, meanSCL, slopeSCL and maxSCR'
        )
        self.df = df
        return df
コード例 #2
0
ファイル: q3Runner.py プロジェクト: Botched135/q3NEAT
def EvaluateNEATBiostate(BVP_array, EDA_array, genomeList, currentGenomeID):

    working_data, hb_measure = hb.process(BVP_array, 64.0, report_time=True)

    processed_eda = nk.eda_process(EDA_array, freq=1.9, sampling_rate=4)

    #Do the evaluation stuff
    return 0
コード例 #3
0
    def extract_eda(self, data_eda, label):
        # try:
        data = nk.eda_process(data_eda, 700)
        # except:
        # return []

        default_features = self.extract_default_features(data_eda)
        default_features.extend([
            np.mean(data['EDA']['SCR_Peaks_Amplitudes']),
            (len(data['EDA']['SCR_Peaks_Indexes']) / len(data_eda))
        ])

        return default_features
コード例 #4
0
def get_eda_features(signal, sample_size, window_size=1, shift=1):
    i = 0
    features = {
        'min': [], 'max': [], 'mean': [], 'std': [], 'range': [], 'slope': [],
        'scl_mean': [], 'scl_std':[], 'scr_std':[],
        'scl_corr': [], 'scr_segs': [],
        'scr_sum_amp': [], 'scr_sum_t': [], 'scr_area': []
    }
    signal = np.array(signal).flatten()
    s_processed = nk.eda_process(eda=signal, sampling_rate=sample_size)
    signal = s_processed['df']["EDA_Filtered"]
    scl = s_processed['df']["EDA_Tonic"]
    scr = s_processed['df']["EDA_Phasic"]
        
    window_size = int(sample_size * window_size)
    shift = int(sample_size * shift)
    duration = s_processed['EDA']['SCR_Peaks_Indexes'] - s_processed['EDA']['SCR_Onsets']
    ampl = s_processed['EDA']['SCR_Peaks_Amplitudes']
    
    while i < len(signal):
        temp = signal[i: i + window_size]
        m, s, mn, mx, dr = extract_default_features(temp)
        features['min'].append(mn)
        features['max'].append(mx)
        features['mean'].append(m)
        features['std'].append(s)
        features['range'].append(dr)
        features['slope'].append(get_slope(temp))
        
        temp = scl[i: i + window_size]
        m, s, mn, mx, dr = extract_default_features(temp)
        features['scl_mean'].append(m)
        features['scl_std'].append(s)
        time = [k * 1.0/sample_size for k in np.arange(len(temp))]
        corr, _ = pearsonr(time, temp)
        features['scl_corr'].append(corr)
        
        temp = scr[i: i + window_size]
        m, s, mn, mx, dr = extract_default_features(temp)
        features['scr_std'].append(s)
        
        temp = s_processed['EDA']['SCR_Peaks_Indexes']
        sel = (temp >= i) & (temp < (i + window_size))
        features['scr_segs'].append(np.count_nonzero(sel))
        features['scr_sum_amp'].append(np.sum(ampl[sel]))
        features['scr_sum_t'].append(np.sum(duration[sel]))
        features['scr_area'].append(np.sum(0.5 * ampl[sel] * duration[sel]))
        
        i += shift

    return features
コード例 #5
0
 def __init__(self,
              signal,
              freq,
              file=False,
              filename=None,
              show_plot=False):
     self._y = signal
     self._freq = freq
     self._derivative = self._get_derivative(signal)
     if file:
         self.data = nk.eda_process(signal, sampling_rate=freq)
         if show_plot:
             nk.plot_events_in_signal(nk.z_score(self.data["df"]),
                                      self.data["EDA"]["SCR_Peaks_Indexes"])
             print(self.data["EDA"]["SCR_Peaks_Indexes"])
             plt.show()
         self.save_to_file(filename, self.data)
     else:
         self.data = self.read_from_file(filename)
コード例 #6
0
def extract_features():
    featureVector1 = {}

    Eda_df = ["EDA_Phasic", "EDA_Tonic"]
    Eda_feature = ["SCR_Peaks_Amplitudes", "SCR_Onsets"]  # SCR_Onsets

    EMG_df = ["EMG_Activation", "EMG_Envelope"]
    EMG_Feature = ["EMG_Pulse_Onsets"]  # EMG_Pulse_Onsets

    #EMG_df_MF = ["EMG_Activation_MF", "EMG_Envelope_MF"]
    #EMG_Feature_MF = ["EMG_Pulse_Onsets_MF"]  # EMG_Pulse_Onsets

    ECG_Feature = ["T_Waves", "P_Waves", "Q_Waves"]
    ECG_df = [
        "Heart_Rate", "ECG_RR_Interval", 'ECG_HRV_HF', 'ECG_HRV_LF',
        'ECG_HRV_ULF', 'ECG_HRV_VHF', 'ECG_HRV_VLF'
    ]

    i = 0
    for key in keysRead:
        print(key)
        '''
        try:
            print("ECG")
            dict_feature = nk.ecg_process(window_ECG[key],  sampling_rate=1000)
            del window_ECG[key]
            df_ECG = dict_feature
            #output = open('/home/gisela.pinto/Tese/Data_pkl/ECG.pkl', 'wb')
            output = open('Data_pkl/ECG_'+key+'.pkl', 'wb')
            pickle.dump(df_ECG, output, protocol=4)
            print("Writing in pkl")


        except Exception as e:
            print("ola")
            print("ola")
            print(e)
            continue
        
        ######     EMGZ        #######
        print("EMGZ")
        dict_feature = nk.emg_process(window_EMGZ[key], sampling_rate=1000)
    
        #new_dict_feature_EMGZ = {df: dict_feature['df'][df] for df in EMG_df}
        #new_feature_EMGZ = {df: dict_feature['EMG'][df] for df in EMG_Feature}
        del window_EMGZ[key]
        df_EMGZ = dict_feature
        #output = open('/home/gisela.pinto/Tese/Data_pkl/EMGZ.pkl', 'wb')
        output = open('Data_pkl/EMGZ_'+key+'.pkl', 'wb')
        pickle.dump(df_EMGZ, output, protocol=4)
        print("Writing in pkl")



        ######     EMGMF        #######
        print("EMGMF")
        dict_feature = nk.emg_process(window_EMGMF[key], sampling_rate=1000)
        #new_dict_feature_EMGMF = {df: dict_feature['df'][df] for df in EMG_df}
        #new_feature_EMGMF = {df: dict_feature['EMG'][df] for df in EMG_Feature}
        del window_EMGMF[key]
        df_EMGMF = dict_feature
        #output = open('/home/gisela.pinto/Tese/Data_pkl/EMGMF.pkl', 'wb')
        output = open('Data_pkl/EMGMF_'+key+'.pkl', 'wb')
        pickle.dump(df_EMGMF, output, protocol=4)
        print("Writing in pkl")
        '''

        ######     EDA        #######
        print("EDA")
        dict_feature = nk.eda_process(window_EDA[key], sampling_rate=1000)
        #new_dict_feature_EDA = {df: dict_feature['df'][df] for df in Eda_df}
        #new_feature_EDA = {df: dict_feature['EDA'][df] for df in Eda_feature}

        del window_EDA[key]
        df_EDA = dict_feature
        #output = open('/home/gisela.pinto/Tese/Data_pkl/EDA.pkl', 'wb')
        output = open('Data_pkl/EDA_' + key + '.pkl', 'wb')
        pickle.dump(df_EDA, output, protocol=4)
        print("Writing in pkl")
        '''
コード例 #7
0
ファイル: q3Runner.py プロジェクト: Botched135/q3NEAT
def EvaluateAdaptiveBiostate(BVP_array=None, EDA_array=None):
    global hb_measures
    global m_baseHR
    global m_baseHRV
    global m_previousHR
    global m_previousHRV

    global EDA_measures
    global m_baseTonic
    global m_basePhasic
    global m_previousTonic
    global m_previousPhasic

    global m_prevLevel
    global m_curLevel
    global m_lastAction

    global levelStatesList
    global progressionStateList
    global m_Iteration
    #1: higher arousal
    #0: no notificable change
    #-1: lower arousal

    hr_rate = 0
    hrv_rate = 0
    tonic_rate = 0
    phasic_rate = 0

    if BVP_array is not None:
        working_data, hb_measure = hb.process(BVP_array,
                                              64.0,
                                              report_time=True)
    #TODO: Test the difference between resting and playing against the easiest possible character
    # High heart rate and high HRV = decrease level

    if EDA_array is not None:
        current_EDA = nk.eda_process(EDA_array, freq=1.9, sampling_rate=4)

    current_HR = hb_measure['bpm']
    current_HRV = hb_measure['rmssd']

    current_Tonic = current_EDA['df']['EDA_Tonic']
    current_Phasic = current_EDA['df']['EDA_Phasic']

    current_Tonic_mean = np.mean(current_Tonic)
    current_Phasic_mean = np.mean(current_Phasic)
    # Firstly, is he excited compared to baseline this is for HR and EDA
    # Secondly, is he exicted compared to previous
    # 1:0 : Might need to switch back
    # 0:1 : switch up
    # 0:0 : switch up
    # 1:1 : stay
    #Do the evaluation stuff

    #If there is NO difference significantly between HR & EDA and the arousal was higher before, switch back

    #HR
    hr_state = m_baseHR * percentage_change < current_HR
    if m_previousHR == None:
        hr_rate = 1 if hr_state else 0
    elif hr_state == 1:
        prev_hr_state = m_previousHR * percentage_change
        if prev_hr_state < current_HR:
            hr_rate = 1
        elif current_HR * percentage_change < m_previousHR:
            hr_rate = -1
        else:
            hr_rate = 0
    else:
        hr_rate = 0

    #HRV, use HRV in the end.
    hrv_state = m_baseHRV > current_HRV * percentage_change
    if m_previousHRV == None:
        hrv_rate = 1 if hrv_state else 0  #Compare with previous set
    elif hrv_state == 1:
        prev_hrv_state = m_previousHRV
        if prev_hrv_state > current_HRV * percentage_change:
            hrv_rate = 1
        elif current_HRV > m_previousHRV * percentage_change:
            hrv_rate = -1
        else:
            hrv_rate = 0
    else:
        if current_HRV > m_previousHRV * percentage_change:
            hrv_rate = -1
        elif current_HRV * percentage_change < m_previousHRV:
            hrv_rate = 1
        else:
            hrv_rate = -1 if current_HRV > m_baseHRV * percentage_change else 0

    #EDA Tonic

    tonic_stats = mw(current_Tonic, m_baseTonic, alternative='greater')

    if m_previousTonic is None:
        if tonic_stats.pvalue <= p_value:
            tonic_rate = 1  #Increase or stay
        else:
            tonic_rate = 0  #Increase!
    else:
        if tonic_stats.pvalue > p_value:
            tonic_rate = 1  #must upgrade
        else:
            tonic_greater_stats = mw(current_Tonic,
                                     m_previousTonic,
                                     alternative='greater')
            tonic_less_stats = mw(current_Tonic,
                                  m_previousTonic,
                                  alternative='less')
            if tonic_greater_stats.pvalue <= p_value:
                # This is good. Stay or increase
                tonic_rate = 1
            elif tonic_less_stats.pvalue <= p_value:
                tonic_rate = -1  #Revert back to the previous!
            else:
                tonic_rate = 0

    #EDA Phasic
    phasic_stats = mw(current_Phasic, m_basePhasic, alternative='greater')

    if m_previousPhasic is None:
        if phasic_stats.pvalue <= p_value:
            phasic_rate = 1
        else:
            phasic_rate = 0
    else:
        if phasic_stats.pvalue > p_value:
            phasic_rate = 1
        else:
            phasic_greater_stats = mw(current_Phasic,
                                      m_previousPhasic,
                                      alternative='greater')
            phasic_less_stats = mw(current_Phasic,
                                   m_previousPhasic,
                                   alternative='less')
            if phasic_greater_stats.pvalue <= p_value:
                #stay! Or increae
                phasic_rate = 1
            elif phasic_less_stats.pvalue <= p_value:
                #Revert back
                phasic_rate = -1
            else:
                #increase! depending on the previous action
                phasic_rate = 0

    #Phasic component is the main,as
    result = 0

    #Higher arousal
    if ((phasic_rate + tonic_rate + hr_rate) / 3.0) > 0.5:
        #Check last action
        if m_lastAction == m_DECREASE:
            if m_curLevel == 1:
                result = 0
                m_lastAction = m_STAY
            elif levelStatesList[m_curLevel - 2]['HR_mean'] is None:
                result = -1
                m_lastAction = m_DECREASE
            else:
                lowerAffectiveState = (
                    (1 if levelStatesList[m_curLevel -
                                          2]['HR_mean'] < current_HR else 0) +
                    (1 if levelStatesList[m_curLevel - 2]['HRV'] > current_HRV
                     else 0) +
                    (1 if levelStatesList[m_curLevel - 2]['Tonic_mean'] <
                     current_Tonic_mean else 0) +
                    (1 if levelStatesList[m_curLevel - 2]['Phasic_mean'] <
                     current_Phasic_mean else 0)) / 4
                if levelStatesList[m_curLevel - 2]['HR_mean'] is None:
                    result = -1
                    m_lastAction = m_DECREASE
                elif lowerAffectiveState > 0.5:
                    result = -1
                    m_lastAction = m_DECREASE
                else:
                    result = 0
                    m_lastAction = m_STAY
        elif m_lastAction == m_INCREASE:
            if m_curLevel == 5:
                result = 0
                m_lastAction = m_STAY
            elif levelStatesList[m_curLevel]['HR_mean'] is None:
                result = 1
                m_lastAction = m_INCREASE
            else:
                upperAffectiveState = (
                    (1 if levelStatesList[m_curLevel]['HR_mean'] < current_HR
                     else 0) +
                    (1 if levelStatesList[m_curLevel]['HRV'] > current_HRV else
                     0) + (1 if levelStatesList[m_curLevel]['Tonic_mean'] <
                           current_Tonic_mean else 0) +
                    (1 if levelStatesList[m_curLevel]['Phasic_mean'] <
                     current_Phasic_mean else 0)) / 4
                if upperAffectiveState > 0.5:
                    if hrv_rate == -1:
                        result = -1
                        m_lastAction = m_DECREASE
                    else:
                        result = 1
                        m_lastAction = m_INCREASE
                else:
                    result = 0
                    m_lastAction = m_STAY
        else:
            if hrv_rate == -1:
                result = -1
                m_lastAction = m_DECREASE
            elif hrv_rate == 0:
                result = 0
                m_lastAction = m_STAY
            else:
                result = 1
                m_lastAction = m_INCREASE
    # significant lower arousal -- SHOULD NOT STAY
    elif ((phasic_rate + tonic_rate + hr_rate) / 3.0) < 0.0:
        #REVERT!
        if m_curLevel == 1:
            result = 1
            m_lastAction = m_INCREASE
        elif m_curLevel == 5:
            result = -1
            m_lastAction = m_DECREASE
        elif m_lastAction == m_DECREASE:
            result = 1
            m_lastAction = m_INCREASE
        elif m_lastAction == m_INCREASE:
            result = -1
            m_lastAction = m_DECREASE
        else:
            upperAffectiveState = (
                (1 if levelStatesList[m_curLevel]['HR_mean'] < current_HR else
                 0) +
                (1 if levelStatesList[m_curLevel]['HRV'] > current_HRV else 0)
                + (1 if levelStatesList[m_curLevel]['Tonic_mean'] <
                   current_Tonic_mean else 0) +
                (1 if levelStatesList[m_curLevel]['Phasic_mean'] <
                 current_Phasic_mean else 0)) / 4
            lowerAffectiveState = (
                (1 if levelStatesList[m_curLevel - 2]['HR_mean'] < current_HR
                 else 0) +
                (1 if levelStatesList[m_curLevel - 2]['HRV'] > current_HRV else
                 0) + (1 if levelStatesList[m_curLevel - 2]['Tonic_mean'] <
                       current_Tonic_mean else 0) +
                (1 if levelStatesList[m_curLevel - 2]['Phasic_mean'] <
                 current_Phasic_mean else 0)) / 4
            if upperAffectiveState > 0.5:
                m_lastAction = m_DECREASE
                result = -1
            elif lowerAffectiveState > 0.5:
                m_lastAction = m_INCREASE
                result = 1
            else:
                m_lastAction = m_DECREASE
                result = -1

    #No real change between this and the previous, do the same action again
    else:
        if m_previousPhasic is None:
            result = 1
            m_lastAction = m_INCREASE
        elif m_curLevel == 1:
            result = 1
            m_lastAction = m_INCREASE
        elif m_curLevel == 5:
            result = -1
            m_lastAction = m_DECREASE
        elif m_lastAction == m_DECREASE:
            result = -1
        elif m_lastAction == m_INCREASE:
            result = 1
        else:
            result = 0
            m_lastAction = m_STAY

    #Finish off

    m_prevLevel = m_curLevel
    m_curLevel += result
    if m_curLevel > 5:
        m_curLevel = 5
    elif m_curLevel < 1:
        m_curLevel = 1

    m_previousHR = current_HR
    m_previousHRV = current_HRV

    levelStatesList[m_prevLevel - 1]['HR_mean'] = m_previousHR
    levelStatesList[m_prevLevel - 1]['HRV'] = m_previousHRV

    progressionStateList[m_Iteration]['HR_mean'] = m_previousHR
    progressionStateList[m_Iteration]['HRV'] = m_previousHRV

    m_previousTonic = current_Tonic
    m_previousPhasic = current_Phasic

    levelStatesList[m_prevLevel - 1]['Tonic_mean'] = current_Tonic_mean
    levelStatesList[m_prevLevel - 1]['Phasic_mean'] = current_Phasic_mean

    progressionStateList[m_Iteration]['Tonic_mean'] = current_Tonic_mean
    progressionStateList[m_Iteration]['Phasic_mean'] = current_Phasic_mean

    progressionStateList[m_Iteration]['Level'] = m_prevLevel

    m_Iteration += 1
    print("Baseline HR: {0}    HRV: {1}".format(m_baseHR, m_baseHRV))
    print(
        "Phasic:{0}, tonic: {1}, hr: {2}(BPM){3:.3f}, hrv: {4}(RMSSD){5:.3f}".
        format(phasic_rate, tonic_rate, hr_rate, current_HR, hrv_rate,
               current_HRV))
    print("Done with result: {0}".format(result))
    return result
コード例 #8
0
ファイル: test_eda.py プロジェクト: rhenanbartels/NeuroKit.py
import neurokit as nk
import pandas as pd
import matplotlib.pyplot as plt
import biosppy
import numpy as np
eda = pd.Series.from_csv("test_eda.csv")  # 100 Hz

#proc = nk.eda_process(eda, sampling_rate=100, use_cvxEDA=True, cvxEDA_normalize=True, cvxEDA_alpha=0.0008, cvxEDA_gamma=0.01)
proc = nk.eda_process(eda, sampling_rate=100, use_cvxEDA=False, cvxEDA_normalize=True, cvxEDA_alpha=0.0008, cvxEDA_gamma=0.01)


print(len(proc["EDA"]["SCR_Peaks_Indexes"]))

proc["df"].plot()
for i in proc["EDA"]["SCR_Peaks_Indexes"]:
    plt.axvline(i, color='red')
#
#eda2 = proc["df"]["EDA_Filtered"]
#scr = dict(biosppy.eda.basic_scr(eda2, sampling_rate=100))
#print(len(scr["peaks"]))
#
#
#onsets, peaks, amps = biosppy.eda.kbk_scr(eda2, sampling_rate=100)
#print(len(peaks))
#onsets, peaks, amps = biosppy.eda.basic_scr(eda2, sampling_rate=100)
#print(len(peaks))
コード例 #9
0
ファイル: q3Baseline.py プロジェクト: Botched135/q3NEAT
    raise SystemExit

Timestamps, BVP_numpy = genfromtxt(
    'NodeJS/CSV/Participant{0}BVPBaseline.csv'.format(args.participantID),
    delimiter=';',
    skip_header=1,
    unpack=True)
EDA_df = pd.read_csv('NodeJS/CSV/Participant{0}EDABaseline.csv'.format(
    args.participantID),
                     delimiter=';')

working_data, measures = hb.process(BVP_numpy,
                                    64.0,
                                    report_time=True,
                                    calc_freq=True)
processed_eda = nk.eda_process(EDA_df["EDA"], freq=1.9, sampling_rate=4)

path = "BaselineData/Participant{0}/".format(args.participantID)
if not os.path.exists(path):
    os.makedirs(path)

hb.plotter(working_data, measures)
print("Average heartrate(BPM): {0}".format(measures['bpm']))
print("Average HRV(RMSSD): {0} ".format(measures['rmssd']))
print("Average HRV(LF): {0}".format(measures['lf']))
processed_eda["df"].plot()

hr_dict = {}
hr_dict['working_data'] = working_data
hr_dict['measures'] = measures
# Store the baseline dicts to be transported
コード例 #10
0
    testType = ''
    Timestamps, BVP_numpy = genfromtxt(
        'NodeJS/CSV/Participant{0}BVP{1}{2}.csv'.format(
            args.participantID, testType, dataType),
        delimiter=';',
        skip_header=1,
        unpack=True)
    EDA_df = pd.read_csv('NodeJS/CSV/Participant{0}EDA{1}{2}.csv'.format(
        args.participantID, testType, dataType),
                         delimiter=';')

    working_data, measures = hb.process(BVP_numpy,
                                        64.0,
                                        report_time=True,
                                        calc_freq=True)
    processed_eda = nk.eda_process(EDA_df["EDA"], freq=1.9, sampling_rate=4)

    path = "BaselineData/Participant{0}/".format(args.participantID)
    if not os.path.exists(path):
        os.makedirs(path)

    hb.plotter(working_data, measures)
    print("Average heartrate(BPM): {0}".format(measures['bpm']))
    print("Average HRV(RMSSD): {0} ".format(measures['rmssd']))
    print("Average HRV(LF): {0}".format(measures['lf']))
    processed_eda["df"].plot()

    hr_dict = {}
    hr_dict['working_data'] = working_data
    hr_dict['measures'] = measures
コード例 #11
0
import pywt


"""
https://github.com/MITMediaLabAffectiveComputing/eda-explorer
http://eda-explorer.media.mit.edu/info/
"""






df, sampling_rate = nk.read_acqknowledge("bio_data.acq", return_sampling_rate=True)
eda = df["EDA, X, PPGED-R"]
eda_processed = nk.eda_process(eda, sampling_rate=sampling_rate)
eda = eda_processed["df"]["EDA_Phasic"]


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_feature3
        waveHalfSecond: DateFrame, index is a list of timestamps at 2Hz, columns include HalfSecond_feature1, HalfSecond_feature2
    '''

    # Create wavelet dataframes
    oneSecond =
コード例 #12
0
ファイル: q3Affective.py プロジェクト: Botched135/q3NEAT
def EvaluateAdaptiveBiostate(BVP_array=None, EDA_array=None):
    #1: higher arousal
    #0: no notificable change
    #-1: lower arousal
    hr_rate = 0
    hrv_rate = 0
    tonic_rate = 0
    phasic_rate = 0

    if BVP_array is not None:
        working_data, hb_measure = hb.process(BVP_array,
                                              64.0,
                                              report_time=True)
    #TODO: Test the difference between resting and playing against the easiest possible character
    # High heart rate and high HRV = decrease level

    if EDA_array is not None:
        current_EDA = nk.eda_process(EDA_array, freq=1.9, sampling_rate=4)

    current_HR = hb_measure['bpm']
    current_HRV = hb_measure['rmssd']
    # Firstly, is he excited compared to baseline this is for HR and EDA
    # Secondly, is he exicted compared to previous
    # 1:0 : Might need to switch back
    # 0:1 : switch up
    # 0:0 : switch up
    # 1:1 : stay
    #Do the evaluation stuff

    #If there is NO difference significantly between HR & EDA and the arousal was higher before, switch back

    #HR
    print(m_baseHR)
    print(percentage_change)
    hr_state = m_baseHR * percentage_change < current_HR
    if m_previousHR == None:
        hr_rate = 1 if hr_state else 0
    elif hr_state == 1:
        prev_hr_state = m_previousHR * percentage_change
        if prev_hr_state < current_HR:
            hr_rate = 1
        elif current_HR * percentage_change < m_previousHR:
            hr_rate = -1
        else:
            hr_rate = 0
    else:
        hr_rate = 0

    #HRV, use HRV in the end.
    hrv_state = m_baseHRV > current_HRV * percentage_change
    if m_previousHRV == None:
        hrv_rate = 1 if hrv_state else 0  #Compare with previous set
    elif hrv_state == 1:
        prev_hrv_state = m_previousHRV
        if prev_hr_state > current_HRV * percentage_change:
            hr_rate = 1
        elif current_HRV < m_previousHRV * percentage_change:
            hrv_rate = -1
        else:
            hrv_rate = 0
    else:
        hrv_rate = -1 if current_HRV > m_baseHRV * percentage_change else 0

    #EDA Tonic
    current_Tonic = current_EDA['df']['EDA_Tonic']
    tonic_stats = mw(current_Tonic, m_baseTonic, alternative='greater')

    if m_previousTonic == None:
        if tonic_stats.p_value > p_value:
            tonic_rate = 1  #must upgrade
        else:
            tonic_greater_stats = mw(current_Tonic,
                                     m_previousTonic,
                                     alternative='greater')
            tonic_less_stats = mw(current_Tonic,
                                  m_previousTonic,
                                  alternative='less')
            if tonic_greater_stats.p_value <= p_value:
                # This is good. Stay or increase
                tonic_rate = 1
            elif tonic_less_stats.p_value <= p_value:
                tonic_rate = -1  #Revert back to the previous!
            else:
                tonic_rate = 0
    else:
        if tonic_stats.p_value <= p_value:
            tonic_rate = 1  #Increase or stay
        else:
            tonic_rate = 0  #Increase!

    #EDA Phasic
    current_Phasic = current_EDA['df']['EDA_Phasic']
    phasic_stats = mw(current_Phasic, m_basePhasic, alternative='greater')

    if m_previousPhasic == None:
        if phasic_stats.p_value > p_value:
            phasic_rate = 1
        else:
            phasic_greater_stats = mw(current_Phasic,
                                      m_previousPhasic,
                                      alternative='greater')
            phasic_less_stats = mw(current_Phasic,
                                   m_previousPhasic,
                                   alternative='less')
            if phasic_greater_stats.p_value <= p_value:
                #stay! Or increae
                phasic_rate = 1
            elif phasic_less_stats.p_value <= p_value:
                #Revert back
                phasic_rate = -1
            else:
                #increase! depending on the previous action
                phasic_rate = 0

    else:
        if phasic_stats.p_value <= p_value:
            phasic_rate = 1
        else:
            phasic_rate = 0

    #Phasic component is the main,as
    result = 0

    #Higher arousal
    if ((current_Phasic + current_Tonic + current_HR) / 3.0) > 0.5:
        if hrv_rate == -1:
            result = -1
            m_lastAction = m_DECREASE
        else:
            result = 1
            m_lastAction = m_INCREASE
            #
    # significant lower arousal --
    elif ((current_Phasic + current_Tonic + current_HR) / 3.0) < 0.0:
        #REVERT!
        result = m_prevLevel - m_curLevel
        m_lastAction = m_REVERT
    #No real change between this and the previous, do the same action again
    else:
        if m_lastAction == m_DECREASE:
            result = -1
        elif m_lastAction == m_INCREASE:
            result = 1

    #Finish off
    m_prevLevel = m_curLevel
    m_curLevel += result

    m_previousHR = hb_measure['bpm']
    m_previousHRV = hb_measure['rmssd']
    m_previousTonic = current_Tonic
    m_previousPhasic = current_Phasic
    return result