a
    yf3                     @   sn   d dl Z d dlmZ d dlm  mZ d dlmZ d dlm	Z	 d dl
mZmZ G dd dejZdddZdS )    Nlinear_sum_assignment)bbox_iou)	xywh2xyxy	xyxy2xywhc                       s,   e Zd ZdZd fdd		Zdd
dZ  ZS )HungarianMatchera  
    A module implementing the HungarianMatcher, which is a differentiable module to solve the assignment problem in an
    end-to-end fashion.

    HungarianMatcher performs optimal assignment over the predicted and ground truth bounding boxes using a cost
    function that considers classification scores, bounding box coordinates, and optionally, mask predictions.

    Attributes:
        cost_gain (dict): Dictionary of cost coefficients: 'class', 'bbox', 'giou', 'mask', and 'dice'.
        use_fl (bool): Indicates whether to use Focal Loss for the classification cost calculation.
        with_mask (bool): Indicates whether the model makes mask predictions.
        num_sample_points (int): The number of sample points used in mask cost calculation.
        alpha (float): The alpha factor in Focal Loss calculation.
        gamma (float): The gamma factor in Focal Loss calculation.

    Methods:
        forward(pred_bboxes, pred_scores, gt_bboxes, gt_cls, gt_groups, masks=None, gt_mask=None): Computes the
            assignment between predictions and ground truths for a batch.
        _cost_mask(bs, num_gts, masks=None, gt_mask=None): Computes the mask cost and dice cost if masks are predicted.
    NTF 1        ?       @c                    sJ   t    |du r"dddddd}|| _|| _|| _|| _|| _|| _dS )zjInitializes a HungarianMatcher module for optimal assignment of predicted and ground truth bounding boxes.N         )classbboxgioumaskZdice)super__init__	cost_gainuse_fl	with_masknum_sample_pointsalphagamma)selfr   r   r   r   r   r   	__class__ X/var/www/html/django/DPS/env/lib/python3.9/site-packages/ultralytics/models/utils/ops.pyr   "   s    
zHungarianMatcher.__init__c                    s  |j \}}	}
t dkr*dd t|D S | d|
}| jrJt|ntj|dd}| dd}|dd|f }| jrd| j	 || j
  d| d	    }| j	d| | j
  |d	    }|| }n| }|d|d  d}d
t|d|ddddd }| jd | | jd |  | jd |  }| jr`|| | ||7 }d|| | B < |||	d }dd t| dD }tdg dd d  fddt|D S )a=  
        Forward pass for HungarianMatcher. This function computes costs based on prediction and ground truth
        (classification cost, L1 cost between boxes and GIoU cost between boxes) and finds the optimal matching between
        predictions and ground truth based on these costs.

        Args:
            pred_bboxes (Tensor): Predicted bounding boxes with shape [batch_size, num_queries, 4].
            pred_scores (Tensor): Predicted scores with shape [batch_size, num_queries, num_classes].
            gt_cls (torch.Tensor): Ground truth classes with shape [num_gts, ].
            gt_bboxes (torch.Tensor): Ground truth bounding boxes with shape [num_gts, 4].
            gt_groups (List[int]): List of length equal to batch size, containing the number of ground truths for
                each image.
            masks (Tensor, optional): Predicted masks with shape [batch_size, num_queries, height, width].
                Defaults to None.
            gt_mask (List[Tensor], optional): List of ground truth masks, each with shape [num_masks, Height, Width].
                Defaults to None.

        Returns:
            (List[Tuple[Tensor, Tensor]]): A list of size batch_size, each element is a tuple (index_i, index_j), where:
                - index_i is the tensor of indices of the selected predictions (in order)
                - index_j is the tensor of indices of the corresponding selected ground truth targets (in order)
                For each batch element, it holds:
                    len(index_i) = len(index_j) = min(num_queries, num_target_boxes)
        r   c                 S   s,   g | ]$}t jg t jd t jg t jd fqS dtypetorchtensorlong).0_r   r   r   
<listcomp>J       z,HungarianMatcher.forward.<locals>.<listcomp>dim   Nr   g:0yE>      ?T)ZxywhZGIoUr   r   r           c                 S   s   g | ]\}}t || qS r   r   )r&   icr   r   r   r(   p   r)   c                    s<   g | ]4\}\}}t j|t jd t j|t jd  |  fqS r   r"   )r&   kr0   j	gt_groupsr   r   r(   r   s   
)shapesumrangedetachviewr   FZsigmoidZsoftmaxr   r   logZ	unsqueezeabsr   squeezer   r   Z
_cost_maskisnanisinfcpu	enumeratesplitr#   Z	as_tensorZcumsum_)r   Zpred_bboxesZpred_scoresZ	gt_bboxesgt_clsr5   masksZgt_maskbsZnqncZneg_cost_classZpos_cost_classZ
cost_classZ	cost_bboxZ	cost_giouCindicesr   r4   r   forward.   s:    &"
&
zHungarianMatcher.forward)NTFr   r	   r
   )NN)__name__
__module____qualname____doc__r   rJ   __classcell__r   r   r   r   r      s   r   d         ?r.   Fc           "         s  |r|dkrdS | d }t |}	t|dkr4dS | }
|
dkrHdn|
}
t|}| d }| d }| d }|d|
 }|d|
 d}|d|
 d	}tj|	|
 tj|jd
|
|	  }|dkrt	|j
|d k }t|d	}tj|d||j|jd
}|||< |dkrt|}|dddf d dd| }t|ddd d }t|}||  d7  < ||9 }||| 7 }|jddd t|}tj|dd}td |
 }|| }tj|||j
d	 |jd}tj||d|jd}tdd |D  tj fddt|
D dd}t fddtd|
 D  ||| f< ||| f< || }tj||gtjd}d||dd|f< t|
D ]} | dkrd|d |  d | d  d | d  |f< | |
d krd|d |  d | d  d|  d f< ndd|d |  d | d  d | d  |f< d|d |  d | d  dd |  f< qdd | jt|ddD |
||gd}!||j||j||j|!fS )a  
    Get contrastive denoising training group. This function creates a contrastive denoising training group with positive
    and negative samples from the ground truths (gt). It applies noise to the class labels and bounding box coordinates,
    and returns the modified labels, bounding boxes, attention mask and meta information.

    Args:
        batch (dict): A dict that includes 'gt_cls' (torch.Tensor with shape [num_gts, ]), 'gt_bboxes'
            (torch.Tensor with shape [num_gts, 4]), 'gt_groups' (List(int)) which is a list of batch size length
            indicating the number of gts of each image.
        num_classes (int): Number of classes.
        num_queries (int): Number of queries.
        class_embed (torch.Tensor): Embedding weights to map class labels to embedding space.
        num_dn (int, optional): Number of denoising. Defaults to 100.
        cls_noise_ratio (float, optional): Noise ratio for class labels. Defaults to 0.5.
        box_noise_scale (float, optional): Noise scale for bounding box coordinates. Defaults to 1.0.
        training (bool, optional): If it's in training mode. Defaults to False.

    Returns:
        (Tuple[Optional[Tensor], Optional[Tensor], Optional[Tensor], Optional[Dict]]): The modified class embeddings,
            bounding boxes, attention mask and meta information for denoising. If not in training mode or 'num_dn'
            is less than or equal to 0, the function returns None for all elements in the tuple.
    r   )NNNNr5   r   clsZbboxesZ	batch_idxr   r*   )r!   devicerQ   .Nr
   r.   r/   )minmaxgư>)Zeps)rS   r-   c                 S   s    g | ]}t jt|t jd qS r   )r#   r$   r8   r%   )r&   numr   r   r   r(      r)   z!get_cdn_group.<locals>.<listcomp>c                    s   g | ]} |  qS r   r   r&   r0   Zmap_indicesZmax_numsr   r   r(      r)   r+   c                    s   g | ]} |  qS r   r   rW   rX   r   r   r(      r)   r    Tc                 S   s   g | ]}| d qS )r*   )Zreshape)r&   pr   r   r   r(      r)   )Z
dn_pos_idxZdn_num_groupZdn_num_split)r7   rU   lenrepeatr:   r#   Zaranger%   rS   Zrandr6   Znonzeror>   Zrandint_liker!   r   Z	rand_likeZclip_r   ZlogitintZzeroscatstackr8   boolrA   rC   listto)"batchZnum_classesZnum_queriesZclass_embedZnum_dnZcls_noise_ratioZbox_noise_scaleZtrainingr5   Z	total_numZ	num_grouprF   rD   Zgt_bboxZb_idxZdn_clsZdn_bboxZdn_b_idxZneg_idxr   idxZ	new_labelZ
known_bboxdiffZ	rand_signZ	rand_partZdn_cls_embedZpadding_clsZpadding_bboxZpos_idxZtgt_sizeZ	attn_maskr0   Zdn_metar   rX   r   get_cdn_group   sz     

 
""
4244


re   )rP   rQ   r.   F)r#   Ztorch.nnnnZtorch.nn.functionalZ
functionalr;   Zscipy.optimizer   Zultralytics.utils.metricsr   Zultralytics.utils.opsr   r   Moduler   re   r   r   r   r   <module>   s     