[med-svn] [python-mne] 110/353: API: read cov now form .fif with mne.read_cov and mne.fiff.read_cov is used to read from file id
Yaroslav Halchenko
debian at onerussian.com
Fri Nov 27 17:24:39 UTC 2015
This is an automated email from the git hooks/post-receive script.
yoh pushed a commit to tag 0.4
in repository python-mne.
commit 989e855144aa7b59ecef7a29033d147615117839
Author: Alexandre Gramfort <alexandre.gramfort at inria.fr>
Date: Fri Mar 9 12:31:57 2012 +0100
API: read cov now form .fif with mne.read_cov and mne.fiff.read_cov is used to read from file id
---
mne/__init__.py | 2 +-
mne/cov.py | 197 ++++++--------------------------------------
mne/fiff/__init__.py | 1 +
mne/fiff/cov.py | 174 ++++++++++++++++++++++++++++++++++++++
mne/minimum_norm/inverse.py | 3 +-
mne/tests/test_cov.py | 17 ++--
6 files changed, 207 insertions(+), 187 deletions(-)
diff --git a/mne/__init__.py b/mne/__init__.py
index 89f389a..8044dcc 100644
--- a/mne/__init__.py
+++ b/mne/__init__.py
@@ -1,6 +1,6 @@
__version__ = '0.2.git'
-from .cov import read_cov, write_cov, write_cov_file, Covariance, \
+from .cov import read_cov, write_cov, Covariance, \
compute_raw_data_covariance, compute_covariance
from .event import read_events, write_events, find_events, merge_events, \
pick_events
diff --git a/mne/cov.py b/mne/cov.py
index 02edf48..e91acba 100644
--- a/mne/cov.py
+++ b/mne/cov.py
@@ -9,15 +9,9 @@ from math import floor, ceil
import numpy as np
from scipy import linalg
-from .fiff.constants import FIFF
-from .fiff.tag import find_tag
-from .fiff.tree import dir_tree_find
-from .fiff.proj import read_proj
-from .fiff.channels import _read_bad_channels
-
-from .fiff.write import start_block, end_block, write_int, write_name_list, \
- write_double, write_float_matrix, start_file, end_file
-from .fiff.proj import write_proj, make_projector
+from . import fiff
+from .fiff.write import start_file, end_file
+from .fiff.proj import make_projector
from .fiff import fiff_open
from .fiff.pick import pick_types, channel_indices_by_type
from .epochs import _is_good
@@ -75,7 +69,7 @@ class Covariance(object):
# Reading
fid, tree, _ = fiff_open(fname)
- cov = read_cov(fid, tree, cov_kind)
+ cov = fiff.read_cov(fid, tree, cov_kind)
fid.close()
self._cov = cov
@@ -85,7 +79,15 @@ class Covariance(object):
def save(self, fname):
"""save covariance matrix in a FIF file"""
- write_cov_file(fname, self._cov)
+ fid = start_file(fname)
+
+ try:
+ fiff.write_cov(fid, self._cov)
+ except Exception as inst:
+ os.remove(fname)
+ raise '%s', inst
+
+ end_file(fid)
def __repr__(self):
s = "kind : %s" % self.kind
@@ -118,114 +120,20 @@ class Covariance(object):
###############################################################################
# IO
-def read_cov(fid, node, cov_kind):
- """Read a noise covariance matrix
+def read_cov(fname):
+ """Read covariance from a FIF file.
Parameters
----------
- fid: file
- The file descriptor
-
- node: dict
- The node in the FIF tree
-
- cov_kind: int
- The type of covariance. XXX : clarify
+ fname: string
+ The name of file containing the covariance matrix.
Returns
-------
- data: dict
- The noise covariance
+ projs: list
+ The list of projection vectors.
"""
- # Find all covariance matrices
- covs = dir_tree_find(node, FIFF.FIFFB_MNE_COV)
- if len(covs) == 0:
- raise ValueError('No covariance matrices found')
-
- # Is any of the covariance matrices a noise covariance
- for p in range(len(covs)):
- tag = find_tag(fid, covs[p], FIFF.FIFF_MNE_COV_KIND)
-
- if tag is not None and int(tag.data) == cov_kind:
- this = covs[p]
-
- # Find all the necessary data
- tag = find_tag(fid, this, FIFF.FIFF_MNE_COV_DIM)
- if tag is None:
- raise ValueError('Covariance matrix dimension not found')
-
- dim = tag.data
- tag = find_tag(fid, this, FIFF.FIFF_MNE_COV_NFREE)
- if tag is None:
- nfree = -1
- else:
- nfree = tag.data
-
- tag = find_tag(fid, this, FIFF.FIFF_MNE_ROW_NAMES)
- if tag is None:
- names = []
- else:
- names = tag.data.split(':')
- if len(names) != dim:
- raise ValueError('Number of names does not match '
- 'covariance matrix dimension')
-
- tag = find_tag(fid, this, FIFF.FIFF_MNE_COV)
- if tag is None:
- tag = find_tag(fid, this, FIFF.FIFF_MNE_COV_DIAG)
- if tag is None:
- raise ValueError('No covariance matrix data found')
- else:
- # Diagonal is stored
- data = tag.data
- diagmat = True
- print (' %d x %d diagonal covariance (kind = %d) found.'
- % (dim, dim, cov_kind))
-
- else:
- from scipy import sparse
- if not sparse.issparse(tag.data):
- # Lower diagonal is stored
- vals = tag.data
- data = np.zeros((dim, dim))
- data[np.tril(np.ones((dim, dim))) > 0] = vals
- data = data + data.T
- data.flat[::dim + 1] /= 2.0
- diagmat = False
- print ' %d x %d full covariance (kind = %d) found.' \
- % (dim, dim, cov_kind)
- else:
- diagmat = False
- data = tag.data
- print ' %d x %d sparse covariance (kind = %d) found.' \
- % (dim, dim, cov_kind)
-
- # Read the possibly precomputed decomposition
- tag1 = find_tag(fid, this, FIFF.FIFF_MNE_COV_EIGENVALUES)
- tag2 = find_tag(fid, this, FIFF.FIFF_MNE_COV_EIGENVECTORS)
- if tag1 is not None and tag2 is not None:
- eig = tag1.data
- eigvec = tag2.data
- else:
- eig = None
- eigvec = None
-
- # Read the projection operator
- projs = read_proj(fid, this)
-
- # Read the bad channel list
- bads = _read_bad_channels(fid, this)
-
- # Put it together
- cov = dict(kind=cov_kind, diag=diagmat, dim=dim, names=names,
- data=data, projs=projs, bads=bads, nfree=nfree, eig=eig,
- eigvec=eigvec)
- return cov
-
- print 'Did not find the desired covariance matrix'
-
- return None
-
+ return Covariance(fname)
###############################################################################
# Estimate from data
@@ -397,58 +305,7 @@ def compute_covariance(epochs, keep_sample_mean=True):
###############################################################################
# Writing
-def write_cov(fid, cov):
- """Write a noise covariance matrix
-
- Parameters
- ----------
- fid: file
- The file descriptor
-
- cov: dict
- The noise covariance matrix to write
- """
- start_block(fid, FIFF.FIFFB_MNE_COV)
-
- # Dimensions etc.
- write_int(fid, FIFF.FIFF_MNE_COV_KIND, cov['kind'])
- write_int(fid, FIFF.FIFF_MNE_COV_DIM, cov['dim'])
- if cov['nfree'] > 0:
- write_int(fid, FIFF.FIFF_MNE_COV_NFREE, cov['nfree'])
-
- # Channel names
- if cov['names'] is not None and len(cov['names']) > 0:
- write_name_list(fid, FIFF.FIFF_MNE_ROW_NAMES, cov['names'])
-
- # Data
- if cov['diag']:
- write_double(fid, FIFF.FIFF_MNE_COV_DIAG, cov['data'])
- else:
- # Store only lower part of covariance matrix
- dim = cov['dim']
- mask = np.tril(np.ones((dim, dim), dtype=np.bool)) > 0
- vals = cov['data'][mask].ravel()
- write_double(fid, FIFF.FIFF_MNE_COV, vals)
-
- # Eigenvalues and vectors if present
- if cov['eig'] is not None and cov['eigvec'] is not None:
- write_float_matrix(fid, FIFF.FIFF_MNE_COV_EIGENVECTORS, cov['eigvec'])
- write_double(fid, FIFF.FIFF_MNE_COV_EIGENVALUES, cov['eig'])
-
- # Projection operator
- write_proj(fid, cov['projs'])
-
- # Bad channels
- if cov['bads'] is not None:
- start_block(fid, FIFF.FIFFB_MNE_BAD_CHANNELS)
- write_name_list(fid, FIFF.FIFF_MNE_CH_NAME_LIST, cov['bads'])
- end_block(fid, FIFF.FIFFB_MNE_BAD_CHANNELS)
-
- # Done!
- end_block(fid, FIFF.FIFFB_MNE_COV)
-
-
-def write_cov_file(fname, cov):
+def write_cov(fname, cov):
"""Write a noise covariance matrix
Parameters
@@ -456,18 +313,10 @@ def write_cov_file(fname, cov):
fname: string
The name of the file
- cov: dict
+ cov: Covariance
The noise covariance
"""
- fid = start_file(fname)
-
- try:
- write_cov(fid, cov)
- except Exception as inst:
- os.remove(fname)
- raise '%s', inst
-
- end_file(fid)
+ cov.save(fname)
###############################################################################
diff --git a/mne/fiff/__init__.py b/mne/fiff/__init__.py
index 7d5b666..1e0fc1c 100644
--- a/mne/fiff/__init__.py
+++ b/mne/fiff/__init__.py
@@ -16,3 +16,4 @@ from .pick import pick_types, pick_channels, pick_types_evoked, \
from .compensator import get_current_comp
from .proj import compute_spatial_vectors
+from .cov import read_cov, write_cov
diff --git a/mne/fiff/cov.py b/mne/fiff/cov.py
new file mode 100644
index 0000000..f92d0ac
--- /dev/null
+++ b/mne/fiff/cov.py
@@ -0,0 +1,174 @@
+# Authors: Alexandre Gramfort <gramfort at nmr.mgh.harvard.edu>
+# Matti Hamalainen <msh at nmr.mgh.harvard.edu>
+#
+# License: BSD (3-clause)
+
+import numpy as np
+
+from .constants import FIFF
+from .write import start_block, end_block, write_int, write_name_list, \
+ write_double, write_float_matrix
+from .tag import find_tag
+from .tree import dir_tree_find
+from .proj import read_proj, write_proj
+from .channels import _read_bad_channels
+
+
+def read_cov(fid, node, cov_kind):
+ """Read a noise covariance matrix
+
+ Parameters
+ ----------
+ fid: file
+ The file descriptor
+
+ node: dict
+ The node in the FIF tree
+
+ cov_kind: int
+ The type of covariance. XXX : clarify
+
+ Returns
+ -------
+ data: dict
+ The noise covariance
+ """
+ # Find all covariance matrices
+ covs = dir_tree_find(node, FIFF.FIFFB_MNE_COV)
+ if len(covs) == 0:
+ raise ValueError('No covariance matrices found')
+
+ # Is any of the covariance matrices a noise covariance
+ for p in range(len(covs)):
+ tag = find_tag(fid, covs[p], FIFF.FIFF_MNE_COV_KIND)
+
+ if tag is not None and int(tag.data) == cov_kind:
+ this = covs[p]
+
+ # Find all the necessary data
+ tag = find_tag(fid, this, FIFF.FIFF_MNE_COV_DIM)
+ if tag is None:
+ raise ValueError('Covariance matrix dimension not found')
+
+ dim = tag.data
+ tag = find_tag(fid, this, FIFF.FIFF_MNE_COV_NFREE)
+ if tag is None:
+ nfree = -1
+ else:
+ nfree = tag.data
+
+ tag = find_tag(fid, this, FIFF.FIFF_MNE_ROW_NAMES)
+ if tag is None:
+ names = []
+ else:
+ names = tag.data.split(':')
+ if len(names) != dim:
+ raise ValueError('Number of names does not match '
+ 'covariance matrix dimension')
+
+ tag = find_tag(fid, this, FIFF.FIFF_MNE_COV)
+ if tag is None:
+ tag = find_tag(fid, this, FIFF.FIFF_MNE_COV_DIAG)
+ if tag is None:
+ raise ValueError('No covariance matrix data found')
+ else:
+ # Diagonal is stored
+ data = tag.data
+ diagmat = True
+ print (' %d x %d diagonal covariance (kind = %d) found.'
+ % (dim, dim, cov_kind))
+
+ else:
+ from scipy import sparse
+ if not sparse.issparse(tag.data):
+ # Lower diagonal is stored
+ vals = tag.data
+ data = np.zeros((dim, dim))
+ data[np.tril(np.ones((dim, dim))) > 0] = vals
+ data = data + data.T
+ data.flat[::dim + 1] /= 2.0
+ diagmat = False
+ print ' %d x %d full covariance (kind = %d) found.' \
+ % (dim, dim, cov_kind)
+ else:
+ diagmat = False
+ data = tag.data
+ print ' %d x %d sparse covariance (kind = %d) found.' \
+ % (dim, dim, cov_kind)
+
+ # Read the possibly precomputed decomposition
+ tag1 = find_tag(fid, this, FIFF.FIFF_MNE_COV_EIGENVALUES)
+ tag2 = find_tag(fid, this, FIFF.FIFF_MNE_COV_EIGENVECTORS)
+ if tag1 is not None and tag2 is not None:
+ eig = tag1.data
+ eigvec = tag2.data
+ else:
+ eig = None
+ eigvec = None
+
+ # Read the projection operator
+ projs = read_proj(fid, this)
+
+ # Read the bad channel list
+ bads = _read_bad_channels(fid, this)
+
+ # Put it together
+ cov = dict(kind=cov_kind, diag=diagmat, dim=dim, names=names,
+ data=data, projs=projs, bads=bads, nfree=nfree, eig=eig,
+ eigvec=eigvec)
+ return cov
+
+ print 'Did not find the desired covariance matrix'
+
+ return None
+
+
+def write_cov(fid, cov):
+ """Write a noise covariance matrix
+
+ Parameters
+ ----------
+ fid: file
+ The file descriptor
+
+ cov: dict
+ The noise covariance matrix to write
+ """
+ start_block(fid, FIFF.FIFFB_MNE_COV)
+
+ # Dimensions etc.
+ write_int(fid, FIFF.FIFF_MNE_COV_KIND, cov['kind'])
+ write_int(fid, FIFF.FIFF_MNE_COV_DIM, cov['dim'])
+ if cov['nfree'] > 0:
+ write_int(fid, FIFF.FIFF_MNE_COV_NFREE, cov['nfree'])
+
+ # Channel names
+ if cov['names'] is not None and len(cov['names']) > 0:
+ write_name_list(fid, FIFF.FIFF_MNE_ROW_NAMES, cov['names'])
+
+ # Data
+ if cov['diag']:
+ write_double(fid, FIFF.FIFF_MNE_COV_DIAG, cov['data'])
+ else:
+ # Store only lower part of covariance matrix
+ dim = cov['dim']
+ mask = np.tril(np.ones((dim, dim), dtype=np.bool)) > 0
+ vals = cov['data'][mask].ravel()
+ write_double(fid, FIFF.FIFF_MNE_COV, vals)
+
+ # Eigenvalues and vectors if present
+ if cov['eig'] is not None and cov['eigvec'] is not None:
+ write_float_matrix(fid, FIFF.FIFF_MNE_COV_EIGENVECTORS, cov['eigvec'])
+ write_double(fid, FIFF.FIFF_MNE_COV_EIGENVALUES, cov['eig'])
+
+ # Projection operator
+ write_proj(fid, cov['projs'])
+
+ # Bad channels
+ if cov['bads'] is not None:
+ start_block(fid, FIFF.FIFFB_MNE_BAD_CHANNELS)
+ write_name_list(fid, FIFF.FIFF_MNE_CH_NAME_LIST, cov['bads'])
+ end_block(fid, FIFF.FIFFB_MNE_BAD_CHANNELS)
+
+ # Done!
+ end_block(fid, FIFF.FIFFB_MNE_COV)
diff --git a/mne/minimum_norm/inverse.py b/mne/minimum_norm/inverse.py
index 4765ed4..9399d06 100644
--- a/mne/minimum_norm/inverse.py
+++ b/mne/minimum_norm/inverse.py
@@ -20,7 +20,8 @@ from ..fiff.write import write_int, write_float_matrix, start_file, \
start_block, end_block, end_file, write_float, \
write_coord_trans
-from ..cov import read_cov, prepare_noise_cov, write_cov
+from ..fiff.cov import read_cov, write_cov
+from ..cov import prepare_noise_cov
from ..forward import compute_depth_prior, compute_depth_prior_fixed
from ..source_space import read_source_spaces_from_tree, \
find_source_space_hemi, _get_vertno, \
diff --git a/mne/tests/test_cov.py b/mne/tests/test_cov.py
index ab28ab1..af405a5 100644
--- a/mne/tests/test_cov.py
+++ b/mne/tests/test_cov.py
@@ -4,10 +4,10 @@ from nose.tools import assert_true
from numpy.testing import assert_array_almost_equal
from scipy import linalg
-from .. import Covariance, read_cov, Epochs, merge_events, \
- find_events, write_cov_file, compute_raw_data_covariance, \
+from .. import Covariance, Epochs, merge_events, \
+ find_events, compute_raw_data_covariance, \
compute_covariance
-from ..fiff import fiff_open, Raw
+from ..fiff import Raw
cov_fname = op.join(op.dirname(__file__), '..', 'fiff', 'tests', 'data',
'test-cov.fif')
@@ -22,15 +22,10 @@ erm_cov_fname = op.join('mne', 'fiff', 'tests', 'data',
def test_io_cov():
"""Test IO for noise covariance matrices
"""
- fid, tree, _ = fiff_open(cov_fname)
- cov_type = 1
- cov = read_cov(fid, tree, cov_type)
- fid.close()
-
- write_cov_file('cov.fif', cov)
-
+ cov = Covariance(cov_fname)
+ cov.save('cov.fif')
cov2 = Covariance('cov.fif')
- assert_array_almost_equal(cov['data'], cov2.data)
+ assert_array_almost_equal(cov.data, cov2.data)
def test_cov_estimation_on_raw_segment():
--
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