K iKddlmZddlZddlmZmZmZmZmZddl Z e jdk\rddlm Z nddl m Z ddl ZddlmZddlmZGddej(ZeeeeefZej2ej4d fej6ej4d fej8ej4d fej:ej4d fej<ej>d fej@ej>dfejBej>dfejDej>dfejFejHdfejJejHdfejLejHdfejNejPdfejRejTdfejVejTdfiZ,Gddej(Z-Gdde Z.Gdde Z/GddZ0Gdd e1Z2Gd!d"Z3y)#) annotationsN)AnyDictIterableOptionalTuple)) TypedDict)_PyArrowBufferc,eZdZdZdZdZdZdZdZdZ dZ y ) 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. rN) __name__ __module__ __qualname____doc__INTUINTFLOATBOOLSTRINGDATETIME CATEGORICAL`/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/pyarrow/interchange/column.pyrr(s,* C D E D FHKr!rcsilCSILefgbuUc$eZdZdZdZdZdZdZdZy)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. rrrr N) rrrr NON_NULLABLEUSE_NAN USE_SENTINEL USE_BITMASK USE_BYTEMASKr r!r"r2r2\s""LGLKLr!r2c,eZdZUded<ded<ded<y) ColumnBufferszTuple[_PyArrowBuffer, Dtype]dataz&Optional[Tuple[_PyArrowBuffer, Dtype]]validityoffsetsNrrr__annotations__r r!r"r:r:us '& 54 43r!r:c,eZdZUded<ded<ded<y)CategoricalDescriptionbool is_ordered is_dictionaryzOptional[_PyArrowColumn] categoriesNr>r r!r"rArAs)(r!rAc eZdZdZdZdZdZdZy) Endiannessz.Enum indicating the byte-order of a data-type.<>=|N)rrrrLITTLEBIGNATIVENAr r!r"rGrGs8 F C F Br!rGceZdZdZy)NoBufferPresentz6Exception to signal that there is no requested buffer.N)rrrrr r!r"rQrQs@r!rQceZdZdZ d ddZddZeddZeddZ ddZ eddZ eddZ edd Z edd Z dd Z d dd ZddZ ddZddZddZy )_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. cpt|tjr>|jdk(r|j d}n|s t d|j }||_tjj|jr\|s t d|j|jd|_ tj|tj|_y||_|j j} |j"}|j|||_ y#t$$rd}Y%wxYw)z; Handles PyArrow Arrays and ChunkedArrays. rrzUChunks 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) isinstancepa ChunkedArray num_chunkschunk RuntimeErrorcombine_chunks _allow_copytypes is_booleantype_dtype_from_arrowdtype_dtypepccastuint8_col bit_width ValueError)selfcolumn allow_copydtyperfs r"__init__z_PyArrowColumn.__init__s fboo .  A%a!&; ..0% 88  v{{ +"I55fkk1EDK 3DIDIIINNE !OO 55eYGDK    s D'' D54D5c,t|jS)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. )lenrerhs r"sizez_PyArrowColumn.sizes499~r!c.|jjS)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``. )reoffsetros r"rrz_PyArrowColumn.offsetsyyr!c|jS)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. )raros r"rkz_PyArrowColumn.dtypes<{{r!c`tjj|rUtj}|j d}|j r |j nd}d|d|}|||tjfStjj|r^tj}|j}|jj}tj|\} }|||tjfStj|d\}}|t!d|d|||tjfS)z/ See `self.dtype` for details. rts:)NNz Data type z& not supported by interchange protocol)rVr] is_timestamprrunittzrGrNrDrreindicesr__PYARROW_KINDSgetrg) rhrkrfkindrvrzf_stringarr indices_dtype_s r"r`z%_PyArrowColumn._dtype_from_arrowdtype(s 88  '%%DAB"XX2BB4q~HHj.?.?? ? XX # #E *((D))CKK,,M(,,];KAxHj.?.?? ?+//|DND(|  'MNPPHj.?.?? ?r!c|j}tjj|js t d|jjj dt|jdS)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)rCrDrE) rerVr]rDr_ TypeErrororderedrS dictionary)rhrs r"describe_categoricalz#_PyArrowColumn.describe_categoricalGsa.iixx%%chh/%  ))..00!(8  r!ch|jdk(rtjdfStjdfS)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. rN) null_countr2r4r7ros r" describe_nullz_PyArrowColumn.describe_nullks2 ??a !..4 4!--q0 0r!cH|jj}|dk7r|}|Sd}|S)z Number of null elements, if known. Note: Arrow uses -1 to indicate "unknown", but None seems cleaner. N)rer)rharrow_null_countns r"rz_PyArrowColumn.null_count}s3 99// 0B 6 =Ar!cy)zY The metadata for the column. See `DataFrame.metadata` for more details. Nr ros r"metadataz_PyArrowColumn.metadatas r!cy)zE Return the number of chunks the column consists of. rr ros r"rXz_PyArrowColumn.num_chunkssr!Nc# K|r|dkDr|j|z}|j|zdk7r|dz }|j}d}td||z|D]/}t|j |||j |dz }1y|yw)zz Return an iterator yielding the chunks. See `DataFrame.get_chunks` for details on ``n_chunks``. rrN)rprerangerSslicer\)rhn_chunks chunk_sizearrayr%starts r" get_chunksz_PyArrowColumn.get_chunkss 1 0Jyy{X%*a IIEAq*x"7D $KKz2D4D4DQ   JsB Bc|jddd} |j|d< |j|d<|S#t$rY!wxYw#t$rY|SwxYw)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)rhbufferss r" get_buffersz_PyArrowColumn.get_bufferss,))+"   "&";";"=GJ  !%!9!9!;GI        s ?A A  A  AAc|j}|j}tjj |j r!|j }t|j}t|j}|dk(rt|jd|fS|dk(rt|jd|fSy)zb Return the buffer containing the data and the buffer's associated dtype. rrr N) rerkrVr]rDr_r{rSrnrr )rhrrkrs r"rz_PyArrowColumn._get_data_buffers   88 ! !%** -MME"5)//E    6!%--/!"45u< < !V!%--/!"45u< <r!ctjddtjf}|j}|j d}|r t ||fStd)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. rr.rzB%H %HN   >@ @-0@ (@>! ! F11"  )-% !.%N= #=.1$=r!rS)4 __future__renumtypingrrrrrsys version_infor typing_extensionspyarrowrVpyarrow.computecomputerbpyarrow.interchange.bufferr IntEnumrrstrDtypeint8rint16int32int64rdruint16uint32uint64float16rfloat32float64bool_rstringr large_stringr|r2r:rArG ExceptionrQrSr r!r"rs$#  v +5 > ic3&' BGGI s# BHHJ$ BHHJ$ BHHJ$ BHHJ% BIIK)..#& BIIK)..#& BIIK)..#&BJJL9??C(BJJL9??C(BJJL9??C( BHHJ% BIIK)""C(BOO ((#.$T\\24I4")Y)  AiAs=s=r!