U PhT @sddlmZddlZddlmZddlmZddlZddl Z ddl Z ddl m Z m Z ddlmZed\ZZeddd \ZZd d d d dddddddg ZedejedejedejiZddddd Zddddd Zddddd Zddddd Zd dZd!d"d#d$dZdAd!d"d&d'd'd'd!d(d)dZdBd!d*d'd'd!d+d,dZ dCd!d-d'd'd!d+d.dZ!dDd!d/d&d"d'd'd0d1d2dZ"dEd!d3d4d'd&d'd0d5d6dZ#d7d8d#d9d:Z$d"d;ddd?d@Z&dS)G) annotationsN)Sequence)Any) DtypeLike NdarrayTensor)optional_importcupyndarray)nameget_numpy_dtype_from_stringget_torch_dtype_from_stringdtype_torch_to_numpydtype_numpy_to_torchget_equivalent_dtypeconvert_data_type get_dtypeconvert_to_cupyconvert_to_numpyconvert_to_tensorconvert_to_dst_typeuint16uint32uint64strznp.dtype)dtypereturncCstjgt|dddjS)zKGet a numpy dtype (e.g., `np.float32`) from its string (e.g., `"float32"`)..r)npemptyrsplitrrr"P/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/utils/type_conversion.pyr .sz torch.dtypecCs tt|S)zNGet a torch dtype (e.g., `torch.float32`) from its string (e.g., `"float32"`).)rr rr"r"r#r 3scCstjg|djS)z.Convert a torch dtype to its numpy equivalent.r)torchr numpyrrr"r"r#r 8scCsttjg|djS)z.Convert a numpy dtype to its torch equivalent.r)r$ from_numpyrr rrr"r"r#r=scCsP|dkr dS|tjks |jdkr8t|tjr0|St|St|tjsH|St|S)aConvert 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__ isinstancerrr )r data_typer"r"r#rBs   rzDtypeLike | torch.dtype)datarcCs.t|dr|jSt|tr&t|dSt|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. rr)hasattrrr*rrtyper,r"r"r#r[s    FzNone | str | torch.devicebool)r,rdevice wrap_sequence track_metasaferc s`ddddfdd }|r$t|}ttjt|tjrR||jtjdSt|tjrt d|j j dkr|j dkrt|}||d Sntrt|tst|tttfr||d St|trfd d |D}|r||d S|St|tr6tfd d |D}|r2||d S|St|tr\fdd|DS|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)tensorkwargsrcs|t|tjs@t|tjr2|jtkr2|t|j}tj|f|}r^t|t j j s^t j |Ssxt|t j j rx|S|SN) r*r$r(rr rUNSUPPORTED_TYPESastype as_tensormonair,r')r5r6)r3r"r#_convert_tensors  z*convert_to_tensor.._convert_tensor)rr1 memory_formatz[SaUO]Nr)rr1csg|]}t|dqSrr1r3r.0ir1rr3r"r# sz%convert_to_tensor..c3s|]}t|dVqdS)r?Nr@rArDr"r# sz$convert_to_tensor..c s"i|]\}}|t|dqSr>r@rBkvrDr"r# sz%convert_to_tensor..)safe_dtype_rangerr$r(r*tocontiguous_formatrr researchrrndimascontiguousarrayhas_cp cp_ndarrayfloatintr0listtupledictitems) r,rr1r2r3r4r<list_ret tuple_retr"rDr#ris,         r)r,rr2r4rcsn|rt|}t|tjrDtj|jddt tj d}nt rht|t rht |jdd}nt|tj tttfrt|tj r|jdkr|jjtjkrt|}tj|d}nt|trfdd|D}|rt|S|St|tr$tfd d |D}|r t|S|St|trFfd d |DSt|tj rj|jdkrjt|}|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)r1rF)copyrcsg|]}t|dqSrrrArr"r#rEsz$convert_to_numpy..c3s|]}t|dVqdSrNr_rArr"r#rFsz#convert_to_numpy..csi|]\}}|t|dqSr^r_rGrr"r#rJsz$convert_to_numpy..)rKr*r$r(rasarraydetachrLr%rr rRrScpZasnumpyr9rTrUr0rPritemsizerQrVrWrXrYr,rr2r4rZr[r"rr#rs*  **     znp.dtype | NonecsB|rt|}t|tjr\|jjdkr\|jtjkrN| tj }dkrNtt |}nt|t tjtjtttfrt |}nt|trfdd|D}|rt |S|St|trtfdd|D}|rt |S|St|trfdd|DSt|t js(td t|d |jd kr>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)]`. cudaNcsg|]}t|qSr"rrArr"r#rEsz#convert_to_cupy..c3s|]}t|VqdSr7rgrArr"r#rFsz"convert_to_cupy..csi|]\}}|t|qSr"rgrGrr"r#rJsz#convert_to_cupy..zThe input data type [z'] cannot be converted into cupy arrays!r)rKr*r$r(r1r.rr0rbrLuint8rcrarSrr rTrUrVrWrXrY ValueErrorrPrQrer"rr#rs.       ztype[NdarrayTensor] | Nonez/tuple[NdarrayTensor, type, torch.device | None])r, output_typer1rr2r4rc Cs&t|tjjrtjj}nHt|tjr,tj}n4t|tjr@tj}n trXt|t jrXt j}nt |}t|tjrr|j nd}|p||}t ||}t |tjrt |tjj} t||||| |d} | ||fSt |tjrt||||d} | ||fStrt |t jrt||||d} | ||fStd|dS)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, , None) N)rr1r2r3r4)rr2r4zUnsupported output type: )r*r;r,r'r$r(rr rRrcr.r1r issubclassrrrri) r,rjr1rr2r4 orig_type orig_devicedtype_r3Zdata_r"r"r#r s<%         rzDtypeLike | torch.dtype | None)srcdstrr2r1r4rc Cs|dkrt|tjr|jn|}|dkr2t|dd}d}t|tjjr`tjj}t|tjjsd}n0t|tjrttj}nt|tj rtj }nt |}t ||||||d\}} } |rt|tjjr| ||| | fS)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` NrFT)r,rjr1rr2r4) r*r$r(r1getattrr;r,r'rr r.rZcopy_meta_from) rorprr2r1r4Z copy_metarjoutput_type_devicer"r"r#rOs0     z$Sequence | torch.Tensor | np.ndarrayrVcCs"t|tjtjfr|St|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(rr tolistrVr/r"r"r#convert_to_lists rvztuple[float, float]cCs`|tkrd}nt|tjj}t|tj}|rDt|jt|j fSt |jt |j fSdS)z Get dtype bound value Args: dtype: dtype to get bound value Returns: (bound_min_value, bound_max_value) FN) r8rr$r(is_floating_pointrarrayfinfominmaxiinfo)rrwr"r"r#get_dtype_bound_values r})r,rrcs0dd}tr&t|tr&t||St|tjrBt||St|tjrX||St|t t t frtdkrt|St|t t t fr̈dk r̈}t |}||dkr|dn|}||dkr|dn|}|St|t rfdd|DSt|tr tfdd |DSt|tr,fd d |DS|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. cSs|dk r |n|j}t|}|jdkr.||f}n6t|tjrPt|t|f}nt|t|f}|d|dks|d|dkrt|tjrt ||d|dSt|tj rt ||d|dSt rt|t rt ||d|dSn|SdS)Nr)rr}rPr*r$r(rzr{rclampr cliprRrSrc)r,r output_dtypedtype_bound_valueZ data_boundr"r"r#_safe_dtype_ranges      z+safe_dtype_range.._safe_dtype_rangeNr~rcsg|]}t|dqSr^rKrArr"r#rEsz$safe_dtype_range..c3s|]}t|dVqdSr`rrArr"r#rFsz#safe_dtype_range..csi|]\}}|t|dqSr^rrGrr"r#rJsz$safe_dtype_range..)rRr*rSrcrarr r$r(rTrUr0r}rVrWrXrY)r,rrrrr"rr#rKs,       rK)NNFFF)NFF)NFF)NNNFF)NFNF)N)' __future__rrNcollections.abcrtypingrr%rr$r;Zmonai.config.type_definitionsrr monai.utilsrrcrRrS___all__rint32int64r8r r r rrrrrrrrrvr}rKr"r"r"r# sf     (G-/H5