a
    BCCf_                     @   s>  d Z ddgZddlZddlZddlmZ ddlmZ ddlZ	ddl
Zddl
mZmZmZmZmZ ddl
mZ dd	lmZ e d
kZdZdZdZdZdZdZdZdZdZdZdZ dZ!dZ"dZ#dZ$dZ%dZ&ededededed ed!iZ'ee!ee"ee#ee$ee%ee&iZ(eeeeeeeeed"	Z)G d#d dZ*G d$d dZ+e*Z,e+Z-dS )%a  
NetCDF reader/writer module.

This module is used to read and create NetCDF files. NetCDF files are
accessed through the `netcdf_file` object. Data written to and from NetCDF
files are contained in `netcdf_variable` objects. Attributes are given
as member variables of the `netcdf_file` and `netcdf_variable` objects.

This module implements the Scientific.IO.NetCDF API to read and create
NetCDF files. The same API is also used in the PyNIO and pynetcdf
modules, allowing these modules to be used interchangeably when working
with NetCDF files.

Only NetCDF3 is supported here; for NetCDF4 see
`netCDF4-python <http://unidata.github.io/netcdf4-python/>`__,
which has a similar API.

netcdf_filenetcdf_variable    N)mul)python_implementation)
frombufferdtypeemptyarrayasarray)little_endian)reducePyPys           s       s      s      s      s      s      s      s      
s      s             s   s     s   |  s   G      b   cr   h   i   fr   d   )	r   )Br   r   r   r   r   r   )lr   )Sr   c                   @   s*  e Zd ZdZdHddZdd	 Zd
d ZeZdd Zdd Z	dd Z
dd Zdd ZeZdd Zdd Zdd Zdd Zdd Zd d! Zd"d# Zd$d% Zd&d' Zd(d) Zd*d+ Zd,d- Zd.d/ Zd0d1 Zd2d3 Zd4d5 Zd6d7 Zd8d9 Zd:d; Z d<d= Z!e!Z"d>d? Z#e#Z$d@dA Z%dBdC Z&dDdE Z'dFdG Z(dS )Ir   a  
    A file object for NetCDF data.

    A `netcdf_file` object has two standard attributes: `dimensions` and
    `variables`. The values of both are dictionaries, mapping dimension
    names to their associated lengths and variable names to variables,
    respectively. Application programs should never modify these
    dictionaries.

    All other attributes correspond to global attributes defined in the
    NetCDF file. Global file attributes are created by assigning to an
    attribute of the `netcdf_file` object.

    Parameters
    ----------
    filename : string or file-like
        string -> filename
    mode : {'r', 'w', 'a'}, optional
        read-write-append mode, default is 'r'
    mmap : None or bool, optional
        Whether to mmap `filename` when reading.  Default is True
        when `filename` is a file name, False when `filename` is a
        file-like object. Note that when mmap is in use, data arrays
        returned refer directly to the mmapped data on disk, and the
        file cannot be closed as long as references to it exist.
    version : {1, 2}, optional
        version of netcdf to read / write, where 1 means *Classic
        format* and 2 means *64-bit offset format*.  Default is 1.  See
        `here <https://docs.unidata.ucar.edu/nug/current/netcdf_introduction.html#select_format>`__
        for more info.
    maskandscale : bool, optional
        Whether to automatically scale and/or mask data based on attributes.
        Default is False.

    Notes
    -----
    The major advantage of this module over other modules is that it doesn't
    require the code to be linked to the NetCDF libraries. This module is
    derived from `pupynere <https://bitbucket.org/robertodealmeida/pupynere/>`_.

    NetCDF files are a self-describing binary data format. The file contains
    metadata that describes the dimensions and variables in the file. More
    details about NetCDF files can be found `here
    <https://www.unidata.ucar.edu/software/netcdf/guide_toc.html>`__. There
    are three main sections to a NetCDF data structure:

    1. Dimensions
    2. Variables
    3. Attributes

    The dimensions section records the name and length of each dimension used
    by the variables. The variables would then indicate which dimensions it
    uses and any attributes such as data units, along with containing the data
    values for the variable. It is good practice to include a
    variable that is the same name as a dimension to provide the values for
    that axes. Lastly, the attributes section would contain additional
    information such as the name of the file creator or the instrument used to
    collect the data.

    When writing data to a NetCDF file, there is often the need to indicate the
    'record dimension'. A record dimension is the unbounded dimension for a
    variable. For example, a temperature variable may have dimensions of
    latitude, longitude and time. If one wants to add more temperature data to
    the NetCDF file as time progresses, then the temperature variable should
    have the time dimension flagged as the record dimension.

    In addition, the NetCDF file header contains the position of the data in
    the file, so access can be done in an efficient manner without loading
    unnecessary data into memory. It uses the ``mmap`` module to create
    Numpy arrays mapped to the data on disk, for the same purpose.

    Note that when `netcdf_file` is used to open a file with mmap=True
    (default for read-only), arrays returned by it refer to data
    directly on the disk. The file should not be closed, and cannot be cleanly
    closed when asked, if such arrays are alive. You may want to copy data arrays
    obtained from mmapped Netcdf file if they are to be processed after the file
    is closed, see the example below.

    Examples
    --------
    To create a NetCDF file:

    >>> from scipy.io import netcdf_file
    >>> import numpy as np
    >>> f = netcdf_file('simple.nc', 'w')
    >>> f.history = 'Created for a test'
    >>> f.createDimension('time', 10)
    >>> time = f.createVariable('time', 'i', ('time',))
    >>> time[:] = np.arange(10)
    >>> time.units = 'days since 2008-01-01'
    >>> f.close()

    Note the assignment of ``arange(10)`` to ``time[:]``.  Exposing the slice
    of the time variable allows for the data to be set in the object, rather
    than letting ``arange(10)`` overwrite the ``time`` variable.

    To read the NetCDF file we just created:

    >>> from scipy.io import netcdf_file
    >>> f = netcdf_file('simple.nc', 'r')
    >>> print(f.history)
    b'Created for a test'
    >>> time = f.variables['time']
    >>> print(time.units)
    b'days since 2008-01-01'
    >>> print(time.shape)
    (10,)
    >>> print(time[-1])
    9

    NetCDF files, when opened read-only, return arrays that refer
    directly to memory-mapped data on disk:

    >>> data = time[:]

    If the data is to be processed after the file is closed, it needs
    to be copied to main memory:

    >>> data = time[:].copy()
    >>> del time
    >>> f.close()
    >>> data.mean()
    4.5

    A NetCDF file can also be used as context manager:

    >>> from scipy.io import netcdf_file
    >>> with netcdf_file('simple.nc', 'r') as f:
    ...     print(f.history)
    b'Created for a test'

    rNr   Fc                 C   s"  |dvrt dt|drL|| _d| _|du r4d}q|rt|dst dn6|| _|d	kr^d
n|}t| jd| | _|du rt }|dkrd}|| _|| _|| _|| _	i | _
i | _g | _d| _d| _d| _d| _| jrtj| j dtjd| _tj| jtjd| _i | _|dv r|   dS )z7Initialize netcdf_file from fileobj (str or file-like).Zrwaz$Mode must be either 'r', 'w' or 'a'.seekNoneNFfilenozCannot use file object for mmapazr+z%sbr#   r   )accessr   ra)
ValueErrorhasattrfpfilenameopenIS_PYPYuse_mmapmodeversion_bytemaskandscale
dimensions	variables_dims_recs_recsize_mm_mm_bufmmmmapr&   ACCESS_READnpr   Zint8_attributes_read)selfr.   r2   r=   versionr4   Zomode rD   L/var/www/html/django/DPS/env/lib/python3.9/site-packages/scipy/io/_netcdf.py__init__   sB    


znetcdf_file.__init__c                 C   s0   z|| j |< W n ty    Y n0 || j|< d S Nr@   AttributeError__dict__rB   attrvaluerD   rD   rE   __setattr__  s
    znetcdf_file.__setattr__c                 C   s   t | dr| jjszd|   W i | _| jdurft| j}d| _| du rV| j	  nt
jdtdd d| _| j	  nZi | _| jdurt| j}d| _| du r| j	  nt
jdtdd d| _| j	  0 dS )zCloses the NetCDF file.r-   Na1  Cannot close a netcdf_file opened with mmap=True, when netcdf_variables or arrays referring to its data still exist. All data arrays obtained from such files refer directly to data on disk, and must be copied before the file can be cleanly closed. (See netcdf_file docstring for more information on mmap.)r   )category
stacklevel)r,   r-   closedflushr6   r;   weakrefrefr:   closewarningswarnRuntimeWarning)rB   rT   rD   rD   rE   rU   "  s6    


	

	znetcdf_file.closec                 C   s   | S rG   rD   rB   rD   rD   rE   	__enter__?  s    znetcdf_file.__enter__c                 C   s   |    d S rG   )rU   )rB   typerM   	tracebackrD   rD   rE   __exit__B  s    znetcdf_file.__exit__c                 C   s0   |du r| j rtd|| j|< | j | dS )a-  
        Adds a dimension to the Dimension section of the NetCDF data structure.

        Note that this function merely adds a new dimension that the variables can
        reference. The values for the dimension, if desired, should be added as
        a variable using `createVariable`, referring to this dimension.

        Parameters
        ----------
        name : str
            Name of the dimension (Eg, 'lat' or 'time').
        length : int
            Length of the dimension.

        See Also
        --------
        createVariable

        Nz&Only first dimension may be unlimited!)r7   r+   r5   appendrB   namelengthrD   rD   rE   createDimensionE  s    
znetcdf_file.createDimensionc           	         s   t  fdd|D }t dd |D }t|}|j|j }}||ftvrVtd| t||dd}t||||| j	d j
|<  j
| S )a  
        Create an empty variable for the `netcdf_file` object, specifying its data
        type and the dimensions it uses.

        Parameters
        ----------
        name : str
            Name of the new variable.
        type : dtype or str
            Data type of the variable.
        dimensions : sequence of str
            List of the dimension names used by the variable, in the desired order.

        Returns
        -------
        variable : netcdf_variable
            The newly created ``netcdf_variable`` object.
            This object has also been added to the `netcdf_file` object as well.

        See Also
        --------
        createDimension

        Notes
        -----
        Any dimensions to be used by the variable should already exist in the
        NetCDF data structure or should be created by `createDimension` prior to
        creating the NetCDF variable.

        c                    s   g | ]} j | qS rD   )r5   .0dimrY   rD   rE   
<listcomp>~      z.netcdf_file.createVariable.<locals>.<listcomp>c                 S   s   g | ]}|pd qS )r   rD   rc   rD   rD   rE   rf     rg   z!NetCDF 3 does not support type %sr    r)   r4   )tupler   charitemsizeREVERSEr+   r   Znewbyteorderr   r4   r6   )	rB   r`   r[   r5   shapeZshape_typecodesizedatarD   rY   rE   createVariable_  s    
znetcdf_file.createVariablec                 C   s    t | dr| jdv r|   dS )z
        Perform a sync-to-disk flush if the `netcdf_file` object is in write mode.

        See Also
        --------
        sync : Identical function

        r2   waN)r,   r2   _writerY   rD   rD   rE   rR     s    	znetcdf_file.flushc                 C   sT   | j d | j d | j t| jd  |   |   |   | 	  d S )Nr      CDF>b)
r-   r$   writer	   r3   tobytes_write_numrecs_write_dim_array_write_gatt_array_write_var_arrayrY   rD   rD   rE   rs     s    znetcdf_file._writec                 C   sF   | j  D ]*}|jr
t|j| jkr
t|j| jd< q
| | j d S Nr8   )r6   valuesisreclenrp   r8   rJ   	_pack_int)rB   varrD   rD   rE   rx     s    znetcdf_file._write_numrecsc                 C   sb   | j rR| jt | t| j  | jD ]&}| | | j | }| |pJd q(n| jt d S )Nr   )	r5   r-   rv   NC_DIMENSIONr   r   r7   _pack_stringABSENTr_   rD   rD   rE   ry     s    


znetcdf_file._write_dim_arrayc                 C   s   |  | j d S rG   )_write_att_arrayr@   rY   rD   rD   rE   rz     s    znetcdf_file._write_gatt_arrayc                 C   sV   |rF| j t | t| | D ]\}}| | | | q&n| j t d S rG   )	r-   rv   NC_ATTRIBUTEr   r   itemsr   _write_att_valuesr   )rB   
attributesr`   r}   rD   rD   rE   r     s    
znetcdf_file._write_att_arrayc                    s    j r jt  t j   fdd}t j |dd}|D ]} | qBtdd  j 	 D  j
d< |D ]} | qtn jt d S )Nc                    s    j |  }|jrdS |jS )N))r6   r~   _shape)nvrY   rD   rE   sortkey  s    
z-netcdf_file._write_var_array.<locals>.sortkeyT)keyreversec                 S   s   g | ]}|j r|jqS rD   )r~   _vsize)rd   r   rD   rD   rE   rf     s   z0netcdf_file._write_var_array.<locals>.<listcomp>r9   )r6   r-   rv   NC_VARIABLEr   r   sorted_write_var_metadatasumr}   rJ   _write_var_datar   )rB   r   r6   r`   rD   rY   rE   r{     s    znetcdf_file._write_var_arrayc                 C   s4  | j | }| | | t|j |jD ]}| j|}| | q*| |j t	|
 | f }| j| |js|jj|jj }|| d 7 }n^z|jd j|jj }W n ty   d}Y n0 tdd | j  D }|dkr|| d 7 }|| j | jd< | | | j | j | jd< | d d S )Nr   r   c                 S   s   g | ]}|j r|qS rD   )r~   )rd   r   rD   rD   rE   rf     s   z3netcdf_file._write_var_metadata.<locals>.<listcomp>r   r   _begin)r6   r   r   r   r5   r7   indexr   r@   rl   rn   rk   r-   rv   r~   rp   ro   
IndexErrorr}   rJ   tell_pack_begin)rB   r`   r   dimnamedimidnc_typevsizerec_varsrD   rD   rE   r     s.    




znetcdf_file._write_var_metadatac           
      C   s  | j | }| j }| j|j | | | j| |jsv| j|j	  |jj
|jj }| ||j|  n| jt|jkr| jf|jjdd   }z|j| W n4 ty   |jj}t|j|||jd< Y n0 | j  }}|jD ]z}	|	js.|	jjdks&|	jjdkr.tr.|	 }	| j|		  |	j
|	j }| ||j|  || j7 }| j| q| j||j  d S )Nr   rp   <=)r6   r-   r   r$   r   r   r~   rv   rp   rw   ro   rk   _write_var_paddingr   r8   r   rm   resizer+   r   r?   astyperJ   	byteorderLITTLE_ENDIANbyteswapr9   )
rB   r`   r   Zthe_beguinecountrm   r   Zpos0posZrecrD   rD   rE   r      s<    


 


znetcdf_file._write_var_datac                 C   s(   |  }|t| }| j||  d S rG   )_get_encoded_fill_valuer   r-   rv   )rB   r   ro   Zencoded_fill_valueZ	num_fillsrD   rD   rE   r   *  s    znetcdf_file._write_var_paddingc                 C   sR  t |dr t|jj|jjf }njttfttft	t
fg}t|t	tfrJ|}n$z|d }W n tyl   |}Y n0 |D ]\}}t||rr qqrt| \}}d| }|dkrdn|}t||d}| j| |jjdkr|j}	n|j}	| |	 |js|jjdks|jjdkrtr| }| j|  |j|j }
| jd	|
 d
   d S )Nr   r   >%sz>cr"   r)   r   r   r   r   )r,   rl   r   rj   rk   intNC_INTfloatNC_FLOATstrNC_CHAR
isinstancebytes	TypeErrorTYPEMAPr
   r-   rv   ro   r   rm   r   r   r   rw   )rB   r}   r   typessampleclass_rn   ro   dtype_Znelemsr   rD   rD   rE   r   /  s<    




znetcdf_file._write_att_valuesc                 C   sb   | j d}|dks"td| j t| j ddd | jd< |   |   |   | 	  d S )N   rt   z&Error: %s is not a valid NetCDF 3 filer   ru   r   r3   )
r-   readr   r.   r   rJ   _read_numrecs_read_dim_array_read_gatt_array_read_var_array)rB   magicrD   rD   rE   rA   X  s    znetcdf_file._readc                 C   s   |   | jd< d S r|   )_unpack_intrJ   rY   rD   rD   rE   r   f  s    znetcdf_file._read_numrecsc                 C   sj   | j d}|ttfvr td|  }t|D ]4}|  d}|  pLd }|| j	|< | j
| q0d S Nr   Unexpected header.latin1)r-   r   ZEROr   r+   r   range_unpack_stringdecoder5   r7   r^   )rB   headerr   re   r`   ra   rD   rD   rE   r   i  s    
znetcdf_file._read_dim_arrayc                 C   s&   |    D ]\}}| || qd S rG   )_read_att_arrayr   rN   )rB   kr   rD   rD   rE   r   u  s    znetcdf_file._read_gatt_arrayc                 C   sX   | j d}|ttfvr td|  }i }t|D ]}|  d}| 	 ||< q4|S r   )
r-   r   r   r   r+   r   r   r   r   _read_att_values)rB   r   r   r   rL   r`   rD   rD   rE   r   y  s    znetcdf_file._read_att_arrayc              
   C   s  | j d}|ttfvr tdd}g g d}g }|  }t|D ]|}|  \	}}}	}
}}}}}|	r(|	d d u r(|| | j	d  |7  < |dkr|}|d | |d t
|	dd  |  |d	v r"ttd
|	dd   | }| d }|r"|d d|  |d d|  d }nztt|	d| }| jrb| j|||  j|d}|	|_n@| j  }| j | t| j ||d }|	|_| j | t||||	||
| jd| j|< qB|rt|dkr|d d d |d< |d d d |d< | jr8| j||| j| j   }|j|d}| jf|_nL| j  }| j | t| j | j| j |d }| jf|_| j | |D ]}|| | j| j	d< qd S )Nr   r   r   )namesformatsr9   r   r   r   Zbchr   z_padding_%dz(%d,)>br)   rh   rp   )r-   r   r   r   r+   r   r   	_read_varr^   rJ   r   r   r   r1   r;   viewrm   r   r$   r   copyr   r4   r6   r   r8   r9   )rB   r   beginZdtypesr   r   r   r`   r5   rm   r   rn   ro   r   begin_r   Zactual_sizepaddingrp   Za_sizer   bufZ	rec_arrayrD   rD   rE   r     sn    









znetcdf_file._read_var_arrayc              	   C   s   |   d}g }g }|  }t|D ]4}|  }| j| }|| | j| }|| q&t|}t|}|  }	| j	
d}
|  }| j| jg| jd   }t|
 \}}d| }||||	|||||f	S )Nr   r   r   r   )r   r   r   r   r7   r^   r5   ri   r   r-   r   _unpack_int64r3   r   )rB   r`   r5   rm   dimsr   r   r   re   r   r   r   r   rn   ro   r   rD   rD   rE   r     s&    


znetcdf_file._read_varc                 C   s   | j d}|  }t| \}}|| }| j t|}| j | d  |dkrzt|d| d }|jdkr|d }n
|d}|S )Nr   r   r   r)   r   r   r   )	r-   r   r   r   r   r   r   rm   rstrip)rB   r   r   rn   ro   r   r}   rD   rD   rE   r     s    


znetcdf_file._read_att_valuesc                 C   s.   | j dkr| | n| j dkr*| | d S )Nr   r   )r3   r   _pack_int64)rB   r   rD   rD   rE   r     s    

znetcdf_file._pack_beginc                 C   s   | j t|d  d S )N>ir-   rv   r	   rw   rB   rM   rD   rD   rE   r     s    znetcdf_file._pack_intc                 C   s   t t| jddd S )Nr   r   r   )r   r   r-   r   rY   rD   rD   rE   r     s    znetcdf_file._unpack_intc                 C   s   | j t|d  d S )N>qr   r   rD   rD   rE   r     s    znetcdf_file._pack_int64c                 C   s   t | jddd S )Nr   r   r   )r   r-   r   rY   rD   rD   rE   r     s    znetcdf_file._unpack_int64c                 C   s>   t |}| | | j|d | jd| d   d S )Nr   r   r   )r   r   r-   rv   encode)rB   sr   rD   rD   rE   r     s    
znetcdf_file._pack_stringc                 C   s0   |   }| j|d}| j| d  |S )Nr   r   )r   r-   r   r   )rB   r   r   rD   rD   rE   r   !  s    znetcdf_file._unpack_string)r#   Nr   F))__name__
__module____qualname____doc__rF   rN   rU   __del__rZ   r]   rb   rq   rR   syncrs   rx   ry   rz   r   r{   r   r   r   r   rA   r   r   r   r   r   r   r   r   r   Z_pack_int32r   Z_unpack_int32r   r   r   r   rD   rD   rD   rE   r   b   sR      
2	.
!*)Wc                   @   s   e Zd ZdZd ddZdd Zdd	 ZeeZd
d ZeeZdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd Zedd ZdS )!r   a  
    A data object for netcdf files.

    `netcdf_variable` objects are constructed by calling the method
    `netcdf_file.createVariable` on the `netcdf_file` object. `netcdf_variable`
    objects behave much like array objects defined in numpy, except that their
    data resides in a file. Data is read by indexing and written by assigning
    to an indexed subset; the entire array can be accessed by the index ``[:]``
    or (for scalars) by using the methods `getValue` and `assignValue`.
    `netcdf_variable` objects also have attribute `shape` with the same meaning
    as for arrays, but the shape cannot be modified. There is another read-only
    attribute `dimensions`, whose value is the tuple of dimension names.

    All other attributes correspond to variable attributes defined in
    the NetCDF file. Variable attributes are created by assigning to an
    attribute of the `netcdf_variable` object.

    Parameters
    ----------
    data : array_like
        The data array that holds the values for the variable.
        Typically, this is initialized as empty, but with the proper shape.
    typecode : dtype character code
        Desired data-type for the data array.
    size : int
        Desired element size for the data array.
    shape : sequence of ints
        The shape of the array. This should match the lengths of the
        variable's dimensions.
    dimensions : sequence of strings
        The names of the dimensions used by the variable. Must be in the
        same order of the dimension lengths given by `shape`.
    attributes : dict, optional
        Attribute values (any type) keyed by string names. These attributes
        become attributes for the netcdf_variable object.
    maskandscale : bool, optional
        Whether to automatically scale and/or mask data based on attributes.
        Default is False.


    Attributes
    ----------
    dimensions : list of str
        List of names of dimensions used by the variable object.
    isrec, shape
        Properties

    See also
    --------
    isrec, shape

    NFc           
      C   sP   || _ || _|| _|| _|| _|| _|p*i | _| j D ]\}}	|	| j|< q8d S rG   )	rp   	_typecode_sizer   r5   r4   r@   r   rJ   )
rB   rp   rn   ro   rm   r5   r   r4   r   r   rD   rD   rE   rF   ]  s    
znetcdf_variable.__init__c                 C   s0   z|| j |< W n ty    Y n0 || j|< d S rG   rH   rK   rD   rD   rE   rN   k  s
    znetcdf_variable.__setattr__c                 C   s   t | jjo| jd  S )aD  Returns whether the variable has a record dimension or not.

        A record dimension is a dimension along which additional data could be
        easily appended in the netcdf data structure without much rewriting of
        the data file. This attribute is a read-only property of the
        `netcdf_variable`.

        r   )boolrp   rm   r   rY   rD   rD   rE   r~   t  s    	znetcdf_variable.isrecc                 C   s   | j jS )zReturns the shape tuple of the data variable.

        This is a read-only attribute and can not be modified in the
        same manner of other numpy arrays.
        )rp   rm   rY   rD   rD   rE   rm     s    znetcdf_variable.shapec                 C   s
   | j  S )z
        Retrieve a scalar value from a `netcdf_variable` of length one.

        Raises
        ------
        ValueError
            If the netcdf variable is an array of length greater than one,
            this exception will be raised.

        )rp   itemrY   rD   rD   rE   getValue  s    znetcdf_variable.getValuec                 C   s$   | j jjstd|| j dd< dS )a  
        Assign a scalar value to a `netcdf_variable` of length one.

        Parameters
        ----------
        value : scalar
            Scalar value (of compatible type) to assign to a length-one netcdf
            variable. This value will be written to file.

        Raises
        ------
        ValueError
            If the input is not a scalar, or if the destination is not a length-one
            netcdf variable.

        zvariable is not writeableN)rp   flagsZ	writeableRuntimeErrorr   rD   rD   rE   assignValue  s    
znetcdf_variable.assignValuec                 C   s   | j S )z
        Return the typecode of the variable.

        Returns
        -------
        typecode : char
            The character typecode of the variable (e.g., 'i' for int).

        )r   rY   rD   rD   rE   rn     s    
znetcdf_variable.typecodec                 C   s   | j S )z
        Return the itemsize of the variable.

        Returns
        -------
        itemsize : int
            The element size of the variable (e.g., 8 for float64).

        )r   rY   rD   rD   rE   rk     s    
znetcdf_variable.itemsizec                 C   s   | j s| j| S | j|  }|  }| ||}| jd}| jd}|d usZ|d urf|tj	}|d urv|| }|d ur||7 }|S )Nscale_factor
add_offset)
r4   rp   r   _get_missing_value_apply_missing_valuer@   getr   r?   Zfloat64)rB   r   rp   missing_valuer   r   rD   rD   rE   __getitem__  s    
znetcdf_variable.__getitem__c                 C   sH  | j r|  pt|dd}| jd| | jd| || jdd | jdd }tj|	|}| j
d	vr|jjd
krt|}| jr:t|tr|d }n|}t|tr|jpdt| }n|d }|t| jkr:|f| jdd   }z| j| W n6 ty8   | jj}t| j||| jd< Y n0 || j|< d S )N
fill_valuei?B r   
_FillValuer   g        r   g      ?fdr   r   r   rp   )r4   r   getattrr@   
setdefaultr   r?   mar
   Zfilledr   r   kindroundr~   r   ri   slicestartr   rp   r   r   r+   r   rJ   )rB   r   rp   r   Z	rec_indexZrecsrm   r   rD   rD   rE   __setitem__  s6    




 znetcdf_variable.__setitem__c                 C   s   t |  |  f }t| S )zO
        The default encoded fill-value for this Variable's data type.
        )rl   rn   rk   FILLMAP)rB   r   rD   rD   rE   _default_encoded_fill_value  s    z+netcdf_variable._default_encoded_fill_valuec                 C   sP   d| j v rDtj| j d | jjd }t||  kr:|S |  S n|  S dS )z
        Returns the encoded fill value for this variable as bytes.

        This is taken from either the _FillValue attribute, or the default fill
        value for this variable's data type.
        r   r)   N)	r@   r?   r	   rp   r   rw   r   rk   r  )rB   r   rD   rD   rE   r     s    


z'netcdf_variable._get_encoded_fill_valuec                 C   s4   d| j v r| j d }nd| j v r,| j d }nd}|S )aw  
        Returns the value denoting "no data" for this variable.

        If this variable does not have a missing/fill value, returns None.

        If both _FillValue and missing_value are given, give precedence to
        _FillValue. The netCDF standard gives special meaning to _FillValue;
        missing_value is  just used for compatibility with old datasets.
        r   r   N)r@   )rB   r   rD   rD   rE   r     s    

z"netcdf_variable._get_missing_valuec              	   C   sb   |du r| }nPzt |}W n ttfy6   d}Y n0 |rHt | }n| |k}t j|| }|S )z
        Applies the given missing value to the data array.

        Returns a numpy.ma array, with any value equal to missing_value masked
        out (unless missing_value is None, in which case the original array is
        returned).
        NF)r?   isnanr   NotImplementedErrorr   Zmasked_where)rp   r   newdataZmissing_value_isnanZmymaskrD   rD   rE   r   )  s    

z$netcdf_variable._apply_missing_value)NF)r   r   r   r   rF   rN   r~   propertyrm   r   r   rn   rk   r   r  r  r   r   staticmethodr   rD   rD   rD   rE   r   (  s(   5  
	
").r   __all__rV   rS   operatorr   platformr   r=   r<   numpyr?   r   r   r   r	   r
   r   r   	functoolsr   r0   r   r   ZNC_BYTEr   ZNC_SHORTr   r   Z	NC_DOUBLEr   r   r   Z	FILL_BYTEZ	FILL_CHARZ
FILL_SHORTZFILL_INTZ
FILL_FLOATZFILL_DOUBLEr   r  rl   r   r   Z
NetCDFFileZNetCDFVariablerD   rD   rD   rE   <module>   s~   !
     K   