U
    PhT                     @  s  d dl mZ d dlZd dlmZ d dlmZ d dlZd dl	Z	d dl
Z
d dlmZmZ d dlmZ ed\ZZeddd	\ZZd
ddddddddddgZedejedejedejiZddddd
ZdddddZdddddZdddddZd d Zd!d"d#d$dZdAd!d"d&d'd'd'd!d(d)dZdBd!d*d'd'd!d+d,dZ dCd!d-d'd'd!d+d.dZ!dDd!d/d&d"d'd'd0d1d2dZ"dEd!d3d4d'd&d'd0d5d6dZ#d7d8d#d9d:Z$d"d;dd<d=Z%dFd!d"d!d>d?d@Z&dS )G    )annotationsN)Sequence)Any)	DtypeLikeNdarrayTensor)optional_importcupyndarray)nameget_numpy_dtype_from_stringget_torch_dtype_from_stringdtype_torch_to_numpydtype_numpy_to_torchget_equivalent_dtypeconvert_data_type	get_dtypeconvert_to_cupyconvert_to_numpyconvert_to_tensorconvert_to_dst_typeuint16uint32uint64strznp.dtype)dtypereturnc                 C  s   t jg t| dd djS )zKGet a numpy dtype (e.g., `np.float32`) from its string (e.g., `"float32"`)..r   )npemptyr   splitr   r    r"   P/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/utils/type_conversion.pyr   .   s    ztorch.dtypec                 C  s   t t| S )zNGet a torch dtype (e.g., `torch.float32`) from its string (e.g., `"float32"`).)r   r   r   r"   r"   r#   r   3   s    c                 C  s   t jg | d jS )z.Convert a torch dtype to its numpy equivalent.r   )torchr    numpyr   r   r"   r"   r#   r   8   s    c                 C  s   t tjg | djS )z.Convert a numpy dtype to its torch equivalent.r   )r$   
from_numpyr   r    r   r   r"   r"   r#   r   =   s    c                 C  sP   | dkrdS |t jks |jdkr8t| t jr0| S t| S t| t jsH| S t| S )a  Convert to the `dtype` that corresponds to `data_type`.

    The input dtype can also be a string. e.g., `"float32"` becomes `torch.float32` or
    `np.float32` as necessary.

    Example::

        im = torch.tensor(1)
        dtype = get_equivalent_dtype(np.float32, type(im))

    N
MetaTensor)r$   Tensor__name__
isinstancer   r   r   )r   	data_typer"   r"   r#   r   B   s    r   zDtypeLike | torch.dtype)datar   c                 C  s.   t | dr| jS t| tr&t| d S t| S )zGet the dtype of an image, or if there is a sequence, recursively call the method on the 0th element.

    This therefore assumes that in a `Sequence`, all types are the same.
    r   r   )hasattrr   r*   r   r   typer,   r"   r"   r#   r   [   s
    

FzNone | str | torch.devicebool)r,   r   devicewrap_sequence
track_metasafer   c           	        s`  ddddfdd}|r$t | } ttjt| tjrR|| j tjdS t| tjrt	
d| jjdkr| jdkrt| } ||  d	S ntrt| tst| tttfr||  d	S t| tr fd
d| D }|r|| d	S |S t| tr6t fdd| D }|r2|| d	S |S t| tr\ fdd|  D S | S )a  
    Utility to convert the input data to a PyTorch Tensor, if `track_meta` is True, the output will be a `MetaTensor`,
    otherwise, the output will be a regular torch Tensor.
    If passing a dictionary, list or tuple, recursively check every item and convert it to PyTorch Tensor.

    Args:
        data: input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc.
            will convert Tensor, Numpy array, float, int, bool to Tensor, strings and objects keep the original.
            for dictionary, list or tuple, convert every item to a Tensor if applicable.
        dtype: target data type to when converting to Tensor.
        device: target device to put the converted Tensor data.
        wrap_sequence: if `False`, then lists will recursively call this function.
            E.g., `[1, 2]` -> `[tensor(1), tensor(2)]`. If `True`, then `[1, 2]` -> `tensor([1, 2])`.
        track_meta: whether to track the meta information, if `True`, will convert to `MetaTensor`.
            default to `False`.
        safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`.
            E.g., `[256, -12]` -> `[tensor(0), tensor(244)]`.
            If `True`, then `[256, -12]` -> `[tensor(255), tensor(0)]`.

    r   )tensorkwargsr   c                   s|   t | tjs@t | tjr2| jtkr2| t| j } tj| f|}  r^t | t	j
js^t	j
| S  sxt | t	j
jrx|  S | S N)r*   r$   r(   r   r	   r   UNSUPPORTED_TYPESastype	as_tensormonair,   r'   )r5   r6   )r3   r"   r#   _convert_tensor   s    z*convert_to_tensor.<locals>._convert_tensor)r   r1   memory_formatz[SaUO]Nr   )r   r1   c                   s   g | ]}t | d qS r   r1   r3   r   .0ir1   r   r3   r"   r#   
<listcomp>   s     z%convert_to_tensor.<locals>.<listcomp>c                 3  s   | ]}t | d V  qdS )r?   Nr@   rA   rD   r"   r#   	<genexpr>   s     z$convert_to_tensor.<locals>.<genexpr>c              	     s"   i | ]\}}|t | d qS r>   r@   rB   kvrD   r"   r#   
<dictcomp>   s      z%convert_to_tensor.<locals>.<dictcomp>)safe_dtype_ranger   r$   r(   r*   tocontiguous_formatr   r	   researchr   r   ndimascontiguousarrayhas_cp
cp_ndarrayfloatintr0   listtupledictitems)	r,   r   r1   r2   r3   r4   r<   list_ret	tuple_retr"   rD   r#   r   i   s,    



r   )r,   r   r2   r4   r   c                   sn  |rt |  } t| tjrDtj|  jdd t	 tj
d} ntrht| trht| j dd} nt| tj
tttfrt| tj
r| jdkr| jjt jk rt| } tj|  d} nt| tr fdd| D }|rt|S |S t| tr$t fd	d
| D }|r t|S |S t| trF fdd|  D S t| tj
rj| jdkrjt| } | S )a  
    Utility to convert the input data to a numpy array. If passing a dictionary, list or tuple,
    recursively check every item and convert it to numpy array.

    Args:
        data: input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc.
            will convert Tensor, Numpy array, float, int, bool to numpy arrays, strings and objects keep the original.
            for dictionary, list or tuple, convert every item to a numpy array if applicable.
        dtype: target data type when converting to numpy array.
        wrap_sequence: if `False`, then lists will recursively call this function.
            E.g., `[1, 2]` -> `[array(1), array(2)]`. If `True`, then `[1, 2]` -> `array([1, 2])`.
        safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`.
            E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`.
    cpu)r1   r   F)copyr   c                   s   g | ]}t | d qS r   r   rA   r   r"   r#   rE      s     z$convert_to_numpy.<locals>.<listcomp>c                 3  s   | ]}t | d V  qdS r   Nr_   rA   r   r"   r#   rF      s     z#convert_to_numpy.<locals>.<genexpr>c                   s   i | ]\}}|t | d qS r^   r_   rG   r   r"   r#   rJ      s      z$convert_to_numpy.<locals>.<dictcomp>)rK   r*   r$   r(   r   asarraydetachrL   r%   r   r	   rR   rS   cpZasnumpyr9   rT   rU   r0   rP   r   itemsizerQ   rV   rW   rX   rY   r,   r   r2   r4   rZ   r[   r"   r   r#   r      s*    
**


znp.dtype | Nonec                   sB  |rt |  } t| tjr\| jjdkr\| jtjkrN|  	tj
}  dkrNt t|  } nt| ttjtjtttfrt|  } nt| tr fdd| D }|rt|S |S t| trt fdd| D }|rt|S |S t| tr fdd|  D S t| tjs(td	t|  d
| jdkr>t| } | S )a7  
    Utility to convert the input data to a cupy array. If passing a dictionary, list or tuple,
    recursively check every item and convert it to cupy array.

    Args:
        data: input data can be PyTorch Tensor, numpy array, cupy array, list, dictionary, int, float, bool, str, etc.
            Tensor, numpy array, cupy array, float, int, bool are converted to cupy arrays,
            for dictionary, list or tuple, convert every item to a numpy array if applicable.
        dtype: target data type when converting to Cupy array, tt must be an argument of `numpy.dtype`,
            for more details: https://docs.cupy.dev/en/stable/reference/generated/cupy.array.html.
        wrap_sequence: if `False`, then lists will recursively call this function.
            E.g., `[1, 2]` -> `[array(1), array(2)]`. If `True`, then `[1, 2]` -> `array([1, 2])`.
        safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`.
            E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`.
    cudaNc                   s   g | ]}t | qS r"   r   rA   r   r"   r#   rE      s     z#convert_to_cupy.<locals>.<listcomp>c                 3  s   | ]}t | V  qd S r7   rg   rA   r   r"   r#   rF      s     z"convert_to_cupy.<locals>.<genexpr>c                   s   i | ]\}}|t | qS r"   rg   rG   r   r"   r#   rJ      s      z#convert_to_cupy.<locals>.<dictcomp>zThe input data type [z'] cannot be converted into cupy arrays!r   )rK   r*   r$   r(   r1   r.   r   r0   rb   rL   uint8rc   ra   rS   r   r	   rT   rU   rV   rW   rX   rY   
ValueErrorrP   rQ   re   r"   r   r#   r      s.    



ztype[NdarrayTensor] | Nonez/tuple[NdarrayTensor, type, torch.device | None])r,   output_typer1   r   r2   r4   r   c                 C  s&  t | tjjrtjj}nHt | tjr,tj}n4t | tjr@tj}n trXt | t	jrXt	j}nt
| }t | tjrr| jnd}|p||}t||}t|tjrt|tjj}	t| ||||	|d}
|
||fS t|tjrt| |||d}
|
||fS trt|t	jrt| |||d}
|
||fS td| dS )ar  
    Convert to `MetaTensor`, `torch.Tensor` or `np.ndarray` from `MetaTensor`, `torch.Tensor`,
    `np.ndarray`, `float`, `int`, etc.

    Args:
        data: data to be converted
        output_type: `monai.data.MetaTensor`, `torch.Tensor`, or `np.ndarray` (if `None`, unchanged)
        device: if output is `MetaTensor` or `torch.Tensor`, select device (if `None`, unchanged)
        dtype: dtype of output data. Converted to correct library type (e.g.,
            `np.float32` is converted to `torch.float32` if output type is `torch.Tensor`).
            If left blank, it remains unchanged.
        wrap_sequence: if `False`, then lists will recursively call this function.
            E.g., `[1, 2]` -> `[array(1), array(2)]`. If `True`, then `[1, 2]` -> `array([1, 2])`.
        safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`.
            E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`.

    Returns:
        modified data, orig_type, orig_device

    Note:
        When both `output_type` and `dtype` are specified with different backend
        (e.g., `torch.Tensor` and `np.float32`), the `output_type` will be used as the primary type,
        for example::

            >>> convert_data_type(1, torch.Tensor, dtype=np.float32)
            (1.0, <class 'torch.Tensor'>, None)

    N)r   r1   r2   r3   r4   )r   r2   r4   zUnsupported output type: )r*   r;   r,   r'   r$   r(   r   r	   rR   rc   r.   r1   r   
issubclassr   r   r   ri   )r,   rj   r1   r   r2   r4   	orig_typeorig_devicedtype_r3   Zdata_r"   r"   r#   r   
  s<    %

     


r   zDtypeLike | torch.dtype | None)srcdstr   r2   r1   r4   r   c                 C  s   |dkrt |tjr|jn|}|dkr2t|dd}d}t |tjjr`tjj}t | tjjsd}n0t |tjrttj}nt |tj	rtj	}nt
|}t| |||||d\}}	}
|rt |tjjr|| ||	|
fS )a  
    Convert source data to the same data type and device as the destination data.
    If `dst` is an instance of `torch.Tensor` or its subclass, convert `src` to `torch.Tensor` with the same data type as `dst`,
    if `dst` is an instance of `numpy.ndarray` or its subclass, convert to `numpy.ndarray` with the same data type as `dst`,
    otherwise, convert to the type of `dst` directly.

    Args:
        src: source data to convert type.
        dst: destination data that convert to the same data type as it.
        dtype: an optional argument if the target `dtype` is different from the original `dst`'s data type.
        wrap_sequence: if `False`, then lists will recursively call this function. E.g., `[1, 2]` -> `[array(1), array(2)]`.
            If `True`, then `[1, 2]` -> `array([1, 2])`.
        device: target device to put the converted Tensor data. If unspecified, `dst.device` will be used if possible.
        safe: if `True`, then do safe dtype convert when intensity overflow. default to `False`.
            E.g., `[256, -12]` -> `[array(0), array(244)]`. If `True`, then `[256, -12]` -> `[array(255), array(0)]`.

    See Also:
        :func:`convert_data_type`
    Nr   FT)r,   rj   r1   r   r2   r4   )r*   r$   r(   r1   getattrr;   r,   r'   r   r	   r.   r   Zcopy_meta_from)ro   rp   r   r2   r1   r4   Z	copy_metarj   output_type_devicer"   r"   r#   r   O  s0         
z$Sequence | torch.Tensor | np.ndarrayrV   c                 C  s"   t | tjtjfr|  S t| S )z
    Convert to list from `torch.Tensor`/`np.ndarray`/`list`/`tuple` etc.
    Args:
        data: data to be converted
    Returns:
        a list

    )r*   r$   r(   r   r	   tolistrV   r/   r"   r"   r#   convert_to_list  s    	rv   ztuple[float, float]c                 C  s`   | t krd}nt| tjj}t| tj} |rDt| jt| j	fS t
| jt
| j	fS dS )z
    Get dtype bound value
    Args:
        dtype: dtype to get bound value
    Returns:
        (bound_min_value, bound_max_value)
    FN)r8   r   r$   r(   is_floating_pointr   arrayfinfominmaxiinfo)r   rw   r"   r"   r#   get_dtype_bound_value  s    r}   )r,   r   r   c                   s0  dd }t r&t| tr&t||  S t| tjrBt||  S t| tjrX||  S t| t	t
tfrt dkrt| S t| t	t
tfr̈ dk	r̈ }t|}| |d kr|d n| } | |d k r|d n| } | S t| tr fdd| D S t| tr
t fdd	| D S t| tr, fd
d|  D S | S )ai  
    Utility to safely convert the input data to target dtype.

    Args:
        data: input data can be PyTorch Tensor, numpy array, list, dictionary, int, float, bool, str, etc.
            will convert to target dtype and keep the original type.
            for dictionary, list or tuple, convert every item.
        dtype: target data type to convert.
    c                 S  s   |d k	r|n| j }t|}| jdkr.| | f}n6t| tjrPt| t| f}nt| t| f}|d |d ks|d |d k rt| tjrt	| |d |d S t| tj
rt| |d |d S trt| trt| |d |d S n| S d S )Nr      )r   r}   rP   r*   r$   r(   rz   r{   r   clampr	   cliprR   rS   rc   )r,   r   output_dtypedtype_bound_valueZ
data_boundr"   r"   r#   _safe_dtype_range  s    

 z+safe_dtype_range.<locals>._safe_dtype_rangeNr~   r   c                   s   g | ]}t | d qS r^   rK   rA   r   r"   r#   rE     s     z$safe_dtype_range.<locals>.<listcomp>c                 3  s   | ]}t | d V  qdS r`   r   rA   r   r"   r#   rF     s     z#safe_dtype_range.<locals>.<genexpr>c                   s   i | ]\}}|t | d qS r^   r   rG   r   r"   r#   rJ     s      z$safe_dtype_range.<locals>.<dictcomp>)rR   r*   rS   rc   ra   r   r	   r$   r(   rT   rU   r0   r}   rV   rW   rX   rY   )r,   r   r   r   r   r"   r   r#   rK     s,    

rK   )NNFFF)NFF)NFF)NNNFF)NFNF)N)'
__future__r   rN   collections.abcr   typingr   r%   r   r$   r;   Zmonai.config.type_definitionsr   r   monai.utilsr   rc   rR   rS   ___all__r   int32int64r8   r   r   r   r   r   r   r   r   r   r   r   rv   r}   rK   r"   r"   r"   r#   <module>   sf   (     G-/     H    5