o  i@sddlmZddlZddlZddlZddlmZmZmZm Z m Z ddl m Z ddl mZmZddlmZmZddlmZddlZddlZddlmZddlZdd lmZmZdd lmZmZdd l m!Z!dd l"m#Z#dd l$m%Z%ddl&m'Z'ddl(m)Z)m*Z*m+Z+ddl,m-Z-ddl.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:ddl;mZ>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZOmPZPddlQmRZRddlSmTZTmUZUmVZVmWZWmXZXeNddeM\ZYZZeNd\Z[Z\eNd\Z]Z^eNd\Z_Z`eNddd\ZaZbeNd\ZcZdgdZedddejffdxd)d*Zgdydzd.d/Zhd{d2d3Zid|d9d:Zjd}dd?Zld~dAdBZmdCdejffddEdFZndCdejffddHdIZoejpfddJdKZqddRdSZrdCdTdUddZd[Zs \dddbdcZt    C    \ TdddvdwZu CdddydzZv   C ddd|d}Zw ~ ddddZx \ddddZy  \ddddZz   \ TddddZ{ddTe|deRj}fdddZ~ddTe|fdddZddTejfdfdddZdTe|deRj}fdddZdeRj}fdddZejejejfdddZdeRj}fdddZejfdddZdeRj}fdddZejfdddZdeRj}fdddZejejfdddZelddd\fdddńZ ~ddddʄZ ͐ddddքZdddلZ \ddddZ ~ \ddddZ ~ T \ ddddZddddZ ddddZ CddddZ C  ddd d Z TddddZe dddZee>ee<ZddddZddZdddZ !ddd'd(ZGd)d*d*Zddd0d1Zd2d3Zd4d5Zdd8d9Zdd=d>Zddd@dAZddCdDZdddFdGZddHdIZdJdKZdLdMZdydÐdOdPZdQdRZdSdTZdUdVZdWdXZeddYdZeRjfdĐd\d]ZdŐdƐdcddZdŐdǐdedfZ  T \  ddd\dgdɐdqdrZddʐdudvZedwkredSdS() annotationsN)CallableHashableIterableMappingSequence)contextmanager) lru_cachewraps) getmembersisclass)Any)Tensor) DtypeLikeIndexSelection)NdarrayOrTensor NdarrayTensor) to_affine_nd)GaussianFilter) meshgrid_ij)Compose) MapTransform Transformapply_transform)erode) any_np_ptascontiguousarray concatenatecumsumisfinitenonzeroravel searchsortedsoftplusunique unravel_indexwhere)GridSampleModeGridSamplePadModeInterpolateMode NdimageMode NumpyPadModePostFixPytorchPadMode SplineMode TraceKeysTraceStatusKeys ensure_tupleensure_tuple_repensure_tuple_sizefall_back_tupleget_equivalent_dtypeissequenceiterablelook_up_option min_versionoptional_importunsqueeze_leftunsqueeze_right)TransformBackends)convert_data_typeconvert_to_cupyconvert_to_dst_typeconvert_to_numpyconvert_to_tensorzskimage.measurez0.14.2zskimage.morphologyz scipy.ndimagecupyndarraynamezskimage.exposure)6allow_missing_keys_modecheck_boundariescompute_divisible_spatial_sizeconvert_applied_interp_modecopypaste_arrayscheck_non_lazy_pending_opscreate_control_grid create_grid create_rotate create_scale create_shearcreate_translateextreme_points_to_image fill_holesFourier#generate_label_classes_crop_centers#generate_pos_neg_label_crop_centersgenerate_spatial_bounding_boxget_extreme_points$get_largest_connected_component_mask!keep_merge_components_with_points$keep_components_with_positive_pointsconvert_points_to_discremove_small_objects img_bounds in_boundsis_empty is_positive!map_and_generate_sampling_centersmap_binary_to_indicesmap_classes_to_indicesmap_spatial_axes rand_choice rescale_arrayrescale_array_int_maxrescale_instance_array resize_centerweighted_patch_samples zero_margins equalize_hist!get_number_image_type_conversionsget_transform_backendsprint_transform_backendsconvert_pad_modeconvert_to_contiguousget_unique_labels scale_affine attach_hooksync_meta_info reset_ops_idresolves_modeshas_status_keysdistance_transform_edt soft_clip?arrrsharpness_factorfloatminv$NdarrayOrTensor | float | int | NonemaxvdtypeDtypeLike | torch.dtypereturncCsb|dur t||d^}}|}|dur|t| |||}|dur/|t||||}|S)a Apply soft clip to the input array or tensor. The intensity values will be soft clipped according to f(x) = x + (1/sharpness_factor)*softplus(- c(x - minv)) - (1/sharpness_factor)*softplus(c(x - maxv)) From https://medium.com/life-at-hopper/clip-it-clip-it-good-1f1bf711b291 To perform one-sided clipping, set either minv or maxv to None. Args: arr: input array to clip. sharpness_factor: the sharpness of the soft clip function, default to 1. minv: minimum value of target clipped array. maxv: maximum value of target clipped array. dtype: if not None, convert input array to dtype before computation. Nr)r=r#)r}r~rrr_vrX/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/transforms/utils.pyr{sr{?probboolcCstt|kS)zv Returns True if a randomly chosen number is less than or equal to `prob`, by default this is a 50/50 chance. )rrandom)rrrrrfsrfimg np.ndarraycCsNtj|dd}tj|dd}tt|dddgt|dddgfS)zt Returns the minimum and maximum indices of non-zero lines in axis 0 of `img`, followed by that for axis 1. raxis)npanyrr&)rax0ax1rrrr^s2r^xymarginmaxxmaxycCs>t||ko ||kno||ko||kSS)zc Returns True if (x,y) is within the rectangle (margin, margin, maxx-margin, maxy-margin). )r)rrrrrrrrr_s>r_np.ndarray | torch.TensorcCs||k S)zd Returns True if `img` is empty, that is its maximum value is not greater than its minimum. )maxminrrrrr`sr`cCs|dkS)z{ Returns a boolean version of `img` where the positive values are converted into True, the other values are False. rrrrrrrasraintcCst|ddddd|fs!t|dddd| dfr#dSt|ddd|ddf oEt|dd| dddf S)zo Returns True if the values within `margin` indices of the edges of `img` in dimensions 1 and 2 are 0. NF)rr)rrrrrrlsBFrl float | NonecCsx|dur t||d^}}|}|}||kr"|dur ||S|S||||}|dus2|dur4|S||||S)a Rescale the values of numpy array `arr` to be from `minv` to `maxv`. If either `minv` or `maxv` is None, it returns `(a - min_a) / (max_a - min_a)`. Args: arr: input array to rescale. minv: minimum value of target rescaled array. maxv: maximum value of target rescaled array. dtype: if not None, convert input array to dtype before computation. Nr)r=rr)r}rrrrZminaZmaxanormrrrrgsrgrcCsBt|j|p|j}t|jdD] }t|||||||<q|S)zT Rescale each array slice along the first dimension of `arr` independently. r)rzerosshaperrangerg)r}rrroutirrrrisricCs0t|p|j}tjt||j|j|p|jdS)zc Rescale the array `arr` to be between the minimum and maximum values of the type `dtype`. r)riinforasarrayrgrr)r}rinforrrrhs rh srccenter Sequence[int] destcenterdimsSequence[int | None]+tuple[tuple[slice, ...], tuple[slice, ...]]c Cst|}t|}tdg|}tdg|}tt||||||D]>\} } } } } }|r_t|ddt| | }t|dddt| | | | }t| || ||| <t| || ||| <q!t|t|fS)a Calculate the slices to copy a sliced area of array in `src_shape` into array in `dest_shape`. The area has dimensions `dims` (use 0 or None to copy everything in that dimension), the source area is centered at `srccenter` index in `src` and copied into area centered at `destcenter` in `dest`. The dimensions of the copied area will be clipped to fit within the source and destination arrays so a smaller area may be copied than expected. Return value is the tuples of slice objects indexing the copied area in `src`, and those indexing the copy area in `dest`. Example .. code-block:: python src_shape = (6,6) src = np.random.randint(0,10,src_shape) dest = np.zeros_like(src) srcslices, destslices = copypaste_arrays(src_shape, dest.shape, (3, 2),(2, 1),(3, 4)) dest[destslices] = src[srcslices] print(src) print(dest) >>> [[9 5 6 6 9 6] [4 3 5 6 1 2] [0 7 3 2 4 1] [3 0 0 1 5 1] [9 4 7 1 8 2] [6 6 5 8 6 7]] [[0 0 0 0 0 0] [7 3 2 4 0 0] [0 0 1 5 0 0] [4 7 1 8 0 0] [0 0 0 0 0 0] [0 0 0 0 0 0]] Nrr)lensliceziprrcliprtuple)Z src_shapeZ dest_shaperrrZs_ndimZd_ndim srcslices destslicesrssdsscdcdimd1d2rrrrJs&&$rJT) fill_valueinplace resize_dims int | Nonerrc Gstt||j}t|jd}t|d}t|j||||\}}|s6t|||j}||||<|S||S)a Resize `img` by cropping or expanding the image from the center. The `resize_dims` values are the output dimensions (or None to use original dimension of `img`). If a dimension is smaller than that of `img` then the result will be cropped and if larger padded with zeros, in both cases this is done relative to the center of `img`. The result is a new image with the specified dimensions and values from `img` copied into its center. r)r4rrrtolistrJfullr) rrrrZhalf_img_shapeZhalf_dest_shaperrdestrrrrjQs  rjF input_arrayrE None | str raise_errorNonecCsFt|tjjr|jr!d|pdd}|rt|t|dSdSdS)aN Check whether the input array has pending operations, raise an error or warn when it has. Args: input_array: input array to be checked. name: an optional name to be included in the error message. raise_error: whether to raise an error, default to False, a warning message will be issued instead. zMThe input image is a MetaTensor and has pending operations, but the function z1 assumes non-lazy input, result may be incorrect.N) isinstancemonaidata MetaTensorpending_operations ValueErrorwarningswarn)rrErmsgrrrrKfs rKlabel spatial_sizeSequence[int] | int num_sampleslabel_spatial_shapeSequence[int] | None num_classesimageNdarrayOrTensor | Noneimage_thresholdmax_samples_per_classratioslist[float | int] | None rand_statenp.random.RandomState | None allow_smallerr tuple[tuple]c  Cs|durtdt|||||} |dur|} nt|tjjr#|} n|jdd} | dur2tdt||| | || | | }t |S)a Combine "map_classes_to_indices" and "generate_label_classes_crop_centers" functions, return crop center coordinates. This calls `map_classes_to_indices` to get indices from `label`, gets the shape from `label_spatial_shape` is given otherwise from the labels, calls `generate_label_classes_crop_centers`, and returns its results. Args: label: use the label data to get the indices of every class. spatial_size: spatial size of the ROIs to be sampled. num_samples: total sample centers to be generated. label_spatial_shape: spatial shape of the original label data to unravel selected centers. indices: sequence of pre-computed foreground indices of every class in 1 dimension. num_classes: number of classes for argmax label, not necessary for One-Hot label. image: if image is not None, only return the indices of every class that are within the valid region of the image (``image > image_threshold``). image_threshold: if enabled `image`, use ``image > image_threshold`` to determine the valid image content area and select class indices only in this area. max_samples_per_class: maximum length of indices in each class to reduce memory consumption. Default is None, no subsampling. ratios: ratios of every class in the label to generate crop centers, including background class. if None, every class will have the same ratio to generate crop centers. rand_state: numpy randomState object to align with other modules. allow_smaller: if `False`, an exception will be raised if the image is smaller than the requested ROI in any dimension. If `True`, any smaller dimensions will be set to match the cropped size (i.e., no cropping in that dimension). warn: if `True` prints a warning if a class is not present in the label. Returns: Tuple of crop centres Nzlabel must not be None.rzclabel_spatial_shape or label with a known shape must be provided to infer the output spatial shape.) rrdrrrrpeek_pending_shaperrUr1)rrrrrrrrrrrrindices_shapecentersrrrrb{s * rb'tuple[NdarrayOrTensor, NdarrayOrTensor]cCst|dd|jddkr|dd}tt|d}t|}|durBt|ddtt||kd}t||td^}}t||@}nt|}t|t dd^}}t|t dd^}}||fS) a Compute the foreground and background of input label data, return the indices after fattening. For example: ``label = np.array([[[0, 1, 1], [1, 0, 1], [1, 1, 0]]])`` ``foreground indices = np.array([1, 2, 3, 5, 6, 7])`` and ``background indices = np.array([0, 4, 8])`` Args: label: use the label data to get the foreground/background information. image: if image is not None, use ``label = 0 & image > image_threshold`` to define background. so the output items will not map to all the voxels in the label. image_threshold: if enabled `image`, use ``image > image_threshold`` to determine the valid image content area and select background only in this area. rcrDrrNrcpudevice) rKrr!rr r?rr=torchr)rrr label_flat fg_indicesimg_flatr bg_indicesrrrrcs    rclist[NdarrayOrTensor]cCs>t|ddd}|durt|ddt||kd}t|}|}|dkr/|dur-td|}g}t|D]g} |dkrHtt|| tdd} nt|| k} |durV|| @} t|t j j r`t j nd} tt| | t dd d} |rt| |krt| dkrttdt| d|t} || | q5|| q5|S) a` Filter out indices of every class of the input label data, return the indices after fattening. It can handle both One-Hot format label and Argmax format label, must provide `num_classes` for Argmax label. For example: ``label = np.array([[[0, 1, 2], [2, 0, 1], [1, 2, 0]]])`` and `num_classes=3`, will return a list which contains the indices of the 3 classes: ``[np.array([0, 4, 8]), np.array([1, 5, 6]), np.array([2, 3, 7])]`` Args: label: use the label data to get the indices of every class. num_classes: number of classes for argmax label, not necessary for One-Hot label. image: if image is not None, only return the indices of every class that are within the valid region of the image (``image > image_threshold``). image_threshold: if enabled `image`, use ``image > image_threshold`` to determine the valid image content area and select class indices only in this area. max_samples_per_class: maximum length of indices in each class to reduce memory consumption. Default is None, no subsampling. rdrDNrrzSchannels==1 indicates not using One-Hot format label, must provide ``num_classes``.rr output_typer)rKr!rrrrr=rrrrrrrr rrroundlinspaceastyperappend)rrrrrrchannelsZ num_classes_rcrrZ cls_indicesZ sample_idrrrrds:    " rdrint | Sequence[int]w n_samplesr_statelistc sPt|dd|durtd|durtj}tj|jtd}tjt||td}t ddt ||D}||}|jt |}|dk rL|| 8}t|}|d r`t|d r`|d dkrk|jdt||d }n||} t| || jd^} } t|| |d d d }t||tjd^}} t||d t|^} fdd|DS)a Computes `n_samples` of random patch sampling locations, given the sampling weight map `w` and patch `spatial_size`. Args: spatial_size: length of each spatial dimension of the patch. w: weight map, the weights must be non-negative. each element denotes a sampling weight of the spatial location. 0 indicates no sampling. The weight map shape is assumed ``(spatial_dim_0, spatial_dim_1, ..., spatial_dim_n)``. n_samples: number of patch samples r_state: a random state container Returns: a list of `n_samples` N-D integers representing the spatial sampling location of patches. rkrDNz w must be an ND array, got None.rcssL|]!\}}||krt|d|||dn t|d|ddVqdS)rrN)r).0rmrrr =sJz)weighted_patch_samples..rr)sizeT)rightrcsg|] }t|qSr)r%rrdiffv_sizerr Nz*weighted_patch_samples..)rKrrr RandomStaterrrr4rrr!rrrrrandintrr?rr"rminimum) rrrrimg_sizewin_sizesridxZ r_samplesrrrr rrk s.      rkr list[int] tuple[Any]c Cst||d}tt||dkr)|std|d|dtddt||D}t|d}t|td |td tj }t |D]\}}|||krY||d 7<qGg}t|||D]\} } } t t | | | d } |t| qbt|S) a~ Utility to correct the crop center if the crop size and centers are not compatible with the image size. Args: centers: pre-computed crop centers of every dim, will correct based on the valid region. spatial_size: spatial size of the ROIs to be sampled. label_spatial_shape: spatial shape of the original label data to compare with ROI. allow_smaller: if `False`, an exception will be raised if the image is smaller than the requested ROI in any dimension. If `True`, any smaller dimensions will be set to match the cropped size (i.e., no cropping in that dimension). defaultrzUThe size of the proposed random crop ROI is larger than the image size, got ROI size z and label image size z respectively.css|] \}}t||VqdSN)r)rlrrrrrjsz'correct_crop_centers..rr)r4rrsubtractrrr floor_dividearrayruint16 enumeraterrrrr1) rrrrZ valid_startZ valid_endrZvalid_sZ valid_centersrZv_sZv_eZcenter_irrrcorrect_crop_centersQs,  ( r" pos_ratiorrc Cs|dur tjjj}g}t|trt|n|}t|tr!t|n|}t|dkr3t|dkr3tdt|dks?t|dkr\t|dkrGdnd}t dt|dt|d|dt |D](} | |krj|n|} | t| } | | } t | |} |t| |||q`t|S) a Generate valid sample locations based on the label with option for specifying foreground ratio Valid: samples sitting entirely within image, expected input shape: [C, H, W, D] or [C, H, W] Args: spatial_size: spatial size of the ROIs to be sampled. num_samples: total sample centers to be generated. pos_ratio: ratio of total locations generated that have center being foreground. label_spatial_shape: spatial shape of the original label data to unravel selected centers. fg_indices: pre-computed foreground indices in 1 dimension. bg_indices: pre-computed background indices in 1 dimension. rand_state: numpy randomState object to align with other modules. allow_smaller: if `False`, an exception will be raised if the image is smaller than the requested ROI in any dimension. If `True`, any smaller dimensions will be set to match the cropped size (i.e., no cropping in that dimension). Raises: ValueError: When the proposed roi is larger than the image. ValueError: When the foreground and background indices lengths are 0. NrzNo sampling location available.rzNum foregrounds z, Num backgrounds zD, unable to generate class balanced samples, setting `pos_ratio` to .)rr__self__rrrrrrrrrandrr%rrr"r1)rrr#rrrrrrrindices_to_use random_intrcenterrrrrV}s*  rVrSequence[NdarrayOrTensor]cCsZ|dur tjjj}|dkrtd|dtt|dur"dgt|n|}t|t|kr=tdt|dt|dtdd|DrNtd |dt|D]\} } t| d krq|| d krqd || <|rqt d | d qRg} |j t||t |t |d } | D] } || } |t| }t| ||}| t||||qt| S)a^ Generate valid sample locations based on the specified ratios of label classes. Valid: samples sitting entirely within image, expected input shape: [C, H, W, D] or [C, H, W] Args: spatial_size: spatial size of the ROIs to be sampled. num_samples: total sample centers to be generated. label_spatial_shape: spatial shape of the original label data to unravel selected centers. indices: sequence of pre-computed foreground indices of every class in 1 dimension. ratios: ratios of every class in the label to generate crop centers, including background class. if None, every class will have the same ratio to generate crop centers. rand_state: numpy randomState object to align with other modules. allow_smaller: if `False`, an exception will be raised if the image is smaller than the requested ROI in any dimension. If `True`, any smaller dimensions will be set to match the cropped size (i.e., no cropping in that dimension). warn: if `True` prints a warning if a class is not present in the label. Nrz:num_samples must be an int number and greater than 0, got r$zDrandom crop ratios must match the number of indices of classes, got z and css|]}|dkVqdS)rNrr rrrrsz6generate_label_classes_crop_centers..z/ratios should not contain negative number, got rzno available indices of class z7 to crop, setting the crop ratio of this class to zero.)rp)rrr%rrr1rrr!rrchoicersumrr%rrr")rrrrrrrrZratios_rrrclassesr'r(r)rrrrUs8 "   $rUspacingSequence[float] | None homogeneousrtorch.device | NonecCsTt|t}|pt}|tjkrt||||S|tjkr"t|||||Std|d)a compute a `spatial_size` mesh. - when ``homogeneous=True``, the output shape is (N+1, dim_size_1, dim_size_2, ..., dim_size_N) - when ``homogeneous=False``, the output shape is (N, dim_size_1, dim_size_2, ..., dim_size_N) Args: spatial_size: spatial size of the grid. spacing: same len as ``spatial_size``, defaults to 1.0 (dense grid). homogeneous: whether to make homogeneous coordinates. dtype: output grid data type, defaults to `float`. device: device to compute and store the output (when the backend is "torch"). backend: APIs to use, ``numpy`` or ``torch``. backend  is not supported)r7r<rNUMPY_create_grid_numpyTORCH_create_grid_torchr)rr/r1rrbackend_backend_dtyperrrrMs   rMcCsp|p tdd|D}ddt||D}tjtj|ddit|tjd}|s*|St|t|dd gS) z; compute a `spatial_size` mesh with the numpy API. cs|]}dVqdSr|Nrrrrrrrz%_create_grid_numpy..cSs<g|]\}}t|d d||dd|t|qS)r|@)rrrrdrrrrr  s<z&_create_grid_numpy..indexingijrNr) rrrrmeshgridr5rCr ones_like)rr/r1rrangescoordsrrrr6s  "r6csb|p tdd|D}fddt||D}t|}|s#t|Stg|t|dS)z; compute a `spatial_size` mesh with the torch API. csr<r=rr>rrrr1r?z%_create_grid_torch..c sJg|]!\}}tj|d d||dd|t|ttjdqS)r|r@rr)rrrr5rrArIrrr 2s z&_create_grid_torch..r)rrrrstackrF)rr/r1rrrGrHrrIrr8's   r8 spatial_shapeSequence[float]c Cst|ttjk}|r tjntj}g}t||D]<\} } |r$tj| |dnt| } | ddkrB| || dd| dddq| || dd| ddqt ||||||dS) zB control grid with two additional point in each direction rrrr|r@rg@)rr/r1rrr9) r7r<r7rceilrr as_tensorrrrM) rKr/r1rrr9Z torch_backendZ ceil_func grid_shaperBrrrrrLBs  ($ rL spatial_dimsradiansSequence[float] | floatr9strcspt|t}|tjkrt||tjtjtjdS|tjkr0t||fddfddfdddSt d|d)a create a 2D or 3D rotation matrix Args: spatial_dims: {``2``, ``3``} spatial rank radians: rotation radians when spatial_dims == 3, the `radians` sequence corresponds to rotation in the 1st, 2nd, and 3rd dim respectively. device: device to compute and store the output (when the backend is "torch"). backend: APIs to use, ``numpy`` or ``torch``. Raises: ValueError: When ``radians`` is empty. ValueError: When ``spatial_dims`` is not one of [2, 3]. )rPrQsin_funccos_funceye_funccttj|tjdSN)rr)rsinrNfloat32thrrrzzcreate_rotate..crWrX)rcosrNrZr[rrrr]{r^ctj|dSNrreyerankrrrr]|r3r4) r7r<r5_create_rotaterrYr_rcr7r)rPrQrr9r:rrrrN[s      rNrTrrUrVc Cst|}|dkr8t|dkr4||d||d}}|d}|| |d<|d<|||d<|d<|Std |dkrd}t|dkrh||d||d}}|d }|| |d<|d <|||d <|d <t|dkr||d||d}}|durtd|d } ||| d<| d<| || d<| d <|| }t|dkr||d||d}}|durtd|d } || | d<| d<||| d<| d<|| }|durtd |Std|d)Nrrrrrrrrr)rrzradians must be non empty.rrrr)rrzAffine should be a matrix.rrrrzUnsupported spatial_dims: z, available options are [2, 3].)r1rr) rPrQrTrUrVsin_cos_raffine_affinerrrrgsH    rgcoefscTt|t}|tjkrt||tjdS|tjkr"t||fdddStd|d)a create a shearing matrix Args: spatial_dims: spatial rank coefs: shearing factors, a tuple of 2 floats for 2D, a tuple of 6 floats for 3D), take a 3D affine as example:: [ [1.0, coefs[0], coefs[1], 0.0], [coefs[2], 1.0, coefs[3], 0.0], [coefs[4], coefs[5], 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], ] device: device to compute and store the output (when the backend is "torch"). backend: APIs to use, ``numpy`` or ``torch``. Raises: NotImplementedError: When ``spatial_dims`` is not one of [2, 3]. )rPrurVcr`rarbrdrrrr]rfzcreate_shear..r3r4)r7r<r5 _create_shearrrcr7r)rPrurr9r:rrrrPs   rPcCs|dkrt|ddd}|d}|d|d|d<|d<|S|dkrVt|d dd}|d }|d|d|d<|d <|d|d|d<|d <|d |d |d<|d<|Std)Nrrrpad_valrhrrrjrkrlrormrprnz4Currently only spatial_dims in [2, 3] are supported.)r3NotImplementedError)rPrurVrrrrrwsrwscaling_factortorch.device | str | Nonecrv)a) create a scaling matrix Args: spatial_dims: spatial rank scaling_factor: scaling factors for every spatial dim, defaults to 1. device: device to compute and store the output (when the backend is "torch"). backend: APIs to use, ``numpy`` or ``torch``. rPr} array_funccsttj|dSra)rdiagrNrrrrr]zcreate_scale..r3r4)r7r<r5 _create_scalerrr7r)rPr}rr9r:rrrrOs    rOcCs"t||dd}||d|dS)Nr|rxr|)r3rrrrrsrshiftcsjt|t}t|}|tjkrt||tjtjdS|tjkr-t||fddfdddSt d|d)a* create a translation matrix Args: spatial_dims: spatial rank shift: translate pixel/voxel for every spatial dim, defaults to 0. device: device to compute and store the output (when the backend is "torch"). backend: APIs to use, ``numpy`` or ``torch``. )rPrrVrcstjt|dSra)rrcrNrrrrr]rz"create_translate..cr`ra)rrNrrrrr]rfr3r4) r7r<rr5_create_translaterrcrr7r)rPrrr9r:rrrrQs     rQcCsBt|}||d}t|d|D] \}}||||f<q||SNr)r1r!)rPrrVrrsrarrrr#s  r select_fnchannel_indicesIndexSelection | Nonetuple[list[int], list[int]]cCst|dd|jdd}|dur|tt|n|}||d}t|j}t||}|D]}|dkr 0. channel_indices: if defined, select foreground only on the specified channels of image. if None, select foreground on the whole image. margin: add margin value to spatial dims of the bounding box, if only 1 value provided, use it for all dims. allow_smaller: when computing box size with `margin`, whether to allow the image edges to be smaller than the final box edges. If `True`, the bounding boxes edges are aligned with the input image edges, if `False`, the bounding boxes edges are aligned with the final box edges. Default to `False`. The default value is changed from `True` to `False` in v1.5.0. rWrDrNrz0margin value should not be negative number, got r$r)rKrrr1rrr2rr! itertools combinationsreversedrrr&rrrrrdetachritem)rrrrrrrndimr box_startbox_enddiaxdtZarg_maxZmin_dZmax_drrrrW-s6     $   $&rWr connectivitynum_componentscCstd\}}to|ot|tjo|jtdk}|r't|}|jj }t }nt s-t dt |tj^}} tj }t}|||dd\} } | |krM|t} n | || } ||| ddd}|d|}|| |} t| || jdd S) aS Gets the largest connected component mask of an image. Args: img: Image to get largest connected component from. Shape is (spatial_dim1 [, spatial_dim2, ...]) connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If ``None``, a full connectivity of ``input.ndim`` is used. for more details: https://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.label. num_components: The number of largest components to preserve. cucim.skimagerzSkimage.measure required.TrZ return_numNrdstrr)r9has_cprrrrr>shortmeasurercp has_measure RuntimeErrorr=rrCrrr argsortbincountisinr?r)rrrskimage has_cucimuse_cpimg_rlibrfeatures num_featuresrnonzerosZfeatures_to_keeprrrrYns& $    rYrrhrorhimg_posimg_neg point_coords point_labelspos_valneg_valmarginsc! Cstd\}}to|ot|tjo|jtdk} | r-t|} t|} |jj } t } n)t s3t dt |tj^} }t |tj^} }| jtksM| jtkrQtdtj } t} | | ddd\}}| | ddd\}}t| }t|jdD]}t||D]\}}|||f|vr|}n |||f|vr|}nq|t|D]}t|tjrt|t\}}}n |\}}}t||dt||d |jd }}t||dt||d |jd }}t||dt||d |jd }}||d||||||fdkr1||d||||||f} ||g| ||g| 7<nqq|qtd ||d k<t |||jd dS)a Keep connected regions of img_pos and img_neg that include the positive points and negative points separately. The function is used for merging automatic results with interactive results in VISTA3D. Args: img_pos: bool type tensor, shape [B, 1, H, W, D], where B means the foreground masks from a single 3D image. img_neg: same format as img_pos but corresponds to negative points. pos_val: positive point label values. neg_val: negative point label values. point_coords: the coordinates of each point, shape [B, N, 3], where N means the number of points. point_labels: the label of each point, shape [B, N]. margins: include points outside of the region but within the margin. rrskimage.measure required.z&img_pos and img_neg must be bool type.rhTrrrrr)!r9rrrrrr>rrrrrrr=rrCrrr zeros_likerrr!rrrrrrrrrr?)!rrrrrrrZ cucim_skimagerrZimg_pos_Zimg_neg_rrrZ features_posZ features_negoutsbsrr+rrrrzrrtrBfbindexrrrrZsR $     (((("  rZ torch.Tensorc Cststdt|}tt|D]}||dks$||dks$q||||dkf||||dkf}t|d|f}t |d|fdkd}t |t j ^}}t j} | |dd} t||jdk} t| |j} g} |D]} | | t| dt| dt| dfq{tt| } | D]}|dkrq|d|f| |k7<q|dk}|d|ft|d|f|}||d|ft| |d|f<q|S)a Keep connected regions that include the positive points. Used for point-only inference postprocessing to remove regions without positive points. Args: img: [1, B, H, W, D]. Output prediction from VISTA3D. Value is before sigmoid and contain NaN value. point_coords: [B, N, 3]. Point click coordinates point_labels: [B, N]. Point click labels. rrhrr)rr)rrrrrrrrisnan nan_to_numr=rrCrr from_numpytorrrrrset logical_andmean)rrrrrrHZ not_nan_maskrrrrZpos_maskrr+rZfill_inrrrr[s4   0 2 &$r[r image_sizepointr point_labelradiusdiscc srtjjdddddgjd}fddtdD}t|d|d|d\}}} ttj||| fddd } | jdddddd} t j jd dD]`\} } t | | fd } || | fd kr|| | fdks{|| | fdkr}dnd}t | | |f| d}|r|| |f| d|dk7<qV|| |ft| d d|d7<qV|S) a Convert a 3D point coordinates into image mask. The returned mask has the same spatial size as `image_size` while the batch dimension is the same as 'point' batch dimension. The point is converted to a mask ball with radius defined by `radius`. The output contains two channels each for negative (first channel) and positive points. Args: image_size: The output size of the converted mask. It should be a 3D tuple. point: [B, N, 3], 3D point coordinates. point_label: [B, N], 0 or 2 means negative points, 1 or 3 means postive points. radius: disc ball radius size. disc: If true, use regular disc, other use gaussian. rrrrc s(g|]}tjd|dtjjdqS)rr)startendsteprr)rarangerZrr rrrrr #sz*convert_points_to_disc..rhrrzNrlr)rrrrrrEr:rJrepeatrndindexr;powr-exp)rrrrrmasks_arrayZ coord_rowsZ coord_colsZcoord_zrHrnZpoint_bnchannelZpow_diffrrrr\s",  ($.r\rlabels label_set max_ppoint max_npoint use_centerc s.|jddks td|durttjrdnd}|d}| }g}g}|D]} | |vr|t | k} | } t t | d dd} t| |tdkrbt| |t| |} tt|}tt| |}||||}|rd}|dd }t|\}}| n tttt|tfd d t|Dtj| |d tjgd |dg||tdg|dg|d g||q/|t||d||t|||dq/t|}t|}||fS)aSample points from labels. Args: labels: [1, 1, H, W, D] label_set: local index, must match values in labels. max_ppoint: maximum positive point samples. max_npoint: maximum negative point samples. device: returned tensor device. use_center: whether to sample points from center. Returns: point: point coordinates of [B, N, 3]. B equals to the length of label_set. point_label: [B, N], always 0 for negative, 1 for positive. rrzlabels must have batch size 1.Ncudarrirrcsg|]}|qSrrr Z plabelpointssorted_indicesrrr lr^z,sample_points_from_label..)k)rrrrrh)rrrrr is_availabler$rnumpyrrrYr unsqueezer rrrrrr-sortrrrshufflerrJchoicestensorr)rrrrrr unique_labelsZ_pointZ _point_labelidZplabelsZnlabelsZ_plabelsZ nlabelpointsZnum_pZnum_npadZpmeanZpdisrZsorted_indices_tensorrrrrrsample_points_from_label6sT    2   r@min_sizeindependent_channels by_measurepixdim+Sequence[float] | float | np.ndarray | Nonec Cs tt|dkr |Ststd|rTt|jdd}t|tjjr&|j }n|dur0t ||}n t dd|}t t |}|dkrLt dd}t ||}n |dur]t dt|t j^} } |sl| dk} n| | dkrvtnt j} t| ||} t| |^} } |s|| } | S) a Use `skimage.morphology.remove_small_objects` to remove small objects from images. See: https://scikit-image.org/docs/dev/api/skimage.morphology.html#remove-small-objects. Data should be one-hotted. Args: img: image to process. Expected shape: C, H,W,[D]. Expected to only have singleton channel dimension, i.e., not be one-hotted. Converted to type int. min_size: objects smaller than this size are removed. connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If ``None``, a full connectivity of ``input.ndim`` is used. For more details refer to linked scikit-image documentation. independent_channels: Whether to consider each channel independently. by_measure: Whether the specified min_size is in number of voxels. if this is True then min_size represents a surface area or volume value of whatever units your image is in (mm^3, cm^2, etc.) default is False. pixdim: the pixdim of the input image. if a single number, this is used for all axes. If a sequence of numbers, the length of the sequence must be equal to the image dimensions. rzSkimage required.NzU`img` is not of type MetaTensor and `pixdim` is None, assuming affine to be identity.rrzPInvalid `pixdim` value detected, set it to 1. Please verify the pixdim settings.z?`pixdim` is specified but not in use when computing the volume.)rr$has_morphologyrrrrrrrr2rrrprodrrMr=rCrrrint32 morphologyr]r?) rrrrrrsrZ_pixdimZ voxel_volumeimg_nprout_nprrrrr]|s8     r] is_onehotdiscardint | Iterable[int] | Noneset[int]cCsn|jd}|rddt|D}n|dkrtd|dtt|}|dur5t|D]}||q-|S)aGet list of non-background labels in an image. Args: img: Image to be processed. Shape should be [C, W, H, [D]] with C=1 if not onehot else `num_classes`. is_onehot: Boolean as to whether input image is one-hotted. If one-hotted, only return channels with discard: Can be used to remove labels (e.g., background). Can be any value, sequence of values, or `None` (nothing is discarded). Returns: Set of labels rcSs h|] \}}|dkr|qS)r)r-)rrrrrr s z$get_unique_labels..rz7If input not one-hotted, should only be 1 channel, got r$N)rr!rrr$rr1r)rrr n_channelsapplied_labelsrrrrrss   rsimg_arrrIterable[int] | Nonec Csd}|j|}|dk}|jd}t||p|}|dur t|nt||}d}|||D]:} tj|jddt d} tj | |d|rJt || n|d| kdd| d|r_t | || <q.| |dt | f<q.|S)a Fill the holes in the provided image. The label 0 will be treated as background and the enclosed holes will be set to the neighboring class label. What is considered to be an enclosed hole is defined by the connectivity. Holes on the edge are always considered to be open (not enclosed). Note: The performance of this method heavily depends on the number of labels. It is a bit faster if the list of `applied_labels` is provided. Limiting the number of `applied_labels` results in a big decrease in processing time. If the image is one-hot-encoded, then the `applied_labels` need to match the channel index. Args: img_arr: numpy array of shape [C, spatial_dim1[, spatial_dim2, ...]]. applied_labels: Labels for which to fill holes. Defaults to None, that is filling holes for all labels. connectivity: Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. Defaults to a full connectivity of ``input.ndim``. Returns: numpy array of shape [C, spatial_dim1[, spatial_dim2, ...]]. rrNrr) structure iterationsmaskorigin border_valueoutput) rrndimagegenerate_binary_structurerrsrrrrbinary_dilation logical_not) rrrZ channel_axis num_channelsZ is_one_hotrPrZbackground_labelrtmprrrrSs.    rS backgroundpertlist[tuple[int, ...]]cstdddurtjjjt|ktddkr"tdfdd}g}tjD]}| t || || t || |q2|S)a Generate extreme points from an image. These are used to generate initial segmentation for annotation models. An optional perturbation can be passed to simulate user clicks. Args: img: Image to generate extreme points from. Expected Shape is ``(spatial_dim1, [, spatial_dim2, ...])``. rand_state: `np.random.RandomState` object used to select random indices. background: Value to be consider as background, defaults to 0. pert: Random perturbation amount to add to the points, defaults to 0.0. Returns: A list of extreme points, its length is equal to 2 * spatial dimension of input image. The output format of the coordinates is: [1st_spatial_dim_min, 1st_spatial_dim_max, 2nd_spatial_dim_min, ..., Nth_spatial_dim_max] Raises: ValueError: When the input image does not have any foreground pixel. rXrDNrz1get_extreme_points: no foreground object in mask!cst||kd}t|tjr|n|}dur|n|}g}tjD],}t||ddur; nd}t |d}t |j |d}| |q(|S)z Select one of the indices within slice containing val. Args: val : value for comparison dim : dimension in which to look for value rNr@rr)r&rrrrr,rrrr&rrrr)valrrptjrrrrrr _get_point9s,  z&get_extreme_points.._get_point) rKrrr%r&rrrrrrrr)rrrrrpointsrrrrrXs   rXrsigma?Sequence[float] | float | Sequence[torch.Tensor] | torch.Tensor rescale_min rescale_maxc stjt|dtjd|D]}d|<qt|tr%fdd|D}ntj|jd}ddt|j d|d}| d } }||||||S) a" Please refer to :py:class:`monai.transforms.AddExtremePointsChannel` for the usage. Applies a gaussian filter to the extreme points image. Then the pixel values in points image are rescaled to range [rescale_min, rescale_max]. Args: points: Extreme points of the object/organ. label: label image to get extreme points from. Shape must be (1, spatial_dim1, [, spatial_dim2, ...]). Doesn't support one-hot labels. 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. rrr|csg|] }tj|jdqS)r)rrNr)rrZ points_imagerrr ssz+extreme_points_to_image..rr)r)rrrNrrrrrrrsqueezerrr) rrrr r!r+gaussian_filterZ min_intensityZ max_intensityrr"rrRUs  rRimg_ndim spatial_axesSequence[int] | int | None channel_firstcCs|durt|r td|St|dSg}t|D]%}|r.||dkr(||n|dq||dkr<|d|dn|q|S)ae Utility to map the spatial axes to real axes in channel first/last shape. For example: If `channel_first` is True, and `img` has 3 spatial dims, map spatial axes to real axes as below: None -> [1, 2, 3] [0, 1] -> [1, 2] [0, -1] -> [1, -1] If `channel_first` is False, and `img` has 3 spatial dims, map spatial axes to real axes as below: None -> [0, 1, 2] [0, 1] -> [0, 1] [0, -1] -> [0, -2] Args: img_ndim: dimension number of the target image. spatial_axes: spatial axes to be converted, default is None. The default `None` will convert to all the spatial axes of the image. If axis is negative it counts from the last to the first axis. If axis is a tuple of ints. channel_first: the image data is channel first or channel last, default to channel first. Nrr)rrr1r)r%r&r(Z spatial_axes_rrrrres   $re transform=MapTransform | Compose | tuple[MapTransform] | tuple[Compose]c cst|r t|}g}t|tr|g}nt|tr#dd|jD}t|dkr-tddd|D}z|D]}d|_q7dVWt ||D]\}}||_qFdSt ||D]\}}||_qUw)aTemporarily set all MapTransforms to not throw an error if keys are missing. After, revert to original states. Args: transform: either MapTransform or a Compose Example: .. code-block:: python data = {"image": np.arange(16, dtype=float).reshape(1, 4, 4)} t = SpatialPadd(["image", "label"], 10, allow_missing_keys=False) _ = t(data) # would raise exception with allow_missing_keys_mode(t): _ = t(data) # OK! cSsg|] }t|tr|qSr)rrrrrrrr rz+allow_missing_keys_mode..rz_allow_missing_keys_mode expects either MapTransform(s) or Compose(s) containing MapTransform(s)cSsg|]}|jqSr)allow_missing_keysr+rrrr sTN) r6rrrflatten transformsr TypeErrorr,r)r)r.Z orig_statesrZo_srrrrFs,   rFnearestmode align_corners bool | Nonecs tttfrfddDSttsStdvrNd}t|ts-|tvr2d<nt|dts?|dtvrNfddttDd<dvrpdurYt j nd}t |rlfddDnd<dvrdvrfd d DSS) a Recursively change the interpolation mode in the applied operation stacks, default to "nearest". See also: :py:class:`monai.transform.inverse.InvertibleTransform` Args: trans_info: applied operation stack, tracking the previously applied invertible transform. mode: target interpolation mode to convert, default to "nearest" as it's usually used to save the mode output. align_corners: target align corner value in PyTorch interpolation API, need to align with the `mode`. csg|] }t|dqS)r1r2rI)rr)r2r1rrr rz/convert_applied_interp_mode..r1rcg|]}qSrrr>)r1rrr r2Ncr6rrr>)_align_cornersrrr r7cs i|] }|t|dqSr4r5)rr)r2r1 trans_inforr sz/convert_applied_interp_mode..) rrrrdictr _interp_modesrrr/NONEr6)r9r1r2 current_modeZ current_valuer)r8r2r1r9rrIs*   rIcCsxt|ttfrdd|DSt|tjjrt|j|_|St|ts$|St |}t j |vr3t j |t j <dd| DS)zbfind MetaTensors in list or dict `data` and (in-place) set ``TraceKeys.ID`` to ``Tracekeys.NONE``.cSsg|]}t|qSrrw)rrBrrrr rz reset_ops_id..cSsi|] \}}|t|qSrr?rrrrrrr:rz reset_ops_id..)rrrrrrrwapplied_operationsrr;r/IDr=items)rrrrrws    rwrcCs^t|dt|}g}t||D]\}}|dkr#tt|||n|}||qt|S)aZ Compute the target spatial size which should be divisible by `k`. Args: spatial_shape: original spatial shape. k: the target k for each spatial dimension. if `k` is negative or 0, the original size is preserved. if `k` is an int, the same `k` be applied to all the input spatial dimensions. rr)r4rrrrrMrr)rKrnew_sizeZk_drnew_dimrrrrH s  " rHr np.ndarray | Nonenum_binsrrc Cs|j}|dur|tj|tdn|}trt||\}}nt||\}}|dd|ddd}|} t | ||d} t ||| }| |S)a Utility to equalize input image based on the histogram. If `skimage` installed, will leverage `skimage.exposure.histogram`, otherwise, use `np.histogram` instead. Args: img: input image to equalize. mask: if provided, must be ndarray of bools or 0s and 1s, and same shape as `image`. only points at which `mask==True` are used for the equalization. num_bins: number of the bins to use in histogram, default to `256`. for more details: https://numpy.org/doc/stable/reference/generated/numpy.histogram.html. min: the min value to normalize input image, default to `0`. max: the max value to normalize input image, default to `255`. Nrrrr)r}rr) rrrr has_skimageexposure histogramr-rrginterpreshape) rr rJrr orig_shapeZhist_imghistbinsZcumrrrrms rmc@s2eZdZdZeddd d Ze ddddZd S)rTz/ Helper class storing Fourier mappings FrrrPr as_contiguousrrcCstt| d}t|tjr6ttjdr#tjjtjj||d|d}n!t jjt jj| |d|d}nt jjt jj||d|d}|rJt |S|S)a Applies fourier transform and shifts the zero-frequency component to the center of the spectrum. Only the spatial dimensions get transformed. Args: x: Image to transform. spatial_dims: Number of spatial dimensions. as_contiguous: Whether to convert the cached NumPy array or PyTorch tensor to be contiguous. Returns k: K-space data. rfftshiftraxes) rrrrrhasattrfftrTfftnrrrr)rrPrSrrrrr shift_fourierHs  &zFourier.shift_fourierNrn_dimsrcCstt| d}t|tjr9ttjdr%tjjtjj||d|ddj }n#t jjt jj| |d|dj }nt jjt jj||d|dj }|rNt |S|S)ax Applies inverse shift and fourier transform. Only the spatial dimensions are transformed. Args: k: K-space data. spatial_dims: Number of spatial dimensions. as_contiguous: Whether to convert the cached NumPy array or PyTorch tensor to be contiguous. Returns: x: Tensor in image space. r ifftshiftrbackward)rrrU)rrrrrrWrXifftnr\realrrrr)rrPr[rSrrrrrinv_shift_fourierbs  "(zFourier.inv_shift_fourierF)rrrPrrSrrrNF) rrrPrr[rrSrrr)__name__ __module__ __qualname____doc__ staticmethodrZr`rrrrrTCsrTr test_datar keyHashable | Nonec sddlmdd}t|||tsdnd}|j}t|s+tfdd|Dr/td|D]<}|||}t|}t|t j rE|j nd } t |||j |j}|||} t| t j r^| j nd } t| |ri| | krm|d 7}q1|S) a Get the number of times that the data need to be converted (e.g., numpy to torch). Conversions between different devices are also counted (e.g., CPU to GPU). Args: transform: composed transforms to be tested test_data: data to be used to count the number of conversions key: if using dictionary transforms, this key will be used to check the number of conversions. rOneOfcSs|dur|S||Srr)objrirrr _get_datasz4get_number_image_type_conversions.._get_datarc3s|]}t|VqdSr)rr rkrrrz4get_number_image_type_conversions..zRNot compatible with `OneOf`, as the applied transform is deterministically chosen.Nr)monai.transforms.composerlrrSr-r.rrtyperrrr map_items unpack_items) r)rhrirnZnum_conversionstr _transformZ prev_dataZ prev_type prev_deviceZ curr_dataZ curr_devicerrkrrns"     rncCsji}g}ttjD])\}}||vrq ||t|r2t|tr2|dvr2tj|j vtj |j vg||<q |S)a6Get the backends of all MONAI transforms. Returns: Dictionary, where each key is a transform, and its corresponding values are a boolean list, stating whether that transform supports (1) `torch.Tensor`, and (2) `np.ndarray` as input without needing to convert. )BatchInverseTransformrCuCIMCuCIMD DecollatedInvertDInvertibleTransformLambdaLambdaDrrl RandCuCIM RandCuCIMD RandomOrderPadListDataCollate RandLambda RandLambdaDRandTorchVisionDRandomizableTransform TorchVisionDr) r rr.rr issubclassrr<r7r9r5)backendsZunique_transformsrrmrrrros   roc s$Gddd}dd|jffdd }t}t|}d\}}}}|dd d |D];\}} t| r;|j} |d 7}n| d rG|j} |d 7}n| d rS|j} |d 7}n|j} |d 7}||| d | d | d q+td|d||jd||jd||jd||jdS)z2Prints a list of backends of all MONAI transforms.c@seZdZdZdZdZdZdS)z(print_transform_backends..Colorsr91Z9293N)rcrdrenoneredgreenyellowrrrrColorss rcSstd|d|ddS)Nzz)print)rcolorrrr print_colorsz-print_transform_backends..print_colorcs$|dd|dd|d|dS)Nz<50 z<8r)rErrrrrrprint_table_columns$z4print_transform_backends..print_table_column)rrrrrzTorch?zNumpy?rr)rzTotal number of transforms:z1Number transforms allowing both torch and numpy: zNumber of TorchTransform: zNumber of NumpyTransform: zNumber of uncategorized: N) rrorrCallrrrr) rrrZn_totalZ n_t_or_npn_tZn_npZn_uncategorizedrrrrrrrps2      rpr str | NonecCstt|tjr|dkr d}n|dkrd}t|tSt|tjr0|dkr%d}n|dkr+d}t|tStdt |d)z Utility to convert padding mode between numpy array and PyTorch Tensor. Args: dst: target data to convert padding mode for, should be numpy array or PyTorch Tensor. mode: current padding mode. wrapcircularedge replicatezunsupported data type: r$) rrrr7r-rrCr+rrq)rr1rrrrqs    rqr7NdarrayOrTensor | str | bytes | Mapping | Sequence[Any])NdarrayOrTensor | Mapping | Sequence[Any]c snt|tjtjttfrt|fiSt|tr#fdd| DSt|t r5t |fdd|DS|S)a Check and ensure the numpy array or PyTorch Tensor in data to be contiguous in memory. Args: data: input data to convert, will recursively convert the numpy array or PyTorch Tensor in dict and sequence. kwargs: if `x` is PyTorch Tensor, additional args for `torch.contiguous`, more details: https://pytorch.org/docs/stable/generated/torch.Tensor.contiguous.html#torch.Tensor.contiguous. cs"i|] \}}|t|fiqSrrrr@kwargsrrr:&s"z)convert_to_contiguous..c3s |] }t|fiVqdSrrr rrrr(sz(convert_to_contiguous..) rrrCrrrSbytesrrrCrrq)rrrrrrrs   rrcenteredcCstt|t|}||krt|dStjddt||Dtd}t||}|r?t |d|dd|d|df<|S)aB Compute the scaling matrix according to the new spatial size Args: spatial_size: original spatial size. new_spatial_size: new spatial size. centered: whether the scaling is with respect to the image center (True, default) or corner (False). Returns: the scaling matrix. rcSs&g|]\}}t|tt|dqSrD)rr)rorrrrr =s&z scale_affine..rNr@r) rrrrcrrrrOrr)rZnew_spatial_sizerrrscalerrrrt-s &rtprecsFddh}t||dkr||n||t|fdd}|S)z Adds `hook` before or after a `func` call. If mode is "pre", the wrapper will call hook then func. If the mode is "post", the wrapper will call func then hook. rpostcs||}||Srr)instr_funcZ_hookrrwrapperOs  zattach_hook..wrapper)r7r )funchookr1 supportedrrrrruDs  rurc Cs:t|ts|St|}t|}||vrtjj||<t||tjjs6tj||||<||||_|| ||jtj j |}||vrStjj ||<||j||}}|sj|||_||<|S|sw|||_||<|S|rt|t|kr|n|}n t|t|kr|n|}|||_||<|S)z Given the key, sync up between metatensor `data_dict[key]` and meta_dict `data_dict[key_transforms/meta_dict]`. t=True: the one with more applied_operations in metatensor vs meta_dict is the output, False: less is the output. )rrr;r,metarrrget_default_metaupdater.TraceableTransform trace_keyget_default_applied_operationsrAr) ri data_dictrrBZ meta_dict_keyZ xform_keyZ from_meta from_dictrefrrrrvWs2  rvcCs4t|trt|dkrtdd|DstddS)z0 Check boundaries for Signal transforms rcss|]}t|tVqdSr)rrr rrrrroz#check_boundaries..z|Stt|t|ttSNr)r7rSr.rr)NEARESTZERO NEAREST_EXACTLINEARONEBILINEAR TRILINEARBICUBICTHREEAREAr interp_moderet_mappingrrr_to_numpy_resample_interp_modes rcCrtt|tdd}|dur|Stjtjtjtjtjtj i}tt||dd}|dur,|Stt|t |t tSr) r7rSr)r.rrrrrrrrrrr_to_torch_resample_interp_modercCrr) r7rSr*r(ZEROSCONSTANTBORDERr REFLECTIONREFLECTrrrrrrr_to_numpy_resample_padding_moderrcCstt|tdd}|dur|Stjtjtjtjtjtjtj tj tj tj tj tj tj tj i}tt||dd}|dur<|Stt|t|ttSr)r7rSr(r*rr GRID_CONSTANTrrrrWRAP GRID_WRAP GRID_MIRRORrrrrr_to_torch_resample_padding_modes rconstantrrcKsdd|pi}}}|dur!tt|tdddurtjntj}|tjkr4t|}t|}||||fSt |}t |}t| dr\| dd}|dkrQt j}n |dkrYt j}nt j}| dd sh||||fS|d krndn|}|d krwd}nt| drd}nt|}||||fS) a Automatically adjust the resampling interpolation mode and padding mode, so that they are compatible with the corresponding API of the `backend`. Depending on the availability of the backends, when there's no exact equivalent, a similar mode is returned. Args: interp_mode: interpolation mode. padding_mode: padding mode. backend: optional backend of `TransformBackends`. If None, the backend will be decided from `interp_mode`. kwargs: additional keyword arguments. currently support ``torch_interpolate_spatial_nd``, to provide additional information to determine ``linear``, ``bilinear`` and ``trilinear``; ``use_compiled`` to use MONAI's precompiled backend (pytorch c++ extensions), default to ``False``. NrlinearZtorch_interpolate_spatial_ndrrrhZ use_compiledF reflectionbicubic)copyr7rSr.r<r5r7rrrrendswithpopr)rrrr')r padding_moder9rZ _interp_modeZ _padding_mode_kwargsndrrrrxs8      rxNo message providedentry list | dict status_keydefault_messagecCst|trt}|D] }|t|||q |St|}tj|vr@||tjvr@|tj|}|dur6|gSt|tr=|S|gSgS)a Check the operations of a MetaTensor to determine whether there are any statuses Args: entry: a dictionary that may contain TraceKey.STATUS entries, or a list of such dictionaries status_key: the status key to search for. This must be an entry in `TraceStatusKeys`_ default_message: The message to provide if no messages are provided for the given status key entry Returns: A list of status messages matching the providing status key N)rrextendcheck_applied_operationsr0r/STATUSES)rrrresultsZ sub_entryZ status_key_reasonrrrr/ s  rcCst}t|ttfr!|D]}t|||\}}|dur||q n4t|tjjr8|jD] }|t |||q+nt|t rU| D]}t|||\}}|durT||qAt |dkr_d|fSdS)a\ Checks whether a given tensor is has a particular status key message on any of its applied operations. If it doesn't, it returns the tuple `(False, None)`. If it does it returns a tuple of True and a list of status messages for that status key. Status keys are defined in :class:`TraceStatusKeys`. This function also accepts: * dictionaries of tensors * lists or tuples of tensors * list or tuples of dictionaries of tensors In any of the above scenarios, it iterates through the collections and executes itself recursively until it is operating on tensors. Args: data: a `torch.Tensor` or `MetaTensor` or collections of torch.Tensor or MetaTensor, as described above status_key: the status key to look for, from `TraceStatusKeys` default_message: a default message to use if the status key entry doesn't have a message set Returns: A tuple. The first entry is `False` or `True`. The second entry is the status messages that can be used for the user to help debug their pipelines. NrF)TN) rrrryrrrrrArr;valuesr)rrrZstatus_key_occurrencesrBrreasonsoprrrryK s*      ry) block_paramsfloat64_distancessamplingNone | float | list[float]return_distancesreturn_indices distancesrtuple[int, int, int] | Noner@None | NdarrayOrTensor | tuple[NdarrayOrTensor, NdarrayOrTensor]c CsJtddd\}} to| ot|tjo|jjdk} |s |s td|jdkr*|jdks.td||} } d \}}| rd \} }|rr|rDtj ntj }|d urUtj |tj |d }nt|tjse|j|jkret d |j|ksnt d t|} |rtj}|d urtj|f|j|d}nt|tjs|j|jkrt d|j|kst dt|}t|}t|jdD] }||||||| d ur| |nd |d ur||nd ||dqtjntstdt|}|r|d urtj |tj d}nt|tjst d|jtj kst d|r3|d urtj|jf|jtjd}nt|tjs(t d|jtjks3t dt|jdD]"}tj||||||d urM||nd |d urW||nd dq:g}|rq| d urq|| rn| n||r~| d ur~|||sd St|tjr|jnd }tt|dkr|dn|t||ddS)a Euclidean distance transform, either GPU based with CuPy / cuCIM or CPU based with scipy. To use the GPU implementation, make sure cuCIM is available and that the data is a `torch.tensor` on a GPU device. Note that the results of the libraries can differ, so stick to one if possible. For details, check out the `SciPy`_ and `cuCIM`_ documentation. .. _SciPy: https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.distance_transform_edt.html .. _cuCIM: https://docs.rapids.ai/api/cucim/nightly/api/#cucim.core.operations.morphology.distance_transform_edt Args: img: Input image on which the distance transform shall be run. Has to be a channel first array, must have shape: (num_channels, H, W [,D]). Can be of any type but will be converted into binary: 1 wherever image equates to True, 0 elsewhere. Input gets passed channel-wise to the distance-transform, thus results from this function will differ from directly calling ``distance_transform_edt()`` in CuPy or SciPy. sampling: Spacing of elements along each dimension. If a sequence, must be of length equal to the input rank -1; if a single number, this is used for all axes. If not specified, a grid spacing of unity is implied. return_distances: Whether to calculate the distance transform. return_indices: Whether to calculate the feature transform. distances: An output array to store the calculated distance transform, instead of returning it. `return_distances` must be True. indices: An output array to store the calculated feature transform, instead of returning it. `return_indicies` must be True. block_params: This parameter is specific to cuCIM and does not exist in SciPy. For details, look into `cuCIM`_. float64_distances: This parameter is specific to cuCIM and does not exist in SciPy. If True, use double precision in the distance computation (to match SciPy behavior). Otherwise, single precision will be used for efficiency. Returns: distances: The calculated distance transform. Returned only when `return_distances` is True and `distances` is not supplied. It will have the same shape and type as image. For cuCIM: Will have dtype torch.float64 if float64_distances is True, otherwise it will have dtype torch.float32. For SciPy: Will have dtype np.float64. indices: The calculated feature transform. It has an image-shaped array for each dimension of the image. The type will be equal to the type of the image. Returned only when `return_indices` is True and `indices` is not supplied. dtype np.float64. z cucim.core.operations.morphologyrzrDrz0Neither return_distances nor return_indices Truerhrlz9Wrong input dimensionality. Use (num_channels, H, W [,D])NNN) memory_formatrz:distances must be a torch.Tensor on the same device as imgzrrrrrr synchronize has_ndimager@rrCrrzrr=r)rrrrrrrrrzrrZdistances_originalZindices_originalZ distances_indices_rrZ channel_idxr_valsrrrrrzz s0          ,rzrsDtypeLike | torch.dtype | Nonec Cst|dtjd}t|jd|}t|t|jd|jddffdd}t||j}|ddddddf}t |||d ^}}|S) a apply affine transformation to a set of points. Args: data: input data to apply affine transformation, should be a tensor of shape (C, N, 2 or 3), where C represents the number of channels and N denotes the number of points. affine: affine matrix to be applied, should be a tensor of shape (3, 3) or (4, 4). dtype: output data dtype. F) track_metarrrrrrNr) rArr rrronesmatmulTr?) rrsrdata_r1Ztransformed_homogeneousZtransformed_coordinatesrrrrrapply_affine_to_points s (r__main__) r}rr~rrrrrrrrr)r)rrrr)rr) rrrrrrrrrrrr)rrrr)rrrrrr) r}rrrrrrrrr) r}rrrrrrrrr)r}rrrrr)rrrrrrrr)rrrrrrrrrb)rrrErrrrr) NNNrNNNFT)rrrrrrrrrrrrrrrrrrrrrrrrrr)Nr)rrrrrrrr)NNrN) rrrrrrrrrrrr)rN) rrrrrrrrrrra) rrrrrrrrrr)rrrrr#rrrrrrrrrrrrr)NNFT)rrrrrrrr*rrrrrrrrrr) rrr/r0r1rrrrr2rr)rrr/r0r1rrr)rrr/r0r1rrr2) rKrr/rLr1rrrrr2) rPrrQrRrr2r9rSrr) rPrrQrRrTrrUrrVrrr)rPrrurRrr2rr)rPrrurRrr)rPrr}rRrr~rr)rPrr}rRrr)rPrrrRrr2rr)rPrrrRrr) rrrrrrrrrrrrr)rrrrrrrr)rrorh)rrrrrrrrrrrrrrrr)rrrrrrrr)rF) rrrrrrrrrr)rrrF) rrrrrrrrrr~rr)rrTFN)rrrrrrrrrrrrrrr)rrrrrrrrr )rrrrrrrr)Nrr) rrrrrrrrrr)rrr|) rrrrrrr rr!rrr)NT)r%rr&r'r(rrr)r)r*)r0N)r1rSr2r3)rKrrr)NrGrrH) rrr rIrJrrrrrrr)r)rrhr rirjrr)rrr1r)rrrr)T)rr)r)rr)rr)rr)rr)r)rrrrSrrS)rrrr rrS)NTFNN)rrrrrrrrrrrrrrrrrr )rrrsrrr) __future__rrrrcollections.abcrrrrr contextlibr functoolsr r inspectr r typingr rrrrr monai.configrrmonai.config.type_definitionsrrmonai.data.utilsrZmonai.networks.layersrZmonai.networks.utilsrrprmonai.transforms.transformrrrZ(monai.transforms.utils_morphological_opsr0monai.transforms.utils_pytorch_numpy_unificationrrrrrr r!r"r#r$r%r& monai.utilsr'r(r)r*r+r,r-r.r/r0r1r2r3r4r5r6r7r8r9r:r;monai.utils.enumsr<Zmonai.utils.type_conversionr=r>r?r@rArrrrrrrr cp_ndarrayrrLrK__all__rZr{rfr^r_r`rarlrgrir rhrJrjrKrbrcrdrkr"rVrUrr5rMr6r8rLrNrYr_rcrgrPrwrOrrrQrrrWrYrZr[r\rr]rsrSrXrRrerFrr<rIrwrHrmrTrnrorprqrrrtrurvrGrrrrrrrr7rxrryrzrrcrrrrs         8\     <#      8A&D53?A")2& B6 H,'HJ<=/#. $$< % 2)%      21