コード例 #1
0
ファイル: DA.py プロジェクト: vancleys/EEGFeatures
def DA(x, y):

    mean = np.subtract(np.mean(x), np.mean(y))
    std = np.subtract(np.std(x), np.std(y))
    # dfa = nolds.dfa(x) - nolds.dfa(y)

    fs = 128
    band = [1, 4, 8, 12, 30]

    power = np.subtract(pyeeg.bin_power(x, band, fs),
                        pyeeg.bin_power(y, band, fs))

    return mean, std, power
コード例 #2
0
 def BandPower(self):
     resp = pyeeg.bin_power(self.channel_data, self.bands,
                            self.samplingFrequency)
     resp = np.array(resp).flatten()
     label = 'bandPower_'
     labels = label + pd.Series(range(len(resp)), dtype=str)
     return [resp, labels.values]
コード例 #3
0
	def SpectralEntropy(self):
		b = pyeeg.bin_power(self.channel_data,self.bands,self.samplingFrequency)
		resp = pyeeg.spectral_entropy(self.channel_data,self.bands,self.samplingFrequency,Power_Ratio=b)
		resp = [0 if math.isnan(x) else x for x in resp]
		label = 'SpectralEntropy_'
		labels = label+pd.Series(range(len(resp)),dtype=str)
		return [np.array(resp),labels.values]
コード例 #4
0
def process_eeg(segment): # untested!
    # Group each channel in a sequence then run the processing on each sequence, missing the formatting for that right now
    
    segment = [line.strip().split(" , ") for line in segment]

    names = segment[0]

    segment = segment[1:]

    segment = numpy.array(segment)

    channels = [onetime[:,i] for i in range(segment.shape[1])]

    features = []

    for channel in channels[1:15]:
        channel = signal.lfilter(b_coef, a_coef, channel)
        windowed_seq = channel*hannwindow
        power, power_ratios = pyeeg.bin_power(windowed_seq, bands, sample_rate)
        feature.append(numpy.concatenate((power, power_ratios)))

    features = numpy.concatenate(features)
    relativetimestamp = numpy.mean(channels[:,17])       
    systemtime = channels[:,-1][-1]
    eegfeatures = numpy.concatenate((features, relativetimestamp, systemtime))
    return eegfeatures
コード例 #5
0
def get_psi_entropies(data):

    bands = [0.5, 4, 7, 12, 30, 100]
    fs = 125
    array_length = 1024

    cols = data.shape[1]
    rows = math.floor(data.shape[0] / array_length)
    alpha_psi_entropies = pd.DataFrame([])
    temp_data = pd.DataFrame()

    for x in range(cols):
        alpha_psis = []
        entropies = []
        temp_col_alpha = 'alpha_psi ' + str(x)
        temp_col_entropy = 'spectral_entropy ' + str(x)
        for y in range(rows):

            psis, power_ratios = bin_power(
                data.iloc[(y * array_length):((y + 1) * array_length), x],
                bands, fs)
            alpha_psis.append(psis[2])

            spec_entropies = spectral_entropy(
                data.iloc[(y * array_length):((y + 1) * array_length), x],
                bands, fs, power_ratios)
            entropies.append(spec_entropies)

        temp_data[temp_col_alpha] = alpha_psis
        temp_data[temp_col_entropy] = entropies

    alpha_psi_entropies = alpha_psi_entropies.append(temp_data,
                                                     ignore_index=True)
    return alpha_psi_entropies
コード例 #6
0
ファイル: ch05_part2.py プロジェクト: Umreen24/cs5310_LabCh5
def get_psi_entropies(data):
    # Setting variables needed for for loop
    band = [0.5, 4, 7, 12, 30, 100]
    fs = 1024
    size = 1024
    
    columns = data.shape[1]
    rows = math.floor(data.shape[0] / size)
    alpha_psi_df = pd.DataFrame([])
    temp_data = pd.DataFrame([])
    
    # Creating for loop
    for x in range(columns):
        alpha_psis = []
        entropies = []
        temp_col_alpha = 'alpha_psi ' + str(x)
        temp_col_entropy = 'spectral_entropy ' + str(x)
        
        for y in range(rows):
            psis, power_ratios = bin_power(data.iloc[(y * size):((y + 1) * size), x], band, fs)
            alpha_psis.append(psis[2])
    
            spec_entropies = spectral_entropy(data.iloc[(y * size):((y + 1) * size), x], band, fs, power_ratios)
            entropies.append(spec_entropies)
        
        temp_data[temp_col_alpha] = alpha_psis
        temp_data[temp_col_entropy] = entropies
        
    alpha_psi_df = alpha_psi_df.append(temp_data, ignore_index = True)
    
    return alpha_psi_df
コード例 #7
0
def spectral_entropy(X, Band, Fs, Power_Ratio=None):
    """Compute spectral entropy of a time series from either two cases below:
    1. X, the time series (default)
    2. Power_Ratio, a list of normalized signal power in a set of frequency
    bins defined in Band (if Power_Ratio is provided, recommended to speed up)

    In case 1, Power_Ratio is computed by bin_power() function.

    Notes
    -----
    To speed up, it is recommended to compute Power_Ratio before calling this
    function because it may also be used by other functions whereas computing
    it here again will slow down.

    Parameters
    ----------

    Band
        list

        boundary frequencies (in Hz) of bins. They can be unequal bins, e.g.
        [0.5,4,7,12,30] which are delta, theta, alpha and beta respectively.
        You can also use range() function of Python to generate equal bins and
        pass the generated list to this function.

        Each element of Band is a physical frequency and shall not exceed the
        Nyquist frequency, i.e., half of sampling frequency.

     X
        list

        a 1-D real time series.

    Fs
        integer

        the sampling rate in physical frequency

    Returns
    -------

    As indicated in return line

    See Also
    --------
    bin_power: pyeeg function that computes spectral power in frequency bins

    """

    if Power_Ratio is None:
        from pyeeg import bin_power
        Power, Power_Ratio = bin_power(X, Band, Fs)

    Spectral_Entropy = 0
    for i in range(0, len(Power_Ratio) - 1):
        Spectral_Entropy += Power_Ratio[i] * numpy.log(Power_Ratio[i])
    Spectral_Entropy /= numpy.log(
        len(Power_Ratio))  # to save time, minus one is omitted
    return -1 * Spectral_Entropy
コード例 #8
0
ファイル: BandPower.py プロジェクト: vancleys/EEGFeatures
def BandPower( x ):

	fs = 128
	band = [1,4,8,12,30]

	resp = pyeeg.bin_power(x,band,fs)

	return resp
コード例 #9
0
def binTheta(l_np):
  freq = l_np.shape[1]
  #print "freq: " + str(freq)
  binPowTheta = np.zeros(l_np.shape[0])
  for i in range(0,l_np.shape[0]):
    binPowerArray = pyeeg.bin_power(l_np[i], [0.5,4,7,12,30], freq)
    binPowTheta[i]=(binPowerArray[1][1])
  return binPowTheta
コード例 #10
0
def binTheta(l_np):
    freq = l_np.shape[1]
    #print "freq: " + str(freq)
    binPowTheta = np.zeros(l_np.shape[0])
    for i in range(0, l_np.shape[0]):
        binPowerArray = pyeeg.bin_power(l_np[i], [0.5, 4, 7, 12, 30], freq)
        binPowTheta[i] = (binPowerArray[1][1])
    return binPowTheta
コード例 #11
0
def bin_power(dataset, fsamp, Band=range(0, 45)):
    dataset_power = []
    for i, data in enumerate(dataset):
        res = []
        for j, channel in enumerate(data):
            power = pyeeg.bin_power(channel, Band=Band, Fs=fsamp)[0]
            res.append(power)
        dataset_power.append(res)
    return dataset_power
コード例 #12
0
def SpectralEntropy(x):

    fs = 128
    band = [1, 4, 8, 12, 30]
    b = pyeeg.bin_power(x, band, fs)
    resp = pyeeg.spectral_entropy(x, band, fs, Power_Ratio=b)

    resp = [0 if math.isnan(x) else x for x in resp]

    return resp
コード例 #13
0
 def SpectralEntropy(self):
     b = pyeeg.bin_power(self.channel_data, self.bands,
                         self.samplingFrequency)
     resp = pyeeg.spectral_entropy(self.channel_data,
                                   self.bands,
                                   self.samplingFrequency,
                                   Power_Ratio=b)
     resp = [0 if math.isnan(x) else x for x in resp]
     label = 'SpectralEntropy_'
     labels = label + pd.Series(range(len(resp)), dtype=str)
     return [np.array(resp), labels.values]
コード例 #14
0
ファイル: rolling_windows.py プロジェクト: fanying2015/BCIpy
def rolling_power_ratio(series, bands=[0.5,4,7,12,30], sample_rate=512, window_size=512, step=64):
    strided = as_strided(series, window_size=window_size, step=step)
    print type(strided)
    print strided
    return pd.DataFrame(
        [
            pyeeg.bin_power(window, bands, sample_rate)[1]
            for timestamp, window in strided.iterrows()
        ],
        index=strided.index
    )
コード例 #15
0
	def frame(self, p,window):
		flen = 50
		spectrum, relative_spectrum = bin_power(p.raw_values[-p.buffer_len:], range(flen),512)
		self.spectra.append(array(relative_spectrum))
		if len(self.spectra)>30:
			self.spectra.pop(0)				
		spectrum = mean(array(self.spectra),axis=0)
		value = (1-sum(spectrum[3:8]))*100
		self.graph.insert_value(time(), value)
		for i in range(6):
			pygame.draw.line(window, pygame.Color(0,0,200),(0,400-i*20*3),(600,400-i*20*3), 2)
		self.graph.draw_graph(window,3.0)
コード例 #16
0
ファイル: feature.py プロジェクト: ylin00/seizurecast
def power(data, fsamp: int, band=range(0, 45)):
    """Power spec of dataset

    Args:
        data: num_of_channel x num_of_sample

    """
    res = []
    for j, channel in enumerate(data):
        power = pyeeg.bin_power(channel, Band=band, Fs=fsamp)[0]
        res.append(power)
    return res
コード例 #17
0
def Calc_AlphaPSI(array):
    Band = [0.5, 4, 7, 12, 30]
    Fs = 1024
    lst = []
    num_rows, num_cols = array.shape
    for i in range(int(num_rows / 1024)):
        for j in range((num_cols)):
            psi = pyeeg.bin_power(array[i * 1024:(i + 1) * 1024, j], Band, Fs)
            lst.append(psi[0][2])
    lst_reshaped = numpy.reshape(lst, (-1, 34))
    AlphaPSI_df = pandas.DataFrame(lst_reshaped)
    return AlphaPSI_df
コード例 #18
0
ファイル: main.py プロジェクト: shimpe/mindwave-python
  def update_ui(self):
    self.counter += 1
 
    if self.counter % 10 == 0:
      self.view['raw']
      self.view['raw'].plot(self.last_512_raw_waves, pen=(255,255,255), clear=True)
    if self.counter >= RAW_VAL_WIN_SIZE:
        self.counter = 0
        spectrum, normalized_spectrum = pyeeg.bin_power(self.last_512_raw_waves, [0.5, 4, 8, 13, 30, 100, 256], 512)
        for i, wavetype in enumerate(WAVE_TYPES):
          self.vals[wavetype].pop()
          self.vals[wavetype].appendleft(normalized_spectrum[i])
          self.view[wavetype].plot(self.vals[wavetype], pen=(255, i*30, i*30), clear=True)
def _bin_power(samples, **kwargs):
    """ValueError:
     Error when checking input: expected flatten_1_input to have 2 dimensions,
     but got array with shape (30520, 1, 2, 4)

     Only for local usage: power functions / power ratio functions
     """
    try:
        sampling_freq = kwargs[SAMPLING_FREQ]
        band = kwargs[BAND]
    except KeyError:
        sampling_freq = SAMPLING_FREQ_DEFAULT
        band = BAND_DEFAULT
    return pyeeg.bin_power(samples, Band=band, Fs=sampling_freq)
def FFT_Processing(sub, channel, band, window_size, step_size, sample_rate):
    meta = []
    with open('./source_data/s' + sub + '.dat', 'rb') as file:
        # seq = int(sub)-1
        subject = pickle.load(
            file, encoding='latin1'
        )  #resolve the python 2 data problem by encoding : latin1

        for i in list:
            # loop over 0-39 trails
            data = subject["data"][i]
            labels = subject["labels"][i]
            start = 384
            while start + window_size < data.shape[1]:
                meta_array = []
                meta_data = []  #meta vector for analysis
                x1_2d = []
                x2_2d = []
                x3_2d = []
                for j in channel:
                    X = data[j][
                        start:start +
                        window_size]  #Slice raw data over 2 sec, at interval of 0.125 sec
                    Y = pe.bin_power(
                        X, band, sample_rate
                    )  #FFT over 2 sec of channel j, in seq of theta, alpha, low beta, high beta, gamma
                    Y = Y[0]
                    x1, x2, x3 = Y[2], Y[3], Y[4]
                    x1_2d.append(x1)
                    x2_2d.append(x2)
                    x3_2d.append(x3)
                x1_2d = data_1Dto2D(x1_2d, 9, 9)
                x2_2d = data_1Dto2D(x2_2d, 9, 9)
                x3_2d = data_1Dto2D(x3_2d, 9, 9)
                meta_data.append(x1_2d)
                meta_data.append(x2_2d)
                meta_data.append(x3_2d)
                meta_data = np.array(meta_data)
                meta_array.append(meta_data)
                meta_array.append(labels)
                meta.append(np.array(meta_array))
                start = start + step_size

        meta = np.array(meta)
        print(meta.shape)
        print(meta[0][0].shape)
        np.save('./processed_data/s' + sub,
                meta,
                allow_pickle=True,
                fix_imports=True)
def extract_train_features(files):
    traindata = []
    target = []
    for file in glob.glob(files):
        if 'preictal' in file:
            targetvalue = 1
            mat = loadmat(file)
        if 'interictal' in file:
            targetvalue = -1
            mat = loadmat(file)
        if 'test' in file:
            continue
        for key in mat.keys():
            if 'preictal' in key:
                data = mat[key]
            if 'interictal' in key:
                data = mat[key]
        Fs = data['sampling_frequency'][0][0][0][0]
        dataarray = np.array(data['data'][0][0])
        dataarraym = np.split(dataarray, 3, axis=1)
        for item in dataarraym:
            dfappend1 = []
            dataarray = item
            i = len(dataarray)
            count = []
            for j in range(i):
                count.append(j)
            for item in count:
                initial = dataarray[item]
                initial = np.array(initial)
                s1 = (initial - np.mean(initial)) / np.std(initial)
                p, pr = pyeeg.bin_power(
                    s1,
                    [0.5, 4, 8, 13, 30, 50, 70, 90, Fs / 2],
                    Fs
                    )
                for it in p:
                    dfappend1.append(it)
                for item1 in count[item + 1:]:
                    final = dataarray[item1]
                    final = np.array(final)
            dfappend1 = preprocessing.scale(
                np.array(dfappend1).astype(float),
                axis=0
                )
            dfappend = dfappend1
            traindata.append(dfappend)
            target.append(targetvalue)
    return traindata, target
コード例 #22
0
ファイル: Lab03-Group4.py プロジェクト: Umreen24/cs5310_lab2
def getPSI(data):
    band = [0.5, 4, 7, 12, 30]
    fs = 1024
    sample = 1024
    cols = data.shape[1]
    rows = math.floor(data.shape[0] / sample)
    alpha_psi = pd.DataFrame(0, index=range(rows), columns=range(cols))
    for x in range(cols):
        bin_powers = []
        for y in range(rows):
            psis = bin_power(data.iloc[(y * sample):((y + 1) * sample), x],
                             band, fs)[0][2]
            bin_powers.append(psis)
        alpha_psi[x] = bin_powers
    return alpha_psi
コード例 #23
0
  def check_eyeblink(self, sensitivity, low_freq, high_freq, raw_waves):
    import pyeeg
    spectrum, rel_spectrum = pyeeg.bin_power(raw_waves, [0.5, low_freq, high_freq,100], 512)
    if rel_spectrum[1] > float(sensitivity) and not self.eyeblink_in_progress:
      self.eyeblink_in_progress = True
      if self.eyeblink_detected_callback:
        self.eyeblink_detected_callback()
        return True

    elif rel_spectrum[1] <= float(sensitivity):
      self.eyeblink_in_progress = False
      if self.eyeblink_not_detected_callback:
        self.eyeblink_not_detected_callback()
        return False

    return False
コード例 #24
0
  def check_eyeblink(self, sensitivity, low_freq, high_freq, raw_waves):
    import pyeeg
    spectrum, rel_spectrum = pyeeg.bin_power(raw_waves, [0.5, low_freq, high_freq,100], 512)
    if rel_spectrum[1] > float(sensitivity) and not self.eyeblink_in_progress:
      self.eyeblink_in_progress = True
      if self.eyeblink_detected_callback:
        self.eyeblink_detected_callback()
        return True

    elif rel_spectrum[1] <= float(sensitivity):
      self.eyeblink_in_progress = False
      if self.eyeblink_not_detected_callback:
        self.eyeblink_not_detected_callback()
        return False

    return False
コード例 #25
0
ファイル: mindwaveParser.py プロジェクト: JackieJ/EEGDrone
 def parse(self):
     while not rospy.is_shutdown():
         self.eegParser.update()
         if self.eegParser.sending_data:
             #print >> sys.stdout, "meditation:", self.eegParser.current_meditation
             #print >> sys.stdout, "attention:", self.eegParser.current_attention
             if len(self.eegParser.raw_values) >= 500:
                 self.outputMap['attention'] = self.eegParser.current_attention
                 self.outputMap['meditation'] = self.eegParser.current_meditation
            
                 #retrieve spectrum from the bin power function
                 spectrum,relativeSpectrum = bin_power(self.eegParser.raw_values[-self.eegParser.buffer_len:], range(self.capVal), 512)
                 self.spectra.append(array(relativeSpectrum))
                 if len(self.spectra) > 30:
                     self.spectra.pop(0)
                 spectrum = mean(array(self.spectra),axis=0)
                 #temp variables
                 delta = []
                 theta = []
                 alpha = []
                 beta = []
                 gamma = []
                 for i in range((self.capVal) - 1):
                     #print >> sys.stdout, "spectrum:",spectrum[i]
                     #print >> sys.stdout, "i value:",i
                     if i < 3:
                         delta.append(spectrum[i])
                     elif i < 8:
                         theta.append(spectrum[i])
                     elif i < 13:
                         alpha.append(spectrum[i])
                     elif i < 30:
                         beta.append(spectrum[i])
                     else:
                         gamma.append(spectrum[i])
                         
                 self.outputMap['delta'] = mean(delta, axis=0)*1000
                 self.outputMap['theta'] = mean(theta, axis=0)*1000
                 self.outputMap['alpha'] = mean(alpha, axis=0)*1000
                 self.outputMap['beta'] = mean(beta, axis=0)*1000
                 self.outputMap['gamma'] = mean(gamma, axis=0)*1000
                 self.publish()
         else:
             print >> sys.stdout, "no data sent...reconnecting......"
             self.eegParser.write_serial("\xc2")
コード例 #26
0
def computefftMap(total_signal, chosen_channels, freqs, sf=128):
    # Init
    fftMap = False

    for ch in chosen_channels:
        input_signal = total_signal[ch]

        # Fast Fourier Transform ========================
        ffts = pe.bin_power(input_signal, freqs, sf)
        fft = ffts[1]
        # ===============================================

        # FFT Map
        if type(fftMap) == bool:
            fftMap = fft
        else:
            fftMap = np.vstack((fftMap, fft))
    return fftMap
コード例 #27
0
    def update_ui(self):
        self.counter += 1

        if self.counter % 10 == 0:
            self.view['raw']
            self.view['raw'].plot(self.last_512_raw_waves,
                                  pen=(255, 255, 255),
                                  clear=True)
        if self.counter >= RAW_VAL_WIN_SIZE:
            self.counter = 0
            spectrum, normalized_spectrum = pyeeg.bin_power(
                self.last_512_raw_waves, [0.5, 4, 8, 13, 30, 100, 256], 512)
            for i, wavetype in enumerate(WAVE_TYPES):
                self.vals[wavetype].pop()
                self.vals[wavetype].appendleft(normalized_spectrum[i])
                self.view[wavetype].plot(self.vals[wavetype],
                                         pen=(255, i * 30, i * 30),
                                         clear=True)
コード例 #28
0
def processFileBinPower(data, owDelta, owTheta, owAlpha, owBeta, freq):
  binPowDelta = np.zeros(data['data'].shape[0])
  binPowTheta = np.zeros(data['data'].shape[0])
  binPowAlpha = np.zeros(data['data'].shape[0])
  binPowBeta = np.zeros(data['data'].shape[0])
  #print "size: " + repr(l_np.shape[0])
  #print
  for i in range(0,data['data'].shape[0]):
    binPowerArray = pyeeg.bin_power(data['data'][i], [0.5,4,7,12,30], freq)
    binPowDelta[i]=(binPowerArray[1][0])
    binPowTheta[i]=(binPowerArray[1][1])
    binPowAlpha[i]=(binPowerArray[1][2])
    binPowBeta[i]=(binPowerArray[1][3])

  owDelta.writerow(binPowDelta)
  owTheta.writerow(binPowTheta)
  owAlpha.writerow(binPowAlpha)
  owBeta.writerow(binPowBeta)
コード例 #29
0
def get_state_features(state):

    nof = len(state)
    po = 600

    pfds = np.zeros((4, int(nof / po)))
    ap_entropy = np.zeros((4, int(nof / po)))
    hursts = np.zeros((4, int(nof / po)))
    hfd = np.zeros((4, int(nof / po)))
    bins = np.zeros(((int(nof / po), 4, 2, 5)))

    lastnum = 0

    for i in range(0, (int(nof / po))):
        channels = np.zeros((4, po))

        for x in range(0, po):
            for y in range(0, 4):

                channels[y, x] = float(state[lastnum + x, y])

        for x in range(0, 4):
            channels[x] = scipy.signal.savgol_filter(channels[x],
                                                     11,
                                                     3,
                                                     deriv=0,
                                                     delta=1.0,
                                                     axis=-1,
                                                     mode='interp',
                                                     cval=0.0)

        #alpha=[]
        if ((nof - lastnum) != 0):
            for x in range(0, 4):
                hursts[x, i] = pyeeg.hurst(channels[x])
                pfds[x, i] = pyeeg.pfd(channels[x])
                #ap_entropy[x,i] = pyeeg.ap_entropy(X, M, R)
                hfd[x, i] = pyeeg.hfd(channels[x], 15)
                bins[i, x] = pyeeg.bin_power(channels[x],
                                             [0.5, 4, 7, 12, 15, 18], 200)
                k = 1
        lastnum = lastnum + po

    return pfds, hursts, bins, hfd
コード例 #30
0
def processFileBinPower(data, owDelta, owTheta, owAlpha, owBeta, freq):
    binPowDelta = np.zeros(data['data'].shape[0])
    binPowTheta = np.zeros(data['data'].shape[0])
    binPowAlpha = np.zeros(data['data'].shape[0])
    binPowBeta = np.zeros(data['data'].shape[0])
    #print "size: " + repr(l_np.shape[0])
    #print
    for i in range(0, data['data'].shape[0]):
        binPowerArray = pyeeg.bin_power(data['data'][i], [0.5, 4, 7, 12, 30],
                                        freq)
        binPowDelta[i] = (binPowerArray[1][0])
        binPowTheta[i] = (binPowerArray[1][1])
        binPowAlpha[i] = (binPowerArray[1][2])
        binPowBeta[i] = (binPowerArray[1][3])

    owDelta.writerow(binPowDelta)
    owTheta.writerow(binPowTheta)
    owAlpha.writerow(binPowAlpha)
    owBeta.writerow(binPowBeta)
コード例 #31
0
ファイル: classifier.py プロジェクト: Ammar793/OpenBCI_Python
def getdata(num,):
	global lastnum
	global pfds
	global dfas
	global hursts
	global bins
	global nof
	global po
	#file = 'C:\\Users\\Ammar Raufi\\Desktop\\openbci\\software\\application.windows64\\SavedData\\OpenBCI-RAW-2017-03-18_18-46-49.txt' 

	#fid = open(file, 'r')
	
	#lines = fid.readlines()

	#numberOfFrames = len(lines)-6
	#print(numberOfFrames-lastnum)
	
	
	channels = np.zeros((4,po))
	
	#alpha = np.zeros(4)
	for x in range(0,po): #numberOfFrames-lastnum-6
		
		for y in range(0,4):
			
			channels[y,x] = float(lines[lastnum+x+6].split(',')[y+1])
	
	#alpha=[]
	if((nof-lastnum)!=0):
		for x in range(0,4):
			hursts[x,num] = pyeeg.hurst(channels[x])
			#pfds[x,num] = pyeeg.pfd(channels[x])
			#dfas[x,num] = pyeeg.dfa(channels[x])			
			bins[num,x] = pyeeg.bin_power(channels[x], [0.5,4,7,12,30], 200)	
			k=1

	print (lastnum)
		#print (alpha)
		
	lastnum=lastnum+po
	return channels[0]
コード例 #32
0
ファイル: preprocessing.py プロジェクト: prami1806/eegp
def eeg_features(data):
    data = np.asarray(data)
    res = np.zeros([22])
    Kmax = 5
    # M    = 10
    # R    = 0.3
    Band = [1, 5, 10, 15, 20, 25]
    Fs = 256
    power, power_ratio = pyeeg.bin_power(data, Band, Fs)
    f, P = welch(data, fs=Fs, window='hanning', noverlap=0,
                 nfft=int(256.))  # Signal power spectrum
    area_freq = cumtrapz(P, f, initial=0)
    res[0] = np.sqrt(np.sum(np.power(data, 2)) /
                     data.shape[0])  # amplitude RMS
    res[1] = statistics.stdev(data)**2  # variance
    res[2] = kurtosis(data)  # kurtosis
    res[3] = skew(data)  # skewness
    res[4] = max(data)  # max amplitude
    res[5] = min(data)  # min amplitude
    res[6] = len(argrelextrema(
        data, np.greater)[0])  # number of local extrema or peaks
    res[7] = ((data[:-1] * data[1:]) < 0).sum()  # number of zero crossings
    res[8] = pyeeg.hfd(data, Kmax)  # Higuchi Fractal Dimension
    res[9] = pyeeg.pfd(data)  # Petrosian Fractal Dimension
    res[10] = pyeeg.hurst(data)  # Hurst exponent
    res[11] = pyeeg.spectral_entropy(
        data, Band, Fs, Power_Ratio=power_ratio)  # spectral entropy (1.21s)
    res[12] = area_freq[-1]  # total power
    res[13] = f[np.where(area_freq >= res[12] / 2)[0][0]]  # median frequency
    res[14] = f[np.argmax(P)]  # peak frequency
    res[15], res[16] = pyeeg.hjorth(data)  # Hjorth mobility and complexity
    res[17] = power_ratio[0]
    res[18] = power_ratio[1]
    res[19] = power_ratio[2]
    res[20] = power_ratio[3]
    res[21] = power_ratio[4]
    # res[22] = pyeeg.samp_entropy(data, M, R)             # sample entropy
    # res[23] = pyeeg.ap_entropy(data, M, R)             # approximate entropy (1.14s)
    return (res)
コード例 #33
0
ファイル: feature.py プロジェクト: ylin00/seizurecast
def feature_channel(channel, fsamp=256, band=range(0, 45)):
    """Convert time series of a given channel to list of features.
    Args:
        channel: 1-D array-like
        fsamp: sampling rate in Hz.
        band: band-pass in Hz.
    Returns:
        list: 1-D array-like
    """

    # catch 22
    res = catch22.catch22_all(channel)['values']

    # power and freq
    power = pyeeg.bin_power(channel, Band=band, Fs=fsamp)[0]
    pwd = np.mean(power)
    freqs = np.arange(0, len(power))
    pdf = np.array(power) / np.sum(power)
    mu = np.sum(freqs * pdf)
    # m2 = np.sum((freqs - mu)**2 * pdf)
    res.extend([pwd, mu])

    return res
コード例 #34
0
def get_state_features(channel):

    nof = len(channel)
    pfds = np.zeros((4))
    ap_entropy = np.zeros((4))
    hursts = np.zeros((4))
    hfd = np.zeros((4))
    bins = np.zeros(((4, 2, 5)))

    lastnum = 0

    #alpha=[]
    if ((nof - lastnum) != 0):
        for x in range(0, 4):
            hursts[x] = pyeeg.hurst(channel[x])
            pfds[x] = pyeeg.pfd(channel[x])
            #ap_entropy[x,i] = pyeeg.ap_entropy(X, M, R)
            hfd[x] = pyeeg.hfd(channel[x], 15)
            bins[x] = pyeeg.bin_power(channel[x], [0.5, 4, 7, 12, 15, 18], 200)

    delta = np.zeros((4))
    beta = np.zeros((4))
    alpha = np.zeros((4))
    theta = np.zeros((4))
    dfas = np.zeros((4))
    bt = np.zeros((4))

    for y in range(0, 4):
        delta[y] = bins[y, 0, 0]
        theta[y] = bins[y, 0, 1]
        alpha[y] = bins[y, 0, 2]
        beta[y] = bins[y, 0, 4]
        bt[y] = theta[y] / beta[y]

    lastnum = lastnum + nof

    return pfds, dfas, hursts, bins, bt, hfd
コード例 #35
0
 def callback(self, path, args, types, src):
     write = sys.stdout.write
     absolutes = [
         "/muse/elements/low_freqs_absolute",
         "/muse/elements/alpha_absolute",
         "/muse/elements/beta_absolute",
         "/muse/elements/delta_absolute",
         "/muse/elements/gamma_absolute",
         "/muse/elements/theta_absolute",
     ]
     relatives = [
         "/muse/elements/alpha_relative",
         "/muse/elements/beta_relative",
         "/muse/elements/delta_relative",
         "/muse/elements/gamma_relative",
         "/muse/elements/theta_relative",
     ]
     raw_ffts = [
         "/muse/elements/raw_fft0",
         "/muse/elements/raw_fft1",
         "/muse/elements/raw_fft2",
         "/muse/elements/raw_fft3",
     ]
     session_scores = [
         "/muse/elements/alpha_session_score",
         "/muse/elements/beta_session_score",
         "/muse/elements/delta_session_score",
         "/muse/elements/gamma_session_score",
         "/muse/elements/theta_session_score",
     ]
     if path == "/muse/elements/experimental/concentration":
         self.attention = args[0]
         # print "CONCENTRATION " + str(args[0])
         pass
     elif path == "/muse/elements/experimental/mellow":
         self.meditation = args[0]
         # print "MELLOW " + str(args[0])
         pass
     elif path == "/muse/eeg":
         pass
     elif path == "/muse/batt":
         pass
     elif path == "/muse/eeg/dropped_samples":
         pass
     elif path == "/muse/acc":
         pass
     elif path == "/muse/config":
         pass
     elif path == "/muse/version":
         pass
     elif path == "/muse/drlref":
         pass
     elif path == "/muse/eeg/quantization":
         pass
     elif path == "/muse/elements/horseshoe":
         pass
     elif path == "/muse/elements/is_good":
         pass
     elif path == "/muse/elements/blink":
         pass
     elif path == "/muse/elements/jaw_clench":
         pass
     elif path == "/muse/elements/touching_forehead":
         pass
     elif path in absolutes:
         pass
     elif path in relatives:
         pass
     elif path in session_scores:
         pass
     elif path in raw_ffts:
         if path == "/muse/elements/raw_fft0":
             self.raw_fft0 = args
             bands = [1, 4, 8, 10, 13, 18, 31, 41, 50]
             bin_powers, bin_relative = pyeeg.bin_power(args, bands, 220)
             self.waves_vector = bin_powers
         elif path == "/muse/elements/raw_fft1":
             self.raw_fft1 = args
         elif path == "/muse/elements/raw_fft2":
             self.raw_fft2 = args
         elif path == "/muse/elements/raw_fft3":
             self.raw_fft3 = args
     else:
         write(path + " ,")
         write(types)
         for a, t in zip(args, types):
             write(" ")
             if t is None:
                 write("[unknown type]")
             elif t == "b":
                 write("[" + self.blob_to_hex(a) + "]")
             else:
                 write(str(a))
         write("\n")
コード例 #36
0
ファイル: sdl_viewer.py プロジェクト: BlueT/python-mindwave
meditation_img = font.render("Meditation", False, redColor)
attention_img = font.render("Attention", False, redColor)

record_baseline = False

while True:
	p.update()
	window.blit(background_img,(0,0))
	if p.sending_data:
		iteration+=1
		
		flen = 50
			
		if len(p.raw_values)>=500:
			spectrum, relative_spectrum = bin_power(p.raw_values[-p.buffer_len:], range(flen),512)
			spectra.append(array(relative_spectrum))
			if len(spectra)>30:
				spectra.pop(0)
				
			spectrum = mean(array(spectra),axis=0)
			for i in range (flen-1):
				value = float(spectrum[i]*1000) 
				if i<3:
					color = deltaColor
				elif i<8:
					color = thetaColor
				elif i<13:
					color = alphaColor
				elif i<30:
					color = betaColor
コード例 #37
0
def pyeegSignal(X,fs=200,bb=[0.5,4,7,12,30]):
    return bin_power(X,Band=bb,Fs=fs)
コード例 #38
0
	def BandPower(self):
		resp = pyeeg.bin_power(self.channel_data,self.bands,self.samplingFrequency)
		resp = np.array(resp).flatten()
		label = 'bandPower_'
		labels = label+pd.Series(range(len(resp)),dtype=str)
		return [resp,labels.values]
コード例 #39
0
ファイル: dataAnalysisFunctions.py プロジェクト: D1o0g9s/MyND
def getPowerRatio(eeg_data, binning, eeg_fs=250):
    power, power_ratio = pyeeg.bin_power(eeg_data, binning, eeg_fs)
    return np.array(power_ratio)
コード例 #40
0
ファイル: ANN_window.py プロジェクト: selwyn96/EEG-Project
					while m<11:
						count=0
						max=450
						min=-50
						a=nos[m]
						electrode=x[a]
						sum=0
						counter=0

						while max<2500:

							max=max+50
							min=min+50

							final= electrode[min:max]
							power,power_ratio=pyeeg.bin_power(final,Band,250)
							power_ratio=np.array(power_ratio)
							sum=sum+power_ratio
							counter=counter+1

						

						sum=sum/counter

						if m==0:
							
						 	temp12=sum
						if (m==1):

						 	image=np.append(temp12,sum)
						if m>1:
コード例 #41
0
    #~ else:
    #~ print "Client send: " + msg
    #~ csock.send("Hello I'm Server.\r\n")
    #~ csock.close()

    #~ csock.send("Hello I'm Server.\r\n")

    while True:
        p.update()
        if p.sending_data:
            iteration += 1

            flen = 50

            if len(p.raw_values) >= 500:
                spectrum, relative_spectrum = bin_power(
                    p.raw_values[-p.buffer_len:], range(flen), 512)
                spectra.append(array(relative_spectrum))
                if len(spectra) > 30:
                    spectra.pop(0)

                spectrum = mean(array(spectra), axis=0)
                for i in range(flen - 1):
                    value = float(spectrum[i] * 1000)
                    #~ if i<3:
                    #~ color = deltaColor
                    #~ elif i<8:
                    #~ color = thetaColor
                    #~ elif i<13:
                    #~ color = alphaColor
                    #~ elif i<30:
                    #~ color = betaColor
コード例 #42
0
ファイル: rolling_windows.py プロジェクト: fanying2015/BCIpy
def rolling_power(series, bands=[0.5,4,7,12,30], sample_rate=512):
    return [ pyeeg.bin_power(window, bands, sample_rate)[0] for window in as_strided(series) ]
コード例 #43
0
ファイル: fft2.py プロジェクト: thegyro/EEG-Classfication
#import pyqtgraph as pg
#from pyqtgraph.Qt import QtCore, QtGui
import numpy as np
import pickle
import pyeeg
import sys
import pylab
from filter_test import butter_bandpass_filter


with open(sys.argv[1]) as eeg:
    net_eeg_data = pickle.load(eeg)


N = 500
Fs = 128

eeg_data = butter_bandpass_filter(net_eeg_data[:N,1].astype(np.int64) - net_eeg_data[:N,3].astype(np.int64),4,40,128,4)
freq = [0.5,4,7,12,30,40,50]
#freq = np.linspace(4,40,N)
power,ratio = pyeeg.bin_power(eeg_data,freq,Fs)

pylab.plot(freq[:-1],power,color='r')
pylab.show()
コード例 #44
0
for k1 in chunkList1:
    dataList1 = str(k1).replace('[','').replace(']','').replace('\'','').split(' ')
    dataListArray1.append(dataList1)
for j in range(len(dataListArray1)):
    for i in range(len(dataListArray1[j])):
        filePath = 'EEG\eyeopen\Teyeopen' + str(j+1) + '.txt'
        with open (filePath,'a') as fo:
            fo.write(dataListArray1[j][i]+'\n')
			
			
			
# here generating the feature using bin_power function for generationg and extracting Alpha signal
with open('resultc3.txt','a') as resultc:
    for i in range(40):
        X = open("EEG\eyeclose\Teyeclose"+str(i+1)+".txt","r")
        power , power_ratio = bin_power(list(X)[-512*3:],[0.5,4,7,12,30], 1024)
        signal_splitted =str(power).split()
        alpha_Signal = signal_splitted[3]
        resultc.write(str(alpha_Signal)+'\n')

with open('resulto3.txt', 'a') as resulto:
    for i in range(40):
        X = open("EEG\eyeopen\Teyeopen" + str(i + 1) + ".txt", "r")
        power, power_ratio = bin_power(list(X)[-512 * 3:], [0.5, 4, 7, 12, 30], 1024)
        signal_splitted = str(power).split()
        alpha_Signal = signal_splitted[3]
        resulto.write(str(alpha_Signal) + '\n')

with open('resultc2.txt','a') as resultc:
    for i in range(40):
        X = open("EEG\eyeclose\Teyeclose"+str(i+1)+".txt","r")