a
    áñh?&  ã                   @   sÊ   d dl mZ d dlZd dlm  m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mZmZ d dlZejjeee edœdd	„ƒZdeeeeedœdd„ZG dd„ deƒZG dd„ dejƒZdS )é    )ÚUnionN)ÚnnÚTensor)Ú	roi_align©Úbox_area)ÚOptionalÚListÚDictÚTuple)ÚlevelsÚunmerged_resultsÚreturnc              	   C   sÀ   |d }|j |j }}tj|  d¡| d¡| d¡| d¡f||d�}tt|ƒƒD ]h}t | |k¡d  dddd¡}| 	| d¡||  d¡||  d¡||  d¡¡}| 
d||| ¡}qR|S )Nr   é   é   é   ©ÚdtypeÚdeviceéÿÿÿÿ)r   r   ÚtorchÚzerosÚsizeÚrangeÚlenÚwhereÚviewÚexpandZscatter)r   r   Zfirst_resultr   r   ÚresÚlevelÚindex© r!   úW/home/yuhw/wc/uboone-dl-vtx/venv/lib/python3.9/site-packages/torchvision/ops/poolers.pyÚ_onnx_merge_levels   s     ÿþýr#   éà   é   ç�íµ ÷Æ°>©Úk_minÚk_maxÚcanonical_scaleÚcanonical_levelÚepsc                 C   s   t | ||||ƒS ©N)ÚLevelMapperr'   r!   r!   r"   ÚinitLevelMapper%   s    r/   c                   @   s<   e Zd ZdZdeeeeedœdd„Zee edœd	d
„Z	dS )r.   zûDetermine which FPN level each RoI in a set of RoIs should map to based
    on the heuristic in the FPN paper.

    Arguments:
        k_min (int)
        k_max (int)
        canonical_scale (int)
        canonical_level (int)
        eps (float)
    r$   r%   r&   r'   c                 C   s"   || _ || _|| _|| _|| _d S r-   )r(   r)   Ús0Úlvl0r,   )Úselfr(   r)   r*   r+   r,   r!   r!   r"   Ú__init__;   s
    zLevelMapper.__init__)Úboxlistsr   c                 C   sv   t  t  dd„ |D ƒ¡¡}t  | jt  || j ¡ t j| j|j	d� ¡}t j
|| j| jd�}| t j¡| j  t j¡S )zA
        Arguments:
            boxlists (list[BoxList])
        c                 S   s   g | ]}t |ƒ‘qS r!   r   )Ú.0Zboxlistr!   r!   r"   Ú
<listcomp>O   ó    z(LevelMapper.__call__.<locals>.<listcomp>©r   )ÚminÚmax)r   ÚsqrtÚcatÚfloorr1   Úlog2r0   Útensorr,   r   Úclampr(   r)   ÚtoÚint64)r2   r4   ÚsZtarget_lvlsr!   r!   r"   Ú__call__I   s    .zLevelMapper.__call__N)r$   r%   r&   )
Ú__name__Ú
__module__Ú__qualname__Ú__doc__ÚintÚfloatr3   r	   r   rD   r!   r!   r!   r"   r.   /   s      úúr.   c                       sÎ   e Zd ZdZeee  ee dœZee	 e
eee ee f edœ‡ fdd„Zee edœdd„Zeee ed	œd
d„Zee eeeef  ddœdd„Zee	ef ee eeeef  edœdd„Z‡  ZS )ÚMultiScaleRoIAligna_  
    Multi-scale RoIAlign pooling, which is useful for detection with or without FPN.

    It infers the scale of the pooling via the heuristics present in the FPN paper.

    Arguments:
        featmap_names (List[str]): the names of the feature maps that will be used
            for the pooling.
        output_size (List[Tuple[int, int]] or List[int]): output size for the pooled region
        sampling_ratio (int): sampling ratio for ROIAlign

    Examples::

        >>> m = torchvision.ops.MultiScaleRoIAlign(['feat1', 'feat3'], 3, 2)
        >>> i = OrderedDict()
        >>> i['feat1'] = torch.rand(1, 5, 64, 64)
        >>> i['feat2'] = torch.rand(1, 5, 32, 32)  # this feature won't be used in the pooling
        >>> i['feat3'] = torch.rand(1, 5, 16, 16)
        >>> # create some random bounding boxes
        >>> boxes = torch.rand(6, 4) * 256; boxes[:, 2:] += boxes[:, :2]
        >>> # original image size, before computing the feature maps
        >>> image_sizes = [(512, 512)]
        >>> output = m(i, [boxes], image_sizes)
        >>> print(output.shape)
        >>> torch.Size([6, 5, 3, 3])

    )ÚscalesÚ
map_levels)Úfeatmap_namesÚoutput_sizeÚsampling_ratioc                    sF   t t| ƒ ¡  t|tƒr ||f}|| _|| _t|ƒ| _d | _	d | _
d S r-   )ÚsuperrK   r3   Ú
isinstancerI   rN   rP   ÚtuplerO   rL   rM   )r2   rN   rO   rP   ©Ú	__class__r!   r"   r3   y   s    

zMultiScaleRoIAlign.__init__)Úboxesr   c                    sT   t j|dd�}|j|j ‰ ‰t j‡ ‡fdd„t|ƒD ƒdd�}t j||gdd�}|S )Nr   )Zdimc              	      s6   g | ].\}}t j|d d …d d…f |ˆt jˆ d�‘qS )Nr   )r   Zlayoutr   )r   Z	full_likeZstrided)r5   ÚiÚb©r   r   r!   r"   r6   Œ   s   ÿz<MultiScaleRoIAlign.convert_to_roi_format.<locals>.<listcomp>r   )r   r<   r   r   Ú	enumerate)r2   rV   Zconcat_boxesÚidsÚroisr!   rY   r"   Úconvert_to_roi_formatˆ   s    þûz(MultiScaleRoIAlign.convert_to_roi_format)ÚfeatureÚoriginal_sizer   c           	      C   s„   |j dd … }tj tt g ¡}t||ƒD ]<\}}t|ƒt|ƒ }dtt |¡ ¡  	¡ ƒ }| 
|¡ q*|d |d ks|J ‚|d S )Néþÿÿÿr   r   r   )Úshaper   ÚjitZannotater	   rJ   Úzipr?   r>   ÚroundÚappend)	r2   r^   r_   r   Zpossible_scalesÚs1Ús2Zapprox_scaleÚscaler!   r!   r"   Úinfer_scale•   s    zMultiScaleRoIAlign.infer_scaleN)ÚfeaturesÚimage_shapesr   c           	         s¸   t |ƒdksJ ‚d}d}|D ] }t|d |ƒ}t|d |ƒ}q||f‰ ‡ ‡fdd„|D ƒ}t tj|d tjd�¡ ¡  }t tj|d tjd�¡ ¡  }|ˆ_tt	|ƒt	|ƒƒˆ_
d S )Nr   r   c                    s   g | ]}ˆ  |ˆ ¡‘qS r!   )ri   )r5   Zfeat©Zoriginal_input_shaper2   r!   r"   r6   ­   r7   z3MultiScaleRoIAlign.setup_scales.<locals>.<listcomp>r8   r   )r   r:   r   r>   r?   Úfloat32ÚitemrL   r/   rI   rM   )	r2   rj   rk   Zmax_xZmax_yra   rL   Zlvl_minZlvl_maxr!   rl   r"   Úsetup_scales    s      zMultiScaleRoIAlign.setup_scales)ÚxrV   rk   r   c                 C   s~  g }|  ¡ D ]\}}|| jv r| |¡ qt|ƒ}|  |¡}| jdu rR|  ||¡ | j}	|	dusdJ ‚|dkrŠt|d || j|	d | j	d�S | j
}
|
dusœJ ‚|
|ƒ}t|ƒ}|d jd }|d j|d j }}tj||f| j ||d�}g }tt||	ƒƒD ]h\}\}}t ||k¡d }|| }t||| j|| j	d�}t ¡ �rT| | |¡¡ qü| |j¡||< qüt ¡ �rzt||ƒ}|S )aÊ  
        Arguments:
            x (OrderedDict[Tensor]): feature maps for each level. They are assumed to have
                all the same number of channels, but they can have different sizes.
            boxes (List[Tensor[N, 4]]): boxes to be used to perform the pooling operation, in
                (x1, y1, x2, y2) format and in the image reference size, not the feature map
                reference.
            image_shapes (List[Tuple[height, width]]): the sizes of each image before they
                have been fed to a CNN to obtain feature maps. This allows us to infer the
                scale factor for each one of the levels to be pooled.
        Returns:
            result (Tensor)
        Nr   r   )rO   Zspatial_scalerP   r   )ÚitemsrN   re   r   r]   rL   ro   r   rO   rP   rM   ra   r   r   r   r   rZ   rc   r   ÚtorchvisionZ_is_tracingrA   r#   )r2   rp   rV   rk   Z
x_filteredÚkÚvZ
num_levelsr\   rL   Zmapperr   Znum_roisZnum_channelsr   r   ÚresultZtracing_resultsr   Zper_level_featurerh   Zidx_in_levelZrois_per_levelZresult_idx_in_levelr!   r!   r"   Úforwardµ   sV    


üýý
	

zMultiScaleRoIAlign.forward)rE   rF   rG   rH   r   r	   rJ   r.   Ú__annotations__Ústrr   rI   r   r3   r   r]   ri   ro   r
   rv   Ú__classcell__r!   r!   rT   r"   rK   W   s&   
þüü
ûrK   )r$   r%   r&   )Útypingr   r   Ztorch.nn.functionalr   Z
functionalÚFr   Ztorchvision.opsr   Ztorchvision.ops.boxesr   Ztorch.jit.annotationsr   r	   r
   r   rr   rb   Zunusedr#   rI   rJ   r/   Úobjectr.   ÚModulerK   r!   r!   r!   r"   Ú<module>   s*      ûû
(