
     i;                         d Z ddlmZmZmZmZ ddlmZ ddlZddlZ	ddl
mZ ddlmZmZmZmZ ddlmZmZmZmZ  G d	 d
e          ZdS )z
mrcobject
---------

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

Classes:
    :class:`MrcObject`: An object representing image or volume data in the MRC
    format.

    )absolute_importdivisionprint_functionunicode_literals)datetimeN   )utils)HEADER_DTYPEVOXEL_SIZE_DTYPENSTART_DTYPEget_ext_header_dtype)MAP_IDIMAGE_STACK_SPACEGROUPVOLUME_SPACEGROUPVOLUME_STACK_SPACEGROUPc                   n    e Zd ZdZ fdZd Zd Zd Zed             Z	ed             Z
ed             Zd	 Zed
             Zd Zd Zd Zed             Zej        d             Zd Zed             Zej        d             Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd"dZd Z d  Z!d"d!Z" xZ#S )#	MrcObjecta	
  An object representing image or volume data in the MRC format.

    The header, extended header and data are stored as numpy arrays and
    exposed as read-only attributes. To replace the data or extended header,
    call :meth:`set_data` or :meth:`set_extended_header`. The header cannot be
    replaced but can be modified in place.

    Voxel size is exposed as a writeable attribute, but is calculated
    on-the-fly from the header's ``cella`` and ``mx``/``my``/``mz`` fields.

    Three-dimensional data can represent either a stack of 2D images, or a 3D
    volume. This is indicated by the header's ``ispg`` (space group) field,
    which is set to 0 for image data and >= 1 for volume data. The
    :meth:`is_single_image`, :meth:`is_image_stack`, :meth:`is_volume` and
    :meth:`is_volume_stack` methods can be used to identify the type of
    information stored in the data array. For 3D data, the
    :meth:`set_image_stack` and :meth:`set_volume` methods can be used to
    switch between image stack and volume interpretations of the data.

    If the data contents have been changed, you can use the
    :meth:`update_header_from_data` and :meth:`update_header_stats` methods to
    make the header consistent with the data. These methods are called
    automatically if the data array is replaced by calling :meth:`set_data`.
    :meth:`update_header_from_data` is fast, even with very large data arrays,
    because it only examines the shape and type of the data array.
    :meth:`update_header_stats` calculates statistics from all items in the
    data array and so can be slow for very large arrays. If necessary, the
    :meth:`reset_header_stats` method can be called to set the header fields to
    indicate that the statistics are undetermined.

    Attributes:

    * :attr:`header`
    * :attr:`extended_header`
    * :attr:`indexed_extended_header`
    * :attr:`data`
    * :attr:`voxel_size`
    * :attr:`nstart`

    Methods:

    * :meth:`set_extended_header`
    * :meth:`set_data`
    * :meth:`is_single_image`
    * :meth:`is_image_stack`
    * :meth:`is_volume`
    * :meth:`is_volume_stack`
    * :meth:`set_image_stack`
    * :meth:`set_volume`
    * :meth:`update_header_from_data`
    * :meth:`update_header_stats`
    * :meth:`reset_header_stats`
    * :meth:`print_header`
    * :meth:`get_labels`
    * :meth:`add_label`

    Attributes and methods relevant to subclasses:

    * ``_read_only``
    * :meth:`_check_writeable`
    * :meth:`_create_default_attributes`
    * :meth:`_close_data`
    * :meth:`_set_new_data`

    c                      t          t          |           j        di | d| _        d| _        d| _        d| _        dS )a  Initialise a new :class:`MrcObject`.

        This initialiser deliberately avoids creating any arrays and simply
        sets the header, extended header and data attributes to :data:`None`.
        This allows subclasses to call :meth:`__init__` at the start of their
        initialisers and then set the attributes themselves, probably by
        reading from a file, or by calling :meth:`_create_default_attributes`
        for a new empty object.

        Note that this behaviour might change in future: this initialiser could
        take optional arguments to allow the header and data to be provided
        by the caller, or might create the standard empty defaults rather than
        setting the attributes to :data:`None`.
        NF )superr   __init___header_extended_header_data
_read_only)selfkwargs	__class__s     [/srv/www/vhosts/g4struct/public_html/venv/lib/python3.11/site-packages/mrcfile/mrcobject.pyr   zMrcObject.__init__c   sK     	(i'11&111  $
    c                 2    | j         rt          d          dS )z~Check that this MRC object is writeable.

        Raises:
            :exc:`ValueError`: If this object is read-only.
        zMRC object is read-onlyN)r   
ValueErrorr   s    r   _check_writeablezMrcObject._check_writeablez   s'     ? 	86777	8 	8r    c                     |                                   t          j        dd          | _        |                     t          j        dt          j                             dS )z<Set valid default values for the header and data attributes.r   V1dtypeN)_create_default_headernpemptyr   _set_new_dataint8r#   s    r   _create_default_attributesz$MrcObject._create_default_attributes   sV    ##%%% "$ 7 7 728ARW55566666r    c                 P   t          j        dt                                        t           j                  | _        | j        }t          |_        d|_        t          j
        |j        j        j                  |_        t          |_        d}||j        _        ||j        _        ||j        _        d|_        d|_        d|_        t1          j                                        d          }d	                    d
|          |j        d<   d|_        |                                  dS )a'  Create a default MRC file header.

        The header is initialised with standard file type and version
        information, default values for some essential fields, and zeros
        elsewhere. The first text label is also set to indicate the file was
        created by this module.
        r   )shaper(   N  g     V@r         z%Y-%m-%d %H:%M:%Sz{0:40s}{1:>39s} zCreated by mrcfile.pyr   N)r*   zerosr
   viewrecarrayr   r   mapnversionr	   machine_stamp_from_byte_ordermoder(   	byteordermachstr   ispgcellbalphabetagammamapcmaprmapsr   nowstrftimeformatlabelnlablreset_header_stats)r   headerdefault_cell_angletimes       r   r)   z MrcObject._create_default_header   s     xb===BB2;OO
;FK<M<WXX ( "/./ |~~&&':;;,334K48: :Q!!!!!r    c                     | j         S )zAGet the header as a :class:`numpy record array <numpy.recarray>`.)r   r#   s    r   rK   zMrcObject.header   s     |r    c                     | j         S )a;  Get the extended header as a :class:`numpy array <numpy.ndarray>`.

        The dtype will be void (raw data, dtype ``V'``). If the actual data type
        of the extended header is known, the dtype of the array can be changed
        to match. For supported types (e.g. ``'FEI1'`` and ``'FEI2'``), the
        indexed part of the extended header (excluding any zero padding) can be
        accessed using :meth:`indexed_extended_header`.

        The extended header may be modified in place. To replace it completely,
        call :meth:`set_extended_header`.
        )r   r#   s    r   extended_headerzMrcObject.extended_header   s     $$r    c                    t          | j        j        | j        j        j        j                  }	 | j        j        |j        k     rt          | j        d|j                 }||_        |d         d         |j        k    rt          nH# t          $ r; t          j        d                    | j        j                  t                     Y dS w xY wt          | j        d                   |j        z  }	 | j        j        |k     rt          | j        d|         }||_        nH# t          $ r; t          j        d                    | j        j                  t                     Y dS w xY w|S )a$  Get the indexed part of the extended header as a
        :class:`numpy array <numpy.ndarray>` with the appropriate dtype set.

        Currently only ``'FEI1'`` and ``'FEI2'`` extended headers are supported.
        Modifications to the indexed extended header will not change the
        extended header data recorded in this :class:`MrcObject`. If the
        extended header type is unrecognised or extended header data is not of
        sufficient length a warning will be produced and the indexed extended
        header will be None.
        r   zMetadata sizezUThe header has exttyp '{}' but the extended header cannot be interpreted as that typeNnz)r   rK   exttypr:   r(   r;   rP   nbytesitemsizer"   warningswarnrG   RuntimeWarningint)r   r(   firstrT   fulls        r   indexed_extended_headerz!MrcObject.indexed_extended_header   s    %T[%7%)[%5%;%EG G	#*U^;;  (5>)9:EEK_%a(EN::   ; 	 	 	M A#VDK$677I I I 44		 T[&''%.8		#*V33  '&1DDJJ 	 	 	M A#VDK$677I I I 44		 s&   AB AC
C1-D AE$#E$c                 H   |                                   |j        t          j        t          j                  j        k    rIt          d                    |j        t          j        t          j                  j                            || _        |j        | j	        _
        dS )at  Replace the extended header.

        If you set the extended header you should also set the
        ``header.exttyp`` field to indicate the type of extended header.

        Raises:
            :exc:`ValueError`: If the new extended header has more than
                2,147,483,647 bytes (and therefore its size cannot be stored
                in the header).
        zMNew extended header is too large! It has {} bytes. The maximum allowed is {}.N)r$   rT   r*   iinfoint32maxr"   rG   r   rK   nsymbt)r   rP   s     r   set_extended_headerzMrcObject.set_extended_header   s     	!BHRX$6$6$::: A$f_%;%'Xbh%7%7%;= => > > !0,3r    c                     | j         S )z7Get the data as a :class:`numpy array <numpy.ndarray>`.r   r#   s    r   datazMrcObject.data  s     zr    c           	         |                                   t          j        |j                  }t          j        |                              |j        j                  }|j        D ]m}|t          j	        t          j
                  j        k    rDt          d                    |t          j	        t          j
                  j                            n||j        k    rd}t          j        ||          }|                                  |                     |           |                                  |                                  dS )a6  Replace the data array.

        This replaces the current data with the given array (or a copy of it),
        and updates the header to match the new data dimensions. The data
        statistics (min, max, mean and rms) stored in the header will also be
        updated.

        Raises:
            :exc:`ValueError`: if the new data has a dimension larger than
                2,147,483,647 (and therefore its size cannot be stored in the
                header).

        Warns:
            RuntimeWarning: If the data array contains Inf or NaN values.
        zUNew data array is too large! Found a dimension of size {}. The maximum allowed is {}.Nr'   )r$   r	   mode_from_dtyper(   dtype_from_modenewbyteorderr;   r0   r*   r^   r_   r`   r"   rG   ascontiguousarray_close_datar,   update_header_from_dataupdate_header_stats)r   re   r:   	new_dtypedimnew_datas         r   set_datazMrcObject.set_data  s:     	 $TZ00*400"l4:#788 	 : 	G 	GCRXbh''+++  "* #)&bhrx.@.@.D"E"EG G G , 
""I 'I>>> 	8$$$$$&&&  """""r    c                     d| _         dS )zClose the data array.Nrd   r#   s    r   rk   zMrcObject._close_data4  s    


r    c                     || _         dS )zReplace the data array with a new one.

        The new data array is not checked - it must already be valid for use in
        an MRC file.
        Nrd   )r   re   s     r   r,   zMrcObject._set_new_data8  s     


r    c                 "   | j         j        j        | j         j        z  }| j         j        j        | j         j        z  }| j         j        j        | j         j        z  }t          j	        
                    |||ft                    }d|j        _        |S )a  Get or set the voxel size in angstroms.

        The voxel size is returned as a structured NumPy :class:`record array
        <numpy.recarray>` with three fields (x, y and z). For example:

        >>> mrc.voxel_size
        rec.array((0.44825, 0.3925, 0.45874998),
          dtype=[('x', '<f4'), ('y', '<f4'), ('z', '<f4')])
        >>> mrc.voxel_size.x
        array(0.44825, dtype=float32)

        Note that changing the voxel_size array in-place will *not* change the
        voxel size in the file -- to prevent this being overlooked
        accidentally, the writeable flag is set to :data:`False` on the
        voxel_size array.

        To set the voxel size, assign a new value to the voxel_size attribute.
        You may give a single number, a 3-tuple ``(x, y ,z)`` or a modified
        version of the voxel_size array. The following examples are all
        equivalent:

        >>> mrc.voxel_size = 1.0

        >>> mrc.voxel_size = (1.0, 1.0, 1.0)

        >>> vox_sizes = mrc.voxel_size
        >>> vox_sizes.flags.writeable = True
        >>> vox_sizes.x = 1.0
        >>> vox_sizes.y = 1.0
        >>> vox_sizes.z = 1.0
        >>> mrc.voxel_size = vox_sizes
        F)rK   cellaxmxymyzmzr*   recarrayr   flags	writeable)r   rv   rx   rz   sizess        r   
voxel_sizezMrcObject.voxel_size@  sr    D K$+.0K$+.0K$+.0aAY(899 %r    c                     |                                   	 t          |          fdz  }n8# t          $ r+ 	 |                                }n# t          $ r |}Y nw xY wY nw xY w | j        |  d S Nr3   )r$   float	TypeErroritemAttributeError_set_voxel_size)r   r   r   s      r   r   zMrcObject.voxel_sizei  s    
	#:&&(1,EE 	# 	# 	## #))! # # #"#	# 	e$$$$2   * 
AA
	A
AAAAAc                     || j         j        z  | j         j        _        || j         j        z  | j         j        _        || j         j        z  | j         j        _        dS )zSet the voxel size.

        Args:
            x_size: The voxel size in the X direction, in angstroms
            y_size: The voxel size in the Y direction, in angstroms
            z_size: The voxel size in the Z direction, in angstroms
        N)rK   rw   ru   rv   ry   rx   r{   rz   )r   x_sizey_sizez_sizes       r   r   zMrcObject._set_voxel_sizey  sL     %t{~5$t{~5$t{~5r    c                     | j         j        }| j         j        }| j         j        }t          j                            |||ft                    }d|j        _	        |S )a  Get or set the grid start locations.

        This provides a convenient way to get and set the values of the
        header's ``nxstart``, ``nystart`` and ``nzstart`` fields. Note that
        these fields are integers and are measured in voxels, not angstroms.
        The start locations are returned as a structured NumPy :class:`record
        array <numpy.recarray>` with three fields (x, y and z). For example:

        >>> mrc.header.nxstart
        array(0, dtype=int32)
        >>> mrc.header.nystart
        array(-21, dtype=int32)
        >>> mrc.header.nzstart
        array(-12, dtype=int32)
        >>> mrc.nstart
        rec.array((0, -21, -12),
          dtype=[('x', '<i4'), ('y', '<i4'), ('z', '<i4')])
        >>> mrc.nstart.y
        array(-21, dtype=int32)

        Note that changing the nstart array in-place will *not* change the
        values in the file -- to prevent this being overlooked accidentally,
        the writeable flag is set to :data:`False` on the nstart array.

        To set the start locations, assign a new value to the nstart
        attribute. You may give a single number, a 3-tuple ``(x, y ,z)`` or a
        modified version of the nstart array. The following examples are all
        equivalent:

        >>> mrc.nstart = -150

        >>> mrc.nstart = (-150, -150, -150)

        >>> starts = mrc.nstart
        >>> starts.flags.writeable = True
        >>> starts.x = -150
        >>> starts.y = -150
        >>> starts.z = -150
        >>> mrc.nstart = starts
        F)
rK   nxstartnystartnzstartr*   r|   r}   r   r~   r   )r   rv   rx   rz   nstarts        r   r   zMrcObject.nstart  sM    T KKKq!Qi66!&r    c                     |                                   	 t          |          fdz  }n8# t          $ r+ 	 |                                }n# t          $ r |}Y nw xY wY nw xY w | j        |  d S r   )r$   rY   r   r   r   _set_nstart)r   r   startss      r   r   zMrcObject.nstart  s    
	 &kk^a'FF 	  	  	    !       	  	&!!!!r   c                 N    || j         _        || j         _        || j         _        dS )a  Set the grid start locations.

        Args:
            nxstart: The location of the first column in the unit cell
            nystart: The location of the first row in the unit cell
            nzstart: The location of the first section in the unit cell
        N)rK   r   r   r   )r   r   r   r   s       r   r   zMrcObject._set_nstart  s(     &%%r    c                 "    | j         j        dk    S )zIdentify whether the file represents a single image.

        Returns:
            :data:`True` if the data array is two-dimensional.
        r2   re   ndimr#   s    r   is_single_imagezMrcObject.is_single_image       y~""r    c                 L    | j         j        dk    o| j        j        t          k    S )zIdentify whether the file represents a stack of images.

        Returns:
            :data:`True` if the data array is three-dimensional and the space group
            is zero.
        r3   re   r   rK   r=   r   r#   s    r   is_image_stackzMrcObject.is_image_stack  )     	!# ?K$(>>	@r    c                 L    | j         j        dk    o| j        j        t          k    S )zIdentify whether the file represents a volume.

        Returns:
            :data:`True` if the data array is three-dimensional and the space
            group is not zero.
        r3   r   r#   s    r   	is_volumezMrcObject.is_volume  r   r    c                 "    | j         j        dk    S )zIdentify whether the file represents a stack of volumes.

        Returns:
            :data:`True` if the data array is four-dimensional.
           r   r#   s    r   is_volume_stackzMrcObject.is_volume_stack  r   r    c                     |                                   | j        j        dk    rt          d          t          | j        _        d| j        _        dS )zChange three-dimensional data to represent an image stack.

        This method changes the space group number (``header.ispg``) to zero.

        Raises:
            :exc:`ValueError`: If the data array is not three-dimensional.
        r3   z/Only 3D data can be changed into an image stackr   N)r$   re   r   r"   r   rK   r=   r{   r#   s    r   set_image_stackzMrcObject.set_image_stack  sK     	9>QNOOO1r    c                     |                                   | j        j        dk    rt          d          |                                 r)t
          | j        _        | j        j        | j        _	        dS dS )a6  Change three-dimensional data to represent a volume.

        If the space group was previously zero (representing an image stack),
        this method sets it to one. Otherwise the space group is not changed.

        Raises:
            :exc:`ValueError`: If the data array is not three-dimensional.
        r3   z)Only 3D data can be changed into a volumeN)
r$   re   r   r"   r   r   rK   r=   rR   r{   r#   s    r   
set_volumezMrcObject.set_volume  sm     	9>QHIII   	,0DK![^DKNNN	, 	,r    c                 \   |                                   | j        }t          j        | j        j                  |_        | j        j        j        }|j        j        j        }|dk    rIt          j        ||          s4|	                    d           |j        
                    |          |_        t          j        |j        j        j                  |_        | j        j        }t          |          }|dk    rDt          |_        |d         x|_        |_        |d         x|_        |_        dx|_        |_        d	S |dk    rd|d         x|_        |_        |d         x|_        |_        |j        t          k    rd|_        |d         |_        d	S |d         x|_        |_        d	S |dk    rrt          j        |j                  st0          |_        |d         x|_        |_        |d         x|_        |_        |d         |_        |d         |d         z  |_        d	S t3          d          )
a  Update the header from the data array.

        This function updates the header byte order and machine stamp to match
        the byte order of the data. It also updates the file mode, space group
        and the dimension fields ``nx``, ``ny``, ``nz``, ``mx``, ``my`` and
        ``mz``.

        If the data is 2D, the space group is set to 0 (image stack). For 3D
        data the space group is not changed, and for 4D data the space group is
        set to 401 (simple P1 volume stack) unless it is already in the volume
        stack range (401--630).

        This means that new 3D data will be treated as an image stack if the
        previous data was a single image or image stack, or as a volume if the
        previous data was a volume or volume stack.

        Note that this function does *not* update the data statistics fields in
        the header (``dmin``, ``dmax``, ``dmean`` and ``rms``). Use the
        :meth:`update_header_stats` function to update the statistics.
        (This is for performance reasons -- updating the statistics can take a
        long time for large data sets, but updating the other header
        information is always fast because only the type and shape of the data
        array need to be inspected.)
        |Tr2   r   r   r3   r   z$Data must be 2-, 3- or 4-dimensionalN)r$   rK   r	   rg   re   r(   r:   r;   byte_orders_equalbyteswapri   r9   r<   r0   lenr   r=   nxrw   nyry   rR   r{   spacegroup_is_volume_stackr   r"   )r   rK   data_byte_orderheader_byte_orderr0   axess         r   rl   z!MrcObject.update_header_from_data  s   2 	 +DIO<< )/3"K-7s""+O=NOO #OOD!!!!<44_EEFL;FK<M=FH H 	5zz1990FK$)!H,FI	$)!H,FI	$%%FI			QYY$)!H,FI	$)!H,FI	{444	!!H			 ).a0	FIIIQYY3FK@@ 65$)!H,FI	$)!H,FI	aFIa58+FIIICDDDr    c                    |                                   | j        j        dk    rt          j        | j                  r<t          j        | j                                        j                  | j        _	        dS | j        
                                }| j                                        }t          j        |          rt          j        dt                     t          j        |          st          j        |          rt          j        dt                     t          j        |          | j        _        t          j        |          | j        _        | j                            t          j                  | j        _        | j                            t          j                  | j        _	        dS |                                  dS )aG  Update the header's ``dmin``, ``dmax``, ``dmean`` and ``rms`` fields
        from the data.

        Note that this can take some time with large files, particularly with
        files larger than the currently available memory.

        Warns:
            RuntimeWarning: If the data array contains Inf or NaN values.
        r   zData array contains NaN valuesz#Data array contains infinite valuesr'   N)r$   re   sizer*   iscomplexobjfloat32stdrealrK   rmsminr`   isnanrV   rW   rX   isinfdmindmaxmeandmeanrJ   )r   r   r`   s      r   rm   zMrcObject.update_header_statsZ  sM    	9>A ty)) B"$*TY]]__-A"B"Bimmooimmoo8C== TM"BNSSS8C== YBHSMM YM"GXXX#%:c?? #%:c?? $(INNN$D$D!"&)--bj-"A"A##%%%%%r    c                     |                                   d| j        _        d| j        _        d| j        _        d| j        _        dS )zBSet the header statistics to indicate that the values are unknown.r   N)r$   rK   r   r   r   r   r#   s    r   rJ   zMrcObject.reset_header_stats}  s?    r    Nc                     | j         j        j        D ]2}t          d                    || j         |                   |           3dS )ak  Print the contents of all header fields.

        Args:
            print_file: The output text stream to use for printing the header.
                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`.
        z{0:15s} : {1}fileN)rK   r(   namesprintrG   )r   
print_filer   s      r   print_headerzMrcObject.print_header  s]     K%+ 	# 	#D/((t{4/@AA!# # # # #	# 	#r    c                 R    d | j         j        d| j         j                 D             S )aD  Get the labels from the MRC header.

        Up to ten labels are stored in the header as arrays of 80 bytes. This method
        returns the labels as Python strings, filtered to remove non-printable
        characters. To access the raw bytes (including any non-printable characters) use
        the ``header.label`` attribute (and note that ``header.nlabl`` stores the number
        of labels currently set).

        Returns:
            The labels, as a list of strings. The list will contain between 0 and 10
            items, each containing up to 80 characters.
        c                 6    g | ]}t          j        |          S r   )r	   printable_string_from_bytes).0rH   s     r   
<listcomp>z(MrcObject.get_labels.<locals>.<listcomp>  s3     
 
 
 -e44
 
 
r    N)rK   rH   rI   r#   s    r   
get_labelszMrcObject.get_labels  s8    
 
*+=DK,=+=>
 
 
 	
r    c                    t          j        |          st          d          t          j        |          }t	          |          dk    rt          d          || j        j        | j        j        <   | j        xj        dz  c_        dS )a
  Add a label to the MRC header.

        The new label will be stored after any labels already in the header. If all ten
        labels are already in use, an exception will be raised.

        Future versions of this method might add checks to ensure that labels containing
        valid text are not overwritten even if the ``nlabl`` value is incorrect.

        Args:
            label: The label value to store, as a string containing only printable
                ASCII characters.

        Raises:
            :exc:`ValueError`: If the label is longer than 80 bytes or contains
                non-printable or non-ASCII characters.
            :exc:`IndexError`: If the file already contains 10 labels and so an
                additional label cannot be stored.
        z4Label contains non-printable or non-ASCII charactersP   z"Label value has more than 80 bytesr   N)r	   is_printable_asciir"   bytes_from_stringr   rK   rH   rI   )r   rH   label_bytess      r   	add_labelzMrcObject.add_label  s    & '.. 	USTTT-e44{b  ABBB/4$++,Qr    c           	         d}fd}| j         j        t          k    r0 |d                    | j         j        t                               d}	 t	          j        | j         j                   n># t          $ r1 t	          j        | j         j                  } |d|z              d}Y nw xY w	 t	          j	        | j         j
                   n:# t          $ r-  |d                    | j         j
                             d}Y nw xY wdD ]3}| j         |         dk     r  |d	                    |                     d}4d
D ]8}| j         j        |         dk     r  |d                    |                     d}9t                      }dD ]/}|                    t          | j         |                              0|h dk    r: |d                    t          t!          |                                         d}t	          j        | j         j                  rR| j         j        | j         j        z  dk    r5 |d                    | j         j        | j         j                             d}d}d}| j         j        D ]>}	t-          |	                                          dk    r|dz  }|r |d           d}<d}?|| j         j        k    r+ |d                    | j         j        |                     d}| j         j        dvr* |d                    | j         j                             d}g d}
| j         j        dk    r]| j         j        |
vrO |d                    | j         j                                                            d                               d}dx}x}x}}| j         j        dk    r| j        1t-          | j        dk              r| j                                         }tC          j"        || j         j        d          s+ |d                    || j         j                             d}| j         j#        | j         j$        k     r| j        Jt-          | j        dk              r2| j        %                                }| j        &                                }| j         j#        |k    r+ |d                    || j         j#                             d}| j         j$        |k    r+ |d                    || j         j$                             d}| j         j'        tK          | j         j#        | j         j$                  k    r| j        =t-          | j        dk              r%| j        (                    tB          j)                  }tC          j"        || j         j'        d          s+ |d                    || j         j'                             d}|S ) a	  Validate this MrcObject.

        This method runs a series of tests to check whether this object
        complies strictly with the MRC2014 format specification:

        #. MRC format ID string: The header's ``map`` field must 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 (that is, there should be no blank labels between
           text-filled ones).
        #. 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, or marked as undetermined.

        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 this MrcObject  is valid, or :data:`False` if it
            does not meet the MRC format specification in any way.
        Tc                 *    t          |            d S )Nr   )r   )messager   s    r   logzMrcObject.validate.<locals>.log  s    '
++++++r    z4Map ID string is incorrect: found {0}, should be {1}FzInvalid machine stamp: zInvalid mode: {0})r   r   rR   rw   ry   r{   r=   rI   r   zHeader field '{0}' is negative)rv   rx   rz   z Cell dimension '{0}' is negative)rB   rC   rD   >   r   r2   r3   z4Invalid axis mapping: found {0}, should be [1, 2, 3]z]Error in dimensions for volume stack: nz should be divisible by mz. Found nz = {0}, mz = {1})r   zJError in header labels: empty labels appear between text-containing labelsz@Error in header labels: nlabl is {0} but {1} labels contain text)iN  r1   zGFile does not declare MRC format version 20140 or 20141: nversion = {0})s   CCP4s   MRCOs   SERIs   AGARs   FEI1s   FEI2s   HDF5zAExtended header type is undefined or unrecognised: exttyp = '{0}'asciiNg{Gz?)rtolz`Data statistics appear to be inaccurate: RMS deviation is {0} but the value in the header is {1}zZData statistics appear to be inaccurate: minimum is {0} but the value in the header is {1}zZData statistics appear to be inaccurate: maximum is {0} but the value in the header is {1}r'   zWData statistics appear to be inaccurate: mean is {0} but the value in the header is {1})*rK   r7   r   rG   r	   byte_order_from_machine_stampr<   r"   pretty_machine_stamprh   r:   ru   setaddrY   sortedlistr   r=   rR   r{   rH   r   striprI   r8   ra   rS   r   decoder   re   r   r*   iscloser   r   r   r`   r   r   float64)r   r   validr   pretty_bytesfieldr   countseen_empty_labelrH   valid_exttypesreal_rmsreal_minreal_max	real_means    `             r   validatezMrcObject.validate  sU   \ 	, 	, 	, 	, 	, ;?f$$CF002 2 2E	/0BCCCC 	 	 	 5dk6HIILC)L8999EEE		!$+"23333 	 	 	C#**4;+;<<===EEE	
 K 	 	E{5!A%%4;;EBBCCC % 	 	E{ '!++6==eDDEEE uu- 	. 	.EHHSU+,,----999CFtDzz**++- - -E +DK,<== 	{~.!33 AVDKNDKN;;= = =   [& 	( 	(E5;;==!!A%%
# "C 1 2 2 2!E#'  DK%%%C ..4fT[5F.N.NP P PE ;~55C vdk2335 5 5E YXX;!!dk&8&N&NC t{16688??HHIIK K KE 676686h;?ay$TY]););$9==??:hdCCC  66<fXt{6W6WY Y Y;dk...y$TY]););$9==??9==??{8++ 228&4;CS2T2TV V V{8++ 228&4;CS2T2TV V V;s4;#3T[5EFFFFy$TY]););$ INNN<<	:i):FFF  228&DKDU2V2VX X Xs$   A. .8B)(B)-C 4DD)N)$__name__
__module____qualname____doc__r   r$   r.   r)   propertyrK   rP   r\   rb   re   rq   rk   r,   r   setterr   r   r   r   r   r   r   r   r   rl   rm   rJ   r   r   r   r   __classcell__)r   s   @r   r   r      s       @ @D         .8 8 87 7 7$" $" $"L   X % % X% ) ) X)V4 4 4(   X*# *# *#X     & & X&P % % %
6 
6 
6 . . X.` ]" " ]"
& 
& 
&# # #@ @ @@ @ @# # #  , , , DE DE DEL!& !& !&F  # # # #
 
 
$  6` ` ` ` ` ` ` `r    r   )r   
__future__r   r   r   r   r   rV   numpyr*    r	   dtypesr
   r   r   r   	constantsr   r   r   r   objectr   r   r    r   <module>r      s<  
 
* * * * * * * * * * * *                 + + + + + + + + + + + +1 1 1 1 1 1 1 1 1 1 1 1A A A A A A A A A Ar    