def freqfilt_eeg(fn_in,fn_out,btype="lp",fl=None,fh=None,border=3,windowed=False): eeg = eegpy.open_eeg(fn_in) out = eegpy.F32(fn_out,"w+",shape=eeg.shape,cNames=eeg.channel_names,Fs=eeg.Fs) if btype == "lp": if not windowed: out[:,:] = filtfilt_low(fl,eeg[:,:],Fs=eeg.Fs,border=border) else: for i in range(0,out.num_datapoints,100000): out[i:min(i+100000,out.num_datapoints),:] = filtfilt_low(fl,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border) elif btype == "hp": #for i_c in range(eeg.num_channels): if not windowed: out[:,:] = filtfilt_high(fh,eeg[:,:],Fs=eeg.Fs,border=border) else: for i in range(0,out.num_datapoints,100000): out[i:min(i+100000,out.num_datapoints),:] = filtfilt_high(fh,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border) elif btype == "bp": if not windowed: out[:,:] = filtfilt_band(fl,fh,eeg[:,:],Fs=eeg.Fs,border=border) else: for i in range(0,out.num_datapoints,100000): out[i:min(i+100000,out.num_datapoints),:] = filtfilt_band(fl,fh,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border) elif btype == "bs": if not windowed: out[:,:] = filtfilt_bandstop(fl,fh,eeg[:,:],Fs=eeg.Fs,border=border) else: for i in range(0,out.num_datapoints,100000): out[i:min(i+100000,out.num_datapoints),:] = filtfilt_bandstop(fl,fh,eeg[i:min(i+100000,out.num_datapoints),:],Fs=eeg.Fs,border=border)
def filter(self): "Do the actual filtering" #Slice-alignment self.check_before_filtering() self.Ya = upsample(self._data[:,self.ch_for_slice_alignment],self.upsf) self.realign_triggers() for i in range(self._data.shape[1]): self.Ya = upsample(self._data[:,i],self.upsf) #ff.Yah = N.memmap("tmp/Yah.np",mode="w+",dtype=N.float64,shape=ff.Ya.shape) self.Yah = filtfilt_high(1.0,self.Ya,Fs=10000.0) self.subtract_mean_from_Ya2(n_ma=20) #ar1 = ff.Ya2.copy() self.subtract_residual_obs()
def filter(self): "Do the actual filtering" #Slice-alignment self.check_before_filtering() self.Ya = upsample(self._data[:, self.ch_for_slice_alignment], self.upsf) self.realign_triggers() for i in range(self._data.shape[1]): self.Ya = upsample(self._data[:, i], self.upsf) #ff.Yah = N.memmap("tmp/Yah.np",mode="w+",dtype=N.float64,shape=ff.Ya.shape) self.Yah = filtfilt_high(1.0, self.Ya, Fs=10000.0) self.subtract_mean_from_Ya2(n_ma=20) #ar1 = ff.Ya2.copy() self.subtract_residual_obs()
def remove_artifacts(self): """Tries to remove the artifacts. Uses mixture of mean-subtraction and OBS-PCA-Subtraction Needs self.slcs to be set. Saves example data in self.examples to make evaluation of filter quality possible""" def obs_fit_error(p,y,x): err = n.zeros((x.shape[0]),"d") err += p[0] for i in range(self.obs_size): err += y[:,i]*p[i+1] err -= x return abs(err**2).sum() def obs_fit_error_lsq(p,y,x): err = n.zeros((x.shape[0]),"d") err += p[0] for i in range(self.obs_size): err += y[:,i]*p[i+1] err -= x return err def las_fit_error_lsq(p,y,x): """Local artifact subtraction""" err = p[0]*y err -= x return err #Shortnames eeg = self.eeg slcs = self.slcs_ups sw = self._new_slice_width *10 k = self.num_neighbors self.examples=[] num_examples=10 #Loop over channels if show_progressbar: pbar = ProgressBar().start() for i_ch in range(eeg.num_channels): #Make Highpass-Version of channel #ch = eeg[:,i_ch].copy() y , fn = upsample_to_memmap(eeg[:,i_ch],10) y_hp,fn_hp = tmp_memmap(dtype=y.dtype,shape=y.shape,mode="w+") y_hp[:] = filtfilt_high(1, y, Fs=10000.0) y_out,fn_out = tmp_memmap(dtype=y.dtype,shape=y.shape,mode="w+") y_out[:] = y[:] #ch_hp = filtfilt_high(1.0,ch,Fs=eeg.Fs) neighbors = n.zeros((sw+2*self._pa_zeros,k)) #Prefill for i in range(k): #print neighbors[:,i].shape, eeg[slcs[i]-sw/2:slcs[i]+sw/2,i_ch].shape neighbors[:,i] = prepend_append_zeros( y_hp[slcs[i]-sw/2:slcs[i]+sw/2] , self._pa_zeros) #Loop over slices and filter next_subst = 0 for i,t in enumerate(slcs): try: if i>k/2 and i<len(slcs)-k/2: neighbors[:,next_subst] = prepend_append_zeros( y_hp[slcs[i+k/2]-sw/2:slcs[i+k/2]+sw/2] , self._pa_zeros) next_subst+=1 next_subst=next_subst%k tmp = prepend_append_zeros( y[t-sw/2:t+sw/2] , self._pa_zeros) #Subtraction #Shift/scale template template = neighbors.mean(axis=1) p = [1.0, 0] p_las = leastsq(las_fit_error_lsq,p,args=(template,tmp))[0] #print p_las[0], tmp -= p_las[0]*template #Beispieldaten speichern: Teil 1 if i_ch == self.ch_for_slice_alignment: if i%(len(slcs)/num_examples)==(len(slcs)/num_examples)/2: print "examples, Teil 1" example = {} example["raw"] = prepend_append_zeros(y[t-sw/2:t+sw/2].copy() , self._pa_zeros ) example["mean"] = p_las[0]*template #OBS-Fit components = pcafilt.unmix(neighbors) #OBS will be first 5 components components -= components.mean(axis=0).reshape(1,-1).repeat(components.shape[0],0) #demeaning column-wise obs = components[:,:self.obs_size].copy() #Fit OBS to artifact p = [0]+[0]*self.obs_size #p_lsq = fmin(obs_fit_error,p,args=(obs,eeg[t-sw/2:t+sw/2,i_ch]),maxiter=1e5,maxfun=1e5)#[0] p_lsq = leastsq(obs_fit_error_lsq,p,args=(obs,tmp))[0] #print i,t,"p_lsq", p_lsq fit = n.zeros((obs.shape[0]),"d") fit +=p_lsq[0] for j in range(self.obs_size): fit += obs[:,j]*p_lsq[j+1] tmp -= fit try: #eeg[t/10-sw/10/2:t/10+sw/10/2,i_ch] = tmp[self._pa_zeros:-self._pa_zeros][::10] y_out[t-sw/2:t+sw/2] = tmp[self._pa_zeros:-self._pa_zeros][:] except ValueError, ve: print i_ch, i,t, eeg[t/10-sw/10/2:t/10+sw/10/2,i_ch].shape, tmp[self._pa_zeros:-self._pa_zeros][::10].shape #Beispieldaten speichern: Teil 2 if i_ch == self.ch_for_slice_alignment: if i%(len(slcs)/num_examples)==(len(slcs)/num_examples)/2: print "examples, Teil 2" #example["fit"] = n.zeros(example["raw"].shape) #fit.copy() example["fit"] = fit.copy() example["obs"] = obs.copy() example["filt1"] = (tmp + fit).copy() example["filt2"] = tmp.copy() self.examples.append(example) if show_progressbar: pbar.update((i_ch+i/len(slcs))*100/eeg.num_channels) except Exception, e: print "Error occurred at slice at t=",t,", ignored" print e
def freqfilt_eeg(fn_in, fn_out, btype="lp", fl=None, fh=None, border=3, windowed=False): eeg = eegpy.open_eeg(fn_in) out = eegpy.F32(fn_out, "w+", shape=eeg.shape, cNames=eeg.channel_names, Fs=eeg.Fs) if btype == "lp": if not windowed: out[:, :] = filtfilt_low(fl, eeg[:, :], Fs=eeg.Fs, border=border) else: for i in range(0, out.num_datapoints, 100000): out[i:min(i + 100000, out.num_datapoints), :] = filtfilt_low( fl, eeg[i:min(i + 100000, out.num_datapoints), :], Fs=eeg.Fs, border=border) elif btype == "hp": #for i_c in range(eeg.num_channels): if not windowed: out[:, :] = filtfilt_high(fh, eeg[:, :], Fs=eeg.Fs, border=border) else: for i in range(0, out.num_datapoints, 100000): out[i:min(i + 100000, out.num_datapoints), :] = filtfilt_high( fh, eeg[i:min(i + 100000, out.num_datapoints), :], Fs=eeg.Fs, border=border) elif btype == "bp": if not windowed: out[:, :] = filtfilt_band(fl, fh, eeg[:, :], Fs=eeg.Fs, border=border) else: for i in range(0, out.num_datapoints, 100000): out[i:min(i + 100000, out.num_datapoints), :] = filtfilt_band( fl, fh, eeg[i:min(i + 100000, out.num_datapoints), :], Fs=eeg.Fs, border=border) elif btype == "bs": if not windowed: out[:, :] = filtfilt_bandstop(fl, fh, eeg[:, :], Fs=eeg.Fs, border=border) else: for i in range(0, out.num_datapoints, 100000): out[i:min(i + 100000, out.num_datapoints), :] = filtfilt_bandstop( fl, fh, eeg[i:min(i + 100000, out.num_datapoints), :], Fs=eeg.Fs, border=border)
def remove_artifacts(self): """Tries to remove the artifacts. Uses mixture of mean-subtraction and OBS-PCA-Subtraction Needs self.slcs to be set. Saves example data in self.examples to make evaluation of filter quality possible""" def obs_fit_error(p, y, x): err = n.zeros((x.shape[0]), "d") err += p[0] for i in range(self.obs_size): err += y[:, i] * p[i + 1] err -= x return abs(err**2).sum() def obs_fit_error_lsq(p, y, x): err = n.zeros((x.shape[0]), "d") err += p[0] for i in range(self.obs_size): err += y[:, i] * p[i + 1] err -= x return err def las_fit_error_lsq(p, y, x): """Local artifact subtraction""" err = p[0] * y err -= x return err #Shortnames eeg = self.eeg slcs = self.slcs_ups sw = self._new_slice_width * 10 k = self.num_neighbors self.examples = [] num_examples = 10 #Loop over channels if show_progressbar: pbar = ProgressBar().start() for i_ch in range(eeg.num_channels): #Make Highpass-Version of channel #ch = eeg[:,i_ch].copy() y, fn = upsample_to_memmap(eeg[:, i_ch], 10) y_hp, fn_hp = tmp_memmap(dtype=y.dtype, shape=y.shape, mode="w+") y_hp[:] = filtfilt_high(1, y, Fs=10000.0) y_out, fn_out = tmp_memmap(dtype=y.dtype, shape=y.shape, mode="w+") y_out[:] = y[:] #ch_hp = filtfilt_high(1.0,ch,Fs=eeg.Fs) neighbors = n.zeros((sw + 2 * self._pa_zeros, k)) #Prefill for i in range(k): #print neighbors[:,i].shape, eeg[slcs[i]-sw/2:slcs[i]+sw/2,i_ch].shape neighbors[:, i] = prepend_append_zeros( y_hp[slcs[i] - sw / 2:slcs[i] + sw / 2], self._pa_zeros) #Loop over slices and filter next_subst = 0 for i, t in enumerate(slcs): try: if i > k / 2 and i < len(slcs) - k / 2: neighbors[:, next_subst] = prepend_append_zeros( y_hp[slcs[i + k / 2] - sw / 2:slcs[i + k / 2] + sw / 2], self._pa_zeros) next_subst += 1 next_subst = next_subst % k tmp = prepend_append_zeros(y[t - sw / 2:t + sw / 2], self._pa_zeros) #Subtraction #Shift/scale template template = neighbors.mean(axis=1) p = [1.0, 0] p_las = leastsq(las_fit_error_lsq, p, args=(template, tmp))[0] #print p_las[0], tmp -= p_las[0] * template #Beispieldaten speichern: Teil 1 if i_ch == self.ch_for_slice_alignment: if i % (len(slcs) / num_examples) == ( len(slcs) / num_examples) / 2: print "examples, Teil 1" example = {} example["raw"] = prepend_append_zeros( y[t - sw / 2:t + sw / 2].copy(), self._pa_zeros) example["mean"] = p_las[0] * template #OBS-Fit components = pcafilt.unmix( neighbors) #OBS will be first 5 components components -= components.mean(axis=0).reshape( 1, -1).repeat(components.shape[0], 0) #demeaning column-wise obs = components[:, :self.obs_size].copy() #Fit OBS to artifact p = [0] + [0] * self.obs_size #p_lsq = fmin(obs_fit_error,p,args=(obs,eeg[t-sw/2:t+sw/2,i_ch]),maxiter=1e5,maxfun=1e5)#[0] p_lsq = leastsq(obs_fit_error_lsq, p, args=(obs, tmp))[0] #print i,t,"p_lsq", p_lsq fit = n.zeros((obs.shape[0]), "d") fit += p_lsq[0] for j in range(self.obs_size): fit += obs[:, j] * p_lsq[j + 1] tmp -= fit try: #eeg[t/10-sw/10/2:t/10+sw/10/2,i_ch] = tmp[self._pa_zeros:-self._pa_zeros][::10] y_out[t - sw / 2:t + sw / 2] = tmp[self._pa_zeros:-self._pa_zeros][:] except ValueError, ve: print i_ch, i, t, eeg[ t / 10 - sw / 10 / 2:t / 10 + sw / 10 / 2, i_ch].shape, tmp[self._pa_zeros:-self. _pa_zeros][::10].shape #Beispieldaten speichern: Teil 2 if i_ch == self.ch_for_slice_alignment: if i % (len(slcs) / num_examples) == ( len(slcs) / num_examples) / 2: print "examples, Teil 2" #example["fit"] = n.zeros(example["raw"].shape) #fit.copy() example["fit"] = fit.copy() example["obs"] = obs.copy() example["filt1"] = (tmp + fit).copy() example["filt2"] = tmp.copy() self.examples.append(example) if show_progressbar: pbar.update( (i_ch + i / len(slcs)) * 100 / eeg.num_channels) except Exception, e: print "Error occurred at slice at t=", t, ", ignored" print e