[Scipy-svn] r2292 - trunk/Lib/io

scipy-svn at scipy.org scipy-svn at scipy.org
Fri Oct 20 06:05:27 CDT 2006


Author: matthew.brett at gmail.com
Date: 2006-10-20 06:05:22 -0500 (Fri, 20 Oct 2006)
New Revision: 2292

Modified:
   trunk/Lib/io/mio.py
   trunk/Lib/io/mio4.py
   trunk/Lib/io/mio5.py
   trunk/Lib/io/miobase.py
Log:
Passing of matrix return options from loadmat, docstring cleanups

Modified: trunk/Lib/io/mio.py
===================================================================
--- trunk/Lib/io/mio.py	2006-10-20 04:01:05 UTC (rev 2291)
+++ trunk/Lib/io/mio.py	2006-10-20 11:05:22 UTC (rev 2292)
@@ -10,37 +10,26 @@
 from numpy import *
 
 from mio4 import MatFile4Reader, MatFile4Writer
-from mio5 import MatFile5Reader
+from mio5 import MatFile5Reader, MatFile5Writer
 
 
-def mat_reader_factory(file_name, append_mat=True):
+def mat_reader_factory(file_name, appendmat=True, **kwargs):
     """Create reader for matlab (TM) .mat format files
     
-    If name not a full path name, search for the file on the sys.path
-    list and use the first one found (the current directory is
-    searched first).
-
-    v4 (Level 1.0), v6 and v7.1 matfiles are supported.  
-
-    Inputs:
-
-      file_name -- name of the mat file (don't need .mat extension
-                   if append_mat=True)
-      append_mat -- True to append the .mat extension to the end of the
-                   given filename.
-      """
-    if append_mat and file_name[-4:] == ".mat":
+    See docstring for loadmat for input options
+    """
+    if appendmat and file_name[-4:] == ".mat":
         file_name = file_name[:-4]
     if os.sep in file_name:
         full_file_name = file_name
-        if append_mat:
+        if appendmat:
             full_name = file_name + ".mat"
     else:
         full_name = None
         junk,file_name = os.path.split(file_name)
         for path in sys.path:
             test_name = os.path.join(path,file_name)
-            if append_mat:
+            if appendmat:
                 test_name += ".mat"
             try:
                 fid = open(test_name,'rb')
@@ -53,17 +42,41 @@
             raise IOError, "%s not found on the path." % file_name
 
     byte_stream = open(full_name, 'rb')
-    MR = MatFile4Reader(byte_stream)
+    MR = MatFile4Reader(byte_stream, **kwargs)
     if MR.format_looks_right():
         return MR
-    return MatFile5Reader(byte_stream)
+    return MatFile5Reader(byte_stream, **kwargs)
 
-def loadmat(file_name,  mdict=None, appendmat=True, basename='raw'):
+def loadmat(file_name,  mdict=None, appendmat=True, basename='raw', **kwargs):
     ''' Load Matlab(tm) file
 
-    See docs for mat_reader_factory for details of input options
+    file_name          - Name of the mat file
+                         (do not need .mat extension if appendmat==True)
+                         If name not a full path name, search for the file on
+                         the sys.path list and use the first one found (the
+                         current directory is searched first).
+    m_dict             - optional dictionary in which to insert matfile variables 
+    appendmat          - True to append the .mat extension to the end of the
+                         given filename.
+    base_name          - base name for unnamed variables (unused in code)
+    byte_order         - byte order ('native', 'little', 'BIG')
+                          in ('native', '=')
+                          or in ('little', '<')
+                          or in ('BIG', '>')
+    mat_dtype          - return arrays in same dtype as loaded into matlab
+                          (instead of the dtype with which they are saved)
+    squeeze_me         - whether to squeeze matrix dimensions or not
+    chars_as_strings   - whether to convert char arrays to string arrays
+    mat_dtype          - return matrices with datatype that matlab would load as
+                          (rather than in the datatype matlab saves as)
+    matlab_compatible   - returns matrices as would be loaded by matlab
+                          (implies squeeze_me=False, chars_as_strings=False,
+                          mat_dtype=True)
+
+    v4 (Level 1.0), v6 and v7.1 matfiles are supported.  
+
     '''
-    MR = mat_reader_factory(file_name, basename)
+    MR = mat_reader_factory(file_name, appendmat, **kwargs)
     matfile_dict = MR.get_variables()
     if mdict is not None:
         mdict.update(matfile_dict)

Modified: trunk/Lib/io/mio4.py
===================================================================
--- trunk/Lib/io/mio4.py	2006-10-20 04:01:05 UTC (rev 2291)
+++ trunk/Lib/io/mio4.py	2006-10-20 11:05:22 UTC (rev 2292)
@@ -29,6 +29,8 @@
 
 np_to_mtypes = {
     'f8': miDOUBLE,
+    'c32': miDOUBLE,    
+    'c24': miDOUBLE,
     'c16': miDOUBLE,
     'f4': miSINGLE,
     'c8': miSINGLE,
@@ -98,7 +100,7 @@
     
     def read_array(self, copy=True):
         ''' Mat4 read array always uses header dtype and dims
-        @copy        - copies array if True
+        copy        - copies array if True
         (buffer is usually read only)
         a_dtype is assumed to be correct endianness
         '''
@@ -213,10 +215,10 @@
 
     def write_header(self, P=0,  T=0, imagf=0, dims=None):
         ''' Write header for given data options
-        @P      - mat4 data type
-        @T      - mat4 matrix class
-        @imagf  - complex flag
-        @dims   - matrix dimensions
+        P      - mat4 data type
+        T      - mat4 matrix class
+        imagf  - complex flag
+        dims   - matrix dimensions
         '''
         if dims is None:
             dims = self.arr.shape
@@ -313,9 +315,9 @@
             
 def matrix_writer_factory(stream, arr, name):
     ''' Factory function to return matrix writer given variable to write
-    @stream      - file or file-like stream to write to
-    @arr         - array to write
-    @name        - name in matlab (TM) workspace
+    stream      - file or file-like stream to write to
+    arr         - array to write
+    name        - name in matlab (TM) workspace
     '''
     if have_sparse:
         if scipy.sparse.issparse(arr):

Modified: trunk/Lib/io/mio5.py
===================================================================
--- trunk/Lib/io/mio5.py	2006-10-20 04:01:05 UTC (rev 2291)
+++ trunk/Lib/io/mio5.py	2006-10-20 11:05:22 UTC (rev 2292)
@@ -324,15 +324,15 @@
             res = self.read_element()
         ''' From the matlab (TM) API documentation, last found here:
         http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/
-        @rowind are simply the row indices for all the (@res) non-zero
-        entries in the sparse array.  @rowind has nzmax entries, so
-        may well have more entries than len(@res), the actual number
-        of non-zero entries, but @rowind[len(res):] can be discarded
-        and should be 0. @colind has length (number of columns + 1),
-        and is such that, if D = diff(@colind), D[j] gives the number
-        of non-zero entries in column j. Because @rowind values are
+        rowind are simply the row indices for all the (res) non-zero
+        entries in the sparse array.  rowind has nzmax entries, so
+        may well have more entries than len(res), the actual number
+        of non-zero entries, but rowind[len(res):] can be discarded
+        and should be 0. colind has length (number of columns + 1),
+        and is such that, if D = diff(colind), D[j] gives the number
+        of non-zero entries in column j. Because rowind values are
         stored in column order, this gives the column corresponding to
-        each @rowind
+        each rowind
         '''
         cols = empty((len(res)), dtype=rowind.dtype)
         col_counts = diff(colind)
@@ -422,17 +422,17 @@
 
     Adds the following attribute to base class
     
-    @uint16_codec       - char codec to use for uint16 char arrays
+    uint16_codec       - char codec to use for uint16 char arrays
                           (defaults to system default codec)
    '''
 
     def __init__(self,
                  mat_stream,
                  byte_order=None,
-                 base_name='raw',
-                 matlab_compatible=False,
+                 mat_dtype=False,
                  squeeze_me=True,
                  chars_as_strings=True,
+                 matlab_compatible=False,
                  uint16_codec=None
                  ):
         self.codecs = {}
@@ -446,10 +446,11 @@
         super(MatFile5Reader, self).__init__(
             mat_stream,
             byte_order,
-            base_name,
+            mat_dtype,
+            squeeze_me,
+            chars_as_strings,
             matlab_compatible,
-            squeeze_me,
-            chars_as_strings)
+            )
         self._array_reader.processor_func = self.processor_func
         self.uint16_codec = uint16_codec
 
@@ -545,10 +546,10 @@
                      is_logical=False,
                      nzmax=0):
         ''' Write header for given data options
-        @mclass      - mat5 matrix class
-        @is_global   - True if matrix is global
-        @is_complex  - True is matrix is complex
-        @is_logical  - True if matrix is logical
+        mclass      - mat5 matrix class
+        is_global   - True if matrix is global
+        is_complex  - True is matrix is complex
+        is_logical  - True if matrix is logical
         nzmax        - max non zero elements for sparse arrays
         '''
         self._mat_tag_pos = self.file_stream.tell()
@@ -641,9 +642,9 @@
 
     def matrix_writer_factory(self, arr, name, is_global=False):
         ''' Factory function to return matrix writer given variable to write
-        @stream      - file or file-like stream to write to
-        @arr         - array to write
-        @name        - name in matlab (TM) workspace
+        stream      - file or file-like stream to write to
+        arr         - array to write
+        name        - name in matlab (TM) workspace
         '''
         if have_sparse:
             if scipy.sparse.issparse(arr):

Modified: trunk/Lib/io/miobase.py
===================================================================
--- trunk/Lib/io/miobase.py	2006-10-20 04:01:05 UTC (rev 2291)
+++ trunk/Lib/io/miobase.py	2006-10-20 11:05:22 UTC (rev 2292)
@@ -56,7 +56,7 @@
 
     Implements common array reading functions
 
-    Inputs @mat_steam - MatFileReader object
+    Inputs mat_steam - MatFileReader object
     '''
 
     def __init__(self, mat_stream):
@@ -66,7 +66,8 @@
         ''' Generic get of byte stream data of known type
 
         Inputs
-        @a_dtype     - dtype of array
+        a_dtype     - dtype of array
+        
         a_dtype is assumed to be correct endianness
         '''
         num_bytes = a_dtype.itemsize
@@ -83,16 +84,20 @@
 class MatFileReader(MatStreamAgent):
     """ Base object for reading mat files
 
-    @initialized byte stream object  - file io interface object
-    @byte_order         - byte order ('native', 'little', 'BIG')
+    mat_stream         - initialized byte stream object  - file io interface object
+    byte_order         - byte order ('native', 'little', 'BIG')
                           in ('native', '=')
                           or in ('little', '<')
                           or in ('BIG', '>')
-    @base_name          - base name for unnamed variables (unused in code)
-    @mat_dtype          - return arrays in same dtype as loaded into matlab
+    mat_dtype          - return arrays in same dtype as loaded into matlab
                           (instead of the dtype with which they are saved)
-    @squeeze_me         - whether to squeeze unit dimensions or not
-    @chars_as_strings   - whether to convert char arrays to string arrays
+    squeeze_me         - whether to squeeze unit dimensions or not
+    chars_as_strings   - whether to convert char arrays to string arrays
+    mat_dtype          - return matrices with datatype that matlab would load as
+                          (rather than in the datatype matlab saves as)
+    matlab_compatible  - returns matrices as would be loaded by matlab
+                         (implies squeeze_me=False, chars_as_strings=False
+                         mat_dtype=True)
 
     To make this class functional, you will need to override the
     following methods:
@@ -106,10 +111,10 @@
 
     def __init__(self, mat_stream,
                  byte_order=None,
-                 base_name='raw',
                  mat_dtype=False,
                  squeeze_me=True,
                  chars_as_strings=True,
+                 matlab_compatible=False,
                  ):
         # Initialize stream
         self.mat_stream = mat_stream
@@ -117,11 +122,13 @@
         if not byte_order:
             byte_order = self.guess_byte_order()
         self.order_code = byte_order # sets dtypes and other things too
-        self.base_name = base_name
-        self._squeeze_me = squeeze_me
-        self._chars_as_strings = chars_as_strings
-        self._mat_dtype = mat_dtype
-        self.processor_func = self.get_processor_func()
+        if matlab_compatible:
+            self.set_matlab_compatible()
+        else:
+            self._squeeze_me = squeeze_me
+            self._chars_as_strings = chars_as_strings
+            self._mat_dtype = mat_dtype
+            self.processor_func = self.get_processor_func()
         
     def set_matlab_compatible(self):
         ''' Sets options to return arrays as matlab (tm) loads them '''
@@ -252,7 +259,7 @@
     def get_variables(self, variable_names=None):
         ''' get variables from stream as dictionary
 
-        @variable_names   - optional list of variable names to get
+        variable_names   - optional list of variable names to get
 
         If variable_names is None, then get all variables in file
         '''
@@ -294,8 +301,8 @@
     header
 
     Accepts
-    @array_reader - array reading object (see below)
-    @header       - header dictionary for matrix being read
+    array_reader - array reading object (see below)
+    header       - header dictionary for matrix being read
     """
     
     def __init__(self, array_reader, header):



More information about the Scipy-svn mailing list