
     ig:                     ~    d Z ddlmZmZmZmZ ddlZddlZddl	m
Z
 ddlmZ ddlmZ ddlmZ  G d	 d
e          ZdS )z
mrcinterpreter
--------------

Module which exports the :class:`MrcInterpreter` class.

Classes:
    :class:`MrcInterpreter`: An object which can interpret an I/O stream as MRC
    data.

    )absolute_importdivisionprint_functionunicode_literalsN   )utils)HEADER_DTYPE)	MrcObject)MAP_IDc                   d     e Zd ZdZd fd	Zd Zd Zd ZddZd	 Z	d
 Z
ddZd Zd Zd Z xZS )MrcInterpretera   An object which interprets an I/O stream as MRC / CCP4 map data.

    The header and data are handled as numpy arrays - see
    :class:`~mrcfile.mrcobject.MrcObject` for details.

    :class:`MrcInterpreter` can be used directly, but it is mostly intended as
    a superclass to provide common stream-handling functionality. This can be
    used by subclasses which will handle opening and closing the stream.

    This class implements the :meth:`~object.__enter__` and
    :meth:`~object.__exit__` special methods which allow it to be used by the
    Python context manager in a :keyword:`with` block. This ensures that
    :meth:`close` is called after the object is finished with.

    When reading the I/O stream, a :exc:`ValueError` is raised if the data is
    invalid in one of the following ways:

    #. The header's ``map`` field is not set correctly to confirm the file
       type.
    #. The machine stamp is invalid and so the data's byte order cannot be
       determined.
    #. The mode number is not recognised. Currently accepted modes are 0, 1, 2,
       4 and 6.
    #. The file is not large enough for the specified extended header size.
    #. The data block is not large enough for the specified data type and
       dimensions.

    :class:`MrcInterpreter` offers a permissive read mode for handling
    problematic files. If ``permissive`` is set to :data:`True` and any of the
    validity checks fails, a :mod:`warning <warnings>` is issued instead of an
    exception, and file interpretation continues. If the mode number is invalid
    or the data block is too small, the
    :attr:`~mrcfile.mrcobject.MrcObject.data` attribute will be set to
    :data:`None`. In this case, it might be possible to inspect and correct the
    header, and then call :meth:`_read` again to read the data correctly. See
    the :doc:`usage guide <../usage_guide>` for more details.

    Methods:

    * :meth:`flush`
    * :meth:`close`

    Methods relevant to subclasses:

    * :meth:`_read`
    * :meth:`_read_data`
    * :meth:`_read_bytearray_from_stream`

    NFc                      t          t          |           j        di | || _        || _        | j        |                     |           dS dS )aI  Initialise a new MrcInterpreter object.

        This initialiser reads the stream if it is given. In general,
        subclasses should call :meth:`__init__` without giving an ``iostream``
        argument, then set the ``_iostream`` attribute themselves and call
        :meth:`_read` when ready.

        To use the MrcInterpreter class directly, pass a stream when creating
        the object (or for a write-only stream, create an MrcInterpreter with
        no stream, call :meth:`._create_default_attributes` and set the
        ``_iostream`` attribute directly).

        Args:
            iostream: The I/O stream to use to read and write MRC data. The
                default is :data:`None`.
            permissive: Read the stream in permissive mode. The default is
                :data:`False`.
            header_only: Only read the header (and extended header) from the
                file. The default is :data:`False`.

        Raises:
            :exc:`ValueError`: If ``iostream`` is given, the data it contains
                cannot be interpreted as a valid MRC file and ``permissive``
                is :data:`False`.

        Warns:
            RuntimeWarning: If ``iostream`` is given, the data it contains
                cannot be interpreted as a valid MRC file and ``permissive``
                is :data:`True`.
        N )superr   __init__	_iostream_permissive_read)selfiostream
permissiveheader_onlykwargs	__class__s        `/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/mrcfile/mrcinterpreter.pyr   zMrcInterpreter.__init__Q   sb    @ 	-nd##,66v666!% >%JJ{##### &%    c                     | S )zCalled by the context manager at the start of a :keyword:`with`
        block.

        Returns:
            This object (``self``).
        r   r   s    r   	__enter__zMrcInterpreter.__enter__z   s	     r   c                 .    |                                   dS )zCalled by the context manager at the end of a :keyword:`with`
        block.

        This ensures that the :meth:`close` method is called.
        N)close)r   exc_typeexc_valexc_tbs       r   __exit__zMrcInterpreter.__exit__   s     	

r   c                 R    	 |                                   dS # t          $ r Y dS w xY w)zAttempt to flush the stream when this object is garbage collected.

        It's better not to rely on this - instead, use a :keyword:`with`
        block or explicitly call the :meth:`close` method.
        N)r!   	Exceptionr   s    r   __del__zMrcInterpreter.__del__   s:    	JJLLLLL 	 	 	DD	s    
&&c                     |                                   |                                  |s|                                  dS dS )a1  Read the header, extended header and data from the I/O stream.

        Before calling this method, the stream should be open and positioned at
        the start of the header. This method will advance the stream to the end
        of the data block (or the end of the extended header if ``header_only``
        is :data:`True`.

        Args:
            header_only: Only read the header and extended header from the
                stream. The default is :data:`False`.

        Raises:
            :exc:`ValueError`: If the data in the stream cannot be interpreted
                 as a valid MRC file and ``permissive`` is :data:`False`.

        Warns:
            RuntimeWarning:  If the data in the stream cannot be interpreted
                 as a valid MRC file and ``permissive`` is :data:`True`.
        N)_read_header_read_extended_header
_read_data)r   r   s     r   r   zMrcInterpreter._read   sP    ( 	""$$$ 	OO	 	r   c                    |                      t          j                  \  }}|t          j        k     rt          d          t	          j        |t                                        d                              t          j                  }t          |j
                  dd         t          dd         k    r3d}| j        rt          j        |t                     nt          |          	 t!          j        |j                  }nI# t          $ r<}| j        r*d}t          j        t'          |          t                     n Y d}~nd}~ww xY w|j                            |          |_        | j        r	 t!          j        |j                   n# t          $ r 	 |j                            |j        j                                                  }t!          j        |           |j                                        |_        t!          j        |j                  }d}t          j        |                    ||j        j        j                  t                     n# t          $ r Y nw xY wY nw xY w| j         |j        _        || _        dS )	a  Read the MRC header from the I/O stream.

        The header will be read from the current stream position, and the
        stream will be advanced by 1024 bytes.

        Raises:
            :exc:`ValueError`: If the data in the stream cannot be interpreted
                 as a valid MRC file and ``permissive`` is :data:`False`.

        Warns:
            RuntimeWarning:  If the data in the stream cannot be interpreted
                 as a valid MRC file and ``permissive`` is :data:`True`.
        z)Couldn't read enough bytes for MRC headerdtyper   N   z=Map ID string not found - not an MRC file, or file is corrupt<z@Machine stamp '{0}' does not match the apparent byte order '{1}')_read_bytearray_from_streamr	   itemsize
ValueErrornp
frombufferreshapeviewrecarraybytesmapr   r   warningswarnRuntimeWarningr   byte_order_from_machine_stampmachststrr/   newbyteorderdtype_from_modemodepretty_machine_stampformat	byteorder
_read_onlyflags	writeable_header)	r   
header_arr
bytes_readheadermsg
byte_ordererropp_modepretty_machsts	            r   r*   zMrcInterpreter._read_header   s~    "&!A!A,BW!X!X
J---HIII z>>>FFrJJOOPRP[\\ RaR F2A2J..9C &c>2222 oo%	<V]KKJJ 	 	 	  
c#hh7777 87777	 |00<<
  	%fk2222   %{//0A0N0N0P0PQQH)(333 $*<#<#<#>#>FL$)$>v}$M$MM\CM#**]FK<M<W"X"X"02 2 2 2!    D  &*_!4sO   .D 
E2E		E8F 
I1C II1
I+(I1*I++I10I1c                    |                      t          | j        j                            \  }}|| j        j        k     rYd                    | j        j        |          }| j        r#t          j        |t                     d| _	        dS t          |          t          j        |d          | _	        | j         | j	        j        _        dS )ah  Read the extended header from the stream.

        If there is no extended header, a zero-length array is assigned to the
        extended_header attribute.

        The dtype is set as void (``'V1'``).

        Raises:
            :exc:`ValueError`: If the stream is not long enough to contain the
                extended header indicated by the header and ``permissive``
                is :data:`False`.

        Warns:
            RuntimeWarning: If the stream is not long enough to contain the
                extended header indicated by the header and ``permissive``
                is :data:`True`.
        z=Expected {0} bytes in extended header but could only read {1}NV1r.   )r2   intrN   nsymbtrF   r   r<   r=   r>   _extended_headerr4   r5   r6   rH   rI   rJ   )r   ext_header_arrrM   rO   s       r   r+   z$MrcInterpreter._read_extended_header   s    $ &*%E%Ec$+J\F]F]%^%^"
***RF4;-z::  &c>222(,% oo% "nD I I I48O0C#---r   r   c                 R   	 t          j        | j                  }nT# t          $ rG}| j        r:t          j        d                    |          t                     d| _	        Y d}~dS  d}~ww xY wt          j
        | j                  }|j        }|D ]}||z  }|dk    rU||k    rOd                    ||          }| j        r#t          j        |t                     d| _	        dS t          |          |                     |          \  }}	|	|k     rOd                    ||	          }| j        r#t          j        |t                     d| _	        dS t          |          t          j        ||                              |          | _	        | j         | j	        j        _        dS )a  Read the data array from the stream.

        This method uses information from the header to set the data array's
        shape and dtype.

        Args:
            max_bytes: Read at most this many bytes from the stream. If zero or
                negative, the full size of the data block as defined in the header
                will be read, even if this is very large.

        Raises:
            :exc:`ValueError`: If the stream is not long enough to contain the
                data indicated by the header and ``permissive`` is
                :data:`False`.

        Warns:
            RuntimeWarning: If the stream is not long enough to contain the
                data indicated by the header and ``permissive`` is
                :data:`True`.
        z{0} - data block cannot be readNr   z1Expected {0} bytes in data block but limit is {1}z8Expected {0} bytes in data block but could only read {1}r.   )r   data_dtype_from_headerrN   r4   r   r<   r=   rF   r>   _datadata_shape_from_headerr3   r2   r5   r6   r7   rH   rI   rJ   )
r   	max_bytesr/   rQ   shapenbytesaxis_lengthrO   data_arrrM   s
             r   r,   zMrcInterpreter._read_data  s   *		0==EE 	 	 	 ?FFsKK,. . .!
	 ,T[99  	" 	"Kk!FFq==Vi//FF69--  &c>222!
 oo%#??GG*MF6:..  &c>222!
 oo%]85999AA%HH
)-%8
"""s    
A-;A('A((A-c                 \    t          |          }| j                            |          }||fS )a  Read a :class:`bytearray` from the stream.

        This default implementation relies on the stream implementing the
        :meth:`~io.BufferedIOBase.readinto` method to avoid copying the new
        array while creating the mutable :class:`bytearray`. Subclasses
        should override this if their stream does not support
        :meth:`~io.BufferedIOBase.readinto`.

        Returns:
            A 2-tuple of the :class:`bytearray` and the number of bytes that
            were read from the stream.
        )	bytearrayr   readinto)r   number_of_bytesresult_arrayrM   s       r   r2   z*MrcInterpreter._read_bytearray_from_streamY  s1     !11^,,\::
Z''r   c                     | j          | j        j        s|                                  d| _         d| _        |                                  dS )z=Flush to the stream and clear the header and data attributes.N)rK   r   closedflushrX   _close_datar   s    r   r!   zMrcInterpreter.closej  sH    <#DN,A#JJLLL $r   c                    | j         s| j                            d           | j                            | j                   | j                            | j                   | j                            t          j        | j                             | j        	                                 | j        
                                 dS dS )ao  Flush the header and data arrays to the I/O stream.

        This implementation seeks to the start of the stream, writes the
        header, extended header and data arrays, and then truncates the stream.

        Subclasses should override this implementation for streams which do not
        support :meth:`~io.IOBase.seek` or :meth:`~io.IOBase.truncate`.
        r   N)rH   r   seekwriterN   extended_headerr5   ascontiguousarraydatatruncaterj   r   s    r   rj   zMrcInterpreter.flushr  s      	#N"""N  ---N  !5666N  !5di!@!@AAAN##%%%N  """""	# 	#r   )NFF)F)r   )__name__
__module____qualname____doc__r   r   r%   r(   r   r*   r+   r,   r2   r!   rj   __classcell__)r   s   @r   r   r      s        0 0d'$ '$ '$ '$ '$ '$R    	 	 	   2G G GR D  D  DD=9 =9 =9 =9~( ( ("  # # # # # # #r   r   )rv   
__future__r   r   r   r   r<   numpyr5    r   dtypesr	   	mrcobjectr
   	constantsr   r   r   r   r   <module>r~      s   
 
* * * * * * * * * * * *                                         d# d# d# d# d#Y d# d# d# d# d#r   