o  i:@sdZddlmZddlZddlmZmZmZmZddl m Z ddl m Z m Z ddlZddlZddlmZmZddlmZdd lmZmZdd lmZdd lmZdd lmZmZdd l m!Z!m"Z"m#Z#ddl$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>m?Z?m@Z@mAZAmBZBmCZCddlDmEZEmFZFddlGmHZHddlImJZJmKZKddlLmMZMmNZNmOZOddlPmQZQgdZReMSZTGddde!ZUGddde!ZVGddde!ZWGddde!ZXGddde!ZYGdd d e!eZZGd!d"d"e!Z[Gd#d$d$e!eZ\Gd%d&d&e!Z]Gd'd(d(e!Z^Gd)d*d*e!Z_Gd+d,d,e!Z`Gd-d.d.e!eZaGd/d0d0e!ZbGd1d2d2e!ZcGd3d4d4e!ZdGd5d6d6e!ZeGd7d8d8e!ZfGd9d:d:e!ZgGd;d<dd>e!ZiGd?d@d@e!eZjGdAdBdBeje#ZkGdCdDdDe!ZlGdEdFdFe!eZmGdGdHdHe!eZnGdIdJdJe!ZoGdKdLdLe"e!ZpGdMdNdNe!ZqGdOdPdPe!eZrGdQdRdRe!ZsGdSdTdTe!eZtGdUdVdVe!ZuGdWdXdXe!ZvGdYdZdZe!ZwGd[d\d\e!ZxGd]d^d^e!eZyGd_d`d`e!ZzGdadbdbe!Z{Gdcdddde!e#Z|Gdedfdfe!eZ}e|Z~Ze{ZZeUZZeVZZeWZZeYZZeXZZeZZZe[ZZe\ZZe]ZZe^ZZe_ZZe`ZZeaZZebZZecZZeeZZefZZegZZehZZeiZZejZZelZZemZZenZZeoZZepZZesZZeqZZerZZetZZekZZeuZZevZZewZZexZZeyZZezZZedZZe}ZZdS)gz A collection of dictionary-based wrappers around the "vanilla" transforms for utility functions defined in :py:class:`monai.transforms.utility.array`. Class names are ended with 'd' to denote dictionary-based transforms. ) annotationsN)CallableHashableMappingSequence)deepcopy)Anycast) DtypeLikeKeysCollection)NdarrayOrTensor)MetaObj MetaTensor) no_collation)InvertibleTransform)MultiSampleTraitRandomizableTrait) MapTransform RandomizableRandomizableTransform)AddCoordinateChannelsAddExtremePointsChannelApplyTransformToPoints AsChannelLast CastToTypeClassesToIndices(ConvertToMultiChannelBasedOnBratsClassesCuCIM DataStatsEnsureChannelFirst EnsureType FgBgToIndicesIdentity ImageFilterIntensityStats LabelToMaskLambda MapLabelValueRemoveRepeatedChannel RepeatChannel SimulateDelaySplitDim SqueezeDimToCupyToDeviceToNumpyToPILTorchIO TorchVisionToTensor Transpose)extreme_points_to_imageget_extreme_points) concatenate) ensure_tupleensure_tuple_rep)PostFix TraceKeysTransformBackends)convert_to_dst_type)wAddCoordinateChannelsDAddCoordinateChannelsDictAddCoordinateChannelsdAddExtremePointsChannelDAddExtremePointsChannelDictAddExtremePointsChanneldAsChannelLastDAsChannelLastDictAsChannelLastd CastToTypeDCastToTypeDict CastToTyped ConcatItemsDConcatItemsDict ConcatItemsd)ConvertToMultiChannelBasedOnBratsClassesD,ConvertToMultiChannelBasedOnBratsClassesDict)ConvertToMultiChannelBasedOnBratsClassesd CopyItemsD CopyItemsDict CopyItemsdCuCIMdCuCIMD CuCIMDict DataStatsD DataStatsDict DataStatsd DeleteItemsDDeleteItemsDict DeleteItemsdEnsureChannelFirstDEnsureChannelFirstDictEnsureChannelFirstd EnsureTypeDEnsureTypeDict EnsureTypedFgBgToIndicesDFgBgToIndicesDictFgBgToIndicesd IdentityD IdentityDict IdentitydIntensityStatsdIntensityStatsDIntensityStatsDict ImageFilterd LabelToMaskDLabelToMaskDict LabelToMaskdLambdaD LambdaDictLambdadMapLabelValueDMapLabelValueDictMapLabelValuedFlattenSubKeysdFlattenSubKeysDFlattenSubKeysDict RandCuCIMd RandCuCIMD RandCuCIMDictRandImageFilterd RandLambdaDRandLambdaDict RandLambdad RandTorchIOd RandTorchIODRandTorchIODictRandTorchVisionDRandTorchVisionDictRandTorchVisiondRemoveRepeatedChannelDRemoveRepeatedChannelDictRemoveRepeatedChanneldRepeatChannelDRepeatChannelDictRepeatChanneld SelectItemsDSelectItemsDict SelectItemsdSimulateDelayDSimulateDelayDictSimulateDelayd SplitDimD SplitDimDict SplitDimd SqueezeDimDSqueezeDimDict SqueezeDimdToCupyD ToCupyDictToCupyd ToDeviced ToDeviceD ToDeviceDictToNumpyD ToNumpyDictToNumpydToPILD ToPILDictToPILd ToTensorD ToTensorDict ToTensordTorchIOD TorchIODictTorchIOd TorchVisionDTorchVisionDict TorchVisiond Transposed TransposeDict TransposeDClassesToIndicesdClassesToIndicesDClassesToIndicesDictApplyTransformToPointsdApplyTransformToPointsDApplyTransformToPointsDictc4eZdZdZejZddfd d ZdddZZS)rgzL Dictionary-based wrapper of :py:class:`monai.transforms.Identity`. Fkeysr allow_missing_keysboolreturnNonect||t|_dS)z Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` allow_missing_keys: don't raise exception if key is missing. N)super__init__r"identityselfrr __class__e/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/utility/dictionary.pyrs zIdentityd.__init__data"Mapping[Hashable, NdarrayOrTensor]dict[Hashable, NdarrayOrTensor]cC.t|}||D] }|||||<q |SN)dict key_iteratorrrrdkeyrrr__call__zIdentityd.__call__Frr rrrrrrrr) __name__ __module__ __qualname____doc__r"backendrr __classcell__rrrrrg  rgcs4eZdZdZejZddfd d ZdddZZS)rFzQ Dictionary-based wrapper of :py:class:`monai.transforms.AsChannelLast`. rFrr channel_dimintrrrrcst||t|d|_dS)aY Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` channel_dim: which dimension of input image is the channel, default is the first dimension. allow_missing_keys: don't raise exception if key is missing. )rN)rrr converter)rrrrrrrrszAsChannelLastd.__init__rrrcCrrrrrrrrrrrzAsChannelLastd.__call__rF)rr rrrrrrr) rrrrrrrrrrrrrrFrrFcs6eZdZdZejZ ddfd d ZdddZZS)r^zV Dictionary-based wrapper of :py:class:`monai.transforms.EnsureChannelFirst`. TFNrr strict_checkrrrrcs t||t||d|_dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` strict_check: whether to raise an error when the meta information is insufficient. allow_missing_keys: don't raise exception if key is missing. channel_dim: This argument can be used to specify the original channel dimension (integer) of the input array. It overrides the `original_channel_dim` from provided MetaTensor input. If the input array doesn't have a channel dim, this value should be ``'no_channel'``. If this is set to `None`, this class relies on `img` or `meta_dict` to provide the channel dimension. )rrN)rrradjuster)rrrrrrrrrszEnsureChannelFirstd.__init__rMapping[Hashable, torch.Tensor]dict[Hashable, torch.Tensor]cCsLt|}||D]}t||tr||jnd}||||||<q |Sr)rr isinstancermetar)rrrr meta_dictrrrrs zEnsureChannelFirstd.__call__)TFN)rr rrrrrrrrrr) rrrrrrrrrrrrrr^s r^c4eZdZdZejZddfd d ZdddZZS)rzQ Dictionary-based wrapper of :py:class:`monai.transforms.RepeatChannel`. Frr repeatsrrrrrct||t||_dSa2 Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` repeats: the number of repetitions for each element. allow_missing_keys: don't raise exception if key is missing. N)rrr)repeaterrrrrrrrr zRepeatChanneld.__init__rrrcCrrrrrrrrrr+rzRepeatChanneld.__call__rrr rrrrrrr) rrrrr)rrrrrrrrrrrcr)rzY Dictionary-based wrapper of :py:class:`monai.transforms.RemoveRepeatedChannel`. Frr rrrrrrcrr)rrr(rrrrrr9rzRemoveRepeatedChanneld.__init__rrrcCrrrrrrrrDrzRemoveRepeatedChanneld.__call__rrr) rrrrr(rrrrrrrrr2rrcs<eZdZejZ      ddfdd ZdddZZS)rNrTFrr output_postfixesSequence[str] | Nonedimrkeepdimr update_meta list_outputrrrcsLt||||_t||||_||_|jdur"|jdur$tddSdS)a' Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` output_postfixes: the postfixes to construct keys to store split data. for example: if the key of input data is `pred` and split 2 classes, the output data keys will be: pred_(output_postfixes[0]), pred_(output_postfixes[1]) if None, using the index number: `pred_0`, `pred_1`, ... `pred_N`. dim: which dimension of input image is the channel, default to 0. keepdim: if `True`, output will have singleton in the split dimension. If `False`, this dimension will be squeezed. update_meta: if `True`, copy `[key]_meta_dict` for each output and update affine to reflect the cropped image list_output: it `True`, the output will be a list of dictionaries with the same keys as original. allow_missing_keys: don't raise exception if key is missing. NzG`output_postfixes` should not be provided when `list_output` is `True`.)rrrr+splitterr ValueError)rrrrrrrrrrrrNszSplitDimd.__init__rrAdict[Hashable, torch.Tensor] | list[dict[Hashable, torch.Tensor]]cs<t|tt}jrGg}fdd|D}t|D]$}tt||}tt|D] }t|||<q4| |q |S|D]R} |} j dur_tt t | nj } t | t | krytdt | dt | dt| D]\} } |d| | } | vrtd| d| | <q}qIS)Ncsg|] }|qSr)r.0rrrrr wsz&SplitDimd.__call__..z-count of splits must match output_postfixes, z != ._z input data already contains key )rlistsetrrzipr differencerappendrrrangelenr enumerate RuntimeError)rrall_keysoutputresultsrownew_dictkrretsZ postfixesirZ split_keyrrrros.    zSplitDimd.__call__)NrTTFF)rr rrrrrrrrrrrrrr)rrrr)rrrr+rrrrrrrrrKs!rc@s2eZdZdZejZejdfdd d ZdddZ dS)rIzN Dictionary-based wrapper of :py:class:`monai.transforms.CastToType`. Frr dtype;Sequence[DtypeLike | torch.dtype] | DtypeLike | torch.dtyperrrrcCs,t|||t|t|j|_t|_dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` dtype: convert image to this data type, default is `np.float32`. it also can be a sequence of dtypes or torch.dtype, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. N)rrr9rrrrr)rrrrrrrrs zCastToTyped.__init__rrrcC:t|}|||jD]\}}|j|||d||<q |S)N)rrrrrrrrrrrrrrszCastToTyped.__call__N)rr rrrrrrr) rrrrrrnpfloat32rrrrrrrIs rIcsHeZdZdZejZ     ddfdd ZdddZdddZZ S)rzL Dictionary-based wrapper of :py:class:`monai.transforms.ToTensor`. NTFrr rtorch.dtype | Nonedevicetorch.device | str | None wrap_sequencer track_meta bool | Nonerrrcs$t||t||||d|_dS)a; Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` dtype: target data content type to convert, for example: torch.float, etc. device: specify the target device to put the Tensor data. wrap_sequence: if `False`, then lists will recursively call this function, default to `True`. E.g., if `False`, `[1, 2]` -> `[tensor(1), tensor(2)]`, if `True`, then `[1, 2]` -> `tensor([1, 2])`. track_meta: if `True` convert to ``MetaTensor``, otherwise to Pytorch ``Tensor``, if ``None`` behave according to return value of py:func:`monai.data.meta_obj.get_track_meta`. allow_missing_keys: don't raise exception if key is missing. )rrrrN)rrr3r)rrrrrrrrrrrszToTensord.__init__rrrcCs:t|}||D]}|||||<|||q |Sr)rrrpush_transformrrrrrs zToTensord.__call__cCs>t|}||D]}|||t}|||||<q |Sr)rr pop_transformr/)rrrrinverse_transformrrrinverses  zToTensord.inverse)NNTNF)rr rrrrrrrrrrrrr) rrrrr3rrrr"rrrrrrs rcs@eZdZdZejZ      ddfdd ZdddZZS)raa Dictionary-based wrapper of :py:class:`monai.transforms.EnsureType`. Ensure the input data to be a PyTorch Tensor or numpy array, support: `numpy array`, `PyTorch Tensor`, `float`, `int`, `bool`, `string` and `object` keep the original. If passing a dictionary, list or tuple, still return dictionary, list or tuple and recursively convert every item to the expected data type if `wrap_sequence=False`. Note: Currently, we only convert tensor data to numpy array or scalar number in the inverse operation. tensorNTFrr data_typestrrrrtorch.device | Nonerrrrrrrcs6t||t|t|j|_t||||d|_dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` data_type: target data type to convert, should be "tensor" or "numpy". dtype: target data content type to convert, for example: np.float32, torch.float, etc. It also can be a sequence of dtype, each element corresponds to a key in ``keys``. device: for Tensor data type, specify the target device. wrap_sequence: if `False`, then lists will recursively call this function, default to `True`. E.g., if `False`, `[1, 2]` -> `[tensor(1), tensor(2)]`, if `True`, then `[1, 2]` -> `tensor([1, 2])`. track_meta: whether to convert to `MetaTensor` when `data_type` is "tensor". If False, the output data type will be `torch.Tensor`. Default to the return value of `get_track_meta`. allow_missing_keys: don't raise exception if key is missing. )r$rrrN)rrr9rrrr r)rrr$rrrrrrrrrs  zEnsureTyped.__init__rrrcCs8t|}|||jD]\}}||||||<q |SrrrrrrrszEnsureTyped.__call__)r#NNTNF)rr r$r%rrrr&rrrrrrrrr) rrrrr rrrrrrrrras rac:eZdZdZejZ   ddfdd ZdddZZS)rK Dictionary-based wrapper of :py:class:`monai.transforms.ToNumpy`. NTFrr rr rrrrrc t||t||d|_dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` dtype: target data type when converting to numpy array. wrap_sequence: if `False`, then lists will recursively call this function, default to `True`. E.g., if `False`, `[1, 2]` -> `[array(1), array(2)]`, if `True`, then `[1, 2]` -> `array([1, 2])`. allow_missing_keys: don't raise exception if key is missing. rrN)rrr/rrrrrrrrrrszToNumpyd.__init__rMapping[Hashable, Any]dict[Hashable, Any]cCrrrrrrrr1rzToNumpyd.__call__NTF) rr rr rrrrrrrr,rr-) rrrrr/rrrrrrrrrsrcr')ra Dictionary-based wrapper of :py:class:`monai.transforms.ToCupy`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` dtype: data type specifier. It is inferred from the input by default. if not None, 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, default to `True`. E.g., if `False`, `[1, 2]` -> `[array(1), array(2)]`, if `True`, then `[1, 2]` -> `array([1, 2])`. allow_missing_keys: don't raise exception if key is missing. NTFrr rnp.dtype | Nonerrrrrc t||t||d|_dS)Nr*)rrr-rr+rrrrIzToCupyd.__init__rrrcCrrrrrrrrSrzToCupyd.__call__r.) rr rr0rrrrrrr) rrrrr-rrrrrrrrr8s rcr)rr(Frr rrrrcr)z Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` allow_missing_keys: don't raise exception if key is missing. N)rrr0rrrrrras zToPILd.__init__rr,r-cCrrrrrrrrkrzToPILd.__call__rrr/) rrrrr0rrrrrrrrrZs  rcs>eZdZdZejZddfd d ZdddZdddZZ S)rzM Dictionary-based wrapper of :py:class:`monai.transforms.Transpose`. Frr indicesSequence[int] | Nonerrrrcst||t||_dSr)rrr4 transform)rrr3rrrrryszTransposed.__init__rrrcCsbt|}||D]%}|||||<|jjp#t||jddd}|j||d|idq |S)Nr3 extra_info)rrr5r3rndimr)rrrrr3rrrr}s  zTransposed.__call__r,r-cCsnt|}||D]+}|||}t|tjd}t|}t| }|||||<| ||q |S)Nr3) rrget_most_recent_transformrarrayr; EXTRA_INFOargsortr4tolistr )rrrrr5Z fwd_indicesZ inv_indicesr!rrrr"s   zTransposed.inverser)rr r3r4rrrrrr/) rrrrr4rrrr"rrrrrrrs   rcs8eZdZdZejejgZddfd d ZddZ Z S)r[z Delete specified items from data dictionary to release memory. It will remove the key-values and copy the others to construct a new dictionary. rFrr sepr%use_reSequence[bool] | boolrrcs(t|||_t|t|j|_dS)a Args: keys: keys of the corresponding items to delete, can be "A{sep}B{sep}C" to delete key `C` in nested dictionary, `C` can be regular expression. See also: :py:class:`monai.transforms.compose.MapTransform` sep: the separator tag to define nested dictionary keys, default to ".". use_re: whether the specified key is a regular expression, it also can be a list of bool values, mapping them to `keys`. N)rrr?r9rrr@)rrr?r@rrrrs zDeleteItemsd.__init__csRddfdd t|}tttt|j|jD]\}}||j||}q|S)NFr@rcsL|dt|dkr|dd||<|Sfdd|DS)Nrcs4i|]\}}rt|rs|kr||qSr)research)rrvrr@rr s4z?DeleteItemsd.__call__.._delete_item..)ritems)rrr@ _delete_itemrFrrJs  z+DeleteItemsd.__call__.._delete_itemr)r@r) rrr rr%rr@splitr?)rrrrr@rrIrrs  zDeleteItemsd.__call__)rF)rr r?r%r@rArr rrrrr<TORCHNUMPYrrrrrrrrr[s  r[c@s$eZdZdZejejgZddZdS)rz Select only specified items from data dictionary to release memory. It will copy the selected key-values and construct a new dictionary. csfdd|DS)Ncsi|]}||qSrrrrrrrGsz)SelectItemsd.__call__..)rrrrrOrrszSelectItemsd.__call__N) rrrrr<rMrNrrrrrrrs  rcs>eZdZdZejejgZ   ddfdd ZddZ Z S)rua] If an item is dictionary, it flatten the item by moving the sub-items (defined by sub-keys) to the top level. {"pred": {"a": ..., "b", ... }} --> {"a": ..., "b", ... } Args: keys: keys of the corresponding items to be flatten sub_keys: the sub-keys of items to be flatten. If not provided all the sub-keys are flattened. delete_keys: whether to delete the key of the items that their sub-keys are flattened. Default to True. prefix: optional prefix to be added to the sub-keys when moving to the top level. By default no prefix will be added. NTrr sub_keysKeysCollection | None delete_keysrprefix str | Nonerrcs"t|||_||_||_dSr)rrrQrSrT)rrrQrSrTrrrrs  zFlattenSubKeysd.__init__cCst|}||D]<}|jdur||n|j}|D]#}|jr(|jd|n|}||vr6td|d|||||<q|jrE||=q |S)Nr'zR' already exists in the top-level keys. Please change `prefix` to avoid duplicity.)rrrQrrTrrS)rrrrrQskZsk_toprrrrs zFlattenSubKeysd.__call__)NTN) rr rQrRrSrrTrUrrrLrrrrrus  rucs6eZdZdZejZ ddfdd ZdddZZS)rzN Dictionary-based wrapper of :py:class:`monai.transforms.SqueezeDim`. rTFrr rrrrrrrcr))a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` dim: dimension to be squeezed. Default: 0 (the first dimension) update_meta: whether to update the meta info if the input is a metatensor. Default is ``True``. allow_missing_keys: don't raise exception if key is missing. )rrN)rrr,r)rrrrrrrrrs zSqueezeDimd.__init__rrrcCrrrrrrrr rzSqueezeDimd.__call__)rTF) rr rrrrrrrrr) rrrrr,rrrrrrrrrs rcsFeZdZdZejZ         d d!fdd Zd"ddZZS)#rXzM Dictionary-based wrapper of :py:class:`monai.transforms.DataStats`. DataTFNrrr rTSequence[str] | strr$rA data_shape value_range data_value meta_infoadditional_info$Sequence[Callable] | Callable | Nonenamer%rrrrc st|| t|t|j|_t|t|j|_t|t|j|_t|t|j|_t|t|j|_ t|t|j|_ t|t|j|_ t | d|_ dS)ah Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` prefix: will be printed in format: "{prefix} statistics". it also can be a sequence of string, each element corresponds to a key in ``keys``. data_type: whether to show the type of input data. it also can be a sequence of bool, each element corresponds to a key in ``keys``. data_shape: whether to show the shape of input data. it also can be a sequence of bool, each element corresponds to a key in ``keys``. value_range: whether to show the value range of input data. it also can be a sequence of bool, each element corresponds to a key in ``keys``. data_value: whether to show the raw value of input data. it also can be a sequence of bool, each element corresponds to a key in ``keys``. a typical example is to print some properties of Nifti image: affine, pixdim, etc. meta_info: whether to show the data of MetaTensor. it also can be a sequence of bool, each element corresponds to a key in ``keys``. additional_info: user can define callable function to extract additional info from input data. it also can be a sequence of string, each element corresponds to a key in ``keys``. name: identifier of `logging.logger` to use, defaulting to "DataStats". allow_missing_keys: don't raise exception if key is missing. )r`N)rrr9rrrTr$rZr[r\r]r^rprinter) rrrTr$rZr[r\r]r^r`rrrrrs%zDataStatsd.__init__rrrc Csht|}|||j|j|j|j|j|j|jD]\}}}}}}} } | |||||||| | ||<q|Sr) rrrTr$rZr[r\r]r^ra) rrrrrTr$rZr[r\r]r^rrrrJs0   zDataStatsd.__call__) rXTTTFFNrF)rr rTrYr$rArZrAr[rAr\rAr]rAr^r_r`r%rrrrr) rrrrrrrrrrrrrrXs/rXcs6eZdZdZejZ ddfd d ZdddZZS)rzQ Dictionary-based wrapper of :py:class:`monai.transforms.SimulateDelay`. Frr delay_timeSequence[float] | floatrrrrcs,t||t|t|j|_t|_dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` delay_time: The minimum amount of time, in fractions of seconds, to accomplish this identity task. It also can be a sequence of string, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. N)rrr9rrrcr*delayer)rrrcrrrrrls  zSimulateDelayd.__init__rrrcCr)N)rc)rrrcre)rrrrrcrrrr|szSimulateDelayd.__call__)rbF)rr rcrdrrrrr) rrrrr*rrrrrrrrres rcs@eZdZdZejejgZ   ddfdd ZdddZ Z S)rRz Copy specified items from data dictionary and save with different key names. It can copy several items together and copy several times. rBNFrr timesrnamesrRrrrrcst|||dkrtd|d|_|dur$fddjDnt|}t|tj|krEtdt|dtj|d|_dS) a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` times: expected copy times, for example, if keys is "img", times is 3, it will add 3 copies of "img" data to the dictionary, default to 1. names: the names corresponding to the newly copied data, the length should match `len(keys) x times`. for example, if keys is ["img", "seg"] and times is 2, names can be: ["img_1", "seg_1", "img_2", "seg_2"]. if None, use "{key}_{index}" as key for copy times `N`, index from `0` to `N-1`. allow_missing_keys: don't raise exception if key is missing. Raises: ValueError: When ``times`` is nonpositive. ValueError: When ``len(names)`` is not ``len(keys) * times``. Incompatible values. rBztimes must be positive, got rNcs*g|]}tjD] }|d|q qS)r)rrf)rrrrrrrs*z'CopyItemsd.__init__..z8len(names) must match len(keys) * times, got len(names)=z len(keys) * times=)rrrrfrr8rrg)rrrfrgrrrhrrs$  zCopyItemsd.__init__rrrcCst|}t|j}t|jD]<}|||j|||d|D](\}}||vr1td|d||}t|t j t j frCt |nt|||<q!q|S)zi Raises: KeyError: When a key in ``self.names`` already exists in ``data``. rBzKey z already exists in data.)rrrrrfrrgKeyErrorrtorchTensorrndarrayr copy_itemsr)rrrZkey_lenrrnew_keyvalrrrrs **zCopyItemsd.__call__)rBNF) rr rfrrgrRrrrrrrLrrrrrRs $rRcs:eZdZdZejejgZddfdd ZdddZ Z S)rLa Concatenate specified items from data dictionary together on the first dim to construct a big array. Expect all the items are numpy array or PyTorch Tensor or MetaTensor. Return the first input's meta information when items are MetaTensor. rFrr r`r%rrrrrrcst||||_||_dS)a Args: keys: keys of the corresponding items to be concatenated together. See also: :py:class:`monai.transforms.compose.MapTransform` name: the name corresponding to the key to store the concatenated data. dim: on which dimension to concatenate the items, default is 0. allow_missing_keys: don't raise exception if key is missing. N)rrr`r)rrr`rrrrrrs  zConcatItemsd.__init__rrrcCst|}g}d}||D]}|durt||}n t|||s%td|||q t|dkr5|S|tjurGtj ||j d||j <|St |t jrZt j||j d||j <|Std|d)z Raises: TypeError: When items in ``data`` differ in type. TypeError: When the item type is not in ``Union[numpy.ndarray, torch.Tensor, MetaTensor]``. Nz*All items in data must have the same type.raxis)rzUnsupported data type: zB, available options are (numpy.ndarray, torch.Tensor, MetaTensor).)rrtyper TypeErrorrrrrlr7rr` issubclassrjrkcat)rrrr r$rrrrrs(    zConcatItemsd.__call__r) rr r`r%rrrrrrrrLrrrrrLs   rLcsDeZdZdZejZedddfdfdd ZdddZddZ Z S)rqa Dictionary-based wrapper of :py:class:`monai.transforms.Lambda`. For example: .. code-block:: python :emphasize-lines: 2 input_data={'image': np.zeros((10, 2, 2)), 'label': np.ones((10, 2, 2))} lambd = Lambdad(keys='label', func=lambda x: x[:4, :, :]) print(lambd(input_data)['label'].shape) (4, 2, 2) Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` func: Lambda/function to be applied. It also can be a sequence of Callable, each element corresponds to a key in ``keys``. inv_func: Lambda/function of inverse operation if want to invert transforms, default to `lambda x: x`. It also can be a sequence of Callable, each element corresponds to a key in ``keys``. track_meta: If `False`, then standard data objects will be returned (e.g., torch.Tensor` and `np.ndarray`) as opposed to MONAI's enhanced objects. By default, this is `True`. overwrite: whether to overwrite the original data in the input dictionary with lambda function output. it can be bool or str, when setting to str, it will create a new key for the output and keep the value of key intact. default to True. it also can be a sequence of bool or str, each element corresponds to a key in ``keys``. allow_missing_keys: don't raise exception if key is missing. Note: The inverse operation doesn't allow to define `extra_info` or access other information, such as the image's original size. If need these complicated information, please write a new InvertibleTransform directly. TFrr funcSequence[Callable] | Callableinv_funcrr overwrite+Sequence[bool] | bool | Sequence[str] | strrrrcsTt||t|t|j|_t|t|j|_t|t|j|_t|d|_ dS)N)r) rrr9rrrvrxryr&_lambdrrrvrxrryrrrrrs  zLambdad.__init__rrrcCsft|}|||j|jD]#\}}}|j|||d}|r't|tr'|||<q t|tr0|||<q |S)N)imgrv)rrrvryr{rrr%rrrrrvryretrrrr)s  zLambdad.__call__cCsBt|}|||jD]\}}|jj||d}|r|||<q |S)NrO)rrryr{r")rrrrryrrrrr"3szLambdad.inverse)rr rvrwrxrwrrryrzrrrrr) rrrrr&rrrrr"rrrrrrqs"  rqc@s>eZdZdZejZeddddfdddZddZdddZ dS)r~a Randomizable version :py:class:`monai.transforms.Lambdad`, the input `func` may contain random logic, or randomly execute the function based on `prob`. so `CacheDataset` will not execute it and cache the results. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` func: Lambda/function to be applied. It also can be a sequence of Callable, each element corresponds to a key in ``keys``. inv_func: Lambda/function of inverse operation if want to invert transforms, default to `lambda x: x`. It also can be a sequence of Callable, each element corresponds to a key in ``keys``. track_meta: If `False`, then standard data objects will be returned (e.g., torch.Tensor` and `np.ndarray`) as opposed to MONAI's enhanced objects. By default, this is `True`. overwrite: whether to overwrite the original data in the input dictionary with lambda function output. default to True. it also can be a sequence of bool, each element corresponds to a key in ``keys``. prob: probability of executing the random function, default to 1.0, with 100% probability to execute. note that all the data specified by `keys` will share the same random probability to execute or not. allow_missing_keys: don't raise exception if key is missing. For more details, please check :py:class:`monai.transforms.Lambdad`. Note: The inverse operation doesn't allow to define `extra_info` or access other information, such as the image's original size. If need these complicated information, please write a new InvertibleTransform directly. T?Frr rvrwrxrrryrAprobfloatrrrc Cs,tj|||||||dtj||dddS)Nr|T)rr do_transform)rqrr)rrrvrxrryrrrrrrXs  zRandLambdad.__init__cCs||t|}|||j|jD]5\}}}||}t|ts$t|}|jr<|j||d}|j |d|j |idn| ||rG|||<q|S)N)rv lambda_infor7) randomizerrrvryrr _do_transformr{rr r~rrrrms   zRandLambdad.__call__rrrcCst|}|||jD]2\}}t||tr=|||}|tjr=||j |tj d|j ||}|r=|||<q |S)Nr) rrryrrr r; DO_TRANSFORMapplied_operationsrr<r{r")rrrrrytrrrrrr"}s zRandLambdad.inverseN)rr rvrwrxrwrrryrArrrrrrr) rrrrr&rrrrr"rrrrr~<s r~cs8eZdZdZejZ  ddfd d ZdddZZS)rna Dictionary-based wrapper of :py:class:`monai.transforms.LabelToMask`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` select_labels: labels to generate mask from. for 1 channel label, the `select_labels` is the expected label values, like: [1, 2, 3]. for One-Hot format label, the `select_labels` is the expected channel indices. merge_channels: whether to use `np.any()` to merge the result on channel dim. if yes, will return a single channel mask with binary data. allow_missing_keys: don't raise exception if key is missing. Frr select_labelsSequence[int] | intmerge_channelsrrrrcr1)N)rr)rrr%r)rrrrrrrrrr2zLabelToMaskd.__init__rrrcCrrrrrrrrszLabelToMaskd.__call__)FF) rr rrrrrrrrr) rrrrr%rrrrrrrrrns rncs@eZdZdZejZ      ddfdd ZdddZZS) rda Dictionary-based wrapper of :py:class:`monai.transforms.FgBgToIndices`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` fg_postfix: postfix to save the computed foreground indices in dict. for example, if computed on `label` and `postfix = "_fg_indices"`, the key will be `label_fg_indices`. bg_postfix: postfix to save the computed background indices in dict. for example, if computed on `label` and `postfix = "_bg_indices"`, the key will be `label_bg_indices`. image_key: if image_key is not None, use ``label == 0 & image > image_threshold`` to determine the negative sample(background). so the output items will not map to all the voxels in the label. image_threshold: if enabled image_key, use ``image > image_threshold`` to determine the valid image content area and select background only in this area. output_shape: expected shape of output indices. if not None, unravel indices to specified shape. allow_missing_keys: don't raise exception if key is missing. _fg_indices _bg_indicesNrbFrr fg_postfixr% bg_postfix image_keyrUimage_thresholdr output_shaper4rrrrcs0t||||_||_||_t|||_dSr)rrrrrr!r)rrrrrrrrrrrrs  zFgBgToIndicesd.__init__rrrcCs`t|}|jr ||jnd}||D]}||||\|t||j<|t||j<q|Sr)rrrrr%rrrrrimagerrrrrs 2zFgBgToIndicesd.__call__)rrNrbNF)rr rr%rr%rrUrrrr4rrrrr) rrrrr!rrrrrrrrrdsrdcsBeZdZdZejZ       ddfdd ZdddZZS) ra Dictionary-based wrapper of :py:class:`monai.transforms.ClassesToIndices`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` indices_postfix: postfix to save the computed indices of all classes in dict. for example, if computed on `label` and `postfix = "_cls_indices"`, the key will be `label_cls_indices`. num_classes: number of classes for argmax label, not necessary for One-Hot label. image_key: if image_key is not None, use ``image > image_threshold`` to define valid region, and only select the indices within the valid region. image_threshold: if enabled image_key, use ``image > image_threshold`` to determine the valid image content area and select only the indices of classes in this area. output_shape: expected shape of output indices. if not None, unravel indices to specified shape. max_samples_per_class: maximum length of indices to sample in each class to reduce memory consumption. Default is None, no subsampling. allow_missing_keys: don't raise exception if key is missing. _cls_indicesNrbFrr indices_postfixr% num_classes int | NonerrUrrrr4max_samples_per_classrrrrc s.t||||_||_t|||||_dSr)rrrrrr) rrrrrrrrrrrrrs zClassesToIndicesd.__init__rr,cCsNt|}|jr ||jnd}||D]}|||||t||j<q|Sr)rrrrr%rrrrrrs  zClassesToIndicesd.__call__)rNNrbNNF)rr rr%rrrrUrrrr4rrrrrr)rr,) rrrrrrrrrrrrrrsrcs4eZdZdZejZddfdd Zdd dZZS)rOa Dictionary-based wrapper of :py:class:`monai.transforms.ConvertToMultiChannelBasedOnBratsClasses`. Convert labels to multi channels based on brats18 classes: label 1 is the necrotic and non-enhancing tumor core label 2 is the peritumoral edema label 4 is the GD-enhancing tumor The possible classes are TC (Tumor core), WT (Whole tumor) and ET (Enhancing tumor). Frr rrcst||t|_dSr)rrrrrrrrrs z2ConvertToMultiChannelBasedOnBratsClassesd.__init__rrrrcCrrrrrrrrrz2ConvertToMultiChannelBasedOnBratsClassesd.__call__r)rr rrr) rrrrrrrrrrrrrrO s  rOc@sBeZdZdZejZ      d$d%ddZd&ddZd'd!d"Zd#S)(rCa^ Dictionary-based wrapper of :py:class:`monai.transforms.AddExtremePointsChannel`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` label_key: key to label source to get the extreme points. background: Class index of background label, defaults to 0. pert: Random perturbation amount to add to the points, defaults to 0.0. sigma: if a list of values, must match the count of spatial dimensions of input data, and apply every value in the list to 1 spatial dimension. if only 1 value provided, use it for all spatial dimensions. rescale_min: minimum value of output data. rescale_max: maximum value of output data. allow_missing_keys: don't raise exception if key is missing. rrb@rFrr label_keyr% backgroundrpertrsigma?Sequence[float] | float | Sequence[torch.Tensor] | torch.Tensor rescale_min rescale_maxrrc Cs<t|||||_||_g|_||_||_||_||_dSr) rrrrpointsrrrr) rrrrrrrrrrrrr:s  z!AddExtremePointsChanneld.__init__labelr rrcCst||j|j|jd|_dS)N) rand_staterr)r6Rrrr)rrrrrrNsz"AddExtremePointsChanneld.randomizerrrcCst|}||j}|jddkrtd||dddf||D]$}||}t|j||j|j |j d}t ||^}}t ||gdd||<q$|S)NrrBz$Only supports single channel labels!)rrrrrrp) rrshaperrrr5rrrrr=r7)rrrrrr} points_imagerrrrrQs" z!AddExtremePointsChanneld.__call__N)rrbrrrF)rr rr%rrrrrrrrrrrr)rr rrr) rrrrrrrrrrrrrrC%s rCcr)ra Dictionary-based wrapper of :py:class:`monai.transforms.TorchVision` for non-randomized transforms. For randomized transforms of TorchVision use :py:class:`monai.transforms.RandTorchVisiond`. Note: As most of the TorchVision transforms only work for PIL image and PyTorch Tensor, this transform expects input data to be dict of PyTorch Tensors, users can easily call `ToTensord` transform to convert Numpy to Tensor. Frr r`r%rrrrcs0t||||_t|g|Ri||_dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` name: The transform name in TorchVision package. allow_missing_keys: don't raise exception if key is missing. args: parameters for the TorchVision transform. kwargs: parameters for the TorchVision transform. N)rrr`r2transrrr`rargskwargsrrrrts zTorchVisiond.__init__rrrcCrrrrrrrrrrrzTorchVisiond.__call__rrr r`r%rrrrr) rrrrr2rrrrrrrrrhs  rc@s,eZdZdZejZddd d ZdddZdS)ra Dictionary-based wrapper of :py:class:`monai.transforms.TorchVision` for randomized transforms. For deterministic non-randomized transforms of TorchVision use :py:class:`monai.transforms.TorchVisiond`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` name: The transform name in TorchVision package. allow_missing_keys: don't raise exception if key is missing. args: parameters for the TorchVision transform. kwargs: parameters for the TorchVision transform. Note: - As most of the TorchVision transforms only work for PIL image and PyTorch Tensor, this transform expects input data to be dict of PyTorch Tensors. Users should call `ToTensord` transform first to convert Numpy to Tensor. - This class inherits the ``Randomizable`` purely to prevent any dataset caching to skip the transform computation. If the random factor of the underlying torchvision transform is not derived from `self.R`, the results may not be deterministic. See Also: :py:class:`monai.transforms.Randomizable`. Frr r`r%rrrrcO0t|||||_t|g|Ri||_dSr)rrr`r2rrrrrrzRandTorchVisiond.__init__rrrcCrrrrrrrrrzRandTorchVisiond.__call__Nrrr)rrrrr2rrrrrrrrs  rc4eZdZdZejZddfd d ZdddZZS)rz Dictionary-based wrapper of :py:class:`monai.transforms.TorchIO` for non-randomized transforms. For randomized transforms of TorchIO use :py:class:`monai.transforms.RandTorchIOd`. Frr r`r%rrrrc:t||||_|j|d<t|g|Ri||_dSa Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` name: The transform name in TorchIO package. allow_missing_keys: don't raise exception if key is missing. args: parameters for the TorchIO transform. kwargs: parameters for the TorchIO transform. includeNrrr`rr1rrrrrr  zTorchIOd.__init__rrcCt||SrrrrPrrrrzTorchIOd.__call__rrrrrr rrrrr1rrrrrrrrr rcr)rz Dictionary-based wrapper of :py:class:`monai.transforms.TorchIO` for randomized transforms. For non-randomized transforms of TorchIO use :py:class:`monai.transforms.TorchIOd`. Frr r`r%rrrrcrrrrrrrrrzRandTorchIOd.__init__rrcCrrrrPrrrrrzRandTorchIOd.__call__rrrrrrrrrrrcs:eZdZdZejZejdfdfdd ZdddZ Z S)rtzQ Dictionary-based wrapper of :py:class:`monai.transforms.MapLabelValue`. Frr orig_labelsr target_labelsrr rrrrcs"t||t|||d|_dS)a8 Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` orig_labels: original labels that map to others. target_labels: expected label values, 1: 1 map to the `orig_labels`. dtype: convert the output data to dtype, default to float32. if dtype is from PyTorch, the transform will use the pytorch backend, else with numpy backend. allow_missing_keys: don't raise exception if key is missing. )rrrN)rrr'mapper)rrrrrrrrrrszMapLabelValued.__init__rrrcCrr)rrrrrrrrrzMapLabelValued.__call__) rr rrrrrr rrrrr) rrrrr'rrrrrrrrrrrtsrtcs>eZdZdZejZdddedfdfdd ZdddZZ S)rhaK Dictionary-based wrapper of :py:class:`monai.transforms.IntensityStats`. Compute statistics for the intensity values of input image and store into the metadata dictionary. For example: if `ops=[lambda x: np.mean(x), "max"]` and `key_prefix="orig"`, may generate below stats: `{"orig_custom_0": 1.5, "orig_max": 3.0}`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` ops: expected operations to compute statistics for the intensity. if a string, will map to the predefined operations, supported: ["mean", "median", "max", "min", "std"] mapping to `np.nanmean`, `np.nanmedian`, `np.nanmax`, `np.nanmin`, `np.nanstd`. if a callable function, will execute the function on input image. key_prefix: the prefix to combine with `ops` name to generate the key to store the results in the metadata dictionary. if some `ops` are callable functions, will use "{key_prefix}_custom_{index}" as the key, where index counts from 0. mask_keys: if not None, specify the mask array for the image to extract only the interested area to compute statistics, mask must have the same shape as the image. it should be a sequence of strings or None, map to the `keys`. channel_wise: whether to compute statistics for every channel of input image separately. if True, return a list of values for every operation, default to False. meta_keys: explicitly indicate the key of the corresponding metadata dictionary. used to store the computed statistics to the meta dict. for example, for data with key `image`, the metadata by default is in `image_meta_dict`. the metadata is a dictionary object which contains: filename, original_shape, etc. it can be a sequence of string, map to the `keys`. if None, will try to construct meta_keys by `key_{meta_key_postfix}`. meta_key_postfix: if meta_keys is None, use `key_{postfix}` to fetch the metadata according to the key data, default is `meta_dict`, the metadata is a dictionary object. used to store the computed statistics to the meta dict. allow_missing_keys: don't raise exception if key is missing. NFrr opsSequence[str | Callable] key_prefixr% mask_keysrR channel_wiser meta_keysmeta_key_postfixrrrc st||t|||d|_|durtdt|jnt||_|dur,tdt|jnt||_ t|jt|j kr?t dt|t|j|_ dS)N)rrrz.meta_keys should have the same length as keys.) rrr$statsr9rrr8rrrr) rrrrrrrrrrrrr2s ""zIntensityStatsd.__init__rcCszt|}|||j|j|jD]+\}}}}|p|d|}|j|||||dur0||ndd\||<||<q|S)Nr)r} meta_datamask)rrrrrrget)rrrrmask_keymeta_keyrrrrrEs"zIntensityStatsd.__call__)rr rrrr%rrRrrrrRrr%rrrr)rr) rrrrr$rDEFAULT_POST_FIXrrrrrrrrh s"rhcs6eZdZdZejZ ddfd d ZdddZZS)rzL Dictionary-based wrapper of :py:class:`monai.transforms.ToDevice`. Frr rtorch.device | strrrrrc s&t||tdd|i||_dS)a Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` device: target device to move the Tensor, for example: "cuda:1". allow_missing_keys: don't raise exception if key is missing. kwargs: other args for the PyTorch `Tensor.to()` API, for more details: https://pytorch.org/docs/stable/generated/torch.Tensor.to.html. rNr)rrr.r)rrrrrrrrrXs zToDeviced.__init__rrrcCrrrrrrrrgrzToDeviced.__call__r)rr rrrrrrr) rrrrr.rrrrrrrrrQs rcs,eZdZdZddfd d Zd dZZS)rSa Dictionary-based wrapper of :py:class:`monai.transforms.CuCIM` for non-randomized transforms. For randomized transforms of CuCIM use :py:class:`monai.transforms.RandCuCIMd`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` name: The transform name in CuCIM package. allow_missing_keys: don't raise exception if key is missing. args: parameters for the CuCIM transform. kwargs: parameters for the CuCIM transform. Note: CuCIM transforms only work with CuPy arrays, this transform expects input data to be `cupy.ndarray`. Users can call `ToCuPy` transform to convert a numpy array or torch tensor to cupy array. Frr r`r%rrrrcs2tj||d||_t|g|Ri||_dS)N)rr)rrr`rrrrrrrszCuCIMd.__init__cCrz Args: data: Dict[Hashable, `cupy.ndarray`] Returns: Dict[Hashable, `cupy.ndarray`] rrrrrr zCuCIMd.__call__rr)rrrrrrrrrrrrSnsrSc@s$eZdZdZddd d Zd dZdS)rxa` Dictionary-based wrapper of :py:class:`monai.transforms.CuCIM` for randomized transforms. For deterministic non-randomized transforms of CuCIM use :py:class:`monai.transforms.CuCIMd`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` name: The transform name in CuCIM package. allow_missing_keys: don't raise exception if key is missing. args: parameters for the CuCIM transform. kwargs: parameters for the CuCIM transform. Note: - CuCIM transform only work with CuPy arrays, so this transform expects input data to be `cupy.ndarray`. Users should call `ToCuPy` transform first to convert a numpy array or torch tensor to cupy array. - This class inherits the ``Randomizable`` purely to prevent any dataset caching to skip the transform computation. If the random factor of the underlying cuCIM transform is not derived from `self.R`, the results may not be deterministic. See Also: :py:class:`monai.transforms.Randomizable`. Frr r`r%rrrrcOrr)rrr`rrrrrrrrzRandCuCIMd.__init__cCrrrrrrrrrzRandCuCIMd.__call__Nrr)rrrrrrrrrrrxs  rxcr)r@am Dictionary-based wrapper of :py:class:`monai.transforms.AddCoordinateChannels`. Args: keys: keys of the corresponding items to be transformed. See also: :py:class:`monai.transforms.compose.MapTransform` spatial_dims: the spatial dimensions that are to have their coordinates encoded in a channel and appended to the input image. E.g., `(0, 1, 2)` represents `H, W, D` dims and append three channels to the input image, encoding the coordinates of the input's three spatial dimensions. allow_missing_keys: don't raise exception if key is missing. Frr spatial_dims Sequence[int]rrrrcst||t|d|_dS)N)r)rrradd_coordinate_channels)rrrrrrrrszAddCoordinateChannelsd.__init__rrrcCrr)rrrrrrrrrzAddCoordinateChannelsd.__call__r)rr rrrrrrr) rrrrrrrrrrrrrr@s  r@cs8eZdZdZejZ  ddfdd ZdddZZS)rka Dictionary-based wrapper of :py:class:`monai.transforms.ImageFilter`. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform kernel: A string specifying the kernel or a custom kernel as `torch.Tenor` or `np.ndarray`. Available options are: `mean`, `laplacian`, `elliptical`, `sobel_{w,h,d}`` kernel_size: A single integer value specifying the size of the quadratic or cubic kernel. Computational complexity increases exponentially with kernel_size, which should be considered when choosing the kernel size. allow_missing_keys: Don't raise exception if key is missing. NFrr kernelstr | NdarrayOrTensor kernel_sizerrrrrc s&t||t||fi||_dSr)rrr#filter)rrrrrrrrrrszImageFilterd.__init__rrrcCrr)rrrrrrrrrzImageFilterd.__call__)NF) rr rrrrrrrrr) rrrrr#rrrrrrrrrks rkc@s2eZdZdZejZ   ddddZdddZdS)r{a Dictionary-based wrapper of :py:class:`monai.transforms.RandomFilterKernel`. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform kernel: A string specifying the kernel or a custom kernel as `torch.Tenor` or `np.ndarray`. Available options are: `mean`, `laplacian`, `elliptical`, `sobel_{w,h,d}`` kernel_size: A single integer value specifying the size of the quadratic or cubic kernel. Computational complexity increases exponentially with kernel_size, which should be considered when choosing the kernel size. prob: Probability the transform is applied to the data allow_missing_keys: Don't raise exception if key is missing. Note: - This transform does not scale output image values automatically to match the range of the input. The output should be scaled by later transforms to match the input if this is desired. N皙?Frr rrrrrrrrrrcKs2t|||t||t||fi||_dSr)rrrr#r)rrrrrrrrrrrs zRandImageFilterd.__init__rrrcCs>t|}|d|jr||D] }|||||<q|Sr)rrrrrrrrrr%s  zRandImageFilterd.__call__)NrF) rr rrrrrrrrrrr)rrrrr#rrrrrrrr{s  r{c@s>eZdZdZdejddddfdddZdddZdddZdS)ra Dictionary-based wrapper of :py:class:`monai.transforms.ApplyTransformToPoints`. The input coordinates are assumed to be in the shape (C, N, 2 or 3), where C represents the number of channels and N denotes the number of points. The output has the same shape as the input. Args: keys: keys of the corresponding items to be transformed. See also: monai.transforms.MapTransform refer_keys: The key of the reference item used for transformation. It can directly refer to an affine or an image from which the affine can be derived. It can also be a sequence of keys, in which case each refers to the affine applied to the matching points in `keys`. dtype: The desired data type for the output. affine: A 3x3 or 4x4 affine transformation matrix applied to points. This matrix typically originates from the image. For 2D points, a 3x3 matrix can be provided, avoiding the need to add an unnecessary Z dimension. While a 4x4 matrix is required for 3D transformations, it's important to note that when applying a 4x4 matrix to 2D points, the additional dimensions are handled accordingly. The matrix is always converted to float64 for computation, which can be computationally expensive when applied to a large number of points. If None, will try to use the affine matrix from the refer data. invert_affine: Whether to invert the affine transformation matrix applied to the points. Defaults to ``True``. Typically, the affine matrix is derived from the image, while the points are in world coordinates. If you want to align the points with the image, set this to ``True``. Otherwise, set it to ``False``. affine_lps_to_ras: Defaults to ``False``. Set to `True` if your point data is in the RAS coordinate system or you're using `ITKReader` with `affine_lps_to_ras=True`. This ensures the correct application of the affine transformation between LPS (left-posterior-superior) and RAS (right-anterior-superior) coordinate systems. This argument ensures the points and the affine matrix are in the same coordinate system. allow_missing_keys: Don't raise exception if key is missing. NTFrr refer_keysrRrDtypeLike | torch.dtypeaffinetorch.Tensor | None invert_affineraffine_lps_to_rasrcCs6t|||t|t|j|_t||||d|_dS)N)rrrr)rrr9rrrrr)rrrrrrrrrrrrNs   z ApplyTransformToPointsd.__init__rrcCsvt|}|||jD]-\}}||}d}|dur0||vr"||}ntd|dt|d|}|||||<q |S)NzThe refer_key 'z' is not found in the data.r)rrrrigetattrr)rrrrZ refer_keycoordsrZ refer_datarrrr^s  z ApplyTransformToPointsd.__call__rrcCs0t|}||D] }|j||||<q |Sr)rrrr"rrrrr"nszApplyTransformToPointsd.inverse)rr rrRrrrrrrrrrr)rrr) rrrrrjfloat64rrr"rrrrr.s" r)r __future__rrCcollections.abcrrrrcopyrtypingrr numpyrrj monai.configr r monai.config.type_definitionsr monai.data.meta_tensorr rmonai.data.utilsrmonai.transforms.inversermonai.transforms.traitsrrmonai.transforms.transformrrrmonai.transforms.utility.arrayrrrrrrrrrrr r!r"r#r$r%r&r'r(r)r*r+r,r-r.r/r0r1r2r3r4monai.transforms.utilsr5r60monai.transforms.utils_pytorch_numpy_unificationr7 monai.utilsr8r9monai.utils.enumsr:r;r<monai.utils.type_conversionr=__all__rrrgrFr^rrrrIrrarrrrr[rrurrXrrRrLrqr~rnrdrrOrCrrrrrtrhrrSrxr@rkr{rRandImageFilterDRandImageFilterDict ImageFilterDImageFilterDictrerfrDrEr\r]rrrrrrrGrHrrr_r`rrrrrrrrrYrZrrrrrVrWrrrPrQrJrKrorprlrmrbrcrrrMrNrArBrrrrrrrrr|r}rrrsrirjrrrTrUryrzr>r?rvrwrrrrrrs     !  z B#34!"#& 1Q=5GN$/0C"%$D&)&0G