def test_UnrecognisedMontageError(): from electrolib.channel.montage import MontageFile, UnrecognisedMontageError from electrolib.io import openeeg import py.test eeg = openeeg('data/wg1.wg1', 'r') with py.test.raises(UnrecognisedMontageError): meeg = MontageFile(eeg, '_invalid_')
def test_MontageFile(): from electrolib.channel.montage import MontageFile from electrolib.io import openeeg eeg = openeeg('data/wg1.wg1', 'r') meeg = MontageFile(eeg, 'special') head = meeg.get_head() blocks = meeg.get_blocks(0, 1)
def open(self, eegname=None, fmt=None): """Open EEG file for viewing open EEGFILE: open file EEGFILE base on extension open EEGFILE FMT: open EEGFILE as FMT typ EEG file Type 'formats' to list supported formats. """ # Open EEG file if eegname is None: if fmt is None: fmt = 'edf' newfile = openeeg(sys.stdin, mode='r', fmt=fmt, cached=True) else: if not os.path.exists(eegname): raise ConsoleError("file '{0}' does not exist".format(eegname)) newfile = openeeg(eegname, mode='r', fmt=fmt) # Close previous file and keep new if self.eegfile: self.eegfile.close() self.eegfile = newfile # Update display self.display.set_eegfile(newfile) self.display.redraw() yield "file '{0}' opened.\n".format(newfile.name)
def __init__(self, eegfile): """Stores infile stream and size""" if isinstance(eegfile, basestring): from electrolib.io import openeeg eegfile = openeeg(eegfile, 'r') self.__file = eegfile if not hasattr(self, 'mode'): self.mode = 'r' self.name = self.__file.name if not 'r' in self.mode: return self.head = self.get_head() self.nblocks = self.head.nblocks self.chan = self.get_chan() self.channames = [ch.label for ch in self.chan] self.tstart = self.head.tstart self.nchan = self.head.nchan self._secsblock = self.head.secsblock for ch in self.chan: ch.deltat = float(self.head.secsblock) / ch.nsblock self._check_tend()
def plot(ax, eegfile, fmt=None, only_eeg=False, channels='all', twindow='all', upside_down=False, tunit='auto', title='', xlabel=True, ylabel='', font_file=None, scale='auto', resolution='auto', resample=False, simplify=True, minmax=False, verbose=False): """Plot the eegfile to the specified matplotlib Axes""" # Parse possible string arguments if twindow != 'all' and isinstance(twindow, basestring): t1, t2 = twindow.split(',') twindow = (float(t1), float(t2)) # Parse options for plot command if channels != 'all' and isinstance(channels, basestring): channels = channels.split(',') # Open file. if isinstance(eegfile, (basestring, file)): output("Opening '{0}'".format(eegfile), verbose) eegfile = openeeg(eegfile, 'r', fmt) # All signals? if channels == 'all': channels = None # Establish time window used if twindow == 'all': sigs = eegfile.get_signals_all(only_eeg=only_eeg, channels=channels) t1, t2 = 0, eegfile.secsdur else: t1, t2 = twindow sigs = eegfile.get_signals(t1, t2, only_eeg=only_eeg, channels=channels) # Retrieve signals from file: Nc = len(sigs) output('Found {0} signals'.format(Nc), verbose) secsdur = eegfile.as_seconds(sigs[0].t2 - sigs[0].t1) # Determine scale automatically? if scale == 'auto': output('Choosing scale automatically'.format(Nc), verbose) scale = 4 * sum(np.std(sig.x) for sig in sigs) / Nc scale = float(scale) if upside_down: scale = -scale output('Scale is {0}'.format(scale), verbose) # Determine resolution automatically? if resolution == 'auto': output('Choosing resolution automatically'.format(Nc), verbose) resolution = secsdur / 1000. resolution = float(resolution) output('Resolution is {0}'.format(resolution), verbose) # Determine time unit automatically? if tunit == 'auto': output('Choosing time unit automatically'.format(Nc), verbose) if secsdur / 3600 > TUNIT_MIN: tunit = 'hours' elif secsdur / 60 > TUNIT_MIN: tunit = 'minutes' elif secsdur > TUNIT_MIN: tunit = 'seconds' else: tunit = 'milliseconds' else: tunit = TUNITS[tunit] tscale = TSCALES[tunit] output('Time unit is {0}'.format(tunit), verbose) # Base plot height for each signal offsets = range(Nc, 0, -1) if simplify: rc_change = {'path.simplify':True, 'path.simplify_threshold':1.0} rc_old = dict((k, rcParams[k]) for k in rc_change) rcParams.update(rc_change) # Adjust sampling ts, xs = [], [] for sig, offset in zip(sigs, offsets): # Number of samples to skip every = max(int(resolution / sig.dt), 1) if every == 1: t, x = sig.t, sig.x # Proper resampling (expensive) elif resample: from scipy.signal import resample ns = min(sig.n, int(np.ceil(secsdur / resolution))) output("Resampling '{0}' to {1}".format(sig.label, ns), verbose) x = resample(sig.x, ns) t = np.linspace(sig.t1, sig.t2, ns) # Plot mins and maxs over downsampling period elif minmax: # Work out the shape of the new arrays nsnew = len(sig.t) // every nsold = every * nsnew t = np.zeros(2*nsnew, float) x = np.zeros_like(t) # Copy in the data t[::2] = t[1::2] = sig.t[:nsold:every] xr = sig.x[:nsold].reshape((nsnew, every)) x[::2] = np.min(xr, 1) x[1::2] = np.max(xr, 1) # Simple downsampling else: output("Downsampling '{0}' by {1}".format(sig.label, every), verbose) t, x = sig.t[::every], sig.x[::every] # Actually plot the line ax.plot(t / tscale, offset + x / scale, color='black', linestyle='-') if simplify: rcParams.update(rc_old) # Finish up the plot output('Formatting plot', verbose) # Load specified font file kwargs = {} if font_file: output('Loading font file {0}'.format(font_file), verbose) kwargs['fontproperties'] = fm.FontProperties(fname=font_file) labels = [sig.label for sig in sigs] tlim = (t1 / tscale, t2 / tscale) ax.set_yticks(offsets) ax.set_yticklabels(labels, size='x-small', **kwargs) ax.set_xlim(tlim) ax.set_ylim([min(offsets) - 1, max(offsets) + 1]) if tunit is None: ax.set_xticks([]) else: xticks = [int(_) if _ == int(_) else _ for _ in ax.get_xticks()] ax.xaxis.set_ticklabels(xticks, size='x-small', **kwargs) if xlabel: ax.set_xlabel('Time ({0})'.format(tunit), **kwargs) if ylabel: ax.set_ylabel(ylabel, **kwargs) if title: ax.set_title(title, **kwargs) # For annotation of the plot: plot_data = { 'labels':labels, 'offsets':offsets, 'scale':scale, 'tlim':tlim, 'tscale':tscale, } return plot_data
def test_openeeg_edf_r_cached(): from electrolib.io import openeeg eeg = openeeg('data/sin.edf', 'r', cached=True)
def test_openeeg_invalid_fmt_EEGFormatError(): from electrolib.io import openeeg, EEGFormatError import py.test with py.test.raises(EEGFormatError): eeg = openeeg('data/sin_tmp.xfg', 'r')
def test_openeeg_wg1_r(): from electrolib.io import openeeg eeg = openeeg('data/wg1.wg1', 'r')
def test_openeeg_alternate_fmt(): from electrolib.io import openeeg eeg = openeeg('data/nblocks.gdf', 'r', fmt='gdf')
def test_openeeg_edf_w(): from electrolib.io import openeeg import os eeg = openeeg('data/sin_tmp.edf', 'w') eeg.close() os.remove('data/sin_tmp.edf')
def test_openeeg_file_object(): from electrolib.io import openeeg eeg = openeeg(open('data/sin.edf', 'rb'), 'r')
def test_openeeg_edf_r(): from electrolib.io import openeeg eeg = openeeg('data/sin.edf', 'r')
def test_blockfile_unknown_length(): from electrolib.blocks.blockfile import BlockFile from electrolib.io import openeeg eeg = openeeg('data/wg1.wg1', 'r') bfile = BlockFile(eeg, 5, 10) assert bfile.head.nblocks == -1
def _open_output_file(outfile, opts): """Processes options and args to open output as an EEG file""" outfile = outfile or sys.stdout fmt = opts['output_format'] or 'edf' return io.openeeg(outfile, 'w', fmt)
def _open_input_file(infile, opts): """Processes options and args to open input as an EEG file""" infile = infile or sys.stdin fmt = opts['input_format'] or 'edf' return io.openeeg(infile, 'r', fmt)