
    FPh3                         d dl Z d dlmZ d dlmc mZ d dlmZ d dlm	Z	 d dl
mZmZ  G d dej                        Z	 	 	 	 ddZy)	    N)linear_sum_assignment)bbox_iou)	xywh2xyxy	xyxy2xywhc                   ,     e Zd ZdZd fd	ZddZ x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.
    c                     t         |           |dddddd}|| _        || _        || _        || _        || _        || _        y)zInitializes HungarianMatcher with cost coefficients, Focal Loss, mask prediction, sample points, and alpha
        gamma factors.
        N         )classbboxgioumaskdice)super__init__	cost_gainuse_fl	with_masknum_sample_pointsalphagamma)selfr   r   r   r   r   r   	__class__s          gC:\Users\daisl\Desktop\realtime-object-detection\venv\Lib\site-packages\ultralytics/models/utils/ops.pyr   zHungarianMatcher.__init__"   sQ     	"#Q1aPI""!2

    c           
         |j                   \  }}	}
t        |      dk(  rat        |      D cg c]L  }t        j                  g t        j
                        t        j                  g t        j
                        fN c}S |j                         j                  d|
      }| j                  rt        j                  |      nt        j                  |d      }|j                         j                  dd      }|dd|f   }| j                  rqd| j                  z
  || j                  z  z  d|z
  dz   j                          z  }| j                  d|z
  | j                  z  z  |dz   j                          z  }||z
  }n| }|j                  d      |j                  d      z
  j!                         j                  d      }d	t#        |j                  d      |j                  d      d
d
      j%                  d      z
  }| j&                  d   |z  | j&                  d   |z  z   | j&                  d   |z  z   }| j(                  r|| j+                  ||||      z  }d||j-                         |j/                         z  <   |j                  ||	d      j1                         }t3        |j5                  |d            D cg c]  \  }}t7        ||          }}}t        j8                  dg|dd       j;                  d      }t3        |      D cg c]X  \  }\  }}t        j                  |t        j
                        t        j                  |t        j
                        ||   z   fZ c}}}S c c}w c c}}w c c}}}w )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   dtypedim   Nr
   g:0yE>      ?T)xywhGIoUr   r   r           )shapesumrangetorchtensorlongdetachviewr   Fsigmoidsoftmaxr   r   log	unsqueezeabsr   squeezer   r   
_cost_maskisnanisinfcpu	enumeratesplitr   	as_tensorcumsum_)r   pred_bboxespred_scores	gt_bboxesgt_cls	gt_groupsmasksgt_maskbsnqnc_neg_cost_classpos_cost_class
cost_class	cost_bbox	cost_giouCicindiceskjs                          r   forwardzHungarianMatcher.forward0   s.   4 !&&
By>QfklnfopfoabU\\"EJJ7bPUPZPZ9[\fopp "((*//B704aii,;\^A_!((*//A6 "!V),;;$**n

1JKQRU`Q`cgQgPlPlPnOnoN!ZZAO

+JKQ\_cQcPhPhPjOjkN'.8J%J !**1-	0C0CA0FFKKMQQRTU	 (;#8#8#;Y=P=PQR=SZ^eijrrsuvv	 NN7#j0NN6"Y./NN6"Y./ >>Yw??A $'!'')aggi
 FF2r2""$;DQWWYXZE[;\];\41a(1.;\]OOQ$83B$89AA!D	 "+7!35!3IAv1 auzz2ELL%**4UXabcXd4de!35 	5O qH ^5s   AM4>M9AM?)NTFi 1  g      ?       @)NN)__name__
__module____qualname____doc__r   rV   __classcell__)r   s   @r   r   r      s    *E5r   r   c           
      	   |r|dk  ry| d   }t        |      }	t        |      }
|
dk(  ry||
z  }|dk(  rdn|}t        |      }| d   }| d   }| d   }|j                  d|z        }|j                  d|z  d      }|j                  d|z        j	                  d	      }t        j                  |	|z  t
        j                  |j                  
      ||	z  z   }|dkD  r|t        j                  |j                        |dz  k  }t        j                  |      j                  d	      }t        j                  |d||j                  |j                  
      }|||<   |dkD  rt        |      }|dddf   dz  j                  dd      |z  }t        j                  |dd      dz  dz
  }t        j                   |      }||xx   dz  cc<   ||z  }|||z  z  }|j#                  dd       t%        |      }t        j&                  |d      }t)        |
dz  |z        }||   }t        j*                  |||j                  d	   |j                        }t        j*                  ||d|j                        }t        j,                  |D cg c]0  }t        j.                  t1        |      t
        j                        2 c}      }t        j2                  t1        |      D  cg c]
  } ||
| z  z    c} d      }!t        j,                  t1        d|z        D  cg c]
  } ||
| z  z    c}       }||||f<   ||||f<   ||z   }"t        j*                  |"|"gt
        j4                        }#d|#|dd|f<   t1        |      D ]  } | dk(  r#d|#|
dz  | z  |
dz  | dz   z  |
dz  | dz   z  |f<   | |dz
  k(  r!d|#|
dz  | z  |
dz  | dz   z  d|
| z  dz  f<   Td|#|
dz  | z  |
dz  | dz   z  |
dz  | dz   z  |f<   d|#|
dz  | z  |
dz  | dz   z  d|
dz  | z  f<    |!j7                         j9                  t;        |      d      D $cg c]  }$|$j=                  d	       c}$|||gd}%|j?                  |j                        |j?                  |j                        |#j?                  |j                        |%fS c c}w c c} w c c} w c c}$w )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   )NNNNrD   r
   clsbboxes	batch_idxr   r!   )r    device      ?.NrW   r%   r(   )minmaxgư>)eps)ra   r$   r   r"   T)
dn_pos_idxdn_num_groupdn_num_split) r*   rd   lenrepeatr0   r,   aranger.   ra   randr)   nonzeror7   randint_liker    r   	rand_likeclip_r   logitintzeroscatr-   r+   stackboolr;   r=   listreshapeto)&batchnum_classesnum_queriesclass_embednum_dncls_noise_ratiobox_noise_scaletrainingrD   	total_nummax_nums	num_grouprG   rC   gt_bboxb_idxdn_clsdn_bboxdn_b_idxneg_idxr   idx	new_label
known_bboxdiff	rand_sign	rand_partdn_cls_embedpadding_clspadding_bboxnummap_indicesrQ   pos_idxtgt_size	attn_maskpdn_metas&                                         r   get_cdn_groupr      s   > 1%k"III9~H1}%("I!^I	YB5\FHoG+E ]]1y=)FnnQ]A.G||A	M*//3H ll9y0

7>>Z]fir]rrGzz&,,'?S+@AmmD!))"-&&sA{&,,W]WdWde	sw'
QR 3&..q!4F&&w15;cA	OOG,	'c!Y	i$&&
Sc*J'++g40A	)*Fv&L++b&,*<*<R*@WK;;r61W^^DL))S\]S\CU\\%*EJJGS\]^KkkuY?OP?O!;A5?OPVWXG))q9}AUVAUA[8a<7AUVWK+7K;'(,3L(K()#HXx0

CI"&Ifgww96`dIhlQ&x!|q1u'==x!|qSTu?UV\?\\]	ATXIhlQ&x!|q1u'==?P1q@P?PPQ`dIhlQ&x!|q1u'==x!|qSTu?UV\?\\]TXIhlQ&x!|q1u'==?P1q@P?PPQ  /6kkm.A.A$y/WX.A.YZ.Yqyy}.YZ!-/G
 >>+,,-|{?Q?Q/RT]T`T`U$% %3 ^PV$ [s   5R0R5R:>R?)d   rb   r%   F)r,   torch.nnnntorch.nn.functional
functionalr1   scipy.optimizer   ultralytics.utils.metricsr   ultralytics.utils.opsr   r   Moduler   r    r   r   <module>r      sC        0 . 6i5ryy i5\ "%"% n%r   