o
    Qe%S  ã                   @   sÊ   d dl m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ddlmZmZ d d	l mZ dd
lmZ ddlmZmZ ddlmZ g Zddd„Z				ddd„Zddd„Zddd„Zddd„ZdS )é   )Úget_cudnn_version)ÚVariable)ÚLayerHelper)Úcheck_variable_and_dtype)Údygraph_utilsé    N)Ú_C_opsÚ_legacy_C_ops)Úis_compiled_with_rocm)Úin_dynamic_mode)Úin_dygraph_modeÚ_in_legacy_dygraph)Ú_non_static_modeTc              	   C   sF  t | tƒs	tdƒ‚tƒ }|dur|dkr|rd}nd}| jd dkr$d}tƒ r)d}tƒ rAt |tƒr7| ¡  ¡ n|}t	 
| |||¡S tƒ r\t |tƒrO| ¡  ¡ n|}t 
| d|d	|d
|¡S tdƒ}t| dddgdƒ | | j¡}d| i}	||dœ}
t |tƒrŠ||	d< t|ddgdƒ n||
d< |jd|	d|it|
ƒdkrdn|
d |S )až	  
    It generates a grid of (x,y) or (x,y,z) coordinates using the parameters of
    the affine transformation that correspond to a set of points where
    the input feature map should be sampled to produce the transformed
    output feature map.

    Args:
        theta (Tensor) - A tensor with shape [N, 2, 3] or [N, 3, 4]. It contains a batch of affine transform parameters.
                           The data type can be float32 or float64.
        out_shape (Tensor | list | tuple): Type can be a 1-D Tensor, list, or tuple. It is used to represent the shape of the output in an affine transformation, in the format ``[N, C, H, W]`` or ``[N, C, D, H, W]``.
                                           When the format is ``[N, C, H, W]``, it represents the batch size, number of channels, height and width. When the format is ``[N, C, D, H, W]``, it represents the batch size, number of channels, depth, height and width.
                                           The data type must be int32.
        align_corners(bool, optional): if True, aligns the centers of the 4 (4D) or 8 (5D) corner pixels of the input and output tensors, and preserves the value of the corner pixels. Default: True
        name(str, optional): The default value is None.  Normally there is no need for user to set this property.  For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Tensor, A Tensor with shape [batch_size, H, W, 2] or [batch, D, H, W, 3] while ('D')'H', 'W' are the (depth)height, width of feature map in affine transformation. The data type is the same as `theta`.

    Examples:

        .. code-block:: python

            import paddle
            import paddle.nn.functional as F
            # theta shape = [1, 2, 3]
            theta = paddle.to_tensor([[[-0.7, -0.4, 0.3],
                                       [ 0.6,  0.5, 1.5]]], dtype="float32")
            y_t = F.affine_grid(
                    theta,
                    [1, 2, 3, 3],
                    align_corners=False)
            print(y_t)

            #[[[[ 1.0333333   0.76666665]
            #   [ 0.76666665  1.0999999 ]
            #   [ 0.5         1.4333333 ]]
            #
            #  [[ 0.5666667   1.1666666 ]
            #   [ 0.3         1.5       ]
            #   [ 0.03333333  1.8333334 ]]
            #
            #  [[ 0.10000002  1.5666667 ]
            #   [-0.16666666  1.9000001 ]
            #   [-0.43333334  2.2333333 ]]]]
    zThe theta should be a Tensor.Nip  TFé   r   Zoutput_shapeÚalign_cornersÚ	use_cudnnÚaffine_gridÚthetaÚfloat32Úfloat64ÚTheta)r   r   ZOutputShapeÚ	out_shapeZint32ÚOutputr   ©ÚtypeÚinputsÚoutputsÚattrs)Ú
isinstancer   Ú
ValueErrorr   Úshaper
   r   ÚnumpyÚtolistr   r   r   r	   r   r   Ú"create_variable_for_type_inferenceÚdtypeÚ	append_opÚlen)r   r   r   ÚnameÚcudnn_versionr   Z
_out_shapeÚhelperÚoutÚiptsr   © r,   úKD:\Projects\ConvertPro\env\Lib\site-packages\paddle/nn/functional/vision.pyr      sf   
.ÿÿýÿýù
ÿ


ÿür   ÚbilinearÚzerosc                 C   sf  ddg}g d¢}||vrt d ||¡ƒ‚||vr t d ||¡ƒ‚t|tƒs,t d |¡ƒ‚tƒ }d}	tƒ sJ|durJ|rJ|dkrJ|d	krJd
}	d| _d|_t|jƒdkrSd}	t	ƒ r_t
 | ||||¡S tƒ rzd|d|d|d|	f}
ttdƒ| |g|
¢R Ž }|S tdi tƒ ¤Ž}t| dddgdƒ t|dddgdƒ | |dœ}||||	dœ}
| | j¡}|jd||
d|id |S )a…  
    Sample input X by using bilinear interpolation or
    nearest interpolation based on flow field grid, which is usually
    generated by :code:`affine_grid` . When the input X is 4-D Tensor,
    the grid of shape [N, H, W, 2] is the concatenation of (x, y)
    coordinates with shape [N, H, W] each, where x is indexing the 4th
    dimension (in width dimension) of input data x and y is indexing
    the 3rd dimension (in height dimension), finally results is the
    bilinear interpolation or nearest value of 4 nearest corner
    points. The output tensor shape will be [N, C, H, W]. When the input X
    is 5-D Tensor, the grid of shape [N, D, H, W, 3] is the concatenation
    of (x, y, z) coordinates with shape [N, D, H, W] each, where x is
    indexing the 5th dimension (in width dimension) of input data x, y is
    indexing the 4th dimension (in height dimension) and z is indexing the
    3rd dimension (in depth dimension) finally results is the bilinear
    interpolation or nearest value of 8 nearest cornerpoints. The output
    tensor shape will be [N, C, D, H, W].



    Step 1:

    Get (x, y) grid coordinates and scale to [0, H-1/W-1].

    .. code-block:: text

        grid_x = 0.5 * (grid[:, :, :, 0] + 1) * (W - 1)
        grid_y = 0.5 * (grid[:, :, :, 1] + 1) * (H - 1)

    Step 2:

    Indices input data X with grid (x, y) in each [H, W] area, and bilinear
    interpolate point value by 4 nearest points or nearest interpolate point value
    by nearest point.

    .. code-block:: text

        wn ------- y_n ------- en
        |           |           |
        |          d_n          |
        |           |           |
        x_w --d_w-- grid--d_e-- x_e
        |           |           |
        |          d_s          |
        |           |           |
        ws ------- y_s ------- wn

        For bilinear interpolation:
        x_w = floor(x)              // west side x coord
        x_e = x_w + 1               // east side x coord
        y_n = floor(y)              // north side y coord
        y_s = y_s + 1               // south side y coord
        d_w = grid_x - x_w          // distance to west side
        d_e = x_e - grid_x          // distance to east side
        d_n = grid_y - y_n          // distance to north side
        d_s = y_s - grid_y          // distance to south side
        wn = X[:, :, y_n, x_w]      // north-west point value
        en = X[:, :, y_n, x_e]      // north-east point value
        ws = X[:, :, y_s, x_w]      // south-east point value
        es = X[:, :, y_s, x_w]      // north-east point value

        output = wn * d_e * d_s + en * d_w * d_s
                + ws * d_e * d_n + es * d_w * d_n

    Args:
        x(Tensor): The input tensor, which is a 4-d tensor with shape
                     [N, C, H, W] or a 5-d tensor with shape [N, C, D, H, W],
                     N is the batch size, C is the channel number,
                     D, H and W is the feature depth, height and width.
                     The data type is float32 or float64.
        grid(Tensor): Input grid tensor, which is a 4-d tensor with shape [N, grid_H,
                        grid_W, 2] or a 5-d tensor with shape [N, grid_D, grid_H,
                        grid_W, 3]. The data type is float32 or float64.
        mode(str, optional): The interpolation method which can be 'bilinear' or 'nearest'.
                         Default: 'bilinear'.
        padding_mode(str, optional) The padding method used when source index
                   is out of input images. It can be 'zeros', 'reflection' and 'border'.
                   Default: zeros.
        align_corners(bool, optional): If `align_corners` is true, it will projects
                   -1 and 1 to the centers of the corner pixels. Otherwise, it will
                   projects -1 and 1 to the image edges.
        name(str, optional): For detailed information, please refer
                             to :ref:`api_guide_Name`. Usually name is no need to set and
                             None by default.

    Returns:

        Tensor, The shape of output is [N, C, grid_H, grid_W] or [N, C, grid_D, grid_H, grid_W] in which `grid_D` is the depth of grid,
                `grid_H` is the height of grid and `grid_W` is the width of grid. The data type is same as input tensor.

    Examples:

        .. code-block:: python

            import paddle
            import paddle.nn.functional as F

            # x shape=[1, 1, 3, 3]
            x = paddle.to_tensor([[[[-0.6,  0.8, -0.5],
                                    [-0.5,  0.2,  1.2],
                                    [ 1.4,  0.3, -0.2]]]],dtype='float64')
            # grid shape = [1, 3, 4, 2]
            grid = paddle.to_tensor([[[[ 0.2,  0.3],
                                       [-0.4, -0.3],
                                       [-0.9,  0.3],
                                       [-0.9, -0.6]],
                                      [[ 0.4,  0.1],
                                       [ 0.9, -0.8],
                                       [ 0.4,  0.5],
                                       [ 0.5, -0.2]],
                                      [[ 0.1, -0.8],
                                       [-0.3, -1. ],
                                       [ 0.7,  0.4],
                                       [ 0.2,  0.8]]]],dtype='float64')
            y_t = F.grid_sample(
                x,
                grid,
                mode='bilinear',
                padding_mode='border',
                align_corners=True)
            print(y_t)

            # output shape = [1, 1, 3, 4]
            # [[[[ 0.34   0.016  0.086 -0.448]
            #    [ 0.55  -0.076  0.35   0.59 ]
            #    [ 0.596  0.38   0.52   0.24 ]]]]
    r.   Znearest)r/   Z
reflectionÚborderz=The mode of grid sample function should be in {}, but got: {}zEThe padding mode of grid sample function should be in {}, but got: {}z-The align corners should be bool, but got: {}FNr/   Té   ÚmodeÚpadding_moder   r   Zgrid_samplerÚgrid_sampleÚxr   r   Úgrid)ÚXZGrid)r2   r3   r   r   r   )r   r   r   r   )r4   )r   Úformatr   Úboolr   r
   Zstop_gradientr&   r    r   r   r4   r   Úgetattrr	   r   Úlocalsr   r#   r$   r%   )r5   r6   r2   r3   r   r'   Z_modesZ_padding_modesr(   r   r   r*   r)   r+   r,   r,   r-   r4   Š   sˆ    	ÿÿÿÿ
ÿÿÿÿø
íÿ
üür4   ÚNCHWc                 C   s¨   t |tƒs	tdƒ‚|dvrtd |¡ƒ‚tƒ rt | ||¡S tƒ r*t	 | d|d|¡S t
di tƒ ¤Ž}t| ddd	gdƒ |j| jd
}|jdd| id|i||dœd |S )a	  
    This API implements pixel shuffle operation.
    See more details in :ref:`api_nn_vision_PixelShuffle` .


    Parameters:
        x(Tensor): 4-D tensor, the data type should be float32 or float64.
        upscale_factor(int): factor to increase spatial resolution.
        data_format (str, optional): The data format of the input and output data. An optional string from: "NCHW", "NHWC". The default is "NCHW". When it is "NCHW", the data is stored in the order of: [batch_size, input_channels, input_height, input_width].
        name (str, optional): The default value is None.  Normally there is no need for user to set this property.

    Returns:
        Out(tensor): Reshaped tensor according to the new dimension.

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn.functional as F

            x = paddle.randn(shape=[2,9,4,4])
            out_var = F.pixel_shuffle(x, 3)
            out = out_var.numpy()
            print(out.shape)
            # (2, 1, 12, 12)
    zupscale factor must be int type©r<   ZNHWCúOAttr(data_format) should be 'NCHW' or 'NHWC'.But recevie Attr(data_format): {} Úupscale_factorÚdata_formatÚpixel_shuffler5   r   r   ©r$   r7   ÚOut)r?   r@   r   N)rA   )r   ÚintÚ	TypeErrorr   r8   r   r   rA   r   r	   r   r;   r   r#   r$   r%   )r5   r?   r@   r'   r)   r*   r,   r,   r-   rA   ^  s.   
þ
ÿürA   c                 C   óÂ   t | jƒdkrtd | j¡ƒ‚t|tƒstdƒ‚|dkr tdƒ‚|dvr+td |¡ƒ‚tƒ r7t 	| d|d	|¡S t
di tƒ ¤Ž}t| dddgd
ƒ |j| jd}|jd
d| id|i||dœd |S )a4  
    This API implements pixel unshuffle operation.
    See more details in :ref:`api_nn_vision_PixelUnshuffle` .

    Parameters:
        x (Tensor): 4-D tensor, the data type should be float32 or float64.
        downscale_factor (int): Factor to decrease spatial resolution.
        data_format (str, optional): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width].
        name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Out (Tensor): Reshaped tensor according to the new dimension.

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn.functional as F
            x = paddle.randn([2, 1, 12, 12])
            out = F.pixel_unshuffle(x, 3)
            print(out.shape)
            # [2, 9, 4, 4]
    é   ú@Input x should be 4D tensor, but received x with the shape of {}z!Downscale factor must be int typer   z!Downscale factor must be positiver=   r>   Údownscale_factorr@   Úpixel_unshuffler5   r   r   rB   r7   rC   )rI   r@   r   N)rJ   )r&   r    r   r8   r   rD   rE   r   r	   rJ   r   r;   r   r#   r$   r%   )r5   rI   r@   r'   r)   r*   r,   r,   r-   rJ   •  s>   ÿÿ
þ
ÿþü	rJ   c                 C   rF   )a§  
    This API implements channel shuffle operation.
    See more details in :ref:`api_nn_vision_ChannelShuffle` .

    Parameters:
        x (Tensor): 4-D tensor, the data type should be float32 or float64.
        groups (int): Number of groups to divide channels in.
        data_format (str): The data format of the input and output data. An optional string of NCHW or NHWC. The default is NCHW. When it is NCHW, the data is stored in the order of [batch_size, input_channels, input_height, input_width].
        name (str, optional): Name for the operation (optional, default is None). Normally there is no need for user to set this property. For more information, please refer to :ref:`api_guide_Name`.

    Returns:
        Out (Tensor): Rearranged tensor keeping the original tensor shape.

    Examples:
        .. code-block:: python

            import paddle
            import paddle.nn.functional as F
            x = paddle.arange(0, 0.6, 0.1, 'float32')
            x = paddle.reshape(x, [1, 6, 1, 1])
            # [[[[0.        ]],
            #   [[0.10000000]],
            #   [[0.20000000]],
            #   [[0.30000001]],
            #   [[0.40000001]],
            #   [[0.50000000]]]]
            y = F.channel_shuffle(x, 3)
            # [[[[0.        ]],
            #   [[0.20000000]],
            #   [[0.40000001]],
            #   [[0.10000000]],
            #   [[0.30000001]],
            #   [[0.50000000]]]]
    rG   rH   zgroups must be int typer   zgroups must be positiver=   r>   Úgroupsr@   Úchannel_shuffler5   r   r   rB   r7   rC   )rK   r@   r   N)rL   )r&   r    r   r8   r   rD   rE   r   r	   rL   r   r;   r   r#   r$   r%   )r5   rK   r@   r'   r)   r*   r,   r,   r-   rL   Ô  s:   #ÿÿ
þ
ÿürL   )TN)r.   r/   TN)r<   N)Zdevicer   Zstaticr   Zfluid.layer_helperr   Zfluid.data_feederr   Zfluidr   r!   ÚnpZpaddler   r	   r
   r   Zpaddle.fluid.frameworkr   r   Zpaddle.frameworkr   Ú__all__r   r4   rA   rJ   rL   r,   r,   r,   r-   Ú<module>   s,   
o
ú 
U
7?