σ
ξ&]\c           @` s]   d  Z  d d l m Z m Z m Z d d l Z d d l Z d g Z d e	 f d     YZ
 d S(   s   
Module to read / write Fortran unformatted sequential files.

This is in the spirit of code written by Neil Martinsen-Burrell and Joe Zuntz.

i    (   t   divisiont   print_functiont   absolute_importNt   FortranFilec           B` sn   e  Z d  Z d e j d  Z d   Z d   Z d   Z d d  Z	 d d	  Z
 d
   Z d   Z d   Z RS(   sέ	  
    A file object for unformatted sequential files from Fortran code.

    Parameters
    ----------
    filename : file or str
        Open file object or filename.
    mode : {'r', 'w'}, optional
        Read-write mode, default is 'r'.
    header_dtype : dtype, optional
        Data type of the header. Size and endiness must match the input/output file.

    Notes
    -----
    These files are broken up into records of unspecified types. The size of
    each record is given at the start (although the size of this header is not
    standard) and the data is written onto disk without any formatting. Fortran
    compilers supporting the BACKSPACE statement will write a second copy of
    the size to facilitate backwards seeking.

    This class only supports files written with both sizes for the record.
    It also does not support the subrecords used in Intel and gfortran compilers
    for records which are greater than 2GB with a 4-byte header.

    An example of an unformatted sequential file in Fortran would be written as::

        OPEN(1, FILE=myfilename, FORM='unformatted')

        WRITE(1) myvariable

    Since this is a non-standard file format, whose contents depend on the
    compiler and the endianness of the machine, caution is advised. Files from
    gfortran 4.8.0 and gfortran 4.1.2 on x86_64 are known to work.

    Consider using Fortran direct-access files or files from the newer Stream
    I/O, which can be easily read by `numpy.fromfile`.

    Examples
    --------
    To create an unformatted sequential Fortran file:

    >>> from scipy.io import FortranFile
    >>> f = FortranFile('test.unf', 'w')
    >>> f.write_record(np.array([1,2,3,4,5], dtype=np.int32))
    >>> f.write_record(np.linspace(0,1,20).reshape((5,4)).T)
    >>> f.close()

    To read this file:

    >>> f = FortranFile('test.unf', 'r')
    >>> print(f.read_ints(np.int32))
    [1 2 3 4 5]
    >>> print(f.read_reals(float).reshape((5,4), order="F"))
    [[0.         0.05263158 0.10526316 0.15789474]
     [0.21052632 0.26315789 0.31578947 0.36842105]
     [0.42105263 0.47368421 0.52631579 0.57894737]
     [0.63157895 0.68421053 0.73684211 0.78947368]
     [0.84210526 0.89473684 0.94736842 1.        ]]
    >>> f.close()

    Or, in Fortran::

        integer :: a(5), i
        double precision :: b(5,4)
        open(1, file='test.unf', form='unformatted')
        read(1) a
        read(1) b
        close(1)
        write(*,*) a
        do i = 1, 5
            write(*,*) b(i,:)
        end do

    t   rc         C` s΄   | d  k r t d   n  t j |  } | j d k rI t j d  n  | d k sg t |  d k rv t d   n  t | d  r | |  _	 n t
 | d |  |  _	 | |  _ d  S(	   Ns   Must specify dtypet   us$   Given a dtype which is not unsigned.t   rwi   s   mode must be either r or wt   seeks   %sb(   t   Nonet
   ValueErrort   npt   dtypet   kindt   warningst   warnt   lent   hasattrt   _fpt   opent   _header_dtype(   t   selft   filenamet   modet   header_dtype(    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt   __init__Z   s    c         C` s%   t  t j |  j d |  j d d  S(   NR   t   counti   (   t   intR
   t   fromfileR   R   (   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt
   _read_sizel   s    c         G` s   t  d   | D  } t d   | D  } t j | g d |  j } | j |  j  x | D] } | j |  j  q^ W| j |  j  d S(   s  
        Write a record (including sizes) to the file.

        Parameters
        ----------
        *items : array_like
            The data arrays to write.

        Notes
        -----
        Writes data items to a file::

            write_record(a.T, b.T, c.T, ...)

            write(1) a, b, c, ...

        Note that data in multidimensional arrays is written in
        row-major order --- to make them read correctly by Fortran
        programs, you need to transpose the arrays yourself when
        writing them.

        c         s` s   |  ] } t  j |  Vq d  S(   N(   R
   t   asarray(   t   .0t   item(    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pys	   <genexpr>   s    c         s` s   |  ] } | j  Vq d  S(   N(   t   nbytes(   R   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pys	   <genexpr>   s    R   N(   t   tuplet   sumR
   t   arrayR   t   tofileR   (   R   t   itemst
   total_sizet   nbR   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt   write_recordo   s    c         O` sς  | j  d d  } | r< t d j t | j       n  | d k	 rX | | f } n | sm t d   n  |  j   } t d   | D  } t d   | D  } t | |  \ } } | d k rα t d j | |    n  t	 |  d k r| | k rt d	 j | |    n  g  } x | D]x } t
 j |  j d | d
 | }	 | j d k r| d k r|	 j d | j k st  |	 d }	 qn  | j |	  q'W|  j   }
 | |
 k rΚt d   n  t	 |  d k rδ| d St |  Sd S(   s?  
        Reads a record of a given type from the file.

        Parameters
        ----------
        *dtypes : dtypes, optional
            Data type(s) specifying the size and endiness of the data.

        Returns
        -------
        data : ndarray
            A one-dimensional array object.

        Notes
        -----
        If the record contains a multi-dimensional array, you can specify
        the size in the dtype. For example::

            INTEGER var(5,4)

        can be read with::

            read_record('(4,5)i4').T

        Note that this function does **not** assume the file data is in Fortran
        column major order, so you need to (i) swap the order of dimensions
        when reading and (ii) transpose the resulting array.

        Alternatively, you can read the data as a 1D array and handle the
        ordering yourself. For example::

            read_record('i4').reshape(5, 4, order='F')

        For records that contain several variables or mixed types (as opposed
        to single scalar or array types), give them as separate arguments::

            double precision :: a
            integer :: b
            write(1) a, b

            record = f.read_record('<f4', '<i4')
            a = record[0]  # first number
            b = record[1]  # second number

        and if any of the variables are arrays, the shape can be specified as
        the third item in the relevant dtype::

            double precision :: a
            integer :: b(3,4)
            write(1) a, b

            record = f.read_record('<f4', np.dtype(('<i4', (4, 3))))
            a = record[0]
            b = record[1].T

        Numpy also supports a short syntax for this kind of type::

            record = f.read_record('<f4', '(3,3)<i4')

        See Also
        --------
        read_reals
        read_ints

        R   s   Unknown keyword arguments {}s   Must specify at least one dtypec         s` s   |  ] } t  j |  Vq d  S(   N(   R
   R   (   R   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pys	   <genexpr>έ   s    c         s` s   |  ] } | j  Vq d  S(   N(   t   itemsize(   R   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pys	   <genexpr>ή   s    i    s@   Size obtained ({0}) is not a multiple of the dtypes given ({1}).i   sT   Size obtained ({0}) does not match with the expected size ({1}) of multi-item recordR   sP   Sizes do not agree in the header and footer for this record - check header dtypeN(    (   i   (   t   popR   R	   t   formatR!   t   keysR   R"   t   divmodR   R
   R   R   t   shapet   AssertionErrort   appendt   IOError(   R   t   dtypest   kwargsR   t
   first_sizet
   block_sizet
   num_blockst	   remaindert   dataR   t   second_size(    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt   read_record   s>    B$		t   i4c         C` s   |  j  |  S(   s»  
        Reads a record of a given type from the file, defaulting to an integer
        type (``INTEGER*4`` in Fortran).

        Parameters
        ----------
        dtype : dtype, optional
            Data type specifying the size and endiness of the data.

        Returns
        -------
        data : ndarray
            A one-dimensional array object.

        See Also
        --------
        read_reals
        read_record

        (   R:   (   R   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt	   read_ints  s    t   f8c         C` s   |  j  |  S(   sΏ  
        Reads a record of a given type from the file, defaulting to a floating
        point number (``real*8`` in Fortran).

        Parameters
        ----------
        dtype : dtype, optional
            Data type specifying the size and endiness of the data.

        Returns
        -------
        data : ndarray
            A one-dimensional array object.

        See Also
        --------
        read_ints
        read_record

        (   R:   (   R   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt
   read_reals  s    c         C` s   |  j  j   d S(   sν   
        Closes the file. It is unsupported to call any other methods off this
        object after closing it. Note that this class supports the 'with'
        statement in modern versions of Python, to call this automatically

        N(   R   t   close(   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyR?   0  s    c         C` s   |  S(   N(    (   R   (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt	   __enter__9  s    c         C` s   |  j    d  S(   N(   R?   (   R   t   typet   valuet   tb(    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt   __exit__<  s    (   t   __name__t
   __module__t   __doc__R
   t   uint32R   R   R(   R:   R<   R>   R?   R@   RD   (    (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyR      s   J		!	r			(   RG   t
   __future__R    R   R   R   t   numpyR
   t   __all__t   objectR   (    (    (    s0   lib/python2.7/site-packages/scipy/io/_fortran.pyt   <module>   s
   	