
    z-PhK                       d dl mZ d dlZd dlmZmZmZmZmZ d dl	Z	e	j
        dk    rd dlmZ nd dlmZ d dlZd dlmZ d dlmZ  G d dej                  Zeeeeef         Z ej                    ej        d	f ej                    ej        d
f ej                    ej        df ej                    ej        df ej                    ej        df ej                     ej        df ej!                    ej        df ej"                    ej        df ej#                    ej$        df ej%                    ej$        df ej&                    ej$        df ej'                    ej(        df ej)                    ej*        df ej+                    ej*        dfiZ, G d dej                  Z- G d de          Z. G d de          Z/ G d d          Z0 G d d e1          Z2 G d! d"          Z3dS )#    )annotationsN)AnyDictIterableOptionalTuple)      )	TypedDict)_PyArrowBufferc                  .    e Zd ZdZdZdZdZdZdZdZ	dZ
d	S )
	DtypeKinda  
    Integer enum for data types.

    Attributes
    ----------
    INT : int
        Matches to signed integer data type.
    UINT : int
        Matches to unsigned integer data type.
    FLOAT : int
        Matches to floating point data type.
    BOOL : int
        Matches to boolean data type.
    STRING : int
        Matches to string data type (UTF-8 encoded).
    DATETIME : int
        Matches to datetime data type.
    CATEGORICAL : int
        Matches to categorical data type.
    r                     N)__name__
__module____qualname____doc__INTUINTFLOATBOOLSTRINGDATETIMECATEGORICAL     Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/pyarrow/interchange/column.pyr   r   (   s=         * CDEDFHKKKr!   r   csilCSILefgbuUc                  &    e Zd ZdZdZdZdZdZdZdS )ColumnNullTypea  
    Integer enum for null type representation.

    Attributes
    ----------
    NON_NULLABLE : int
        Non-nullable column.
    USE_NAN : int
        Use explicit float NaN value.
    USE_SENTINEL : int
        Sentinel value besides NaN.
    USE_BITMASK : int
        The bit is set/unset representing a null on a certain position.
    USE_BYTEMASK : int
        The byte is set/unset representing a null on a certain position.
    r   r   r   r	      N)	r   r   r   r   NON_NULLABLEUSE_NANUSE_SENTINELUSE_BITMASKUSE_BYTEMASKr    r!   r"   r2   r2   \   s3         " LGLKLLLr!   r2   c                  .    e Zd ZU ded<   ded<   ded<   dS )ColumnBufferszTuple[_PyArrowBuffer, Dtype]dataz&Optional[Tuple[_PyArrowBuffer, Dtype]]validityoffsetsNr   r   r   __annotations__r    r!   r"   r:   r:   u   s<          '&&&
 5444 433333r!   r:   c                  .    e Zd ZU ded<   ded<   ded<   dS )CategoricalDescriptionbool
is_orderedis_dictionaryzOptional[_PyArrowColumn]
categoriesNr>   r    r!   r"   rA   rA      s:           )(((((r!   rA   c                  "    e Zd ZdZdZdZdZdZdS )
Endiannessz.Enum indicating the byte-order of a data-type.<>=|N)r   r   r   r   LITTLEBIGNATIVENAr    r!   r"   rG   rG      s(        88F
CF	BBBr!   rG   c                      e Zd ZdZdS )NoBufferPresentz6Exception to signal that there is no requested buffer.N)r   r   r   r   r    r!   r"   rQ   rQ      s        @@@@r!   rQ   c                      e Zd ZdZ	 d&d'd	Zd(dZed(d            Zed)d            Zd*dZ	ed+d            Z
ed,d            Zed(d            Zed-d            Zd(dZ	 d.d/dZd0d!Zd1d#Zd1d$Zd1d%ZdS )2_PyArrowColumna  
    A column object, with only the methods and properties required by the
    interchange protocol defined.

    A column can contain one or more chunks. Each chunk can contain up to three
    buffers - a data buffer, a mask buffer (depending on null representation),
    and an offsets buffer (if variable-size binary; e.g., variable-length
    strings).

    TBD: Arrow has a separate "null" dtype, and has no separate mask concept.
         Instead, it seems to use "children" for both columns with a bit mask,
         and for nested dtypes. Unclear whether this is elegant or confusing.
         This design requires checking the null representation explicitly.

         The Arrow design requires checking:
         1. the ARROW_FLAG_NULLABLE (for sentinel values)
         2. if a column has two children, combined with one of those children
            having a null dtype.

         Making the mask concept explicit seems useful. One null dtype would
         not be enough to cover both bit and byte masks, so that would mean
         even more checking if we did it the Arrow way.

    TBD: there's also the "chunk" concept here, which is implicit in Arrow as
         multiple buffers per array (= column here). Semantically it may make
         sense to have both: chunks were meant for example for lazy evaluation
         of data which doesn't fit in memory, while multiple buffers per column
         could also come from doing a selection operation on a single
         contiguous buffer.

         Given these concepts, one would expect chunks to be all of the same
         size (say a 10,000 row dataframe could have 10 chunks of 1,000 rows),
         while multiple buffers could have data-dependent lengths. Not an issue
         in pandas if one column is backed by a single NumPy array, but in
         Arrow it seems possible.
         Are multiple chunks *and* multiple buffers per column necessary for
         the purposes of this interchange protocol, or must producers either
         reuse the chunk concept for this or copy the data?

    Note: this Column object can only be produced by ``__dataframe__``, so
          doesn't need its own version or ``__column__`` protocol.
    Tcolumnpa.Array | pa.ChunkedArray
allow_copyrB   returnNonec                j   t          |t          j                  rF|j        dk    r|                    d          }n%|st          d          |                                }|| _        t          j        	                    |j
                  r^|st          d          |                     |j
        d          | _        t          j        |t          j                              | _        dS || _        | j        j
        }	 |j        }n# t$          $ r d}Y nw xY w|                     ||          | _        dS )z;
        Handles PyArrow Arrays and ChunkedArrays.
        r   r   zUChunks will be combined and a copy is required which is forbidden by allow_copy=FalsezdBoolean column will be casted to uint8 and a copy is required which is forbidden by allow_copy=Falser
   N)
isinstancepaChunkedArray
num_chunkschunkRuntimeErrorcombine_chunks_allow_copytypes
is_booleantype_dtype_from_arrowdtype_dtypepccastuint8_col	bit_width
ValueError)selfrT   rV   dtyperk   s        r"   __init__z_PyArrowColumn.__init__   sE    fbo.. 		1 A%%a! &;    ..00%8v{++ 	H "I   55fk1EEDK

33DIIIDIINE!O		    			 55eYGGDKKKs   >D DDintc                *    t          | j                  S )aF  
        Size of the column, in elements.

        Corresponds to DataFrame.num_rows() if column is a single chunk;
        equal to size of this current chunk otherwise.

        Is a method rather than a property because it may cause a (potentially
        expensive) computation for some dataframe implementations.
        )lenrj   rm   s    r"   sizez_PyArrowColumn.size   s     49~~r!   c                    | j         j        S )z
        Offset of first element.

        May be > 0 if using chunks; for example for a column with N chunks of
        equal size M (only the last chunk may be shorter),
        ``offset = n * M``, ``n = 0 .. N-1``.
        )rj   offsetrs   s    r"   rv   z_PyArrowColumn.offset   s     yr!   Tuple[DtypeKind, int, str, str]c                    | j         S )a  
        Dtype description as a tuple ``(kind, bit-width, format string,
        endianness)``.

        Bit-width : the number of bits as an integer
        Format string : data type description format string in Apache Arrow C
                        Data Interface format.
        Endianness : current only native endianness (``=``) is supported

        Notes:
            - Kind specifiers are aligned with DLPack where possible (hence the
              jump to 20, leave enough room for future extension)
            - Masks must be specified as boolean with either bit width 1 (for
              bit masks) or 8 (for byte masks).
            - Dtype width in bits was preferred over bytes
            - Endianness isn't too useful, but included now in case in the
              future we need to support non-native endianness
            - Went with Apache Arrow format strings over NumPy format strings
              because they're more complete from a dataframe perspective
            - Format strings are mostly useful for datetime specification, and
              for categoricals.
            - For categoricals, the format string describes the type of the
              categorical in the data buffer. In case of a separate encoding of
              the categorical (e.g. an integer to string mapping), this can
              be derived from ``self.describe_categorical``.
            - Data types not included: complex, Arrow-style null, binary,
              decimal, and nested (list, struct, map, union) dtypes.
        )rf   rs   s    r"   rn   z_PyArrowColumn.dtype  s    < {r!   rn   pa.DataTyperk   c                <   t           j                            |          rPt          j        }|j        d         }|j        r|j        nd}d                    ||          }|||t          j	        fS t           j        
                    |          rLt          j        }| j        }|j        j        }t                              |          \  }	}|||t          j	        fS t                              |d          \  }}|t#          d| d          |||t          j	        fS )	z/
        See `self.dtype` for details.
        r    zts{ts}:{tz})tstz)NNNz
Data type z& not supported by interchange protocol)r[   rb   is_timestampr   r   unitr}   formatrG   rN   rD   r   rj   indicesrd   _PYARROW_KINDSgetrl   )
rm   rn   rk   kindr|   r}   f_stringarrindices_dtype_s
             r"   re   z%_PyArrowColumn._dtype_from_arrowdtype(  s    8  '' 	@%DAB"X-2B$++rb+99HHj.???X##E** 	@(D)CK,M(,,];;KAxHj.???+//|DDND(| NNNNP P P Hj.???r!   rA   c                    | j         }t          j                            |j                  st          d          | j         j        j        dt          |j                  dS )a  
        If the dtype is categorical, there are two options:
        - There are only values in the data buffer.
        - There is a separate non-categorical Column encoding categorical
          values.

        Raises TypeError if the dtype is not categorical

        Returns the dictionary with description on how to interpret the
        data buffer:
            - "is_ordered" : bool, whether the ordering of dictionary indices
                             is semantically meaningful.
            - "is_dictionary" : bool, whether a mapping of
                                categorical values to other objects exists
            - "categories" : Column representing the (implicit) mapping of
                             indices to category values (e.g. an array of
                             cat1, cat2, ...). None if not a dictionary-style
                             categorical.

        TBD: are there any other in-memory representations that are needed?
        zCdescribe_categorical only works on a column with categorical dtype!T)rC   rD   rE   )	rj   r[   rb   rD   rd   	TypeErrororderedrS   
dictionary)rm   r   s     r"   describe_categoricalz#_PyArrowColumn.describe_categoricalG  sg    . ix%%ch// 	%   ).0!(88
 
 	
r!   Tuple[ColumnNullType, Any]c                P    | j         dk    rt          j        dfS t          j        dfS )a7  
        Return the missing value (or "null") representation the column dtype
        uses, as a tuple ``(kind, value)``.

        Value : if kind is "sentinel value", the actual value. If kind is a bit
        mask or a byte mask, the value (0 or 1) indicating a missing value.
        None otherwise.
        r   N)
null_countr2   r4   r7   rs   s    r"   describe_nullz_PyArrowColumn.describe_nullk  s-     ?a!.44!-q00r!   c                2    | j         j        }|dk    r|nd}|S )z
        Number of null elements, if known.

        Note: Arrow uses -1 to indicate "unknown", but None seems cleaner.
        N)rj   r   )rm   arrow_null_countns      r"   r   z_PyArrowColumn.null_count}  s)      9/ 0B 6 6Dr!   Dict[str, Any]c                    dS )zY
        The metadata for the column. See `DataFrame.metadata` for more details.
        Nr    rs   s    r"   metadataz_PyArrowColumn.metadata  s	    
 	r!   c                    dS )zE
        Return the number of chunks the column consists of.
        r   r    rs   s    r"   r]   z_PyArrowColumn.num_chunks  s	     qr!   Nn_chunksOptional[int]Iterable[_PyArrowColumn]c              #  4  K   |r|dk    r|                                  |z  }|                                  |z  dk    r|dz  }| j        }d}t          d||z  |          D ]2}t          |                    ||          | j                  V  |dz  }3dS | V  dS )zz
        Return an iterator yielding the chunks.

        See `DataFrame.get_chunks` for details on ``n_chunks``.
        r   r   N)rt   rj   rangerS   slicera   )rm   r   
chunk_sizearrayr%   starts         r"   
get_chunksz_PyArrowColumn.get_chunks  s        	10Jyy{{X%**a
IEAq*x"7DD  $KKz22D4D     Q	  JJJJJr!   r:   c                    |                                  ddd}	 |                                 |d<   n# t          $ r Y nw xY w	 |                                 |d<   n# t          $ r Y nw xY w|S )ab  
        Return a dictionary containing the underlying buffers.

        The returned dictionary has the following contents:

            - "data": a two-element tuple whose first element is a buffer
                      containing the data and whose second element is the data
                      buffer's associated dtype.
            - "validity": a two-element tuple whose first element is a buffer
                          containing mask values indicating missing data and
                          whose second element is the mask value buffer's
                          associated dtype. None if the null representation is
                          not a bit or byte mask.
            - "offsets": a two-element tuple whose first element is a buffer
                         containing the offset values for variable-size binary
                         data (e.g., variable-length strings) and whose second
                         element is the offsets buffer's associated dtype. None
                         if the data buffer does not have an associated offsets
                         buffer.
        N)r;   r<   r=   r<   r=   )_get_data_buffer_get_validity_bufferrQ   _get_offsets_buffer)rm   bufferss     r"   get_buffersz_PyArrowColumn.get_buffers  s    , ))++"
 "
	"&";";"="=GJ 	 	 	D		!%!9!9!;!;GI 	 	 	D	 s   2 
??A 
A('A(Tuple[_PyArrowBuffer, Any]c                   | j         }| j        }t          j                            |j                  r|j        }t          |          j        }t          |	                                          }|dk    r)t          |	                                d                   |fS |dk    r)t          |	                                d                   |fS dS )zb
        Return the buffer containing the data and the buffer's
        associated dtype.
        r   r   r	   N)rj   rn   r[   rb   rD   rd   r   rS   rr   r   r   )rm   r   rn   r   s       r"   r   z_PyArrowColumn._get_data_buffer  s     	

 8!!%*-- 	0ME"5))/E  66!%--//!"455u<<!VV!%--//!"455u<< Vr!   c                    t           j        ddt          j        f}| j        }|                                d         }|rt          |          |fS t          d          )z
        Return the buffer containing the mask values indicating missing data
        and the buffer's associated dtype.
        Raises NoBufferPresent if null representation is not a bit or byte
        mask.
        r   r.   r   z<There are no missing values so does not have a separate mask)r   r   rG   rN   rj   r   r   rQ   )rm   rn   r   buffs       r"   r   z#_PyArrowColumn._get_validity_buffer  sb     C):;	}}q! 	1!$''..!01 1 1r!   c                   | j         }t          |                                          }|dk    rt          d          |dk    r| j         j        }t
          j                            |          rt          j	        ddt          j        f}nt          j	        ddt          j        f}t          |                                d                   |fS d	S )
a  
        Return the buffer containing the offset values for variable-size binary
        data (e.g., variable-length strings) and the buffer's associated dtype.
        Raises NoBufferPresent if the data buffer does not have an associated
        offsets buffer.
        r   zJThis column has a fixed-length dtype so it does not have an offsets bufferr	   @   r&       r%   r   N)rj   rr   r   rQ   rd   r[   rb   is_large_stringr   r   rG   rN   r   )rm   r   r   rn   s       r"   r   z"_PyArrowColumn._get_offsets_buffer  s     	  66!5   !VVINEx''.. D"C1BC"C1BC!%--//!"455u<< Vr!   )T)rT   rU   rV   rB   rW   rX   )rW   rp   )rW   rw   )rn   ry   rk   rp   rW   rw   )rW   rA   )rW   r   )rW   r   )N)r   r   rW   r   )rW   r:   )rW   r   )r   r   r   r   ro   rt   propertyrv   rn   re   r   r   r   r   r]   r   r   r   r   r   r    r!   r"   rS   rS      s       ) )X FJ%H %H %H %H %HN
 
 
 
       X     X>@ @ @ @> !
 !
 !
 X!
F 1 1 1 X1"    X    X    )-    .% % % %N= = = =.1 1 1 1$= = = = = =r!   rS   )4
__future__r   enumtypingr   r   r   r   r   sysversion_infor   typing_extensionspyarrowr[   pyarrow.computecomputerg   pyarrow.interchange.bufferr   IntEnumr   rp   strDtypeint8r   int16int32int64ri   r   uint16uint32uint64float16r   float32float64bool_r   stringr   large_stringr   r2   r:   rA   rG   	ExceptionrQ   rS   r    r!   r"   <module>r      sT  $ # " " " " "               


v       ++++++           5 5 5 5 5 5       > 	ic3&' BGII	s#BHJJ$BHJJ$BHJJ$BHJJ%BIKK).#&BIKK).#&BIKK).#&BJLL9?C(BJLL9?C(BJLL9?C(BHJJ%BIKK)"C(BO	(#.$    T\   24 4 4 4 4I 4 4 4") ) ) ) )Y ) ) )       A A A A Ai A A As= s= s= s= s= s= s= s= s= s=r!   