o
    #j#,                     @   s   d dl 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mZ d dlmZmZ ddgZd	d
 Zdd Zdd Zdd Z	dddZe	dddZdS )    N)_C_opsin_dynamic_mode)convert_dtype)_current_expected_place_get_paddle_placecoredygraph_only)LayerHelper)max	to_tensorsparse_coo_tensorsparse_csr_tensorc                 C   s(   |rt |t | jkr| t |S | S )N)r   dtypeZastype)datar    r   W/var/www/html/Deteccion_Ine/venv/lib/python3.10/site-packages/paddle/sparse/creation.py_handle_dtype#   s   r   c                 C   sZ   t | jdks	J t| dd}|d }| }t |jdkr)t||jdd  }t|S )N      )Zaxis)lenshaper
   numpynpappendlist)indicesvaluesZlensr   r   r   _infer_dense_shape*   s   r   c                 C   s@   t | } | d u rt } | S t| tjtjtjtjfstd| S )Nz^'place' must be any of paddle.Place, paddle.CPUPlace, paddle.CUDAPinnedPlace, paddle.CUDAPlace)	r   r   
isinstancer   ZPlaceZCPUPlaceZCUDAPinnedPlaceZ	CUDAPlace
ValueError)placer   r   r   
_get_place4   s   r!   c                 C   s$   | t jt jt jt jfvrtdd S )NzDthe dtype of indices must be 'int8' or 'int16' or 'int32' or 'int64')paddleZint8Zint16Zint32Zint64	TypeError)r   r   r   r   _check_indices_dtypeA   s
   r$   Tc                 C   s  t  rt|}t| tjjst| d|dd} t|tjjs$t||||}t| jdkr/t	d| jd }| jd }t
| j ||jd krPt	d||jd t|jd }| j|sc| |d	} |j|so||d	}t||}||_t| |}	|du r|	}n%t|}||	k rt	d
|	 d| t||| krt	d||t|t|| |S d}
|| d}|d du rd|d< d|i}t|
}||}|j|
|d|i|d |S )a&  
    Constructs a sparse ``paddle.Tensor`` in coordinate format according to the indices
    and values of the specified non-zero elements.

    Args:
        indices(list|tuple|ndarray|Tensor): the indices of non-zero elements.
            Can be a list, tuple, numpy\.ndarray, paddle\.Tensor. The indices must be 2-D.
        values(list|tuple|ndarray|Tensor): Initial values for the tensor.
            Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor.
        shape(list|tuple, optional): The shape of the sparse tensor also represents the shape of
            original dense tensor. If not provided the smallest shape will be inferred to
            hold all elements.
        dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' ,
            'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8',
            'complex64' , 'complex128'. Default: None, infers dtype from ``data``
            except for python float number which gets dtype from ``get_default_type`` .
        place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be
            CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is
            string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs.
        stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True.

    Returns:
        Tensor: A Tensor constructed from ``indices`` and ``values`` .

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> indices = [[0, 1, 2], [1, 2, 0]]
            >>> values = [1.0, 2.0, 3.0]
            >>> dense_shape = [3, 3]
            >>> coo = paddle.sparse.sparse_coo_tensor(indices, values, dense_shape)
            >>> print(coo)
            Tensor(shape=[3, 3], dtype=paddle.float32, place=Place(cpu), stop_gradient=True,
                   indices=[[0, 1, 2],
                            [1, 2, 0]],
                   values=[1., 2., 3.])
    NTr   r    stop_gradientr   z'indices' must be 2-D.r   r   zKthe indices and values must have same number of non-zero, but get {} and {}Fzthe minimun shape required is z
, but get zVthe number of dimensions(len(shape) must be sparse_dim({}) + dense_dim({}), but get {}sparse_sparse_coo_tensor)r   r   r   out)typeinputsZoutputsattrs)r   r!   r   r   eagerTensorr   r   r   r   r$   r   formatr    _equals_copy_tor   r&   r   r   r   r'   r	   Z)create_sparse_variable_for_type_inferenceZ	append_op)r   r   r   r   r    r&   ZnnzZ
sparse_dimZ	dense_dimZ	min_shapeZop_typer+   r,   helperr)   r   r   r   r   H   sh   ,








c                 C   s  t |}t| tjjst| d|dd} t|tjjs"t|d|dd}t|tjjs0t||||}t| j t|j t|dkrMt|dkrMt	d| |t|d  }| j
|sa| |d} |j
|sm||d}|j
|sy||d}t||}||_t| jdkst|jdkst|jdkrt	d	t|t|krt	d
t|dkr| jd |d krt	d| jd || d dkrt	d| d |jd krt	dn| jd |d  dkrt	d| jd |tj| ||||S )a<	  
    Constructs a sparse ``paddle.Tensor`` in CSR(Compressed Sparse Row) format according to the
    ``crows``, ``cols`` and ``values``.
    Currently, the crows and cols of each batch must be incrementd.

    Args:
        crows(list|tuple|ndarray|Tensor): 1-D array, each element in the rows represents the
            starting position of the first non-zero element of each row in values.
            Can be a list, tuple, numpy\.ndarray, paddle\.Tensor.
        cols(list|tuple|ndarray|Tensor): 1-D array, the column of non-zero elements.
            Can be a list, tuple, numpy\.ndarray, paddle\.Tensor.
        values(list|tuple|ndarray|Tensor): 1-D array, the non-zero elements.
            Can be a scalar, list, tuple, numpy\.ndarray, paddle\.Tensor.
        shape(list|tuple, optional): The shape of the sparse tensor also represents the shape of
            original dense tensor.
            hold all elements.
        dtype(str|np.dtype, optional): The desired data type of returned tensor. Can be 'bool' , 'float16' ,
            'float32' , 'float64' , 'int8' , 'int16' , 'int32' , 'int64' , 'uint8',
            'complex64' , 'complex128'. Default: None, infers dtype from ``data``
            except for python float number which gets dtype from ``get_default_type`` .
        place(CPUPlace|CUDAPinnedPlace|CUDAPlace|str, optional): The place to allocate Tensor. Can be
            CPUPlace, CUDAPinnedPlace, CUDAPlace. Default: None, means global place. If ``place`` is
            string, It can be ``cpu``, ``gpu:x`` and ``gpu_pinned``, where ``x`` is the index of the GPUs.
        stop_gradient(bool, optional): Whether to block the gradient propagation of Autograd. Default: True.

    Returns:
        Tensor: A Tensor constructed from ``crows``, ``cols`` and ``values`` .

    Examples:

        .. code-block:: python

            >>> import paddle

            >>> crows = [0, 2, 3, 5]
            >>> cols = [1, 3, 2, 0, 1]
            >>> values = [1, 2, 3, 4, 5]
            >>> dense_shape = [3, 4]
            >>> csr = paddle.sparse.sparse_csr_tensor(crows, cols, values, dense_shape)
            >>> print(csr)
            Tensor(shape=[3, 4], dtype=paddle.int64, place=Place(cpu), stop_gradient=True,
                   crows=[0, 2, 3, 5],
                   cols=[1, 3, 2, 0, 1],
                   values=[1, 2, 3, 4, 5])
    NTr%   r      z>SparseCsrTensor only support 2-D or 3-D matrix. but get shape Fr   z-The 'crows', 'cols' and 'values' must be 1-D.z3the length of cols must be same as length of valuesr   zBThe length({}) of crows must be equal to the rows({})+1 of matrix.z the 0th value of crows must be 0r(   z<the last value of crows must be equal the number of non-zerozCThe length({}) of crows must be divisible the rows({})+1 of matrix.)r!   r   r   r-   r.   r   r$   r   r   r   r    r0   r1   r   r&   r   r/   r   )Zcrowscolsr   r   r   r    r&   rowsr   r   r   r      sb   2


*


)NNNT)NNT)r   r   r"   r   r   Zpaddle.base.data_feederr   Zpaddle.base.frameworkr   r   r   r   Zpaddle.base.layer_helperr	   Zpaddle.tensorr
   r   __all__r   r   r!   r$   r   r   r   r   r   r   <module>   s&   

p