
    dJ                       d Z ddlmZ ddlZddlmZmZ ddlm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mZmZ ddlmZ dd	lmZ dd
lmZ e
reeedf         eeef         Zeedf         Z G d de           Z! G d d          Z" G d dej#                  Z$ G d dej#                  Z% G d dej#                  Z&dEdZ'dFdZ(dFd Z)dGdHd%Z*	 dGdId*Z+dJd0Z, G d1 d2e"          Z-dKd3Z.dLd8Z/ G d9 d:e"          Z0 G d; d<e"          Z1 G d= d>e"          Z2 G d? d@e"          Z3 G dA dBe"          Z4 G dC dDe"          Z5dS )Mz'Coders for individual Variable objects.    )annotationsN)HashableMutableMapping)partial)TYPE_CHECKINGAnyCallableUnion)dtypesduck_array_opsindexing)get_chunked_array_type)is_chunked_array)Variable.c                      e Zd ZdZdS )SerializationWarningz9Warnings about encoding/decoding issues in serialization.N)__name__
__module____qualname____doc__     7lib/python3.11/site-packages/xarray/coding/variables.pyr   r      s        CCCCr   r   c                  &    e Zd ZdZd
ddZd
dd	ZdS )VariableCodera  Base class for encoding and decoding transformations on variables.

    We use coders for transforming variables between xarray's data model and
    a format suitable for serialization. For example, coders apply CF
    conventions for how data should be represented in netCDF files.

    Subclasses should implement encode() and decode(), which should satisfy
    the identity ``coder.decode(coder.encode(variable)) == variable``. If any
    options are necessary, they should be implemented as arguments to the
    __init__ method.

    The optional name argument to encode() and decode() exists solely for the
    sake of better error messages, and should correspond to the name of
    variables in the underlying store.
    Nvariabler   nameT_Namereturnc                    t                      )z1Convert an encoded variable to a decoded variableNotImplementedErrorselfr   r   s      r   encodezVariableCoder.encode+       !###r   c                    t                      )z1Convert an decoded variable to a encoded variabler!   r#   s      r   decodezVariableCoder.decode/   r&   r   Nr   r   r   r   r   r   r   r   r   r   r%   r(   r   r   r   r   r      sP          $ $ $ $ $$ $ $ $ $ $ $r   r   c                  F    e Zd ZdZddZedd	            Zd
 Zd ZddZ	dS )_ElementwiseFunctionArrayzLazily computed array holding values of elemwise-function.

    Do not construct this object directly: call lazy_elemwise_func instead.

    Values are computed upon indexing or coercion to a NumPy array.
    funcr	   dtypenp.typing.DTypeLikec                v    t          |          rJ t          j        |          | _        || _        || _        d S r)   )r   r   as_indexablearrayr.   _dtype)r$   r3   r.   r/   s       r   __init__z"_ElementwiseFunctionArray.__init__<   s:    #E******511
	r   r   np.dtypec                4    t          j        | j                  S r)   )npr/   r4   r$   s    r   r/   z_ElementwiseFunctionArray.dtypeB   s    x$$$r   c                `     t          |           | j        |         | j        | j                  S r)   )typer3   r.   r/   r$   keys     r   __getitem__z%_ElementwiseFunctionArray.__getitem__F   s&    tDzz$*S/49djAAAr   c                Z    |                      | j                                                  S r)   )r.   r3   get_duck_arrayr9   s    r   r@   z(_ElementwiseFunctionArray.get_duck_arrayI   s"    yy2244555r   strc                t    d                     t          |           j        | j        | j        | j                  S )Nz{}({!r}, func={!r}, dtype={!r}))formatr;   r   r3   r.   r/   r9   s    r   __repr__z"_ElementwiseFunctionArray.__repr__L   s2    077JJTY

 
 	
r   Nr.   r	   r/   r0   r   r6   )r   rA   )
r   r   r   r   r5   propertyr/   r>   r@   rD   r   r   r   r-   r-   4   s             % % % X%B B B6 6 6
 
 
 
 
 
r   r-   c                  >    e Zd ZdZdZddZedd            Zdd	Zd
S )NativeEndiannessArraya  Decode arrays on the fly from non-native to native endianness

    This is useful for decoding arrays from netCDF3 files (which are all
    big endian) into native endianness, so they can be used with Cython
    functions, such as those found in bottleneck and pandas.

    >>> x = np.arange(5, dtype=">i2")

    >>> x.dtype
    dtype('>i2')

    >>> NativeEndiannessArray(x).dtype
    dtype('int16')

    >>> indexer = indexing.BasicIndexer((slice(None),))
    >>> NativeEndiannessArray(x)[indexer].dtype
    dtype('int16')
    r3   r   Nonec                8    t          j        |          | _        d S r)   r   r2   r3   r$   r3   s     r   r5   zNativeEndiannessArray.__init__h       *511


r   r6   c                    t          j        | j        j        j        t	          | j        j        j                  z             S r)   )r8   r/   r3   kindrA   itemsizer9   s    r   r/   zNativeEndiannessArray.dtypek   s/    x
(-DJ4D4M0N0NNOOOr   
np.ndarrayc                N    t          j        | j        |         | j                  S Nr/   r8   asarrayr3   r/   r<   s     r   r>   z!NativeEndiannessArray.__getitem__o       z$*S/<<<<r   Nr   rK   rF   r   rS   	r   r   r   r   	__slots__r5   rG   r/   r>   r   r   r   rI   rI   R   sq         & I2 2 2 2 P P P XP= = = = = =r   rI   c                  >    e Zd ZdZdZddZedd            Zdd	Zd
S )BoolTypeArraya  Decode arrays on the fly from integer to boolean datatype

    This is useful for decoding boolean arrays from integer typed netCDF
    variables.

    >>> x = np.array([1, 0, 1, 1, 0], dtype="i1")

    >>> x.dtype
    dtype('int8')

    >>> BoolTypeArray(x).dtype
    dtype('bool')

    >>> indexer = indexing.BasicIndexer((slice(None),))
    >>> BoolTypeArray(x)[indexer].dtype
    dtype('bool')
    rJ   r   rK   c                8    t          j        |          | _        d S r)   rM   rN   s     r   r5   zBoolTypeArray.__init__   rO   r   r6   c                *    t          j        d          S )Nbool)r8   r/   r9   s    r   r/   zBoolTypeArray.dtype   s    xr   rS   c                N    t          j        | j        |         | j                  S rU   rW   r<   s     r   r>   zBoolTypeArray.__getitem__   rY   r   NrZ   rF   r[   r\   r   r   r   r_   r_   s   sm         $ I2 2 2 2       X = = = = = =r   r_   r.   r	   r/   r0   c                    t          |           r't          |           }|                    || |          S t          | ||          S )a  Lazily apply an element-wise function to an array.
    Parameters
    ----------
    array : any valid value of Variable._data
    func : callable
        Function to apply to indexed slices of an array. For use with dask,
        this should be a pickle-able object.
    dtype : coercible to np.dtype
        Dtype for the result of this function.

    Returns
    -------
    Either a dask.array.Array or _ElementwiseFunctionArray.
    rV   )r   r   
map_blocksr-   )r3   r.   r/   chunkmanagers       r   lazy_elemwise_funcrg      sN      =-e44&&tU%&@@@(e<<<r   varr   r   
T_VarTuplec                ~    | j         | j        | j                                        | j                                        fS r)   )dimsdataattrscopyencodingrh   s    r   unpack_for_encodingrq      s/    8SXsy~~//1B1B1D1DDDr   c                ~    | j         | j        | j                                        | j                                        fS r)   )rk   _datarm   rn   ro   rp   s    r   unpack_for_decodingrt      s/    8SY	 0 0#,2C2C2E2EEEr   r=   r   r   r   c                p    || v r,|rd|nd}t          d                    ||                    || |<   d S )Nz on variable  zfailed to prevent overwriting existing key {} in attrs{}. This is probably an encoding field used by xarray to describe how a variable is serialized. To proceed, remove this key from the variable's attributes manually.)
ValueErrorrC   )destr=   valuer   var_strs        r   safe_setitemr{      sZ    
d{{.2:*$***2 39&g2F2F	
 
 	
 DIIIr   sourcer   rx   r   c                \    |                      |d          }|t          ||||           |S )z
    A convenience function which pops a key k from source to dest.
    None values are not passed on.  If k already exists in dest an
    error is raised.
    Nr   )popr{   )r|   rx   r=   r   ry   s        r   pop_tor      s9     JJsD!!ET3D1111Lr   rl   rS   encoded_fill_valueslistdecoded_fill_valuec                z    t          j        | |          } d}|D ]}|| |k    z  }t          j        |||           S )z+Mask all matching values in a NumPy arrays.rV   F)r8   rX   where)rl   r   r   r/   	conditionfvs         r   _apply_maskr      sQ     :d%(((DI!    TRZ		8I14888r   c                  &    e Zd ZdZd	d
dZd	d
dZdS )CFMaskCoderz7Mask or unmask fill values according to CF conventions.Nr   r   r   r   c           	        t          |          \  }}}}t          j        |                    d|j                            }|                    d          }|                    d          }	|d u}
|	d u}|
s|s|S |
r0|r.t	          j        ||	          st          d|d| d|	 d          |
rT|                    |          |d<   t          ||d|          }t          j
        |          st	          j        ||          }|rV|                    |	          |d<   t          ||d|          }t          j
        |          s|
st	          j        ||          }t          ||||d	
          S )Nr/   
_FillValuemissing_valuez	Variable z has conflicting _FillValue (z) and missing_value (z). Cannot encode data.r~   Tfastpath)rq   r8   r/   getr   allclose_or_equivrw   r;   r   pdisnullfillnar   )r$   r   r   rk   rl   rm   ro   r/   r   mv	fv_exists	mv_exists
fill_values                r   r%   zCFMaskCoder.encode   s   &9(&C&C#dE8gtz::;;\\,''\\/**dN	dN	 	 	O 	 	>+KBPR+S+S 	tDttttZ\ttt    	?%*ZZ^^H\"%DIIIJ9Z(( ?%,T:>> 	?(-

2H_%%tLLLJ9Z(( ? ?%,T:>>dE8dCCCCr   c                  
 t          |          \  }}

fddD             }|rd |D             }t          |          dk    r0t          j        d                    |          t
          d           t          j        |j                  \  }}|r)t          t          |||          }	t          ||	|          }t          ||
d	
          S |S )Nc                6    g | ]}t          |           S )r~   )r   ).0attrrm   ro   r   s     r   
<listcomp>z&CFMaskCoder.decode.<locals>.<listcomp>  s:     
 
 
 5(Dt444
 
 
r   )r   r   c                h    h | ]/}t          j        |          D ]}t          j        |          |0S r   )r8   ravelr   r   )r   optionr   s      r   	<setcomp>z%CFMaskCoder.decode.<locals>.<setcomp>  sW     # # #(6**# # y}}	## # # #r      zFvariable {!r} has multiple fill values {}, decoding all values to NaN.   
stacklevel)r   r   r/   Tr   )rt   lenwarningswarnrC   r   r   maybe_promoter/   r   r   rg   r   )r$   r   r   rk   rl   raw_fill_valuesr   r/   r   	transformrm   ro   s     `       @@r   r(   zCFMaskCoder.decode   s4   &9(&C&C#dE8
 
 
 
 
 
7
 
 
  	# #-# # # &''!++228&?R2S2S( 	    )/(<TZ(H(H%E%" B#(;'9	  	 *$	5AAD$x$GGGGOr   r)   )r   r   r   r   r+   r   r   r   r   r      sR        AA D  D  D  D  DD$ $ $ $ $ $ $r   r   c                P    |                      |d          } || |z  } || |z  } | S )NTr/   rn   )astype)rl   scale_factor
add_offsetr/   s       r   _scale_offset_decodingr   &  s<    ;;U;..D
Kr   r6   
has_offsetrb   type[np.floating[Any]]c                    | j         dk    r+t          j        | t          j                  rt          j        S | j         dk    r-t          j        | t          j                  r|st          j        S t          j        S )zBReturn a float dtype that can losslessly represent `dtype` values.      )rR   r8   
issubdtypefloatingfloat32integerfloat64)r/   r   s     r   _choose_float_dtyper   /  sh     ~r}UBK@@z~r}UBJ??
  	: :r   c                  &    e Zd ZdZd
ddZd
dd	ZdS )CFScaleOffsetCoderzScale and offset variables according to CF conventions.

    Follows the formula:
        decode_values = encoded_values * scale_factor + add_offset
    Nr   r   r   r   r   c                &   t          |          \  }}}}d|v sd|v r.t          |j        d|v           }t          j        ||d          }d|v r|t          ||d|          z  }d|v r|t          ||d|          z  }t          ||||d          S )Nr   r   Tr   r~   r   )rq   r   r/   r   r   r   r   r$   r   r   rk   rl   rm   ro   r/   s           r   r%   zCFScaleOffsetCoder.encodeI  s    &9(&C&C#dE8X%%)A)A'
LH4LMME!(UFFFD8##F8ULtDDDDDX%%F8UNFFFFDdE8dCCCCr   c                :   |j         }d|v sd|v r
t          |          \  }}}}t          ||d|          }t          ||d|          }	t          |j        d|v           }
t          j        |          dk    r&t          j        |                                          }t          j        |	          dk    r&t          j        |	                                          }	t          t          ||	|
          }t          |||
          }t          ||||d          S |S )Nr   r   r~   r   )r   r   r/   Tr   )rm   rt   r   r   r/   r8   ndimrX   itemr   r   rg   r   )r$   r   r   _attrsrk   rl   rm   ro   r   r   r/   r   s               r   r(   zCFScaleOffsetCoder.decodeV  s'   V##|v'='=*=h*G*G'D$x!%>MMMLxDIIIJ'
LH4LMMEw|$$q((!z,77<<>>wz""Q&&Z
3388::
&)%	  I &dIu==DD$x$GGGGOr   r)   r*   r+   r   r   r   r   r   B  sU         D D D D D      r   r   c                  "    e Zd Zd	d
dZd	d
dZdS )UnsignedIntegerCoderNr   r   r   r   r   c                   |j                             dd          dk    rt          |          \  }}}}t          ||d           t	          j        d|j        j                   }d|v r |                    |d                   }||d<   t          j	        t          j
        |          |          }t          ||||d          S |S )N	_Unsignedfalsetrueir   Tr   )ro   r   rq   r   r8   r/   rR   r;   r   r   aroundr   )	r$   r   r   rk   rl   rm   ro   signed_dtypenew_fills	            r   r%   zUnsignedIntegerCoder.encodep  s    
   g66&@@*=h*G*G'D$x8UK0008$=
(;$=$=>>Lu$$',,U<-@AA&.l#!()>t)D)DlSSDD$x$GGGGOr   c                   d|j         v rit          |          \  }}}}t          ||d          }|j        j        dk    rx|dk    rqt          j        d|j        j                   }t          t
          j        |          }	t          ||	|          }d|v r |
                    |d                   }
|
|d<   n|j        j        dk    rx|dk    rqt          j        d|j        j                   }t          t
          j        |          }	t          ||	|          }d|v r |
                    |d                   }
|
|d<   n t          j        d|d	t          d
           t          ||||d          S |S )Nr   r   r   urV   r   r   z	variable zH has _Unsigned attribute but is not of integer type. Ignoring attribute.r   r   Tr   )rm   rt   r   r/   rQ   r8   rR   r   rX   rg   r;   r   r   r   r   )r$   r   r   rk   rl   rm   ro   unsignedunsigned_dtyper   r   r   s               r   r(   zUnsignedIntegerCoder.decode  s   (.((*=h*G*G'D$xeX{;;Hz#%%v%%%'X.G$*2E.G.G%H%HN '
. I I II-dI~NND#u,,#1#6#6u\7J#K#K.6l+C''w&&#%8,E
0C,E,E#F#FL '
, G G GI-dI|LLD#u,,#/#4#4U<5H#I#I.6l+; ; ; ;( 	    D$x$GGGGOr   r)   r*   )r   r   r   r%   r(   r   r   r   r   r   o  sF            &             r   r   c                  &    e Zd ZdZd
ddZd
dd	ZdS )DefaultFillvalueCoderz$Encode default _FillValue if needed.Nr   r   r   r   r   c                    t          |          \  }}}}d|vrcd|vr_t          j        |j        t          j                  r;|j                            t          j                  |d<   t          ||||d          S |S )Nr   Tr   )rq   r8   r   r/   r   r;   nanr   r$   r   r   rk   rl   rm   ro   s          r   r%   zDefaultFillvalueCoder.encode  s    &9(&C&C#dE8 %%H,,hnbk:: - #+."5"5bf"="=E,D$x$GGGGOr   c                    t                      r)   r!   r#   s      r   r(   zDefaultFillvalueCoder.decode      !###r   r)   r*   r+   r   r   r   r   r     sL        ..    $ $ $ $ $ $ $r   r   c                  &    e Zd ZdZd
ddZd
dd	ZdS )BooleanCoderzCode boolean values.Nr   r   r   r   r   c                    |j         t          k    rVd|j        vrMd|j        vrDt	          |          \  }}}}d|d<   t          j        |dd          }t          ||||d          S |S )Nr/   rb   i1Tr   r   )r/   rb   ro   rm   rq   r   r   r   r   s          r   r%   zBooleanCoder.encode  s~    ^t## 111..*=h*G*G'D$x#E'N!(TEEEDD$x$GGGGOr   c                    |j                             dd          dk    rOt          |          \  }}}}|                    d          |d<   t	          |          }t          ||||d          S |S )Nr/   Frb   Tr   )rm   r   rt   r   r_   r   r   s          r   r(   zBooleanCoder.decode  sx    >gu--77*=h*G*G'D$x !&		' 2 2HW &&DD$x$GGGGOr   r)   r*   r+   r   r   r   r   r     sL            	 	 	 	 	 	 	r   r   c                  "    e Zd ZdZd Zd
dd	ZdS )EndianCoderzDecode Endianness to native.c                    t                      r)   r!   r9   s    r   r%   zEndianCoder.encode  r   r   Nr   r   r   r   r   c                    t          |          \  }}}}|j        j        s#t          |          }t	          ||||d          S |S )NTr   )rt   r/   isnativerI   r   r   s          r   r(   zEndianCoder.decode  sP    &9(&C&C#dE8z" 	(..DD$x$GGGGOr   r)   r*   r+   r   r   r   r   r     sB        &&$ $ $      r   r   c                  "    e Zd ZdZd
ddZd	 ZdS )NonStringCoderz,Encode NonString variables if dtypes differ.Nr   r   r   r   r   c                8   d|j         v r|j         d         dt          fvrt          |          \  }}}}t          j        |                    d                    }||j        k    rt          j        |t          j                  rjt          j        |j        t          j                  r2d|j	        vr)d|j	        vr t          j        d| dt          d           t          j        |          }|                    |	          }t          ||||d
          S |S )Nr/   S1r   r   zsaving variable zT with floating point data as an integer dtype without any _FillValue to use for NaNs
   r   rV   Tr   )ro   rA   rq   r8   r/   r   r   r   r   rm   r   r   r   r   r   r   r   s           r   r%   zNonStringCoder.encode  s/   h'''H,=g,FO
 -
 -
 +>h*G*G'D$xHX\\'2233E&&=
33 +hnbkBB(>>+8>AA =t = = = 1')    9T??D{{{//D$x$GGGGOr   c                    t                      r)   r!   r9   s    r   r(   zNonStringCoder.decode  r   r   r)   r*   r+   r   r   r   r   r     sB        66    6$ $ $ $ $r   r   rE   )rh   r   r   ri   r)   )r=   r   r   r   )
r|   r   rx   r   r=   r   r   r   r   r   )
rl   rS   r   r   r   r   r/   r0   r   rS   )r/   r0   )r/   r6   r   rb   r   r   )6r   
__future__r   r   collections.abcr   r   	functoolsr   typingr   r   r	   r
   numpyr8   pandasr   xarray.corer   r   r   xarray.core.parallelcompatr   xarray.core.pycompatr   xarray.core.variabler   tupledictri   r   RuntimeWarningr   r   ExplicitlyIndexedNDArrayMixinr-   rI   r_   rg   rq   rt   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   <module>r      s   - - " " " " " "  4 4 4 4 4 4 4 4       6 6 6 6 6 6 6 6 6 6 6 6         8 8 8 8 8 8 8 8 8 8 = = = = = = 1 1 1 1 1 1 ) ) ) ) ) ) #uXs]+S$<=J8T>"FD D D D D> D D D$ $ $ $ $ $ $ $4
 
 
 
 
 F 
 
 
<= = = = =HB = = =B= = = = =H: = = =@= = = =.E E E EF F F F	 	 	 	 	 QU    9 9 9 9I I I I I- I I IX      &* * * * * * * *Z4 4 4 4 4= 4 4 4n$ $ $ $ $M $ $ $(    =   :    -   $ $ $ $ $] $ $ $ $ $r   