U
    •Ê¹j¼0  ã                   @   sÜ   d dl Z d dl mZ d dlmZmZmZmZmZmZm	Z	m
Z
mZ dddddd	gZed
dd�ZG dd„ de	e ƒZG dd„ dee ƒZG dd„ dee ƒZG dd„ dee ƒZG dd	„ d	ee ƒZG dd„ deee  ƒZdS )é    N)ÚTensor)	ÚIteratorÚIterableÚOptionalÚSequenceÚListÚTypeVarÚGenericÚSizedÚUnionÚBatchSamplerÚRandomSamplerÚSamplerÚSequentialSamplerÚSubsetRandomSamplerÚWeightedRandomSamplerÚT_coT)Ú	covariantc                   @   s8   e Zd ZdZd	ee ddœdd„Zee dœdd„Z	dS )
r   a/  Base class for all Samplers.

    Every Sampler subclass has to provide an :meth:`__iter__` method, providing a
    way to iterate over indices or lists of indices (batches) of dataset elements, and a :meth:`__len__` method
    that returns the length of the returned iterators.

    Args:
        data_source (Dataset): This argument is not used and will be removed in 2.2.0.
            You may still have custom implementation that utilizes it.

    Example:
        >>> # xdoctest: +SKIP
        >>> class AccedingSequenceLengthSampler(Sampler[int]):
        >>>     def __init__(self, data: List[str]) -> None:
        >>>         self.data = data
        >>>
        >>>     def __len__(self) -> int:
        >>>         return len(self.data)
        >>>
        >>>     def __iter__(self) -> Iterator[int]:
        >>>         sizes = torch.tensor([len(x) for x in self.data])
        >>>         yield from torch.argsort(sizes).tolist()
        >>>
        >>> class AccedingSequenceLengthBatchSampler(Sampler[List[int]]):
        >>>     def __init__(self, data: List[str], batch_size: int) -> None:
        >>>         self.data = data
        >>>         self.batch_size = batch_size
        >>>
        >>>     def __len__(self) -> int:
        >>>         return (len(self.data) + self.batch_size - 1) // self.batch_size
        >>>
        >>>     def __iter__(self) -> Iterator[List[int]]:
        >>>         sizes = torch.tensor([len(x) for x in self.data])
        >>>         for batch in torch.chunk(torch.argsort(sizes), len(self)):
        >>>             yield batch.tolist()

    .. note:: The :meth:`__len__` method isn't strictly required by
              :class:`~torch.utils.data.DataLoader`, but is expected in any
              calculation involving the length of a :class:`~torch.utils.data.DataLoader`.
    N©Údata_sourceÚreturnc                 C   s   |d k	rdd l }| d¡ d S )Nr   zz`data_source` argument is not used and will be removed in 2.2.0.You may still have custom implementation that utilizes it.)ÚwarningsÚwarn)Úselfr   r   © r   úW/var/www/html/bwave/python/venv/lib/python3.8/site-packages/torch/utils/data/sampler.pyÚ__init__<   s    zSampler.__init__©r   c                 C   s   t ‚d S ©N)ÚNotImplementedError©r   r   r   r   Ú__iter__C   s    zSampler.__iter__)N)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r
   r   r   r   r!   r   r   r   r   r      s   )c                   @   sJ   e Zd ZU dZeed< eddœdd„Zee dœdd	„Z	edœd
d„Z
dS )r   z~Samples elements sequentially, always in the same order.

    Args:
        data_source (Dataset): dataset to sample from
    r   Nr   c                 C   s
   || _ d S r   )r   )r   r   r   r   r   r   j   s    zSequentialSampler.__init__r   c                 C   s   t tt| jƒƒƒS r   )ÚiterÚrangeÚlenr   r    r   r   r   r!   m   s    zSequentialSampler.__iter__c                 C   s
   t | jƒS r   )r(   r   r    r   r   r   Ú__len__p   s    zSequentialSampler.__len__)r"   r#   r$   r%   r
   Ú__annotations__r   r   Úintr!   r)   r   r   r   r   r   b   s
   
c                   @   sn   e Zd ZU dZeed< eed< deeee ddœdd„Z	e
ed	œd
d„ƒZee d	œdd„Zed	œdd„ZdS )r   aÚ  Samples elements randomly. If without replacement, then sample from a shuffled dataset.
    If with replacement, then user can specify :attr:`num_samples` to draw.

    Args:
        data_source (Dataset): dataset to sample from
        replacement (bool): samples are drawn on-demand with replacement if ``True``, default=``False``
        num_samples (int): number of samples to draw, default=`len(dataset)`.
        generator (Generator): Generator used in sampling.
    r   ÚreplacementFN)r   r,   Únum_samplesr   c                 C   s^   || _ || _|| _|| _t| jtƒs4td| j› �ƒ‚t| jtƒrJ| jdkrZt	d| j› �ƒ‚d S )Nú;replacement should be a boolean value, but got replacement=r   úDnum_samples should be a positive integer value, but got num_samples=)
r   r,   Ú_num_samplesÚ	generatorÚ
isinstanceÚboolÚ	TypeErrorr-   r+   Ú
ValueError)r   r   r,   r-   r1   r   r   r   r   �   s    zRandomSampler.__init__r   c                 C   s   | j d krt| jƒS | j S r   )r0   r(   r   r    r   r   r   r-   Ž   s    

zRandomSampler.num_samplesc                 c   s   t | jƒ}| jd krDttjdtjd� ¡  ¡ ƒ}t 	¡ }| 
|¡ n| j}| jrªt| jd ƒD ]"}tj|dtj|d� ¡ E d H  q^tj|| jd ftj|d� ¡ E d H  nRt| j| ƒD ]}tj||d� ¡ E d H  q¸tj||d� ¡ d | j| … E d H  d S )Nr   ©Údtypeé    )r8   )ÚhighÚsizer7   r1   ©r1   )r(   r   r1   r+   ÚtorchÚemptyZint64Zrandom_ÚitemÚ	GeneratorZmanual_seedr,   r'   r-   ÚrandintÚtolistÚrandperm)r   ÚnÚseedr1   Ú_r   r   r   r!   •   s    

 (zRandomSampler.__iter__c                 C   s   | j S r   ©r-   r    r   r   r   r)   §   s    zRandomSampler.__len__)FNN)r"   r#   r$   r%   r
   r*   r3   r   r+   r   Úpropertyr-   r   r!   r)   r   r   r   r   r   t   s   
	    ÿ ÿc                   @   sT   e Zd ZU dZee ed< dee ddœdd„Zee dœdd	„Z	edœd
d„Z
dS )r   zÉSamples elements randomly from a given list of indices, without replacement.

    Args:
        indices (sequence): a sequence of indices
        generator (Generator): Generator used in sampling.
    ÚindicesN)rH   r   c                 C   s   || _ || _d S r   )rH   r1   )r   rH   r1   r   r   r   r   ´   s    zSubsetRandomSampler.__init__r   c                 c   s,   t jt| jƒ| jd�D ]}| j| V  qd S ©Nr;   )r<   rB   r(   rH   r1   )r   Úir   r   r   r!   ¸   s    zSubsetRandomSampler.__iter__c                 C   s
   t | jƒS r   )r(   rH   r    r   r   r   r)   ¼   s    zSubsetRandomSampler.__len__)N)r"   r#   r$   r%   r   r+   r*   r   r   r!   r)   r   r   r   r   r   «   s
   
c                   @   sd   e Zd ZU dZeed< eed< eed< dee	 eeddœdd	„Z
ee d
œdd„Zed
œdd„ZdS )r   aN  Samples elements from ``[0,..,len(weights)-1]`` with given probabilities (weights).

    Args:
        weights (sequence)   : a sequence of weights, not necessary summing up to one
        num_samples (int): number of samples to draw
        replacement (bool): if ``True``, samples are drawn with replacement.
            If not, they are drawn without replacement, which means that when a
            sample index is drawn for a row, it cannot be drawn again for that row.
        generator (Generator): Generator used in sampling.

    Example:
        >>> # xdoctest: +IGNORE_WANT("non-deterministic")
        >>> list(WeightedRandomSampler([0.1, 0.9, 0.4, 0.7, 3.0, 0.6], 5, replacement=True))
        [4, 4, 1, 4, 5]
        >>> list(WeightedRandomSampler([0.9, 0.4, 0.05, 0.2, 0.3, 0.1], 5, replacement=False))
        [0, 1, 4, 3, 2]
    Úweightsr-   r,   TN)rK   r-   r,   r   c                 C   s�   t |tƒrt |tƒs|dkr*td|› �ƒ‚t |tƒsBtd|› �ƒ‚tj|tjd�}t|jƒdkrttdt	|jƒ› �ƒ‚|| _
|| _|| _|| _d S )Nr   r/   r.   r6   é   z=weights should be a 1d sequence but given weights have shape )r2   r+   r3   r5   r<   Z	as_tensorÚdoubler(   ÚshapeÚtuplerK   r-   r,   r1   )r   rK   r-   r,   r1   Zweights_tensorr   r   r   r   Ö   s    ÿ
zWeightedRandomSampler.__init__r   c                 c   s0   t j| j| j| j| jd�}t| ¡ ƒE d H  d S rI   )r<   ZmultinomialrK   r-   r,   r1   r&   rA   )r   Zrand_tensorr   r   r   r!   è   s    zWeightedRandomSampler.__iter__c                 C   s   | j S r   rF   r    r   r   r   r)   ì   s    zWeightedRandomSampler.__len__)TN)r"   r#   r$   r%   r   r*   r+   r3   r   Úfloatr   r   r!   r)   r   r   r   r   r   À   s   
   ÿ
 ÿc                   @   sX   e Zd ZdZeee ee f eeddœdd„Z	e
ee  dœdd„Zedœd	d
„ZdS )r   ai  Wraps another sampler to yield a mini-batch of indices.

    Args:
        sampler (Sampler or Iterable): Base sampler. Can be any iterable object
        batch_size (int): Size of mini-batch.
        drop_last (bool): If ``True``, the sampler will drop the last batch if
            its size would be less than ``batch_size``

    Example:
        >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=False))
        [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]
        >>> list(BatchSampler(SequentialSampler(range(10)), batch_size=3, drop_last=True))
        [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
    N)ÚsamplerÚ
batch_sizeÚ	drop_lastr   c                 C   sX   t |tƒrt |tƒs|dkr*td|› �ƒ‚t |tƒsBtd|› �ƒ‚|| _|| _|| _d S )Nr   zBbatch_size should be a positive integer value, but got batch_size=z7drop_last should be a boolean value, but got drop_last=)r2   r+   r3   r5   rQ   rR   rS   )r   rQ   rR   rS   r   r   r   r      s    ÿ
zBatchSampler.__init__r   c                 #   s¶   | j rPt| jƒ‰ z"‡ fdd„t| jƒD ƒ}|V  W q tk
rJ   Y q²Y qX qnbdg| j }d}| jD ]4}|||< |d7 }|| jkrf|V  d}dg| j }qf|dkr²|d |… V  d S )Nc                    s   g | ]}t ˆ ƒ‘qS r   )Únext)Ú.0rE   ©Zsampler_iterr   r   Ú
<listcomp>  s     z)BatchSampler.__iter__.<locals>.<listcomp>r   rL   )rS   r&   rQ   r'   rR   ÚStopIteration)r   ÚbatchZidx_in_batchÚidxr   rV   r   r!     s$    



zBatchSampler.__iter__c                 C   s4   | j rt| jƒ| j S t| jƒ| j d | j S d S )NrL   )rS   r(   rQ   rR   r    r   r   r   r)   $  s    zBatchSampler.__len__)r"   r#   r$   r%   r   r   r+   r   r3   r   r   r   r!   r)   r   r   r   r   r   ð   s   $)r<   r   Útypingr   r   r   r   r   r   r	   r
   r   Ú__all__r   r   r+   r   r   r   r   r   r   r   r   r   Ú<module>   s    ,ú	P70