
     i (                     Z    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	  G d de	          Z
dS )z
mrcfile
-------

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

Classes:
    :class:`MrcFile`: An object which represents an MRC file.

    )absolute_importdivisionprint_functionunicode_literalsN   )MrcInterpreterc                   l     e Zd ZdZ	 	 d fd	Zd Zd Zd fd	Z fdZd	 Z	 fd
Z
d Zd fd	Z xZS )MrcFilea  An object which represents an MRC file.
    
    The header and data are handled as numpy arrays - see
    :class:`~mrcfile.mrcobject.MrcObject` for details.
        
    :class:`MrcFile` supports a permissive read mode for attempting to open
    corrupt or invalid files. See
    :class:`mrcfile.mrcinterpreter.MrcInterpreter` or the :doc:`usage guide
    <../usage_guide>` for more information.
    
    Usage:
        To create a new MrcFile object, pass a file name and optional mode. To
        ensure the file is written to disk and closed correctly, it's best to
        use the :keyword:`with` statement:
        
        >>> with MrcFile('tmp.mrc', 'w+') as mrc:
        ...     mrc.set_data(np.zeros((10, 10), dtype=np.int8))
        
        In mode ``r`` or ``r+``, the named file is opened from disk and read.
        In mode ``w+`` a new empty file is created and will be written to disk
        at the end of the :keyword:`with` block (or when
        :meth:`~.MrcInterpreter.flush` or :meth:`close` is called).
    
    rFc                 B    t          t          |           j        dd|i| |dvr"t          d                    |                    t          |          }d|v rCt          j                            |          r$|s"t          d                    |                    || _	        | j	        dk    | _
        |                     |           	 d|v r|                                  dS |                     |           dS # t          $ r |                                   w xY w)	a  Initialise a new :class:`MrcFile` object.
        
        The given file name is opened in the given mode. For mode ``r`` or
        ``r+`` the header, extended header and data are read from the file. For
        mode ``w+`` a new file is created with a default header and empty
        extended header and data arrays.
        
        Args:
            name: The file name to open, as a string or pathlib Path.
            mode: The file mode to use. This should be one of the following:
                ``r`` for read-only, ``r+`` for read and write, or ``w+`` for a
                new empty file. The default is ``r``.
            overwrite: Flag to force overwriting of an existing file if the
                mode is ``w+``. If :data:`False` and a file of the same name
                already exists, the file is not overwritten and an exception is
                raised. The default is :data:`False`.
            permissive: Read the file in permissive mode. (See
                :class:`mrcfile.mrcinterpreter.MrcInterpreter` for details.)
                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 the mode is not one of ``r``, ``r+`` or
                ``w+``.
            :exc:`ValueError`: If the file is not a valid MRC file and
                ``permissive`` is :data:`False`.
            :exc:`ValueError`: If the mode is ``w+``, the file already exists
                and overwrite is :data:`False`.
            :exc:`OSError`: If the mode is ``r`` or ``r+`` and the file does
                not exist.
        
        Warns:
            RuntimeWarning: If the file appears to be a valid MRC file but the
                data block is longer than expected from the dimensions in the
                header.
            RuntimeWarning: If the file is not a valid MRC file and
                ``permissive`` is :data:`True`.
            RuntimeWarning: If the header's ``exttyp`` field is set to a known
                value but the extended header's size is not a multiple of the
                number of bytes in the corresponding dtype.
        
permissive)r   zr+zw+zMode '{0}' not supportedwz=File '{0}' already exists; set overwrite=True to overwrite itr   N )superr
   __init__
ValueErrorformatstrospathexists_mode
_read_only
_open_file_create_default_attributes_read	Exception_close_file)selfnamemode	overwriter   header_onlykwargs	__class__s          Y/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/mrcfile/mrcfile.pyr   zMrcFile.__init__4   s:   X 	&gt%FFFvFFF(((7>>tDDEEE4yy4KKBGNN400KK //5vd||= = = 
:,	d{{//11111

;''''' 	 	 		s   C> 'C> > Dc                 L    d                     | j        j        | j                  S )NzMrcFile('{0}', mode='{1}'))r   	_iostreamr    r   r   s    r&   __repr__zMrcFile.__repr__x   s&    +224>3F37:? ? 	?    c                 @    t          || j        dz             | _        dS )z,Open a file object to use as the I/O stream.bN)openr   r(   )r   r    s     r&   r   zMrcFile._open_file|   s    dDJ$455r+   c                     | j                             d           t          t          |                               |           dS )z5Override _read() to move back to start of file first.r   N)r(   seekr   r
   r   )r   r#   r%   s     r&   r   zMrcFile._read   s=    Agt"";/////r+   c                 v   |                                  }| j        j        t          | j        j                  z   }||z
  }t          t          |                               |           | j        F| j        j        }||k     r6d	                    ||z
            }t          j        |t                     dS dS dS )zAOverride _read_data() to check file size matches data block size.)	max_bytesNz*MRC file is {0} bytes larger than expected)_get_file_sizeheadernbytesintnsymbtr   r
   
_read_datadatar   warningswarnRuntimeWarning)r   	file_sizeheader_sizeremaining_file_size	data_sizemsgr%   s         r&   r8   zMrcFile._read_data   s    ''))	 k(3t{/A+B+BB'+5gt''2E'FFF 9 	(I...C2Y>?? c>22222 ! ..r+   c                     | j                                         }| j                             dt          j                   | j                                         }| j                             |t          j                   |S )z8Return the size of the underlying file object, in bytes.r   )r(   tellr0   r   SEEK_ENDSEEK_SET)r   possizes      r&   r3   zMrcFile._get_file_size   sa    n!!##Ar{+++~""$$C---r+   c                 ~    t          t          |                                            |                                  dS )zFlush any changes to disk and close the file.
        
        This override calls :meth:`.MrcInterpreter.close` to ensure the stream
        is flushed and closed, then closes the file object.
        N)r   r
   closer   )r   r%   s    r&   rI   zMrcFile.close   s9     	gt""$$$r+   c                 8    | j                                          dS )zClose the file object.N)r(   rI   r)   s    r&   r   zMrcFile._close_file   s    r+   Nc                 ^   t          t          |                               |          }| j        h|                                 }| j        j        | j        j        z   | j        j        z   }||k    r't          d	                    ||          |           d}nt          d|           d}|S )a	  Validate this MRC file.
        
        The tests are:
        
        #. MRC format ID string: The ``map`` field in the header should
           contain "MAP ".
        #. Machine stamp: The machine stamp should contain one of
           ``0x44 0x44 0x00 0x00``, ``0x44 0x41 0x00 0x00`` or
           ``0x11 0x11 0x00 0x00``.
        #. MRC mode: the ``mode`` field should be one of the supported mode
           numbers: 0, 1, 2, 4, 6 or 12. (Note that MRC modes 3 and 101 are
           also valid according to the MRC 2014 specification but are not
           supported by mrcfile.)
        #. Map and cell dimensions: The header fields ``nx``, ``ny``, ``nz``,
           ``mx``, ``my``, ``mz``, ``cella.x``, ``cella.y`` and ``cella.z``
           must all be positive numbers.
        #. Axis mapping: Header fields ``mapc``, ``mapr`` and ``maps`` must
           contain the values 1, 2, and 3 (in any order).
        #. Volume stack dimensions: If the spacegroup is in the range 401--630,
           representing a volume stack, the ``nz`` field should be exactly
           divisible by ``mz`` to represent the number of volumes in the stack.
        #. Header labels: The ``nlabl`` field should be set to indicate the
           number of labels in use, and the labels in use should appear first
           in the label array.
        #. MRC format version: The ``nversion`` field should be 20140 or 20141
           for compliance with the MRC2014 standard.
        #. Extended header type: If an extended header is present, the
           ``exttyp`` field should be set to indicate the type of extended
           header.
        #. Data statistics: The statistics in the header should be correct for
           the actual data in the file, or marked as undetermined.
        #. File size: The size of the file on disk should match the expected
           size calculated from the MRC header.
        
        Args:
            print_file: The output text stream to use for printing messages
                about the validation. This is passed directly to the ``file``
                argument of Python's :func:`print` function. The default is
                :data:`None`, which means output will be printed to
                :data:`sys.stdout`.
        
        Returns:
            :data:`True` if the file is valid, or :data:`False` if the file
            does not meet the MRC format specification in any way.
        )
print_fileNzgFile is larger than expected. Actual size: {0} bytes; expected size: {1} bytes (calculated from header))fileFz4Data block could not be read - file size not checked)
r   r
   validater9   r3   r4   r5   extended_headerprintr   )r   rL   validr=   mrc_sizer%   s        r&   rN   zMrcFile.validate   s    \ gt$$---DD9 ++--I*.56)*+H X%% Jvi22%' ' ' ' H!# # # #Er+   )r   FFF)F)N)__name__
__module____qualname____doc__r   r*   r   r   r8   r3   rI   r   rN   __classcell__)r%   s   @r&   r
   r
      s        2 DI"B B B B B BH? ? ?6 6 60 0 0 0 0 0
3 3 3 3 3&        A A A A A A A A A Ar+   r
   )rV   
__future__r   r   r   r   r   r:   mrcinterpreterr   r
   r   r+   r&   <module>rZ      s   	 	* * * * * * * * * * * * 
			  * * * * * *U U U U Un U U U U Ur+   