Ejemplo n.º 1
0
def bandpass(x, sampling_rate, f_min, f_max, verbose=0):
    """
	xf = bandpass(x, sampling_rate, f_min, f_max)

	Description
	--------------

	Phasen-treue mit der rueckwaerts-vorwaerts methode!
	Function bandpass-filters a signal without roleoff.  The cutoff frequencies,
	f_min and f_max, are sharp.

	Arguements
	--------------
		x: 			input timeseries
		sampling_rate: 			equidistant sampling with sampling frequency sampling_rate
		f_min, f_max:			filter constants for lower and higher frequency
	
	Returns
	--------------
		xf:		the filtered signal
	"""
    x, N = np.asarray(x, dtype=float), len(x)
    t = np.arange(N) / np.float(sampling_rate)
    xn = detrend_linear(x)
    del t

    yn = np.concatenate((xn[::-1], xn))  # backwards forwards array
    f = np.float(sampling_rate) * np.asarray(np.arange(2 * N) / 2,
                                             dtype=int) / float(2 * N)
    s = rfft(yn) * (f > f_min) * (f < f_max)  # filtering

    yf = irfft(s)  # backtransformation
    xf = (yf[:N][::-1] + yf[N:]) / 2.  # phase average

    return xf
Ejemplo n.º 2
0
def bandpass(x, sampling_rate, f_min, f_max, verbose=0):
	"""
	xf = bandpass(x, sampling_rate, f_min, f_max)

	Description
	--------------

	Phasen-treue mit der rueckwaerts-vorwaerts methode!
	Function bandpass-filters a signal without roleoff.  The cutoff frequencies,
	f_min and f_max, are sharp.

	Arguements
	--------------
		x: 			input timeseries
		sampling_rate: 			equidistant sampling with sampling frequency sampling_rate
		f_min, f_max:			filter constants for lower and higher frequency
	
	Returns
	--------------
		xf:		the filtered signal
	"""
	x, N = np.asarray(x, dtype=float), len(x)
	t = np.arange(N)/np.float(sampling_rate)
	xn = detrend_linear(x)
	del t

	yn = np.concatenate((xn[::-1], xn))		# backwards forwards array
	f = np.float(sampling_rate)*np.asarray(np.arange(2*N)/2, dtype=int)/float(2*N)
	s = rfft(yn)*(f>f_min)*(f<f_max)			# filtering

	yf = irfft(s)					# backtransformation
	xf = (yf[:N][::-1]+yf[N:])/2.			# phase average

	return xf
Ejemplo n.º 3
0
 def __init__(self, x, y):
     '''
         initialized Arser instance object, detrendedy values, mean, period are calculated
     '''
     self.x = np.array(x)
     self.y = np.array(y)
     self.mean = np.mean(self.y)
     self.dt_y = detrend_linear(self.y)
     self.delta = self.x[1] - self.x[0]
     self.R2 = -1
     self.R2adj = -1
     self.coef_var = -1
     self.pvalue = -1
     self.phase = []
     self.estimate_period = []
     self.amplitude = []
Ejemplo n.º 4
0
def rescaleMe(series, phase, period, numDays=4, n_neighbors=2, axs=[]):
    dayBreaks = [phase+period*day for day in range(numDays+1)]
    timePoints = []
    axs[0].plot(series.index, numpy.array(series), label='normal')
    axs[0].plot(series.index, detrend_linear(numpy.array(series)), label='detrend')
    #axs[0].plot(numpy.array(times_per_day).flatten(), 10000*valuesFlat, label='detrend each')
    
    for i in range(numDays):
        values = map(float, list(series.index[(series.index > dayBreaks[i]) & 
                                              (series.index < dayBreaks[i+1])]))
        timePoints.append(values)
    for i in range(numDays):
        axs[1].plot(numpy.array(timePoints[i]-phase) % period, 
                    cycle_adjust(series.ix[timePoints[i]]), 'o', label=str(i))
        axs[1].set_title('Raw Data Phase Shifted')
        axs[1].legend(loc='best')
Ejemplo n.º 5
0
Archivo: arser.py Proyecto: hmhme/Luc
 def __init__(self, x, y):
     '''
         initialized Arser instance object, detrendedy values, mean, period are calculated
     '''
     self.x = np.array(x)
     self.y = np.array(y)
     self.mean = np.mean(self.y)
     self.dt_y = detrend_linear(self.y)
     self.delta = self.x[1] - self.x[0]
     self.R2 = -1
     self.R2adj = -1
     self.coef_var = -1
     self.pvalue = -1
     self.phase = []
     self.estimate_period = []
     self.amplitude = []
Ejemplo n.º 6
0
def prepare_seeg_observable(seeg_path,
                            on_off_set,
                            channels,
                            win_len=5.0,
                            low_freq=10.0,
                            high_freq=None,
                            log_flag=True,
                            plot_flag=False):
    import re
    from pylab import detrend_linear
    from mne.io import read_raw_edf
    raw_data = read_raw_edf(seeg_path, preload=True)
    rois = np.where(
        [np.in1d(s.split("POL ")[-1], channels) for s in raw_data.ch_names])[0]
    raw_data.resample(128.0)
    fs = raw_data.info['sfreq']
    data, times = raw_data[:, :]
    data = data[rois].T
    plotter = Plotter()
    if plot_flag:
        plotter.plot_spectral_analysis_raster(times,
                                              data,
                                              time_units="sec",
                                              freq=np.array(range(1, 51, 1)),
                                              title='Spectral Analysis',
                                              figure_name='Spectral Analysis',
                                              labels=channels,
                                              log_scale=True)
    data_bipolar = []
    bipolar_channels = []
    data_filtered = []
    bipolar_ch_inds = []
    for iS in range(data.shape[1] - 1):
        if (channels[iS][0] == channels[iS+1][0]) and \
                (int(re.findall(r'\d+', channels[iS])[0]) == int(re.findall(r'\d+', channels[iS+1])[0])-1):
            data_bipolar.append(data[:, iS] - data[:, iS + 1])
            bipolar_channels.append(channels[iS] + "-" + channels[iS + 1])
            data_filtered.append(
                filter_data(data_bipolar[-1],
                            fs,
                            low_freq,
                            60.0,
                            "bandpass",
                            order=3))
            bipolar_ch_inds.append(iS)
    data_bipolar = np.array(data_bipolar).T
    data_filtered = np.array(data_filtered).T
    # filter_data, times = raw_data.filter(low_freq, 100.0, picks=rois)[:, :]
    if plot_flag:
        plotter.plot_spectral_analysis_raster(
            times,
            data_bipolar,
            time_units="sec",
            freq=np.array(range(1, 51, 1)),
            title='Spectral Analysis',
            figure_name='Spectral Analysis Bipolar',
            labels=bipolar_channels,
            log_scale=True)
        plotter.plot_spectral_analysis_raster(
            times,
            data_filtered,
            time_units="sec",
            freq=np.array(range(1, 51, 1)),
            title='Spectral Analysis_bipolar',
            figure_name='Spectral Analysis Filtered',
            labels=bipolar_channels,
            log_scale=True)
    del data
    t_onset = np.where(times > (on_off_set[0] - 2 * win_len))[0][0]
    t_offset = np.where(times > (on_off_set[1] + 2 * win_len))[0][0]
    times = times[t_onset:t_offset]
    data_filtered = data_filtered[t_onset:t_offset]
    observation = np.abs(data_filtered)
    del data_filtered
    if log_flag:
        observation = np.log(observation)
    for iS in range(observation.shape[1]):
        observation[:, iS] = detrend_linear(observation[:, iS])
    observation -= observation.min()
    for iS in range(observation.shape[1]):
        observation[:,
                    iS] = np.convolve(observation[:, iS],
                                      np.ones(
                                          (np.int(np.round(win_len * fs), ))),
                                      mode='same')
    n_times = times.shape[0]
    dtimes = n_times - 4096
    t_onset = int(np.ceil(dtimes / 2.0))
    t_offset = n_times - int(np.floor(dtimes / 2.0))
    # t_onset = np.where(times > (on_off_set[0] - win_len))[0][0]
    # t_offset = np.where(times > (on_off_set[1] + win_len))[0][0]
    times = times[t_onset:t_offset]
    observation = observation[t_onset:t_offset]
    observation = zscore(observation, axis=None) / 3.0
    # observation -= observation.min()
    # observation /= observation.max()
    if plot_flag:
        plotter.plot_raster({"observation": observation},
                            times,
                            time_units="sec",
                            special_idx=None,
                            title='Time Series',
                            offset=1.0,
                            figure_name='TimeSeries',
                            labels=bipolar_channels)
    # n_times = times.shape[0]
    # observation = resample_poly(observation, 2048, n_times)
    observation = decimate(observation, 2, axis=0, zero_phase=True)
    times = decimate(times, 2, zero_phase=True)
    if plot_flag:
        plotter.plot_timeseries({"observation": observation},
                                times,
                                time_units="sec",
                                special_idx=None,
                                title='Time Series',
                                figure_name='TimeSeriesDecimated',
                                labels=bipolar_channels)
    return observation, times, fs / 2