o
    si(                     @   s>   d dl Z d dlmZ d dlZd dlmZ G dd dejZdS )    N)combinations)nnc                       s\   e Zd ZdZd fdd	ZdddZed	d
 Zedd Zedd Z	edd Z
  ZS )MixITLossWrappera  Mixture invariant loss wrapper.

    Args:
        loss_func: function with signature (est_targets, targets, **kwargs).
        generalized (bool): Determines how MixIT is applied. If False ,
            apply MixIT for any number of mixtures as soon as they contain
            the same number of sources (:meth:`~MixITLossWrapper.best_part_mixit`.)
            If True (default), apply MixIT for two mixtures, but those mixtures do not
            necessarly have to contain the same number of sources.
            See :meth:`~MixITLossWrapper.best_part_mixit_generalized`.
        reduction (string, optional): Specifies the reduction to apply to
            the output:
            ``'none'`` | ``'mean'``. ``'none'``: no reduction will be applied,
            ``'mean'``: the sum of the output will be divided by the number of
            elements in the output.

    For each of these modes, the best partition and reordering will be
    automatically computed.

    Examples:
        >>> import torch
        >>> from asteroid.losses import multisrc_mse
        >>> mixtures = torch.randn(10, 2, 16000)
        >>> est_sources = torch.randn(10, 4, 16000)
        >>> # Compute MixIT loss based on pairwise losses
        >>> loss_func = MixITLossWrapper(multisrc_mse)
        >>> loss_val = loss_func(est_sources, mixtures)

    References
        [1] Scott Wisdom et al. "Unsupervised sound separation using
        mixtures of mixtures." arXiv:2006.12701 (2020)
    Tmeanc                    s    t    || _|| _|| _d S )N)super__init__	loss_funcgeneralized	reduction)selfr   r	   r
   	__class__ Q/home/ubuntu/.local/lib/python3.10/site-packages/asteroid/losses/mixit_wrapper.pyr   )   s   

zMixITLossWrapper.__init__Fc           
      K   s   |j d |j d ksJ |j d |j d ksJ | js+| j| j||fi |\}}}n| j| j||fi |\}}}| jdkrC| n|}|sI|S | ||||}	||	fS )at  Find the best partition and return the loss.

        Args:
            est_targets: torch.Tensor. Expected shape :math:`(batch, nsrc, *)`.
                The batch of target estimates.
            targets: torch.Tensor. Expected shape :math:`(batch, nmix, ...)`.
                The batch of training targets
            return_est: Boolean. Whether to return the estimated mixtures
                estimates (To compute metrics or to save example).
            **kwargs: additional keyword argument that will be passed to the
                loss function.

        Returns:
            - Best partition loss for each batch sample, average over
              the batch. torch.Tensor(loss_value)
            - The estimated mixtures (estimated sources summed according to the partition)
              if return_est is True. torch.Tensor of shape :math:`(batch, nmix, ...)`.
        r      r   )shaper	   best_part_mixitr   best_part_mixit_generalizedr
   r   reorder_source)
r   est_targetstargets
return_estkwargsmin_lossmin_loss_idxpartsreturned_loss	reorderedr   r   r   forward/   s$   zMixITLossWrapper.forwardc                    s   |j d }|j d }|| dkrtd|| } fdd t t|||}tj| f|||d|}tj|ddd\}	}
|	|
|fS )	a0  Find best partition of the estimated sources that gives the minimum
        loss for the MixIT training paradigm in [1]. Valid for any number of
        mixtures as soon as they contain the same number of sources.

        Args:
            loss_func: function with signature ``(est_targets, targets, **kwargs)``
                The loss function to get batch losses from.
            est_targets: torch.Tensor. Expected shape :math:`(batch, nsrc, ...)`.
                The batch of target estimates.
            targets: torch.Tensor. Expected shape :math:`(batch, nmix, ...)`.
                The batch of training targets (mixtures).
            **kwargs: additional keyword argument that will be passed to the
                loss function.

        Returns:
            - :class:`torch.Tensor`:
              The loss corresponding to the best permutation of size (batch,).

            - :class:`torch.LongTensor`:
              The indices of the best partition.

            - :class:`list`:
              list of the possible partitions of the sources.

           r   z>The mixtures are assumed to contain the same number of sourcesc                 3   s`    |dkr
g V  d S t | |D ]  fdd| D }|||d D ]
}t g|V  q"qd S )Nr   c                       g | ]}| vr|qS r   r   .0xcr   r   
<listcomp>       zIMixITLossWrapper.best_part_mixit.<locals>.parts_mixit.<locals>.<listcomp>r   )r   list)lstklrestrparts_mixitr$   r   r/   }   s   
z5MixITLossWrapper.best_part_mixit.<locals>.parts_mixitr   r   r   Tdimkeepdim)r   
ValueErrorr(   ranger   loss_set_from_partstorchmin)r   r   r   r   nmixnsrcnsrcmixr   loss_setr   min_loss_indexesr   r.   r   r   X   s    



z MixITLossWrapper.best_part_mixitc                 K   sp   |j d }|j d }|dkrtddd }|t|}tj| f|||d|}tj|ddd\}	}
|	|
|fS )	a  Find best partition of the estimated sources that gives the minimum
        loss for the MixIT training paradigm in [1]. Valid only for two mixtures,
        but those mixtures do not necessarly have to contain the same number of
        sources e.g the case where one mixture is silent is allowed..

        Args:
            loss_func: function with signature ``(est_targets, targets, **kwargs)``
                The loss function to get batch losses from.
            est_targets: torch.Tensor. Expected shape :math:`(batch, nsrc, ...)`.
                The batch of target estimates.
            targets: torch.Tensor. Expected shape :math:`(batch, nmix, ...)`.
                The batch of training targets (mixtures).
            **kwargs: additional keyword argument that will be passed to the
                loss function.

        Returns:
            - :class:`torch.Tensor`:
              The loss corresponding to the best permutation of size (batch,).

            - :class:`torch.LongTensor`:
              The indexes of the best permutations.

            - :class:`list`:
              list of the possible partitions of the sources.
        r   r   zWorks only with two mixturesc                    sR   g }t t| d D ]}t| |D ]  fdd| D }|t |g qq
|S )Nr   c                    r    r   r   r!   r$   r   r   r&      r'   zYMixITLossWrapper.best_part_mixit_generalized.<locals>.parts_mixit_gen.<locals>.<listcomp>)r5   lenr   appendr(   )r)   
partitionsr*   r,   r   r$   r   parts_mixit_gen   s   zEMixITLossWrapper.best_part_mixit_generalized.<locals>.parts_mixit_genr0   Tr1   )r   r4   r5   r   r6   r7   r8   )r   r   r   r   r9   r:   rA   r   r<   r   r=   r   r   r   r      s   

	
z,MixITLossWrapper.best_part_mixit_generalizedc           	         sv   g }|D ]-}t j fdd|D dd}| ||fi |}|jdkr&td||dddf  qt j|dd}|S )z(Common loop between both best_part_mixitc                    s(   g | ]} d d |d d f  dqS Nr   sumr"   idxr   r   r   r&      s   ( z8MixITLossWrapper.loss_set_from_parts.<locals>.<listcomp>r   r2   z6Loss function return value should be of size (batch,).N)r7   stackndimr4   r?   cat)	r   r   r   r   r   r<   	partition	est_mixesloss_partitionr   rG   r   r6      s   
z$MixITLossWrapper.loss_set_from_partsc                    sX   t |}t|D ] \ }|| }t j fdd|D dd| ddddf< q	|S )aI  Reorder sources according to the best partition.

        Args:
            est_targets: torch.Tensor. Expected shape :math:`(batch, nsrc, ...)`.
                The batch of target estimates.
            targets: torch.Tensor. Expected shape :math:`(batch, nmix, ...)`.
                The batch of training targets.
            min_loss_idx: torch.LongTensor. The indexes of the best permutations.
            parts: list of the possible partitions of the sources.

        Returns:
            :class:`torch.Tensor`: Reordered sources of shape :math:`(batch, nmix, time)`.

        c                    s6   g | ]} |d d f d d d d d f  dqS rB   rC   rE   br   r   r   r&      s   6 z3MixITLossWrapper.reorder_source.<locals>.<listcomp>r   rH   N)r7   
zeros_like	enumeraterI   )r   r   r   r   orderedrF   right_partitionr   rO   r   r      s   
zMixITLossWrapper.reorder_source)Tr   )F)__name__
__module____qualname____doc__r   r   staticmethodr   r   r6   r   __classcell__r   r   r   r   r      s    !
)
7
3
r   )warnings	itertoolsr   r7   r   Moduler   r   r   r   r   <module>   s
    