o
    Qe‡-  ã                   @   sÈ   d dl Z d dl mZmZ d dlmZmZ d dlmZmZ d dlm	Z	m
Z
 d dlmZmZmZmZ d dl mZ d dlmZ d dl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Ú_legacy_C_ops)ÚcoreÚdygraph_only)Ú_current_expected_placeÚ_get_paddle_place)Ú	to_tensorÚmax)Úcheck_variable_and_dtypeÚ
check_typeÚcheck_dtypeÚconvert_dtype)Úin_dynamic_mode)ÚLayerHelperÚsparse_coo_tensorÚsparse_csr_tensorc                 C   s(   |rt |ƒt | jƒkr|  t |ƒ¡S | S )N)r   ÚdtypeZastype)Údatar   © r   úFD:\Projects\ConvertPro\env\Lib\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_place6   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_dtypeC   s
   ÿÿr(   Tc                 C   s¨  t ƒ r©t|ƒ}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||	k r�t	d
 |	|¡ƒ‚t|ƒ|| kr¢t	d ||t|ƒ¡ƒ‚t || |¡S d}
|| dœ}|d du rºd|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=[2, 3], dtype=paddle.float32, place=Place(gpu:0), 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 {}, 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   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/   r0   Úhelperr-   r   r   r   r   J   sj   ,ÿ



ÿÿ

ÿÿ
ÿÿ

ÿ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s–t|jƒdks–t|jƒdkršt	d	ƒ‚t|ƒt|ƒkr¦t	d
ƒ‚t|ƒdkrØ| jd |d krÀt	d 
| jd |¡ƒ‚| d dkrÊt	dƒ‚| d |jd kr×t	dƒ‚n| jd |d  dkrît	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(gpu:0), 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   r1   r2   r   r(   r   r   r#   r3   r$   r4   r5   r   r*   r   r   )ZcrowsÚcolsr    r   r   r$   r*   Úrowsr   r   r   r   »   sf   2

ÿÿ
*
ÿÿÿÿ
ÿÿ
ÿ)NNNT)NNT)r&   r   r   Zpaddle.fluid.frameworkr   r   r   r   Zpaddle.tensorr   r	   Zpaddle.fluid.data_feederr
   r   r   r   r   Zpaddle.fluid.layer_helperr   r   r   Ú__all__r   r!   r%   r(   r   r   r   r   r   r   Ú<module>   s*   þ

ÿqÿ