[med-svn] [python-mne] 23/376: starting to write functions doc + increasing coverage

Yaroslav Halchenko debian at onerussian.com
Fri Nov 27 17:21:58 UTC 2015


This is an automated email from the git hooks/post-receive script.

yoh pushed a commit to annotated tag v0.1
in repository python-mne.

commit fd29a5b8282df2517d89f2a98d3237f13d809d7a
Author: Alexandre Gramfort <alexandre.gramfort at inria.fr>
Date:   Thu Dec 30 17:45:31 2010 -0500

    starting to write functions doc + increasing coverage
---
 README.rst                 |   7 +-
 fiff/forward.py            | 269 ++++++++++++++++++++++++---------------------
 fiff/inverse.py            |   6 +-
 fiff/meas_info.py          |  76 +++++++------
 fiff/open.py               |  23 ++++
 fiff/proj.py               |  34 ++++--
 fiff/raw.py                | 108 +++++++++++-------
 fiff/tests/test_forward.py |   1 +
 8 files changed, 307 insertions(+), 217 deletions(-)

diff --git a/README.rst b/README.rst
index eec0a48..d57af32 100644
--- a/README.rst
+++ b/README.rst
@@ -6,6 +6,8 @@ About
 pyfiff is a python module for reading and writing the fif files
 produced by Neuromag MEG systems.
 
+It is mainly a reimplementation of the Matlab code written by Matti Hämäläinen.
+
 Download
 ========
 
@@ -59,4 +61,7 @@ gramfort at nmr.mgh.harvard.edu
 Testing
 -------
 
-You can launch the test suite using nosetest from the source folder.
\ No newline at end of file
+You can launch the test suite using nosetest from the source folder.
+
+You'll need before to have run the MNE tutorial to have the required files
+on your drive.
diff --git a/fiff/forward.py b/fiff/forward.py
index 489e717..887b7af 100644
--- a/fiff/forward.py
+++ b/fiff/forward.py
@@ -11,20 +11,20 @@ from .source_space import read_source_spaces, find_source_space_hemi
 from .matrix import read_named_matrix, transpose_named_matrix
 
 
-def block_diag(A, n):
-    """
-    %
-    %   function bd = mne_block_diag(A,n)
-    %
-    %   Make or extract a sparse block diagonal matrix
-    % 
-    %   If A is not sparse, then returns a sparse block diagonal "bd", diagonalized from the
+def _block_diag(A, n):
+    """Constructs a block diagonal from a packed structure
+
+    You have to try it on a matrix to see what it's doing.
+
+    %   If A is not sparse, then returns a sparse block diagonal "bd",
+    %   diagonalized from the
     %   elements in "A".
     %   "A" is ma x na, comprising bdn=(na/"n") blocks of submatrices.
     %   Each submatrix is ma x "n", and these submatrices are
     %   placed down the diagonal of the matrix.
     %
-    %   If A is already sparse, then the operation is reversed, yielding a block
+    %   If A is already sparse, then the operation is reversed, yielding
+    # a block
     %   row matrix, where each set of n columns corresponds to a block element
     %   from the block diagonal.
     %
@@ -32,56 +32,52 @@ def block_diag(A, n):
     """
     from scipy import sparse
 
-    import pdb; pdb.set_trace()
-
-    # if not sparse.issparse(A): # then make block sparse
-    #     ma, na = A.shape
-    #     bdn = na / float(n) # number of submatrices
-    # 
-    #     if bdn > int(bdn):
-    #         raise ValueError, 'Width of matrix must be even multiple of n'
-    # 
-    #     tmp = reshape([1:(ma*bdn)]',ma,bdn);
-    #     i = zeros(ma*n,bdn);
-    #     for iblock = 1:n:
-    #         i((iblock-1)*ma+[1:ma],:) = tmp
-    # 
-    #     i = i.ravel() # row indices foreach sparse bd
-    # 
-    #     j = [1:na];
-    #     j = j(ones(ma,1),:);
-    #     j = j(:) # column indices foreach sparse bd
-    # 
-    #     bd = sparse(i,j,A(:));
-    # else: # already is sparse, unblock it
-    #     [mA,na] = size(A);        % matrix always has na columns
-    #     % how many entries in the first column?
-    #     bdn = na/n;           % number of blocks
-    #     ma = mA/bdn;          % rows in first block
-    # 
-    #     % blocks may themselves contain zero entries.  Build indexing as above
-    #     tmp = reshape([1:(ma*bdn)]',ma,bdn);
-    #     i = zeros(ma*n,bdn);
-    #     for iblock = 1:n,
-    #     i((iblock-1)*ma+[1:ma],:) = tmp;
-    #     end  
-    # 
-    #     i = i(:);             % row indices foreach sparse bd
-    # 
-    # 
-    #     j = [0:mA:(mA*(na-1))];
-    #     j = j(ones(ma,1),:);
-    #     j = j.ravel()
-    # 
-    #     i += j
-    # 
-    #     bd = full(A(i));  % column vector
-    #     bd = reshape(bd,ma,na);   % full matrix
+    if not sparse.issparse(A): # then make block sparse
+        ma, na = A.shape
+        bdn = na / int(n) # number of submatrices
+
+        if na % n > 0:
+            raise ValueError, 'Width of matrix must be a multiple of n'
+
+        tmp = np.arange(ma*bdn, dtype=np.int).reshape(bdn, ma)
+        tmp = np.tile(tmp, (1, n))
+        ii = tmp.ravel()
+
+        jj = np.arange(na, dtype=np.int)[None,:]
+        jj = jj * np.ones(ma, dtype=np.int)[:,None]
+        jj = jj.T.ravel() # column indices foreach sparse bd
+
+        bd = sparse.coo_matrix((A.T.ravel(), np.c_[ii, jj].T))
+    else: # already is sparse, unblock it
+        import pdb; pdb.set_trace()
+        # [mA,na] = size(A);        % matrix always has na columns
+        # % how many entries in the first column?
+        # bdn = na/n;           % number of blocks
+        # ma = mA/bdn;          % rows in first block
+        #
+        # % blocks may themselves contain zero entries. Build indexing as above
+        # tmp = reshape([1:(ma*bdn)]',ma,bdn);
+        # i = zeros(ma*n,bdn);
+        # for iblock = 1:n,
+        # i((iblock-1)*ma+[1:ma],:) = tmp;
+        # end
+        #
+        # i = i(:);             % row indices foreach sparse bd
+        #
+        #
+        # j = [0:mA:(mA*(na-1))];
+        # j = j(ones(ma,1),:);
+        # j = j.ravel()
+        #
+        # i += j
+        #
+        # bd = full(A(i));  % column vector
+        # bd = reshape(bd,ma,na);   % full matrix
 
     return bd
 
 
-def transform_source_space_to(src, dest, trans):
+def _transform_source_space_to(src, dest, trans):
     """
     %
     % [res] = mne_transform_source_space_to(src,dest,trans)
@@ -99,9 +95,10 @@ def transform_source_space_to(src, dest, trans):
         return res
 
     if trans['to'] == src['coord_frame'] and trans['from_'] == dest:
-        trans = invert_transform(trans)
+        trans = _invert_transform(trans)
     elif trans['from_'] != src['coord_frame'] or trans['to'] != dest:
-        raise ValueError, 'Cannot transform the source space using this coordinate transformation'
+        raise ValueError, 'Cannot transform the source space using this ' \
+                          'coordinate transformation'
 
     t = trans['trans'][:3,:]
     res = src
@@ -112,13 +109,8 @@ def transform_source_space_to(src, dest, trans):
     return res
 
 
-def invert_transform(trans):
-    """
-    %
-    % [itrans] = fiff_invert_transform(trans)
-    %
-    % Invert a coordinate transformation
-    %
+def _invert_transform(trans):
+    """Invert a transformation between coordinate systems
     """
     itrans = copy.copy(trans)
     aux = itrans['from_']
@@ -128,11 +120,8 @@ def invert_transform(trans):
     return itrans
 
 
-def read_one(fid, node):
-    """
-    %
-    %   Read all interesting stuff for one forward solution
-    %
+def _read_one(fid, node):
+    """Read all interesting stuff for one forward solution
     """
     if node is None:
         return None
@@ -163,14 +152,16 @@ def read_one(fid, node):
 
     one['nchan'] = tag.data
     try:
-        one['sol'] = read_named_matrix(fid, node, FIFF.FIFF_MNE_FORWARD_SOLUTION)
+        one['sol'] = read_named_matrix(fid, node,
+                                            FIFF.FIFF_MNE_FORWARD_SOLUTION)
         one['sol'] = transpose_named_matrix(one['sol'])
     except Exception as inst:
         fid.close()
         raise 'Forward solution data not found (%s)' % inst
 
     try:
-        one['sol_grad'] = read_named_matrix(fid,node,FIFF.FIFF_MNE_FORWARD_SOLUTION_GRAD)
+        one['sol_grad'] = read_named_matrix(fid, node,
+                                        FIFF.FIFF_MNE_FORWARD_SOLUTION_GRAD)
         one['sol_grad'] = transpose_named_matrix(one['sol_grad'])
     except Exception as inst:
         one['sol_grad'] = None
@@ -185,26 +176,39 @@ def read_one(fid, node):
         if one['sol_grad']['data'].shape[0] != one['nchan'] or \
                 (one['sol_grad']['data'].shape[1] != 3*one['nsource'] and
                  one['sol_grad']['data'].shape[1] != 3*3*one['nsource']):
-           fid.close()
-           raise ValueError, 'Forward solution gradient matrix has wrong dimensions'
+            fid.close()
+            raise ValueError, 'Forward solution gradient matrix has ' \
+                              'wrong dimensions'
 
     return one
 
 
 def read_forward_solution(fname, force_fixed=False, surf_ori=False,
                               include=None, exclude=None):
-    """
-    %
-    % [fwd] = mne_read_forward_solution(fname,force_fixed,surf_ori,include,exclude)
-    %
-    % A forward solution from a fif file
-    %
-    % fname        - The name of the file
-    % force_fixed  - Force fixed source orientation mode? (optional)
-    % surf_ori     - Use surface based source coordinate system? (optional)
-    % include      - Include these channels (optional)
-    % exclude      - Exclude these channels (optional)
-    %
+    """Read a forward solution a.k.a. lead field
+
+    Parameters
+    ----------
+    fname: string
+        The file name.
+
+    force_fixed: bool, optional (default False)
+        Force fixed source orientation mode?
+
+    surf_ori: bool, optional (default False)
+        Use surface based source coordinate system?
+
+    include: list, optional
+        List of names of channels to include
+
+    exclude: list, optional
+        List of names of channels to exclude
+
+    Returns
+    -------
+    fwt: dict
+        The forward solution
+
     """
 
     #   Open the file, create directory
@@ -218,7 +222,7 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
         raise ValueError, 'No forward solutions in %s' % fname
 
     #   Parent MRI data
-    parent_mri = dir_tree_find(tree,FIFF.FIFFB_MNE_PARENT_MRI_FILE)
+    parent_mri = dir_tree_find(tree, FIFF.FIFFB_MNE_PARENT_MRI_FILE)
     if len(fwds) == 0:
         fid.close()
         raise ValueError, 'No parent MRI information in %s' % fname
@@ -231,7 +235,7 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
         raise ValueError, 'Could not read the source spaces (%s)' % inst
 
     for s in src:
-       s['id'] = find_source_space_hemi(s)
+        s['id'] = find_source_space_hemi(s)
 
     fwd = None
 
@@ -247,36 +251,37 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
         tag = find_tag(fid, fwds[k], FIFF.FIFF_MNE_INCLUDED_METHODS)
         if tag is None:
             fid.close()
-            raise ValueError, 'Methods not listed for one of the forward solutions'
+            raise ValueError, 'Methods not listed for one of the forward ' \
+                              'solutions'
 
         if tag.data == FIFF.FIFFV_MNE_MEG:
             megnode = fwds[k]
         elif tag.data == FIFF.FIFFV_MNE_EEG:
             eegnode = fwds[k]
 
-    megfwd = read_one(fid, megnode)
+    megfwd = _read_one(fid, megnode)
     if megfwd is not None:
         if megfwd['source_ori'] == FIFF.FIFFV_MNE_FIXED_ORI:
             ori = 'fixed'
         else:
             ori = 'free'
 
-        print '\tRead MEG forward solution (%d sources, %d channels, %s orientations)' % (
-                                    megfwd['nsource'], megfwd['nchan'], ori)
+        print '\tRead MEG forward solution (%d sources, %d channels, ' \
+              '%s orientations)' % (megfwd['nsource'], megfwd['nchan'], ori)
 
-    eegfwd = read_one(fid, eegnode)
+    eegfwd = _read_one(fid, eegnode)
     if eegfwd is not None:
         if eegfwd['source_ori'] == FIFF.FIFFV_MNE_FIXED_ORI:
             ori = 'fixed'
         else:
             ori = 'free'
 
-        print '\tRead EEG forward solution (%d sources, %d channels, %s orientations)' % (
-                                    eegfwd['nsource'], eegfwd['nchan'], ori)
+        print '\tRead EEG forward solution (%d sources, %d channels, ' \
+               '%s orientations)' % (eegfwd['nsource'], eegfwd['nchan'], ori)
 
     #   Merge the MEG and EEG solutions together
     if megfwd is not None and eegfwd is not None:
-        if (megfwd['sol']['data'].shape[1] != eegfwd['sol']['data'].shape[1] or 
+        if (megfwd['sol']['data'].shape[1] != eegfwd['sol']['data'].shape[1] or
                 megfwd['source_ori'] != eegfwd['source_ori'] or
                 megfwd['nsource'] != eegfwd['nsource'] or
                 megfwd['coord_frame'] != eegfwd['coord_frame']):
@@ -285,20 +290,24 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
 
         fwd = megfwd
         fwd['sol']['data'] = np.r_[fwd['sol']['data'], eegfwd['sol']['data']]
-        fwd['sol']['nrow'] = fwd['sol']['nrow'] + eegfwd['sol']['nrow'];
+        fwd['sol']['nrow'] = fwd['sol']['nrow'] + eegfwd['sol']['nrow']
 
-        fwd['sol']['row_names'] = fwd['sol']['row_names'] + eegfwd['sol']['row_names']
+        fwd['sol']['row_names'] = fwd['sol']['row_names'] + \
+                                  eegfwd['sol']['row_names']
         if fwd['sol_grad'] is not None:
-            fwd['sol_grad']['data'] = np.r_[fwd['sol_grad']['data'], eegfwd['sol_grad']['data']]
-            fwd['sol_grad']['nrow'] = fwd['sol_grad']['nrow'] + eegfwd['sol_grad']['nrow']
-            fwd['sol_grad']['row_names'] = fwd['sol_grad']['row_names'] + eegfwd['sol_grad']['row_names']
+            fwd['sol_grad']['data'] = np.r_[fwd['sol_grad']['data'],
+                                            eegfwd['sol_grad']['data']]
+            fwd['sol_grad']['nrow'] = fwd['sol_grad']['nrow'] + \
+                                      eegfwd['sol_grad']['nrow']
+            fwd['sol_grad']['row_names'] = fwd['sol_grad']['row_names'] + \
+                                           eegfwd['sol_grad']['row_names']
 
         fwd['nchan'] = fwd['nchan'] + eegfwd['nchan']
         print '\tMEG and EEG forward solutions combined'
     elif megfwd is not None:
-        fwd = megfwd;
+        fwd = megfwd
     else:
-        fwd = eegfwd;
+        fwd = eegfwd
 
     del megfwd
     del eegfwd
@@ -312,36 +321,39 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
         mri_head_t = tag.data;
         if (mri_head_t['from_'] != FIFF.FIFFV_COORD_MRI or
                 mri_head_t['to'] != FIFF.FIFFV_COORD_HEAD):
-            mri_head_t = invert_transform(mri_head_t)
+            mri_head_t = _invert_transform(mri_head_t)
             if (mri_head_t['from_'] != FIFF.FIFFV_COORD_MRI
                 or mri_head_t['to'] != FIFF.FIFFV_COORD_HEAD):
                 fid.close()
-                raise ValueError, 'MRI/head coordinate transformation not found'
+                raise ValueError, 'MRI/head coordinate transformation not ' \
+                                  'found'
 
     fid.close()
 
-    fwd['mri_head_t'] = mri_head_t;
+    fwd['mri_head_t'] = mri_head_t
 
     #   Transform the source spaces to the correct coordinate frame
     #   if necessary
 
     if (fwd['coord_frame'] != FIFF.FIFFV_COORD_MRI and
             fwd['coord_frame'] != FIFF.FIFFV_COORD_HEAD):
-        raise ValueError, 'Only forward solutions computed in MRI or head coordinates are acceptable'
+        raise ValueError, 'Only forward solutions computed in MRI or head ' \
+                          'coordinates are acceptable'
 
     nuse = 0
     for s in src:
-       try:
-          s = transform_source_space_to(s, fwd['coord_frame'], mri_head_t)
-       except Exception as inst:
-          raise ValueError, 'Could not transform source space (%s)' % inst
+        try:
+            s = _transform_source_space_to(s, fwd['coord_frame'], mri_head_t)
+        except Exception as inst:
+            raise ValueError, 'Could not transform source space (%s)' % inst
 
-       nuse += s['nuse']
+        nuse += s['nuse']
 
     if nuse != fwd['nsource']:
         raise ValueError, 'Source spaces do not match the forward solution.'
 
-    print '\tSource spaces transformed to the forward solution coordinate frame'
+    print '\tSource spaces transformed to the forward solution ' \
+          'coordinate frame'
     fwd['src'] = src;
 
     #   Handle the source locations and orientations
@@ -357,14 +369,15 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
         #   Modify the forward solution for fixed source orientations
         if fwd['source_ori'] != FIFF.FIFFV_MNE_FIXED_ORI:
             print '\tChanging to fixed-orientation forward solution...'
-            fix_rot = block_diag(fwd['source_nn'].T, 1)
+            fix_rot = _block_diag(fwd['source_nn'].T, 1)
             fwd['sol']['data'] *= fix_rot
             fwd['sol']['ncol'] = fwd['nsource']
             fwd['source_ori'] = FIFF.FIFFV_MNE_FIXED_ORI
 
             if fwd['sol_grad'] is not None:
-               fwd['sol_grad']['data'] = np.dot(fwd['sol_grad']['data'], np.kron(fix_rot, np.eye(3)))
-               fwd['sol_grad']['ncol'] = 3*fwd['nsource']
+                fwd['sol_grad']['data'] = np.dot(fwd['sol_grad']['data'],
+                                                 np.kron(fix_rot, np.eye(3)))
+                fwd['sol_grad']['ncol'] = 3*fwd['nsource']
 
             print '[done]'
     else:
@@ -375,12 +388,13 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
             pp = 1
             fwd['source_rr'] = np.zeros(fwd['nsource'], 3)
             for s in src:
-                fwd['source_rr'][nuse+1:nuse + s['nuse'],:] = s['rr'][s['vertno'],:]
+                fwd['source_rr'][nuse+1:nuse + s['nuse'],:] = \
+                                                    s['rr'][s['vertno'],:]
                 for p in range(s['nuse']):
                     #  Project out the surface normal and compute SVD
                     nn = s['nn'][s['vertno'][p],:].T
                     nn = nn[:,None]
-                    [ U, S, V ]  = linalg.svd(np.eye(3,3) - nn*nn.T)
+                    U, S, _ = linalg.svd(np.eye(3,3) - nn*nn.T)
                     #  Make sure that ez is in the direction of nn
                     if np.sum(nn*U[:,2]) < 0:
                         U *= -1
@@ -388,10 +402,11 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
                         pp += 3
                     nuse += s['nuse']
 
-            surf_rot = block_diag(fwd['source_nn'].T, 3)
+            surf_rot = _block_diag(fwd['source_nn'].T, 3)
             fwd['sol']['data'] = np.dot(fwd['sol']['data'], surf_rot)
             if fwd['sol_grad'] is not None:
-                fwd['sol_grad']['data'] = np.dot(fwd['sol_grad']['data'] * np.kron(surf_rot, np.eye(3)))
+                fwd['sol_grad']['data'] = np.dot(fwd['sol_grad']['data'] * \
+                                                 np.kron(surf_rot, np.eye(3)))
 
             print '[done]'
         else:
@@ -399,10 +414,11 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
             nuse = 0
             fwd['source_rr'] = np.zeros((fwd['nsource'], 3))
             for s in src:
-                fwd['source_rr'][nuse:nuse+s['nuse'],:] = s['rr'][s['vertno'],:]
+                fwd['source_rr'][nuse:nuse+s['nuse'],:] = \
+                                                s['rr'][s['vertno'],:]
                 nuse += s['nuse']
 
-            fwd['source_nn'] = np.kron(np.ones((fwd['nsource'], 1)), np.eye(3));
+            fwd['source_nn'] = np.kron(np.ones((fwd['nsource'], 1)), np.eye(3))
             print '[done]'
 
     #   Do the channel selection
@@ -427,15 +443,16 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
                         pick[p] = False
 
         #   Do we have something?
-        nuse = pick.sum();
+        nuse = pick.sum()
         if nuse == 0:
             raise ValueError, 'Nothing remains after picking'
 
-        print '\t%d out of %d channels remain after picking\n' % (nuse, fwd['nchan'])
+        print '\t%d out of %d channels remain after picking\n' % (nuse,
+                                                                fwd['nchan'])
 
         #   Pick the correct rows of the forward operator
         fwd['nchan'] = nuse
-        fwd['sol']['data'] = fwd['sol']['data'][pick == 1,:]
+        fwd['sol']['data'] = fwd['sol']['data'][pick == 1, :]
         fwd['sol']['nrow'] = nuse
         fwd['sol']['row_names'] = [fwd['sol']['row_names'][k]
                                     for k in range(len(pick)) if pick[k]]
@@ -444,6 +461,6 @@ def read_forward_solution(fname, force_fixed=False, surf_ori=False,
             fwd['sol_grad']['data'] = fwd['sol_grad']['data'][pick == 1, :]
             fwd['sol_grad']['nrow'] = nuse
             fwd['sol_grad']['row_names'] = [fwd['sol_grad']['row_names'][k]
-                                            for k in range(len(pick)) if pick[k]]
+                                        for k in range(len(pick)) if pick[k]]
 
-    return fwd
\ No newline at end of file
+    return fwd
diff --git a/fiff/inverse.py b/fiff/inverse.py
index 5d516d1..6ce1fac 100644
--- a/fiff/inverse.py
+++ b/fiff/inverse.py
@@ -6,7 +6,7 @@ from .cov import read_cov
 from .proj import read_proj
 from .tree import dir_tree_find
 from .source_space import read_source_spaces, find_source_space_hemi
-from .forward import invert_transform, transform_source_space_to
+from .forward import _invert_transform, _transform_source_space_to
 
 
 def read_inverse_operator(fname):
@@ -181,7 +181,7 @@ def read_inverse_operator(fname):
         mri_head_t = tag.data;
         if mri_head_t['from_'] != FIFF.FIFFV_COORD_MRI or \
                         mri_head_t['to'] != FIFF.FIFFV_COORD_HEAD:
-            mri_head_t = invert_transform(mri_head_t)
+            mri_head_t = _invert_transform(mri_head_t)
             if mri_head_t['from_'] != FIFF.FIFFV_COORD_MRI or \
                         mri_head_t['to'] != FIFF.FIFFV_COORD_HEAD:
                 fid.close()
@@ -218,7 +218,7 @@ def read_inverse_operator(fname):
     nuse = 0
     for k in range(len(inv['src'])):
        try:
-          inv['src'][k] = transform_source_space_to(inv['src'][k],
+          inv['src'][k] = _transform_source_space_to(inv['src'][k],
                                                 inv['coord_frame'], mri_head_t)
        except Exception as inst:
           fid.close()
diff --git a/fiff/meas_info.py b/fiff/meas_info.py
index 2f6aa9d..9858fed 100644
--- a/fiff/meas_info.py
+++ b/fiff/meas_info.py
@@ -10,13 +10,25 @@ from .channels import read_bad_channels
 
 
 def read_meas_info(source, tree=None):
-    """[info,meas] = fiff_read_meas_info(source,tree)
+    """Read the measurement info
 
-     Read the measurement info
+    Parameters
+    ----------
+    source: string or file
+        If string it is the file name otherwise it's the file descriptor.
+        If tree is missing, the meas output argument is None
+
+    tree: tree
+        FIF tree structure
+
+    Returns
+    -------
+    info: dict
+       Info on dataset
+
+    meas: dict
+        Node in tree that contains the info.
 
-     If tree is specified, source is assumed to be an open file id,
-     otherwise a the name of the file to read. If tree is missing, the
-     meas output argument should not be specified.
     """
     if tree is None:
        fid, tree, _ = fiff_open(source)
@@ -83,39 +95,33 @@ def read_meas_info(source, tree=None):
         elif kind == FIFF.FIFF_COORD_TRANS:
             tag = read_tag(fid, pos)
             cand = tag.data
-            if cand.from_ == FIFF.FIFFV_COORD_DEVICE and \
-                                cand.to == FIFF.FIFFV_COORD_HEAD: # XXX : from
+            if cand['from_'] == FIFF.FIFFV_COORD_DEVICE and \
+                                cand['to'] == FIFF.FIFFV_COORD_HEAD: # XXX : from
                 dev_head_t = cand
-            elif cand.from_ == FIFF.FIFFV_MNE_COORD_CTF_HEAD and \
-                                cand.to == FIFF.FIFFV_COORD_HEAD:
+            elif cand['from_'] == FIFF.FIFFV_MNE_COORD_CTF_HEAD and \
+                                cand['to'] == FIFF.FIFFV_COORD_HEAD:
                 ctf_head_t = cand
 
-    #  XXX : fix
-    #   Check that we have everything we need
-    # if ~exist('nchan','var')
-    #    if open_here
-    #       fclose(fid);
-    #    end
-    #    error(me,'Number of channels in not defined');
-    # end
-    # if ~exist('sfreq','var')
-    #    if open_here
-    #       fclose(fid);
-    #    end
-    #    error(me,'Sampling frequency is not defined');
-    # end
-    # if ~exist('chs','var')
-    #    if open_here
-    #       fclose(fid);
-    #    end
-    #    error(me,'Channel information not defined');
-    # end
-    # if length(chs) ~= nchan
-    #    if open_here
-    #       fclose(fid);
-    #    end
-    #    error(me,'Incorrect number of channel definitions found');
-    # end
+    # Check that we have everything we need
+    if nchan is None:
+       if open_here:
+           fid.close()
+       raise ValueError, 'Number of channels in not defined'
+
+    if sfreq is None:
+        if open_here:
+            fid.close()
+        raise ValueError, 'Sampling frequency is not defined'
+
+    if len(chs) == 0:
+        if open_here:
+            fid.close()
+        raise ValueError, 'Channel information not defined'
+
+    if len(chs) != nchan:
+        if open_here:
+            fid.close()
+        raise ValueError, 'Incorrect number of channel definitions found'
 
     if dev_head_t is None or ctf_head_t is None:
         hpi_result = dir_tree_find(meas_info, FIFF.FIFFB_HPI_RESULT)
diff --git a/fiff/open.py b/fiff/open.py
index 5feaa90..93c2db0 100644
--- a/fiff/open.py
+++ b/fiff/open.py
@@ -4,6 +4,29 @@ from .constants import FIFF
 
 
 def fiff_open(fname, verbose=False):
+    """Open a FIF file.
+
+    Parameters
+    ----------
+    fname: string
+        name of the fif file
+
+    verbose: bool
+        verbose mode if True
+
+    Returns
+    -------
+    fid: file
+        The file descriptor of the open file
+
+    tree: fif tree
+        The tree is a complex structure filled with dictionaries,
+        lists and tags.
+
+    directory: list
+        list of nodes.
+
+    """
 
     fid = open(fname, "rb") # Open in binary mode
 
diff --git a/fiff/proj.py b/fiff/proj.py
index a531592..caf17b5 100644
--- a/fiff/proj.py
+++ b/fiff/proj.py
@@ -5,11 +5,20 @@ from .bunch import Bunch
 
 
 def read_proj(fid, node):
-    """
-    [ projdata ] = fiff_read_proj(fid,node)
+    """Read a projection operator from a FIF file.
+
+    Parameters
+    ----------
+    fid: file
+        The file descriptor of the open file
 
-     Read the SSP data under a given directory node
+    node: tree node
+        The node of the tree where to look
 
+    Returns
+    -------
+    projdata: dict
+        The projection operator
     """
 
     projdata = []
@@ -111,15 +120,16 @@ from .write import write_int, write_float, write_string, write_name_list, \
                    write_float_matrix, end_block, start_block
 
 def write_proj(fid, projs):
-    """
-    %
-    % fiff_write_proj(fid,projs)
-    % 
-    % Writes the projection data into a fif file
-    %
-    %     fid           An open fif file descriptor
-    %     projs         The compensation data to write
-    %
+    """Write a projection operator to a file.
+
+    Parameters
+    ----------
+    fid: file
+        The file descriptor of the open file
+
+    projs: dict
+        The projection operator
+
     """
     start_block(fid, FIFF.FIFFB_PROJ)
 
diff --git a/fiff/raw.py b/fiff/raw.py
index a69e802..7687b61 100644
--- a/fiff/raw.py
+++ b/fiff/raw.py
@@ -9,15 +9,20 @@ from .tag import read_tag
 
 
 def setup_read_raw(fname, allow_maxshield=False):
-    """
-    %
-    % [data] = setup_read_raw(fname,allow_maxshield)
-    %
-    % Read information about raw data file
-    %
-    % fname               Name of the file to read
-    % allow_maxshield     Accept unprocessed MaxShield data
-    %
+    """Read information about raw data file
+
+    Parameters
+    ----------
+    fname: string
+        The name of the raw file
+
+    allow_maxshield: bool, (default False)
+        allow_maxshield if True XXX ???
+
+    Returns
+    -------
+    data: dict
+        Infos about raw data
     """
 
     #   Open the file
@@ -135,22 +140,34 @@ def setup_read_raw(fname, allow_maxshield=False):
 
 
 def read_raw_segment(raw, from_=None, to=None, sel=None):
-    """
-    %
-    % [data,times] = fiff_read_raw_segment(raw,from_,to,sel)
-    %
-    % Read a specific raw data segment
-    %
-    % raw    - structure returned by fiff_setup_read_raw
-    % from_   - first sample to include. If omitted, defaults to the
-    %          first sample in data
-    % to     - last sample to include. If omitted, defaults to the last
-    %          sample in data
-    % sel    - optional channel selection vector
-    %
-    % data   - returns the data matrix (channels x samples)
-    % times  - returns the time values corresponding to the samples (optional)
-    %
+    """Read a chunck of raw data
+
+    Parameters
+    ----------
+    raw: dict
+        The dict returned by setup_read_raw
+
+    from_: int
+        first sample to include. If omitted, defaults to the first
+        sample in data
+
+    to: int
+        Last sample to include. If omitted, defaults to the last sample in data
+
+    sel: array, optional
+        Indices of channels to select
+
+    node: tree node
+        The node of the tree where to look
+
+    Returns
+    -------
+    data: array, [channels x samples]
+       the data matrix (channels x samples)
+
+    times: array, [samples]
+        returns the time values corresponding to the samples
+
     """
 
     if to is None:
@@ -285,22 +302,33 @@ def read_raw_segment(raw, from_=None, to=None, sel=None):
 
 
 def read_raw_segment_times(raw, from_, to, sel=None):
-    """
-    %
-    % [data,times] = fiff_read_raw_segment_times(raw,from,to)
-    %
-    % Read a specific raw data segment
-    %
-    % raw    - structure returned by fiff_setup_read_raw
-    % from   - starting time of the segment in seconds
-    % to     - end time of the segment in seconds
-    % sel    - optional channel selection vector
-    %
-    % data   - returns the data matrix (channels x samples)
-    % times  - returns the time values corresponding to the samples (optional)
-    %
-    """
+    """Read a chunck of raw data
+
+    Parameters
+    ----------
+    raw: dict
+        The dict returned by setup_read_raw
+
+    from_: float
+        Starting time of the segment in seconds
 
+    to: float
+        End time of the segment in seconds
+
+    sel: array, optional
+        Indices of channels to select
+
+    node: tree node
+        The node of the tree where to look
+
+    Returns
+    -------
+    data: array, [channels x samples]
+       the data matrix (channels x samples)
+
+    times: array, [samples]
+        returns the time values corresponding to the samples
+    """
     #   Convert to samples
     from_ = floor(from_ * raw['info']['sfreq'])
     to   = ceil(to * raw['info']['sfreq'])
diff --git a/fiff/tests/test_forward.py b/fiff/tests/test_forward.py
index 82bd638..4693c0f 100644
--- a/fiff/tests/test_forward.py
+++ b/fiff/tests/test_forward.py
@@ -14,4 +14,5 @@ def test_io_forward():
     """Test IO for forward solutions
     """
     fwd = fiff.read_forward_solution(fname)
+    fwd = fiff.read_forward_solution(fname, force_fixed=True)
     leadfield = fwd['sol']['data']

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-med/python-mne.git



More information about the debian-med-commit mailing list