コード例 #1
0
ファイル: brainvision.py プロジェクト: teonbrooks/Eelbrain
def events(vhdr_path=None):
    if vhdr_path is None:
        vhdr_path = ui.ask_file("Pick a Brain Vision EEG Header File", 
                                "Pick a Brain Vision EEG Header File",
                                ext=[('vhdr', 'Brain Vision Header File')])
        if not vhdr_path:
            return
    
    hdr = vhdr(vhdr_path)
    if hdr.markerfile is None:
        raise IOError("No marker file referenced in %r" % vhdr_path)
    elif hdr.DataType == 'FREQUENCYDOMAIN':
        raise NotImplementedError
    
    txt = open(hdr.markerfile).read()
    m = marker_re.findall(txt)
    m = np.array(m)
    
    name, _ = os.path.split(os.path.basename(hdr.path))
    ds = dataset(name=name)
    ds['Mk'] = var(np.array(m[:,0], dtype=int))
    ds['event_type'] = factor(m[:,1])
    ds['event_ID'] = var(np.array(m[:,3], dtype=int))
    ds['i_start'] = var(np.array(m[:,4], dtype=int))
    ds['points'] = var(np.array(m[:,5], dtype=int))
    ds['channel'] = var(np.array(m[:,6], dtype=int))
    
    ds.info['hdr'] = hdr
    ds.info['samplingrate'] = hdr.samplingrate
    return ds
コード例 #2
0
ファイル: load.py プロジェクト: kriek197/Eelbrain
def fiff_events(source_path=None, name=None):
    """
    Returns a dataset containing events from a raw fiff file. Use
    :func:`fiff_epochs` to load MEG data corresponding to those events.
    
    source_path : str (path)
        the location of the raw file (if ``None``, a file dialog will be 
        displayed).
    
    name : str
        A name for the dataset.
    """
    if source_path is None:
        source_path = ui.ask_file("Pick a Fiff File", "Pick a Fiff File",
                                  ext=[('fif', 'Fiff')])
    
    if name is None:
        name = os.path.basename(source_path)
    
    raw = mne.fiff.Raw(source_path)
    events = mne.find_events(raw)
    if any(events[:,1] != 0):
        raise NotImplementedError("Events starting with ID other than 0")
        # this was the case in the raw-eve file, which contained all event 
        # offsets, but not in the raw file created by kit2fiff. For handling
        # see :func:`fiff_event_file`
    istart = _data.var(events[:,0], name='i_start')
    event = _data.var(events[:,2], name='eventID')
    info = {'source': source_path}
    return _data.dataset(event, istart, name=name, info=info)
コード例 #3
0
ファイル: shell.py プロジェクト: kriek197/Eelbrain
 def OnFindPath(self, event=None):
     filenames = ui.ask_file(wildcard='', mult=True)
     if filenames:
         if len(filenames) == 1:
             filenames = '"'+filenames[0]+'"'
         else:
             filenames = str(filenames)
         self.shell.ReplaceSelection(filenames)
コード例 #4
0
ファイル: param.py プロジェクト: teonbrooks/Eelbrain
 def import_pickled(self, path=None):
     "Imports the values from a pickled python object."
     if path is None:
         path = ui.ask_file(title="Import Parameter Values", 
                            message="Select a file that contains the pickle parameter values:",
                            ext=[('pickled', "pickled Python object")])
     
     with open(path, 'r') as f:
         self._value.update(pickle.load(f))
コード例 #5
0
ファイル: shell.py プロジェクト: kriek197/Eelbrain
 def FileOpen(self, path=None, internal_call=False):
     if path is None:
         path = ui.ask_file(title="Open File",
                            message="Open a Python script in an editor", 
                            ext=[('py', 'Python script')])
         if not path:
             return
     
     if isinstance(path, basestring) and os.path.isfile(path):
         ext = path.split(os.extsep)[-1].lower()
         if ext == 'py':
             self.create_py_editor(pyfile=path)
         else:
             msg = "Error: %r is no known file extension." % ext
             self.shell_message(msg, internal_call=internal_call)
     else:
         msg = "No valid file path: %r" % path
         self.shell_message(msg, internal_call=internal_call)
コード例 #6
0
 def REJECTION_IMPORT(self, fn=None):
     if fn is None:
         fn = ui.ask_file(wildcard = "pickled file (*.pickled)|*.pickled")
     if os.path.exists(fn):
         with open(fn, 'r') as f:
             rej = pickle.load(f)
         safety = rej.pop('safety')
         for s in self.segments:
             if s.name != safety[s.id]:
                 raise IOError("segment mismatch!")
         remove = []
         for id, d in rej.iteritems():
             try:
                 int(id)
                 if len(d) > 0:
                     self.delete_cache(id)
             except:
                 remove.append(id)
                 print "Dict contained invalid item: {k}: {v}".format(k=id, v=d)
         [rej.pop(id) for id in remove]
         self._reject_dict = rej
コード例 #7
0
ファイル: eyelink.py プロジェクト: teonbrooks/Eelbrain
    def __init__(self, path=None):
        """
        Parameters
        ----------
        path : str(path) | None
            Path to the .edf file. The If path contains '*', the files matching
            the pattern are concatenated. If None, a file-open dialogue will be
            displayed.

        """
        if path is None:
            path = ui.ask_file("Load an eyelink .edf file", "Pick the edf file",
                               ext=[('edf', 'eyelink data format')])

        # find all paths from which to read
        self.path = path
        if '*' in path:
            head, tail = os.path.split(path)
            if '*' in head:
                err = ("Invalid path: %r. All edf files need to be in the same "
                       "directory." % path)
                raise ValueError(err)

            fnames = sorted(fnmatch.filter(os.listdir(head), tail))
            self.paths = [os.path.join(head, fname) for fname in fnames]
        else:
            self.paths = [path]

        triggers = []
        artifacts = []
        for path in self.paths:
            edf = subp.edf_file(path)
            triggers += edf.triggers
            artifacts += edf.artifacts

        dtype = [('T', np.uint32), ('Id', np.uint8)]
        self.triggers = np.array(triggers, dtype=dtype)
        dtype = np.dtype([('event', np.str_, 6), ('start', np.uint32), ('stop', np.uint32)])
        self.artifacts = np.array(artifacts, dtype=dtype)
コード例 #8
0
ファイル: shell.py プロジェクト: kriek197/Eelbrain
 def OnInsertPath(self, event, t=None):
     if t is None:
         t = event.GetSelection()
     # get
     if t == 0: # File
         filenames = ui.ask_file(mult=True)
     elif t == 1: # Dir
         filenames = ui.ask_dir()
     elif t == 2: # New
         filenames = ui.ask_saveas(title = "Get New File Name",
                                   message = "Please Pick a File Name", 
                                   ext = None)
     # put to terminal
     if filenames:
         if len(filenames) == 1:
             filenames = '"'+filenames[0]+'"'
         else:
             filenames = '"'+str(filenames)+'"'
         
         if 'wxMSW' in wx.PlatformInfo:
             filenames = 'r'+filenames
         
         self.InsertStr(filenames)
コード例 #9
0
ファイル: txt.py プロジェクト: teonbrooks/Eelbrain
def var(path=None, name=None):
    """
    Loads a ``var`` object from a text file by splitting at white-spaces.

    path : str(path) | None
        Source file. If None, a system file dialog is opened.
    name : str | None
        Name for the var.

    """
    if path is None:
        path = ui.ask_file("Select var File", "()")

    FILE = open(path)
    lines = FILE.read().split()
    FILE.close()
    is_bool = all(line in ['True', 'False'] for line in lines)

    if is_bool:
        x = np.genfromtxt(path, dtype=bool)
    else:
        x = np.loadtxt(path)

    return _data.var(x, name=None)
コード例 #10
0
ファイル: fiff.py プロジェクト: teonbrooks/Eelbrain
def Raw(path=None, proj=False, **kwargs):
    """
    Returns a mne.fiff.Raw object with added projections if appropriate.

    Parameters
    ----------
    path : None | str(path)
        path to the raw fiff file. If ``None``, a file can be chosen form a
        file dialog.
    proj : bool | str(path)
        Add projections from a separate file to the Raw object.
        **``False``**: No proj file will be added.
        **``True``**: ``'{raw}*proj.fif'`` will be used.
        ``'{raw}'`` will be replaced with the raw file's path minus '_raw.fif',
        and '*' will be expanded using fnmatch. If multiple files match the
        pattern, a ValueError will be raised.
        **``str``**: A custom path template can be provided, ``'{raw}'`` and
        ``'*'`` will be treated as with ``True``.
    kwargs
        Additional keyword arguments are forwarded to mne.fiff.Raw
        initialization.

    """
    if path is None:
        path = ui.ask_file("Pick a Raw Fiff File", "Pick a Raw Fiff File",
                           ext=[('fif', 'Fiff')])
        if not path:
            return

    if not os.path.isfile(path):
        raise IOError("%r is not a file" % path)

    raw = mne.fiff.Raw(path, **kwargs)

    if proj:
        if proj == True:
            proj = '{raw}*proj.fif'

        if '{raw}' in proj:
            raw_file = raw.info['filename']
            raw_root, _ = os.path.splitext(raw_file)
            raw_root = raw_root.rstrip('raw')
            proj = proj.format(raw=raw_root)

        if '*' in proj:
            head, tail = os.path.split(proj)
            names = fnmatch.filter(os.listdir(head), tail)
            if len(names) == 1:
                proj = os.path.join(head, names[0])
            else:
                if len(names) == 0:
                    err = "No file matching %r"
                else:
                    err = "Multiple files matching %r"
                raise ValueError(err % proj)

        # add the projections to the raw file
        proj = mne.read_proj(proj)
        raw.add_proj(proj, remove_existing=True)

    return raw
コード例 #11
0
ファイル: txt.py プロジェクト: teonbrooks/Eelbrain
def tsv(path=None, names=True, types='auto', empty='nan', delimiter=None,
        skiprows=0):
    """
    returns a ``dataset`` with data from a tab-separated values file.


    Parameters
    ----------

    names : list of str | bool
        * ``['name1', ...]`` use these names
        * ``True``: look for names on the first line of the file
        * ``False``: use "v1", "v2", ...
    types : 'auto' | list of int
        * ``'auto'`` -> import as var if all values can be converted float,
          otherwise as factor
        * list of 0=auto, 1=factor, 2=var. e.g. ``[0,1,1,0]``
    empty :
        value to substitute for empty cells
    delimiter : str
        value delimiting cells in the input file (None = any whitespace;
        e.g., ``'\\t'``)
    skiprows : int
        Skip so many rows at the beginning of the file (for tsv files with
        headers). Column names (if names==True) are expected to come after
        the skipped rows.

    """
    if path is None:
        path = ui.ask_file("Select file to import as dataframe",
                           "Select file to import as dataframe")
        if not path:
            return

    with open(path) as f:
        for i in xrange(skiprows):
            f.readline()

        # read / create names
        if names == True:
            names = f.readline().split(delimiter)
            names = [n.strip().strip('"') for n in names]

        lines = []
        for line in f:
            values = []
            for v in line.split(delimiter):
                v = v.strip()
                if not v:
                    v = empty
                values.append(v)
            lines.append(values)

    n_vars = len(lines[0])

    if not names:
        names = ['v%i' % i for i in xrange(n_vars)]

    n = len(names)
    # decide whether to drop first column
    if n_vars == n:
        start = 0
    elif n_vars == n + 1:
        start = 1
    else:
        raise ValueError("number of header different from number of data")

    if types in ['auto', None, False, True]:
        types = [0] * n
    else:
        assert len(types) == n

    # prepare for reading data
    data = []
    for _ in xrange(n):
        data.append([])

    # read rest of the data
    for line in lines:
        for i, v in enumerate(line[start:]):
            for str_del in ["'", '"']:
                if v[0] == str_del:
                    v = v.strip(str_del)
                    types[i] = 1
            data[i].append(v)

    ds = _data.dataset(name=os.path.basename(path))

    for name, values, force_type in zip(names, data, types):
        v = np.array(values)
        if force_type in [0, 2]:
            try:
                v = v.astype(float)
                f = _data.var(v, name=name)
            except:
                f = _data.factor(v, name=name)
        else:
            f = _data.factor(v, name=name)
        ds.add(f)

    return ds
コード例 #12
0
ファイル: brainvision.py プロジェクト: teonbrooks/Eelbrain
    def __init__(self, path=None):
        """
        Reads a .vhdr file and returns its content as a dictionary
        
        The .markerfile and .datafile attributes provide absolute paths to those
        files.
        
        """
        if path is None:
            path = ui.ask_file("Pick a Brain Vision EEG Header File", 
                               "Pick a Brain Vision EEG Header File",
                               ext=[('vhdr', 'Brain Vision Header File')])
            if not path:
                raise RuntimeError("User Canceled")

        kv_re = re.compile('^(\w+)=(.+)', re.MULTILINE)
        
        hdr_section = {}
        with open(path) as FILE:
            if not FILE.readline().startswith(vhdr_hdr):
                err = ("Not a brain vision vhdr file: %r (needs to start with"
                       " %r" % (path, vhdr_hdr))
                raise IOError(err)
            for line in FILE:
                m = section_re.match(line)
                if m:
                    name = m.group(1)
                    hdr_section = self[name] = {}
                else:
                    m = kv_re.match(line)
                    if m:
                        key = m.group(1)
                        value = m.group(2).strip()
                        hdr_section[key] = value
        
        self.path = path
        info = self['Common Infos']
        
        # paths
        self.dirname, self.basename = os.path.split(path)
        datafile = info['DataFile']
        if os.path.isabs(datafile):
            self.datafile = datafile
        else:
            self.datafile = os.path.join(self.dirname, datafile)
        
        if 'MarkerFile' in info:
            markerfile = info['MarkerFile']
            if os.path.isabs(markerfile):
                self.markerfile = markerfile
            else:
                self.markerfile = os.path.join(self.dirname, markerfile)
        else:
            self.markerfile = None
        
        # other info
        self.DataFormat = info.get('DataFormat', 'ASCII')
        self.DataOrientation = info.get('DataOrientation', 'MULTIPLEXED')
        self.DataType = info.get('DataType', 'TIMEDOMAIN')
        self.NumberOfChannels = int(info['NumberOfChannels'])
        self.samplingrate = 1e6 / float(info['SamplingInterval'])