
    2VhC                        d dl Z d dlZd dlZd dlmZ d dlmZ d dlmZ d dl	m
Z 	 d dlZej                  fZereej                   ej"                  fz   Z G d d      Z G d d	e      Z G d
 de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z G d de      Z e j:                  dg d      Zd Zd Z d  Z!d#d!Z"d" Z#y# e$ r dZY w xY w)$    N)backend)tree)data_adapter_utils
tensorflowc                   l    e Zd ZdZd Zd Zed        Zed        Zed        Z	ed        Z
ed        Zy	)
	Sliceableaa  `Sliceable` wrapping a tensor.

    A `Sliceable` implements the subscript operator to slice or index against
    the first dimension of the array. It also has conversion methods for each
    one of the backends.

    Args:
        array: the native array or tensor to wrap.

    Attributes:
        shape: the shape of the full dense native array.
    c                     || _         y Narray)selfr   s     ^/home/dcms/DCMS/lib/python3.12/site-packages/keras/src/trainers/data_adapters/array_slicing.py__init__zSliceable.__init__'   s	    
    c                      | j                   |   S )a/  Select elements in the 0th dimension.

        Args:
            indices: the indices to select. Only needs to support one dimension,
                the 0th dimension. Should support a `slice` or a list, tuple,
                `np.array` or 1D tensor.
        Returns: A slice of `self.array`.
        r   r   indicess     r   __getitem__zSliceable.__getitem__*   s     zz'""r   c                 $    |j                  |      S )zCast a tensor to a different dtype.

        Only called on a full array as provided by the user.

        Args:
            x: the tensor to cast.
        Returns: the cast tensor.
        )astype)clsxdtypes      r   castzSliceable.cast5   s     xxr   c                     |S )zConvert a tensor to a NumPy array.

        Only called after slicing using `__getitem__`.

        Args:
            x: the tensor to convert.
        Returns: the converted tensor.
         r   r   s     r   convert_to_numpyzSliceable.convert_to_numpyA   s	     r   c                     |S )ak  Convert a tensor to something compatible with `tf.data.Dataset`.

        This can be a NumPy array, `tf.Tensor` or any other type of tensor that
        `tf.data.Dataset.from_tensors` can consume.
        Only called on a full array as provided by the user.

        Args:
            x: the tensor to convert.
        Returns: converted version tensor.
        r   r   s     r    convert_to_tf_dataset_compatiblez*Sliceable.convert_to_tf_dataset_compatibleM   	     r   c                     |S )a`  Convert a tensor to something that the JAX backend can consume.

        This can be a `JAX` array, `JAXSparse` or a NumPy array.
        Only called after slicing using `__getitem__`.
        Used to convert sparse tensors and densify ragged tensors.

        Args:
            x: the tensor to convert.
        Returns: the converted tensor.
        r   r   s     r   convert_to_jax_compatiblez#Sliceable.convert_to_jax_compatible[   r"   r   c                     |S )a  Convert a tensor to something that the Torch backend can consume.

        This can be a Torch tensor, NumPy array or any other type of tensor that
        `keras.backend.torch.core.convert_to_tensor()` can consume.
        Only called after slicing using `__getitem__`.
        Used to densify sparse tensors and ragged tensors.

        Args:
            x: the tensor to convert.
        Returns: the converted tensor.
        r   r   s     r   convert_to_torch_compatiblez%Sliceable.convert_to_torch_compatiblei   s	     r   N)__name__
__module____qualname____doc__r   r   classmethodr   r   r!   r$   r&   r   r   r   r	   r	      su    	# 	 	 	 	      r   r	   c                       e Zd Zy)NumpySliceableNr'   r(   r)   r   r   r   r-   r-   y       r   r-   c                   2    e Zd Zd Zed        Zed        Zy)TensorflowSliceablec                     ddl m} t        |t              r| j                  |   S  |j
                  | j                  |d      S )Nr   r   axis)keras.src.utils.module_utilsr   
isinstanceslicer   gather)r   r   tfs      r   r   zTensorflowSliceable.__getitem__~   s7    Agu%::g&&299TZZq99r   c                      ddl m}  |||      S Nr   )r   )!keras.src.backend.tensorflow.corer   r   r   r   r   s       r   r   zTensorflowSliceable.cast   s    :Au~r   c                     ddl m}  ||      S Nr   r   )r<   r   r   r   r   s      r   r   z$TensorflowSliceable.convert_to_numpy   s    F""r   N)r'   r(   r)   r   r+   r   r   r   r   r   r1   r1   }   s/    :  
 # #r   r1   c                   ,    e Zd Zed        Zed        Zy)TensorflowRaggedSliceablec                 $    | j                  |      S r   r@   r   s     r   r$   z3TensorflowRaggedSliceable.convert_to_jax_compatible       ##A&&r   c                 "    |j                         S r   )	to_tensorr   s     r   r&   z5TensorflowRaggedSliceable.convert_to_torch_compatible   s    {{}r   N)r'   r(   r)   r+   r$   r&   r   r   r   rC   rC      s(    ' '  r   rC   c                   d     e Zd Z fdZed        Zd Zed        Zed        Z	ed        Z
 xZS )TensorflowSparseSliceablec                 6    t         |   t        |             y r   )superr   to_tensorflow_sparse_wrapperr   r   	__class__s     r   r   z"TensorflowSparseSliceable.__init__   s    5e<=r   c                 B    | j                   j                  j                  S r   )r   sparseshape)r   s    r   rQ   zTensorflowSparseSliceable.shape   s    zz  &&&r   c                 .    t        | j                  |      S r   )slice_tensorflow_sparse_wrapperr   r   s     r   r   z%TensorflowSparseSliceable.__getitem__   s    .tzz7CCr   c                     t        |      S r   )rL   r   s     r   r!   z:TensorflowSparseSliceable.convert_to_tf_dataset_compatible   s    +A..r   c                 ,    t        j                  |      S r   )r   tf_sparse_to_jax_sparser   s     r   r$   z3TensorflowSparseSliceable.convert_to_jax_compatible   s    !99!<<r   c                 0    ddl m} |j                  |      S )Nr   )rP   )keras.src.backend.tensorflowrP   sparse_to_dense)r   r   	tf_sparses      r   r&   z5TensorflowSparseSliceable.convert_to_torch_compatible   s    D((++r   )r'   r(   r)   r   propertyrQ   r   r+   r!   r$   r&   __classcell__rN   s   @r   rI   rI      s^    > ' 'D / / = = , ,r   rI   c                   B    e Zd Zd Zed        Zed        Zed        Zy)JaxSparseSliceablec                 $    | j                   |df   S )N.r   r   s     r   r   zJaxSparseSliceable.__getitem__   s    zz'3,''r   c                     ddl m}  ||      S r?   )keras.src.backend.jax.corer   rA   s      r   r   z#JaxSparseSliceable.convert_to_numpy   s    ?""r   c                 >    t        t        j                  |            S r   )rL   r   jax_sparse_to_tf_sparse)r   r   s     r   r!   z3JaxSparseSliceable.convert_to_tf_dataset_compatible   s    +66u=
 	
r   c                 "    |j                         S r   todenser   s     r   r&   z.JaxSparseSliceable.convert_to_torch_compatible       yy{r   N)r'   r(   r)   r   r+   r   r!   r&   r   r   r   r_   r_      sC    ( # #
 
 

  r   r_   c                   ,    e Zd Zed        Zed        Zy)TorchSliceablec                      ddl m}  |||      S r;   )keras.src.backend.torch.corer   r=   s       r   r   zTorchSliceable.cast   s    5Au~r   c                     ddl m}  ||      S r?   )rl   r   rA   s      r   r   zTorchSliceable.convert_to_numpy   s    A""r   N)r'   r(   r)   r+   r   r   r   r   r   rj   rj      s(     
 # #r   rj   c                   R    e Zd Zd Zed        Zed        Zed        Zed        Zy)PandasSliceablec                 4    | j                   j                  |   S r   )r   ilocr   s     r   r   zPandasSliceable.__getitem__   s    zzw''r   c                 "    |j                         S r   )to_numpyr   s     r   r   z PandasSliceable.convert_to_numpy   s    zz|r   c                 $    | j                  |      S r   r@   r   s     r   r!   z0PandasSliceable.convert_to_tf_dataset_compatible   rE   r   c                 $    | j                  |      S r   r@   r   s     r   r$   z)PandasSliceable.convert_to_jax_compatible   rE   r   c                 $    | j                  |      S r   r@   r   s     r   r&   z+PandasSliceable.convert_to_torch_compatible   rE   r   N)	r'   r(   r)   r   r+   r   r!   r$   r&   r   r   r   ro   ro      sW    (   ' ' ' ' ' 'r   ro   c                       e Zd Zy)PandasDataFrameSliceableNr.   r   r   r   rx   rx      r/   r   rx   c                       e Zd Zed        Zy)PandasSeriesSliceablec                 L    t        j                  |j                         d      S )Nr3   )npexpand_dimsrs   r   s     r   r   z&PandasSeriesSliceable.convert_to_numpy   s    ~~ajjl44r   N)r'   r(   r)   r+   r   r   r   r   rz   rz      s    5 5r   rz   c                   ^     e Zd Z fdZed        Zed        Zed        Zed        Z xZ	S )ScipySparseSliceablec                 @    t         |   |j                                y r   )rK   r   tocsrrM   s     r   r   zScipySparseSliceable.__init__   s     	'r   c                 "    |j                         S r   rf   r   s     r   r   z%ScipySparseSliceable.convert_to_numpy   rh   r   c                 >    t        t        j                  |            S r   )rL   r   scipy_sparse_to_tf_sparser   s     r   r!   z5ScipySparseSliceable.convert_to_tf_dataset_compatible  s    +88;
 	
r   c                 ,    t        j                  |      S r   )r   scipy_sparse_to_jax_sparser   s     r   r$   z.ScipySparseSliceable.convert_to_jax_compatible	  s    !<<Q??r   c                 "    |j                         S r   rf   r   s     r   r&   z0ScipySparseSliceable.convert_to_torch_compatible  rh   r   )
r'   r(   r)   r   r+   r   r!   r$   r&   r\   r]   s   @r   r   r      sZ    (
   
 

 @ @  r   r   TensorflowSparseWrapper)rP   ragged_indicesragged_valuesc                    ddl m} | j                  d d df   }|j                  j                  j                  |      j                         } |j                  |j                  j                  | j                  |      |j                        }|j                  j                  | j                  |      }t        | ||      S )Nr   r   )r5   r   r   experimentalRowPartitionfrom_value_rowids
row_splitsr   RaggedTensorfrom_row_splitsint64valuesr   )rP   r9   row_idsr   r   r   s         r   rL   rL   %  s    =nnQT"G--??jl  RWW
''
CRXXN OO33FMM:NM"6>=IIr   c                    ddl m} t        |t              r8| j                  |   }| j
                  |   }|j                  |j                  z
  }n| |j                  | j                  |      } |j                  | j
                  |      }t        |t              rt        |      }n&|j                  d   }| |j                  |      d   }|j                         }|j                  d d dd f   } |j                   |j                  |d      |gd      }|j                  }|ft!        | j"                  j                  j%                         dd        z   } |j&                  |||      S )Nr   r      r|   r3   )r5   r   r6   r7   r   r   stopstartr8   listlenrQ   value_rowidsflat_valuesconcatr~   tuplerP   as_listSparseTensor)sparse_wrapperr   r9   sparse_indicessparse_values	batch_dimr   sparse_shapes           r   rS   rS   4  sN   ='5!'66w?&44W=LL7==0	">#@#@'J!		.">">Hgt$GIa(I $BHHW-a0	))+G#//126NRYY		$n5AN "--M<%##++-ab1# L 2??>=,GGr   c                    | d u xsz t        | t              xsh t        j                  |       xsQ t        j                  |       xs: t        j
                  |       xs# t        j                  |       xs t        | d      S )N	__array__)r6   ARRAY_TYPESr   is_tensorflow_tensoris_jax_arrayis_torch_tensoris_scipy_sparsehasattr)r   s    r   can_slice_arrayr   R  s    	T	 	#a%	#2215	# **1-	# --a0		#
 --a0	# 1k"r   c                 :    fd}t        j                  ||       S )a  Convert a structure of arrays into `Sliceable` instances

    Args:
        arrays: the arrays to convert.
        target_backend: the target backend for the output:
            - `None` indicates that `arrays` will be wrapped into `Sliceable`s
              as-is without using a different representation. This is used by
              `train_validation_split()`.
            - `tensorflow` indicates that
              `Sliceable.convert_to_tf_dataset_compatible` will be called. The
              returned structure therefore contains arrays, not `Sliceable`s.
            - `numpy`, `jax` or `torch` indices that the arrays will eventually
              be converted to this backend type after slicing. In this case,
              the intermediary `Sliceable`s may use a different representation
              from the input `arrays` for better performance.
    Returns: the same structure with `Sliceable` instances or arrays.
    c                    | | S t        | t        j                        rXt        | j                        dk(  r@t        j
                         dk(  r)t        d | D              rt        j                  | d      } t        | t        j                        rt        }nmt        j                  |       rBt        j                  |       rt        }n;t        j                  |       rt        }nt         }nt        j"                  |       r8t        j$                  |       rt&        }nt        j(                  |       } t        }nt        j*                  |       rt,        }nt.        !t        | t.        j0                        rt2        }nt.        !t        | t.        j4                        rt6        }n_t        j8                  |       rt:        }nCt=        | d      rt        j(                  |       } t        }nt?        d|  dtA        |        d	      d
 d }t.        Wt        | t.        j0                        r=tC        fd| jD                  jF                  D              r;t        jH                         }n& | j                        rt        jH                         }||jK                  | |      }  ||       S dk(  r|jM                  |       S dk(  r)|t         t,        fv rt        j(                  |       } t        } ||       S )Nobjectr   c              3   <   K   | ]  }t        |t                y wr   )r6   str).0es     r   	<genexpr>zEconvert_to_sliceable.<locals>.convert_single_array.<locals>.<genexpr>z  s     21Jq#&2s   stringr   r   zExpected a NumPy array, tf.Tensor, tf.RaggedTensor, tf.SparseTensor, jax.np.ndarray, jax.experimental.sparse.JAXSparse, torch.Tensor, Pandas Dataframe, or Pandas Series. Received invalid input: z
 (of type )c                     | t         uxrB t        j                  |       xr+ t        j                  |       t        j                         k(   S r   )r   r   is_float_dtypestandardize_dtypefloatxr   s    r   is_non_floatx_floatzOconvert_to_sliceable.<locals>.convert_single_array.<locals>.is_non_floatx_float  sF    V# M**51M11%8GNN<LLLr   c              3   .   K   | ]  } |        y wr   r   )r   dr   s     r   r   zEconvert_to_sliceable.<locals>.convert_single_array.<locals>.<genexpr>  s     Ca&q)Cs   jax)'r6   r}   ndarrayr   r   r   allr9   convert_to_tensorr-   r   r   is_tensorflow_raggedrC   is_tensorflow_sparserI   r1   r   is_jax_sparser_   asarrayr   rj   pandas	DataFramerx   Seriesrz   r   r   r   
ValueErrortypeanydtypesr   r   r   r!   )r   sliceable_class
cast_dtyper   target_backends      @r   convert_single_arrayz2convert_to_sliceable.<locals>.convert_single_arrayq  sV   9H q"**%AGG(!\1222$$Qh7A a$,O44Q7!66q9";#88;";"5,,Q/!//2"4JJqM"0//2,OJq&2B2B$C6OJq&--$@3O//22OQ$

1A,OO #ZQy	+ 	 
*Q0@0@"AC188??CC$^^-
"177+$^^-
!$$Q
3A !"1%%\)"CCAFF U";
 (
 

1A,Oq!!r   )r   map_structure)arraysr   r   s    ` r   convert_to_sliceabler   ^  s     &W"r 2F;;r   c                 ,  	
 t        j                  |       }|D cg c]  }t        |      rt        |       }}|rt	        d|       t        d |D              r| | fS d}|D ]  }||} n t        |j                  d         
t        t        j                  
d|z
  z              dk(  s
k(  rt	        d
 d| d      d	 	t        |       }t        j                  	fd
|      }t        j                  	
fd|      }||fS c c}w )a  Split arrays into train and validation subsets in deterministic order.

    The last part of data will become validation data.

    Args:
        arrays: Tensors to split. Allowed inputs are arbitrarily nested
            structures of Tensors and NumPy arrays.
        validation_split: Float between 0 and 1. The proportion of the dataset
            to include in the validation split. The rest of the dataset will be
            included in the training split.

    Returns:
        `(train_arrays, validation_arrays)`
    zpArgument `validation_split` is only supported for tensors or NumPy arrays.Found incompatible type in the input: c              3   $   K   | ]  }|d u  
 y wr   r   )r   ts     r   r   z)train_validation_split.<locals>.<genexpr>  s     
*19
*s   Nr   g      ?zTraining data contains zs samples, which is not sufficient to split it into a validation and training set as specified by `validation_split=zV`. Either provide more data, or a different value for the `validation_split` argument.c                     | | S | || S r   r   )r   r   ends      r   _splitz&train_validation_split.<locals>._split  s    9Hs|r   c                      | d      S )Nr   r   r   r   )r   r   split_ats    r   <lambda>z(train_validation_split.<locals>.<lambda>  s    &!2 r   c                      |       S )Nr   r   )r   r   r   r   s    r   r   z(train_validation_split.<locals>.<lambda>  s    &(	: r   )r   flattenr   r   r   r   intrQ   mathfloorr   r   )r   validation_splitflat_arraysr   unsplitablefirst_non_none
sliceablestrain_arrays
val_arraysr   r   r   s            @@@r   train_validation_splitr     sJ     ,,v&K$/Jqq7I47JKJ55@MC
 	
 
*k
**v~N =N N((+,I4::i31A+ABCDH1}I-%i[ 1..>-? @++
 	

 &f-J%%2JL ##:JJ ##U Ks
   DDr   )$collectionsr   numpyr}   	keras.srcr   r    keras.src.trainers.data_adaptersr   r5   r   r9   r   ImportErrorr   r   r   r   r	   r-   r1   rC   rI   r_   rj   ro   rx   rz   r   
namedtupler   rL   rS   r   r   r   r   r   r   <module>r      s"        ? 9 zzm	0@0@ AAK] ]@	Y 	#) #, 3 , 3 ,4 *#Y #'i '*	 	5O 59 N 1+00L 
JH<	l<^;$A  Fs   C2 2C<;C<