U Ph~&@s ddlmZddlZddlZddlZddlZddlZddlZddlZddl m Z m Z ddl m Z mZmZmZmZddlmZddlmZddlmZmZmZddlmZdd lmZddlZddl Z dd l!m"Z"dd l#m$Z$dd l%m&Z&m'Z'm(Z(dd l)m*Z*ddl+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8m9Z9m:Z:m;Z;mZ>e;d\Z?Z@e;ddd\ZAZ@e;d\ZBZ@ddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6d7d8d9d:d;g&ZCdd>d?d@dAdBd ZFdd>dFd>dGdHdIdJdKd%ZGdd>d>d>dHdLdMdNdZHdd>dPd>dQdHdRdSd$ZIddCdDdEe/jJfdTdFd>dGdHdUdVdWdXdYd#ZKd>dPdZd[d\d!ZLdd^d_d`dad]ZMe0jNZOeOdEfdHdbdcddZPddedfdgZQdhdiZRdjdkdld'ZSdmdHdHdndodpZTddHdqdrdZUe.jVe/jWfdjd_d_dsdtd*ZXdud(ZYd^dvdwdxd5ZZd^d^dydzd2Z[d{e\dEfd|d^dHd|d}d~dZ]ddZ^dd.Z_ddddHddd6Z`dddTdTdHddddZaejbfdd|d|ddd4Zcd>dTdTdddd/Zddd_ddddHdHd_dddZee-jWdde jffdZddGddddddZgdddHddd"ZhddjdddHd^dHdHddd+Ziddjd>dddHd^dHdHddd,ZjddjddHd^ddd0ZkddFdddd1Zldddd&Zmejnfdddd-Zoddd3ZpdddddddddZqd|d|ddd)ZrdVddvddd7ZsdVdvddd8Ztdddd9ZudHddd;ZvdS)) annotationsN)abc defaultdict) GeneratorIterableMappingSequenceSizeddeepcopy)reduce)productstarmap zip_longest)PurePath)Any)default_collate)config)NdarrayOrTensor NdarrayTensorPathLike)MetaObj)MAX_SEED BlendModeMethod NumpyPadMode TraceKeysconvert_data_typeconvert_to_dst_type ensure_tupleensure_tuple_repensure_tuple_sizefall_back_tuplefirstget_equivalent_dtypeissequenceiterablelook_up_optionoptional_import pytorch_after )collate_tensor_fndefault_collate_fn_mappandas DataFrame)namenibabel AFFINE_TOLSUPPORTED_PICKLE_MODaffine_to_spacingcompute_importance_mapcompute_shape_offsetconvert_tables_to_dicts!correct_nifti_header_if_necessarycreate_file_basenamedecollate_batchdense_patch_slicesget_random_patchget_valid_patch_sizeis_supported_format iter_patchiter_patch_positioniter_patch_slices json_hashinglist_data_collate no_collationorientation_ras_lpspad_list_data_collatepartition_datasetpartition_dataset_classespickle_hashingrectify_header_sform_qformreorient_spatial_axesresample_datalistselect_cross_validation_foldsset_rnd sorted_dict to_affine_ndworker_init_fn zoom_affine remove_keysremove_extra_metadataget_extra_metadata_keysPICKLE_KEY_SUFFIX is_no_channelpickleMbP?z Sequence[int]znp.random.RandomState | Noneztuple[slice, ...])dims patch_size rand_statereturncsJ|dkrtjjn|jtfddt||D}tddt||DS)a, Returns a tuple of slices to define a random patch in an array of shape `dims` with size `patch_size` or the as close to it as possible within the given dimension. It is expected that `patch_size` is a valid patch for a source of shape `dims` as returned by `get_valid_patch_size`. Args: dims: shape of source array patch_size: shape of patch size to generate rand_state: a random state object to generate random numbers from Returns: (tuple of slice): a tuple of slice objects defining the patch Nc3s0|](\}}||kr$d||dndVqdS)rr)N.0mspsZrand_intr]E/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/data/utils.py sz#get_random_patch..css |]\}}t|||VqdSNslice)r_mcrar]r]rcrds)nprandomrandinttuplezip)rYrZr[ min_cornerr]rbrcr;psr]TzSequence[int] | intzSequence[float] | floatboolz(Generator[tuple[slice, ...], None, None]) image_sizerZ start_posoverlappaddedr\ccs@t||}t|||||dD]}tddt||DVqdS)a Yield successive tuples of slices defining patches of size `patch_size` from an array of dimensions `image_size`. The iteration starts from position `start_pos` in the array, or starting at the origin if this isn't provided. Each patch is chosen in a contiguous grid using a rwo-major ordering. Args: image_size: dimensions of array to iterate over patch_size: size of patches to generate slices for, 0 or None selects whole dimension start_pos: starting position in the array, default is 0 for each dimension overlap: the amount of overlap of neighboring patches in each dimension (a value between 0.0 and 1.0). If only one float number is given, it will be applied to all dimensions. Defaults to 0.0. padded: if the image is padded so the patches can go beyond the borders. Defaults to False. Yields: Tuples of slice objects defining each patch rqrZrrrsrtcss |]\}}t|||VqdSrerfr_spr]r]rcrdsz$iter_patch_slices..N)r<r?rlrm)rqrZrrrsrt patch_size_positionr]r]rcr@s  zlist[tuple[slice, ...]])rqrZ scan_interval return_slicer\csPt}tt|g}t|D]tdkrD|dq(ttt}t fddt|D}||dk r|dndq(g}t|D]X} g} t|| D]8} | | } | t | | | d8} | | q|| qt ddt j |dd iDj} |r>fd d| DSfd d| DS) a Enumerate all slices defining ND patches of size `patch_size` from an `image_size` input image. Args: image_size: dimensions of image to iterate over patch_size: size of patches to generate slices scan_interval: dense patch sampling interval return_slice: whether to return a list of slices (or tuples of indices), defaults to True Returns: a list of slice objects defining each patch rr)c3s.|]&}|kr|VqdSrer]r_dirqrZr{r]rcrdsz%dense_patch_slices..NcSsg|] }|qSr])flattenr_xr]r]rc sz&dense_patch_slices..indexingijcs&g|]}tfddt|DqS)c3s$|]\}}t|||VqdSrerfr_r~rwrZr]rcrds0dense_patch_slices...rl enumeraterrr]rcrscs&g|]}tfddt|DqS)c3s"|]\}}|||fVqdSrer]rrr]rcrdsrrrrr]rcrs)lenr<r!rangeappendintmathceilfloatr#maxriasarraymeshgridT)rqrZr{r|num_spatial_dimsZscan_numnumZscan_dimstartsdimZ dim_startsidx start_idxoutr]rrcr:s,          "Fz Sequence[int] | int | np.ndarrayz-Sequence[float] | float | Sequence[int] | intruc Cst|}t||}t||}t||}t|dtrNtddt||D}ntddt||D}|rn|ntddt||D}tt t|||} t | S)a_ Yield successive tuples of upper left corner of patches of size `patch_size` from an array of dimensions `image_size`. The iteration starts from position `start_pos` in the array, or starting at the origin if this isn't provided. Each patch is chosen in a contiguous grid using a rwo-major ordering. Args: image_size: dimensions of array to iterate over patch_size: size of patches to generate slices for, 0 or None selects whole dimension start_pos: starting position in the array, default is 0 for each dimension overlap: the amount of overlap of neighboring patches in each dimension. Either a float or list of floats between 0.0 and 1.0 to define relative overlap to patch size, or an int or list of ints to define number of pixels for overlap. If only one float/int number is given, it will be applied to all dimensions. Defaults to 0.0. padded: if the image is padded so the patches can go beyond the borders. Defaults to False. Yields: Tuples of positions defining the upper left corner of each patch rcss"|]\}}t|d|VqdS)?Nroundr_rxor]r]rcrdsz&iter_patch_position..css|]\}}||VqdSrer]rr]r]rcrdscss"|]\}}|t|dVqdS)r)Nrrvr]r]rcrds) rr<r!r isinstancerrlrmrrr ) rqrZrrrsrtndimrystepsend_posrangesr]r]rcr?s    rz str | Nonedictz9Generator[tuple[NdarrayOrTensor, np.ndarray], None, None])arrrZrrrs copy_backmodepad_optsr\c+snddlm}t|j|}t||j}t|ddt||jD} tfddt|| D} ddtt ||j| D} r||fdd| D|d |} td dt|| D} td dt|j| D}n|} |} |j}t ||| | d D]J}rtd dt|| D}ntdd|D}| |t |fVq|rjtddt| |jD}| ||d<dS)a Yield successive patches from `arr` of size `patch_size`. The iteration can start from position `start_pos` in `arr` but drawing from a padded array extended by the `patch_size` in each dimension (so these coordinates can be negative to start in the padded region). If `copy_back` is True the values from each patch are written back to `arr`. Args: arr: array to iterate over patch_size: size of patches to generate slices for, 0 or None selects whole dimension. For 0 or None, padding and overlap ratio of the corresponding dimension will be 0. start_pos: starting position in the array, default is 0 for each dimension overlap: the amount of overlap of neighboring patches in each dimension (a value between 0.0 and 1.0). If only one float number is given, it will be applied to all dimensions. Defaults to 0.0. copy_back: if True data from the yielded patches is copied back to `arr` once the generator completes mode: available modes: (Numpy) {``"constant"``, ``"edge"``, ``"linear_ramp"``, ``"maximum"``, ``"mean"``, ``"median"``, ``"minimum"``, ``"reflect"``, ``"symmetric"``, ``"wrap"``, ``"empty"``} (PyTorch) {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``}. One of the listed string values or a user supplied function. If None, no wrapping is performed. Defaults to ``"wrap"``. See also: https://numpy.org/doc/stable/reference/generated/numpy.pad.html https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html requires pytorch >= 1.10 for best compatibility. pad_opts: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. Yields: Patches of array data from `arr` which are views into a padded array which can be modified, if `copy_back` is True these changes will be reflected in `arr` once the iteration completes. Note: coordinate format is: [1st_dim_start, 1st_dim_end, 2nd_dim_start, 2nd_dim_end, ..., Nth_dim_start, Nth_dim_end]] r)pad_ndcSsg|] }t|qSr])rpr_rxr]r]rcr=sziter_patch..c3s"|]\}}|rr|ndVqdSrNr])r_rxvrtr]rcrd>sziter_patch..cSsg|]\}}|r|ndqS)ror])r_oprr]r]rcr?scSsg|] }||fqSr]r]rr]r]rcrBs)Zto_padrcss|]\}}||VqdSrer]rvr]r]rcrdDscss|]\}}||VqdSrer]rvr]r]rcrdHsrcss&|]\}}|j||j|fVqdSrestartstop)r_coordrxr]r]rcrdQscss|]}|j|jfVqdSrer)r_rr]r]rcrdSscss |]\}}t|||VqdSrerf)r_rxrwr]r]rcrdXs.N) Z#monai.transforms.croppad.functionalrr<shaper!rrprlrmr r@rir)rrZrrrsrrrrryZis_vZ _pad_sizeZ_overlapZarrpadZstart_pos_paddedZ iter_sizeslicesZ coords_no_padr]rrcr>s,/    ztuple[int, ...])rqrZr\cCs*t|}t||}tddt||DS)a Given an image of dimensions `image_size`, return a patch size tuple taking the dimension from `patch_size` if this is not 0/None. Otherwise, or if `patch_size` is shorter than `image_size`, the dimension from `image_size` is taken. This ensures the returned patch size is within the bounds of `image_size`. If `patch_size` is a single number this is interpreted as a patch of the same dimensionality of `image_size` with that size in each dimension. css |]\}}t||p|VqdSreminr^r]r]rcrdgsz'get_valid_patch_size..)rr!rlrm)rqrZrryr]r]rcr<\s  dev_collaterstrlevel logger_namec s*|d}t|}d}|ddt|dkr4dnd}t|tjr(z$t|dt|dWSt k r}zN z ... z collate/stack a list of tensorsz E: z, type cSsg|]}t|jqSr]type__name__r_elemr]r]rcrszdev_collate..z in collate()z, shape cSsg|] }|jqSr])rrr]r]rcrsnumpystr_string_)ndarraymemmapz% collate/stack a list of numpy arrayscSsg|]}t|qSr])torch as_tensorr_br]r]rcrsrr]z collate dict key "z " out of z keyscsg|] }|qSr]r]r}keyr]rcrsr)cSsg|] }t|qSr])rrr]r]rcrscSsg|]}t|jqSr]rrr]r]rcrsz E: type z collate list of sizes: .c3s|]}|dkVqdSrr]r_rw)sizesr]rcrdszdev_collate..z, collate list inconsistent sizes, got size: z , in collate(csg|]}t|ddqS)r)r)r)r_samplesrr]rcrsz E: unsupported type in collate )rrrrTensorlogging getLoggercriticalstack TypeError RuntimeError __module__rrrrrrbytesrrriterlistanyrm) batchrrr elem_typeZl_strZ batch_streritZelstypes transposedr])rrrrrcrjsd $ $ $$  &("  is_encodecst|trt|}|D]Z}|rrLt||tsLt||d||<st||trt||||<qfdd|DSt|t t frfdd|DS|S)a Applied_operations are dictionaries with varying sizes, this method converts them to bytes so that we can (de-)collate. Args: data: a list or dictionary with substructures to be pickled/unpickled. key: the key suffix for the target substructures, defaults to "_transforms" (`data.utils.PICKLE_KEY_SUFFIX`). is_encode: whether it's encoding using pickle.dumps (True) or decoding using pickle.loads (False). rcs i|]\}}|t|dqS)rrpickle_operationsr_krrrr]rc sz%pickle_operations..csg|]}t|dqSrrr_itemrr]rcrsz%pickle_operations..) rrrendswithrrWdumpsloadsitemsrrl)datarrrr]rrcrs  r)collate_fn_mapcsvtddrtnt}||}dd|D}tjdd|DrRfdd|D}t||_dd|D|_d|_|S) z Collate a sequence of meta tensor into a single batched metatensor. This is called by `collage_meta_tensor` and so should not be used as a collate function directly in dataloaders. r)r*cSsg|]}|jptjqSr])metarNONEr_rr]r]rcrsz*collate_meta_tensor_fn..cSs"g|]}t|trt|qSr])rrsetkeysr}r]r]rcrs cs.g|]&ttr$fddDntjqS)csi|]}||qSr]r])r_rr~r]rcrsz5collate_meta_tensor_fn...)rrrrr_Zcommon_rrcrscSsg|]}|jptjqSr])applied_operationsrrrr]r]rcrsT)r(r+rr intersectionrris_batch)rr collate_fnZcollatedZ meta_dictsr]rrccollate_meta_tensor_fns rcsvttstt}t|tr*tSt|trFfdd|DSt|ttfrnfddt t |DSt S)zcollate a sequence of meta tensor sequences/dictionaries into a single batched metatensor or a dictionary of batched metatensorcs$i|]tfddDqS)csg|] }|qSr]r]r}rr]rcrsz2collate_meta_tensor...collate_meta_tensorrrrrcrsz'collate_meta_tensor..cs"g|]tfddDqS)csg|] }|qSr]r]r}rr]rcrsz2collate_meta_tensor...r rr r rcrsz'collate_meta_tensor..) rrNotImplementedErrorr#rrrrlrrrr)rZelem_0r]r rcr s   r rr c stddr$ddlm}t|ti|d}t|trDdd|Dn|}dtddrZtnt }zXt j rnt |}t|t ri}|D]&}|fdd|D}|||<qn||}|WStk r}zFt|} d | krdk r| d d 7} | d 7} t|} t| |W5d}~XYnttk r}zTt|} d | krld| krldk rd| d d 7} | d7} t|} t| |W5d}~XYnXdS)aI Enhancement for PyTorch DataLoader default collate. If dataset already returns a list of batch data that generated in transforms, need to merge all data to 1 list. Then it's same as the default collate behavior. Note: Need to use this collate if apply some transforms that can generate batch data. r)r*r) MetaTensorcSsg|]}|D]}|q qSr]r])r_rrr]r]rcrsz%list_data_collate..Ncsg|] }|qSr]r]r}rr]rcrsz equal sizez Collate error on the key 'z' of dictionary data.z MONAI hint: if your transforms intentionally create images of different shapes, creating your `DataLoader` with `collate_fn=pad_list_data_collate` might solve this problem (check its documentation).rrz MONAI hint: if your transforms intentionally create mixtures of torch Tensor and numpy ndarray, creating your `DataLoader` with `collate_fn=pad_list_data_collate` might solve this problem (check its documentation).)r(Zmonai.data.meta_tensorrr,updaterrrrr r USE_META_DICTrrrrrr) rrrrrretrZdata_for_batchreZre_str_r]rrcrBsL    zMapping | Iterable) batch_datadetachpadc sttr$fddD}n.csg|]}t|dqSrrr)rrrr]rcr+sz&_non_zipping_check..Unable to de-collate: , type: rr)rrrr rrrrrrrrrr rr) rrrrZ_deco batch_size non_iterablerrr]rrc_non_zipping_check s   ".  r)rc s$|dkr |St|ttttfs6t|jdkr:t|ts:|St|tj r|rT| }|j dkrn|rj| S|Stj |dd}t|trt|t|jD]\}}t|tr||_d|_qt||jD]\}}t|tr||_d|_q|dj dkr|rdd|DSt|St||||\}}|dkr0S|r^|D]"fddt|D<q:ttr|rtd |in t} fd d| D} tjs| St| dd Sttr|rtd |int} d d| D} tjs| St| dd Std |dt|ddS)aS De-collate a batch of data (for example, as produced by a `DataLoader`). Returns a list of structures with the original tensor's 0-th dimension sliced into elements using `torch.unbind`. Images originally stored as (B,C,H,W,[D]) will be returned as (C,H,W,[D]). Other information, such as metadata, may have been stored in a list (or a list inside nested dictionaries). In this case we return the element of the list corresponding to the batch idx. Return types aren't guaranteed to be the same as the original, since numpy arrays will have been converted to torch.Tensor, sequences may be converted to lists of tensors, mappings may be converted into dictionaries. For example: .. code-block:: python batch_data = { "image": torch.rand((2,1,10,10)), DictPostFix.meta("image"): {"scl_slope": torch.Tensor([0.0, 0.0])} } out = decollate_batch(batch_data) print(len(out)) >>> 2 print(out[0]) >>> {'image': tensor([[[4.3549e-01...43e-01]]]), DictPostFix.meta("image"): {'scl_slope': 0.0}} batch_data = [torch.rand((2,1,10,10)), torch.rand((2,3,5,5))] out = decollate_batch(batch_data) print(out[0]) >>> [tensor([[[4.3549e-01...43e-01]]], tensor([[[5.3435e-01...45e-01]]])] batch_data = torch.rand((2,1,10,10)) out = decollate_batch(batch_data) print(out[0]) >>> tensor([[[4.3549e-01...43e-01]]]) batch_data = { "image": [1, 2, 3], "meta": [4, 5], # undetermined batch size } out = decollate_batch(batch_data, pad=True, fill_value=0) print(out) >>> [{'image': 1, 'meta': 4}, {'image': 2, 'meta': 5}, {'image': 3, 'meta': 0}] out = decollate_batch(batch_data, pad=False) print(out) >>> [{'image': 1, 'meta': 4}, {'image': 2, 'meta': 5}] Args: batch: data to be de-collated. detach: whether to detach the tensors. Scalars tensors will be detached into number types instead of torch tensors. pad: when the items in a batch indicate different batch size, whether to pad all the sequences to the longest. If False, the batch size will be the length of the shortest sequence. fill_value: when `pad` is True, the `fillvalue` to use when padding, defaults to `None`. NrrrFcSsg|] }|qSr])r)r_tr]r]rcrsz#decollate_batch..csg|]}tqSr]r )r_rdecorr]rcrs fillvaluecsg|]}tt|qSr])rrmr)r#r]rcrsrcSsg|] }t|qSr])rrr]r]rcrsrrr)rrrrrrrrrrrrrunbindrrmr9rrrrrrrrvaluesrrrr ) rrrrZout_listr!mrr_genrZret_listr]r"rcr9:sZ8        $   )rmethodrcKs$ddlm}|f||d||S)aS Function version of :py:class:`monai.transforms.croppad.batch.PadListDataCollate`. Same as MONAI's ``list_data_collate``, except any tensors are centrally padded to match the shape of the biggest tensor in each dimension. This transform is useful if some of the applied transforms generate batch data of different sizes. This can be used on both list and dictionary data. Note that in the case of the dictionary data, this decollate function may add the transform information of `PadListDataCollate` to the list of invertible transforms if input batch have different spatial shape, so need to call static method: `monai.transforms.croppad.batch.PadListDataCollate.inverse` before inverting other transforms. Args: batch: batch of data to pad-collate method: padding method (see :py:class:`monai.transforms.SpatialPad`) mode: padding mode (see :py:class:`monai.transforms.SpatialPad`) kwargs: other arguments for the `np.pad` or `torch.pad` function. note that `np.pad` treats channel dimension as the first dimension. r)PadListDataCollate)r)r)Zmonai.transforms.croppad.batchr*)rr)rkwargsr*r]r]rcrEs cCs|S)z% No any collation operation. r])rr]r]rcrCsNone) worker_idr\cCs tjj}t|j|jddS)z Callback function for PyTorch DataLoader `worker_init_fn`. It can set different random seed for the transforms in different workers. seedN)rutilsrget_worker_inforMdatasetr/)r- worker_infor]r]rcrPs )r/r\cCst|ttfr<|}|D]}t||d}q||kr4|S|dSt|dsJ|St|drl|j|td|dS|jD]"}|drqrt|j||d}qr|S)z Set seed or random state for all randomizable properties of obj. Args: obj: object to set seed or random state for. seed: set the random state with an integer seed. r.r)__dict__set_random_state__) rrlrrMhasattrr5rr4 startswith)objr/_seedrrr]r]rcrMs    r)affinersuppress_zerosr\cCst|jdks"|jd|jdkr4td|jdt|d|d|f||d^}}t|tjr|ttj||dd}nt t j||dd }|rd ||dk<t|||d^}}|S) ap Computing the current spacing from the affine matrix. Args: affine: a d x d affine matrix. r: indexing based on the spatial rank, spacing is computed from `affine[:r, :r]`. dtype: data type of the output. suppress_zeros: whether to suppress the zeros with ones. Returns: an `r` dimensional vector of spacing. rr)z$affine must be a square matrix, got rN)dstdtyper axisr) rr ValueErrorrrrrsqrtsumri)r<r=rAr>_affinerspacingZspacing_r]r]rcr3s ""  cCsz|jddkr|S|jdd}|dkr.|St|jd|}t|j|d}t||rd|St|drvt |S|S)z Check nifti object header's format, update the header if needed. In the updated image pixdim matches the affine. Args: img_nii: nifti image object rNrr= get_sform) headergetrir get_zoomsr3r<allcloser7rI)img_niirpixdimZ norm_affiner]r]rcr7s  c Cs|jdd}t|jd|}||}}t||d}t||d}t|| }t|| }|jddkr|s|S|s|||S|jddkr|s|S|s| ||St|j |d} |j | |S)a Look at the sform and qform of the nifti object and correct it if any incompatibilities with pixel dimensions Adapted from https://github.com/NifTK/NiftyNet/blob/v0.6.0/niftynet/io/misc_io.py Args: img_nii: nifti image object rrNrJZ sform_codeZ qform_code) rLrirrNrKZ get_qformr3rOZ set_sformZ set_qformr<Z set_zooms) rPr~rQZsformqformZ norm_sformZ norm_qformZsform_mismatchZqform_mismatchnormr]r]rcrIs,    z np.ndarrayznp.ndarray | Sequence[float])r<scalediagonalc CsTtj|tdd}t|t|dkrFtdt|dt|ddtj|tdd}t|d}t||d}t||krt||t|d }|d |}tt||}d ||dk<|rt t|d gS|d d d d f}tj |j |j }|tj |}tt |t|} tt|} |t | | d d d d f<| S) a# To make column norm of `affine` the same as `scale`. If diagonal is False, returns an affine that combines orthogonal rotation and the new scale. This is done by first decomposing `affine`, then setting the zoom factors to `scale`, and composing a new affine; the shearing factors are removed. If diagonal is True, returns a diagonal matrix, the scaling factors are set to the diagonal elements. This function always return an affine with zero translations. Args: affine (nxn matrix): a square matrix. scale: new scaling factor along each dimension. if the components of the `scale` are non-positive values, will use the corresponding components of the original pixdim, which is computed from the `affine`. diagonal: whether to return a diagonal scaling matrix. Defaults to True. Raises: ValueError: When ``affine`` is not a square matrix. ValueError: When ``scale`` contains a nonpositive scalar. Returns: the updated `n x n` affine. TrAcopyrzaffine must be n x n, got z x rr)rJNr)riarrayrrrDr3rrr"diaglinalgcholeskyrinvsignabseye) r<rTrUZscale_npr~rSZrzszsrotationrw new_affiner]r]rcrQ;s("     znp.ndarray | Sequence[int]ztuple[np.ndarray, np.ndarray]) spatial_shape in_affine out_affine scale_extentr\c sPtj|dtd}t|}tt||tjd}tt||tjd}fdd|D}ttj|ddi t|df} t | t | d d f} ztj ||| } Wn8tj jk r} ztd |d | W5d } ~ XYnX|| } | d d} | d d| d} r*t| jd d nt| jd d d} d }t| jd D]R}t| | d d ||d fd }tj|dtdrR| d d|f}qqR|d kr|d dd df|d|d ddf|d dd df| d}r>td|| dd}t|||dd dt|}| jtdd|fS)a Given input and output affine, compute appropriate shapes in the output space based on the input array's shape. This function also returns the offset to put the shape in a good position with respect to the world coordinate system. Args: spatial_shape: input array's shape in_affine (matrix): 2D affine matrix out_affine (matrix): 2D affine matrix scale_extent: whether the scale is computed based on the spacing or the full extent of voxels, for example, for a factor of 0.5 scaling: option 1, "o" represents a voxel, scaling the distance between voxels:: o--o--o o-----o option 2, each voxel has a physical extent, scaling the full voxel extent:: | voxel 1 | voxel 2 | voxel 3 | voxel 4 | | voxel 1 | voxel 2 | Option 1 may reduce the number of locations that requiring interpolation. Option 2 is more resolution agnostic, that is, resampling coordinates depend on the scaling factor, not on the number of voxels. Default is False, using option 1 to compute the shape and offset. T)rWrArcs(g|] }rd|dfn d|dfqS)g?rorr])r_rrgr]rcrsz(compute_shape_offset..rrrXNr)zAffine z is not invertiblerBrro)rtol@rhF)rW)rirYrrrrOrrrreshape concatenate ones_liker[solve LinAlgErrorrDrWrptprrrrOr1rr_r^astyper)rdrerfrgrsrZ in_affine_Z out_affine_Z in_coordscornersZ corners_outrZall_dist out_shapeoffsetrrnZ in_offsetr]rircr5os6"$$.$  H(znp.ndarray | int)r=r<r\c Cs$t|tj}t|tj|ddd}|}|jdkrFtd|jdtj||dd}|jdkrt| tj }t |r|dkrtd|dtj |d |d }t tt|d t|d d }|d |d |f|d |d |f<|d kr|d |d f|d |d f<t|||d ^}}|S) aP Using elements from affine, to create a new affine matrix by assigning the rotation/zoom/scaling matrix and the translation vector. When ``r`` is an integer, output is an (r+1)x(r+1) matrix, where the top left kxk elements are copied from ``affine``, the last column of the output affine is copied from ``affine``'s last column. `k` is determined by `min(r, len(affine) - 1)`. When ``r`` is an affine matrix, the output has the same shape as ``r``, and the top left kxk elements are copied from ``affine``, the last column of the output affine is copied from ``affine``'s last column. `k` is determined by `min(len(r) - 1, len(affine) - 1)`. Args: r (int or matrix): number of spatial dimensions or an output affine to be filled. affine (matrix): 2D affine matrix dtype: data type of the output array. Raises: ValueError: When ``affine`` dimensions is not 2. ValueError: When ``r`` is nonpositive. Returns: an (r+1) x (r+1) matrix (tensor or ndarray depends on the input ``affine`` data type) T) output_typerA wrap_sequencerr?z#affine must have 2 dimensions, got rrVzr must be positive, got r))rANrX)r$rirrrWrrDrYrrruintisfiniter`rrrr) r=r<rAZ affine_nprcrsr~outputrr]r]rcrOs"    $ z"tuple[np.ndarray, NdarrayOrTensor]) data_shape init_affine target_affiner\c Cst|tj^}}t|tj^}}tj|}tj|}ztj||}Wn:tk r} ztd|d|d| W5d} ~ XYnX|tj||} t | |^} }|| fS)ac Given the input ``init_affine``, compute the orientation transform between it and ``target_affine`` by rearranging/flipping the axes. Returns the orientation transform and the updated affine (tensor or ndarray depends on the input ``affine`` data type). Note that this function requires external module ``nibabel.orientations``. zThe input affine z and target affine z are not compatible.N) rrirnibZ orientationsZio_orientationornt_transformrDZ inv_ornt_affr) r|r}r~Z init_affine_rZtarget_affine_Z start_orntZ target_orntrrrcr]r]rcrJs   *rr)postfixinput_file_name folder_path data_root_dirseparate_foldermakedirsr\c Cstj|\}}tj|\}} | dkr8tj|\}} d} |rR|rRtj||} tj|| } |rrtj| |} |rtj| ddtj| |dkr|d|n|} |dk r| d|7} tj| S)a Utility function to create the path to the output file based on the input filename (file name extension is not added by this function). When ``data_root_dir`` is not specified, the output file name is: `folder_path/input_file_name (no ext.) /input_file_name (no ext.)[_postfix][_patch_index]` otherwise the relative path with respect to ``data_root_dir`` will be inserted, for example: .. code-block:: python from monai.data import create_file_basename create_file_basename( postfix="seg", input_file_name="/foo/bar/test1/image.png", folder_path="/output", data_root_dir="/foo/bar", separate_folder=True, makedirs=False) # output: /output/test1/image/image_seg Args: postfix: output name's postfix input_file_name: path to the input image file. folder_path: path for the output file data_root_dir: if not empty, it specifies the beginning parts of the input file's absolute path. This is used to compute `input_file_rel_path`, the relative path to the file from `data_root_dir` to preserve folder structure when saving in case there are files in different folders with the same file names. separate_folder: whether to save every file in a separate folder, for example: if input filename is `image.nii`, postfix is `seg` and folder_path is `output`, if `True`, save as: `output/image/image_seg.nii`, if `False`, save as `output/image_seg.nii`. default to `True`. patch_index: if not None, append the patch index to filename. makedirs: whether to create the folder if it does not exist. z.gzrT)exist_okrN)ospathsplitsplitextrelpathjoinrnormpath) rrrrr patch_indexrZfiledirfilenameextZfiledir_rel_pathr{r]r]rcr8s ."g?cpuzBlendMode | strztorch.device | int | strztorch.dtype | str | Nonez torch.Tensor)rZr sigma_scaledevicerAr\c Cs8t|t}t|}|tjkr2tj||tjd}n|tjkrt|t |}ddt ||D}t t |D]v}tj ||d d||dddtj|d}t |dd||d}|d kr|d |d |n|}qjn td |d tjdtjdtt|d} tj|tj| d|}|S)a9Get importance map for different weight modes. Args: patch_size: Size of the required importance map. This should be either H, W [,D]. mode: {``"constant"``, ``"gaussian"``} How to blend output of overlapping windows. Defaults to ``"constant"``. - ``"constant``": gives equal weight to all predictions. - ``"gaussian``": gives less weight to predictions on edges of windows. sigma_scale: Sigma_scale to calculate sigma for each dimension (sigma = sigma_scale * dim_size). Used for gaussian mode only. device: Device to put importance map on. dtype: Data type of the output importance map. Raises: ValueError: When ``mode`` is not one of ["constant", "gaussian"]. Returns: Tensor of size patch_size. )rrAcSsg|]\}}||qSr]r])r_rZsigma_sr]r]rcrcsz*compute_importance_map..r)rk)rendrArr?rrXrezUnsupported mode: z, available options are [z, z].rXr)r&rrrCONSTANTonesrGAUSSIANr rrmrarangeexp unsqueezerDrrrclamp_to) rZrrrrAZimportance_mapsigmasrrZ min_non_zeror]r]rcr4@s,    &zSequence[PathLike] | PathLikez Sequence[str])rsuffixesr\csJt|}|D]8}dttjt|jtfdd|Dr dSq dS)a Verify whether the specified file or files format match supported suffixes. If supported suffixes is None, skip the verification and return True. Args: filename: file name or a list of file names to read. if a list of files, verify all the suffixes. suffixes: all the supported image suffixes of current reader, must be a list of lower case suffixes. rc3s |]}d|kVqdS)rN)lowerrZ full_suffixr]rcrdsz&is_supported_format..FT)rrmaprrrrall)rr filenamesr/r]rrcr=us zSequence[float] | Nonez int | Nonerratiosnum_partitionsshuffler/ drop_lasteven_divisiblecszt}g}tt|} |r2tj|} | | |rd} t|} |D]F} | }t|t | | |d|} | fdd| || DqF|S|st d|s|rt d||krt d|d|r||dkrt |||}nt ||}|r||n|}|s4||dkr4| | d ||7} n | d |} t|D],}| |||}| fd d|DqH|S) a> Split the dataset into N partitions. It can support shuffle based on specified random seed. Will return a set of datasets, every dataset contains 1 partition of original dataset. And it can split the dataset based on specified ratios or evenly split into `num_partitions`. Refer to: https://pytorch.org/docs/stable/distributed.html#module-torch.distributed.launch. Note: It also can be used to partition dataset for ranks in distributed training. For example, partition dataset before training and use `CacheDataset`, every rank trains with its own data. It can avoid duplicated caching content in each rank, but will not do global shuffle before every epoch: .. code-block:: python data_partition = partition_dataset( data=train_files, num_partitions=dist.get_world_size(), shuffle=True, even_divisible=True, )[dist.get_rank()] train_ds = SmartCacheDataset( data=data_partition, transform=train_transforms, replace_rate=0.2, cache_num=15, ) Args: data: input dataset to split, expect a list of data. ratios: a list of ratio number to split the dataset, like [8, 1, 1]. num_partitions: expected number of the partitions to evenly split, only works when `ratios` not specified. shuffle: whether to shuffle the original dataset before splitting. seed: random seed to shuffle the dataset, only works when `shuffle` is True. drop_last: only works when `even_divisible` is False and no ratios specified. if True, will drop the tail of the data to make it evenly divisible across partitions. if False, will add extra indices to make the data evenly divisible across partitions. even_divisible: if True, guarantee every partition has same length. Examples:: >>> data = [1, 2, 3, 4, 5] >>> partition_dataset(data, ratios=[0.6, 0.2, 0.2], shuffle=False) [[1, 2, 3], [4], [5]] >>> partition_dataset(data, num_partitions=2, shuffle=False) [[1, 3, 5], [2, 4]] >>> partition_dataset(data, num_partitions=2, shuffle=False, even_divisible=True, drop_last=True) [[1, 3], [2, 4]] >>> partition_dataset(data, num_partitions=2, shuffle=False, even_divisible=True, drop_last=False) [[1, 3, 5], [2, 4, 1]] >>> partition_dataset(data, num_partitions=2, shuffle=False, even_divisible=False, drop_last=False) [[1, 3, 5], [2, 4]] rrhcsg|] }|qSr]r]rrr]rcrsz%partition_dataset..z,must specify number of partitions or ratios.z1drop_last only works when even_divisible is True.z)there is no enough data to be split into z partitions.Ncsg|] }|qSr]r]r_jrr]rcrs)rrrrirj RandomStaterrFrrrrDrrr)rrrrr/rrdata_lendatasetsindicesrsZnext_idxrsumr=r num_samples total_sizer_indicesr]rrcrFs>>   "  )rclassesrrrr/rrc st|rt|tkr2td|dtdg}tt} t|D]\} } | | | qFg} t| D]D\} }t |||||||d}| s|} qnt | |D]\}}||7}qqnt j |}| D]*}|r|||fdd|Dq|S)a_ Split the dataset into N partitions based on the given class labels. It can make sure the same ratio of classes in every partition. Others are same as :py:class:`monai.data.partition_dataset`. Args: data: input dataset to split, expect a list of data. classes: a list of labels to help split the data, the length must match the length of data. ratios: a list of ratio number to split the dataset, like [8, 1, 1]. num_partitions: expected number of the partitions to evenly split, only works when no `ratios`. shuffle: whether to shuffle the original dataset before splitting. seed: random seed to shuffle the dataset, only works when `shuffle` is True. drop_last: only works when `even_divisible` is False and no ratios specified. if True, will drop the tail of the data to make it evenly divisible across partitions. if False, will add extra indices to make the data evenly divisible across partitions. even_divisible: if True, guarantee every partition has same length. Examples:: >>> data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14] >>> classes = [2, 0, 2, 1, 3, 2, 2, 0, 2, 0, 3, 3, 1, 3] >>> partition_dataset_classes(data, classes, shuffle=False, ratios=[2, 1]) [[2, 8, 4, 1, 3, 6, 5, 11, 12], [10, 13, 7, 9, 14]] zlength of classes z must match the dataset length rrcsg|] }|qSr]r]rrr]rcr6sz-partition_dataset_classes..)r%rrDrrrrsortedrrFrmrirjrr)rrrrrr/rrrZ class_indicesrcZclass_partition_indicesrZper_class_indicesZper_class_partition_indicespartZ data_indicesrrr]rrcrGs6#    r)rfactor random_pickr/cCsft|\}}t}tt|D]}|tt|q |dkrb|t||d|g||dd|S)aY Utility function to resample the loaded datalist for training, for example: If factor < 1.0, randomly pick part of the datalist and set to Dataset, useful to quickly test the program. If factor > 1.0, repeat the datalist to enhance the Dataset. Args: data: original datalist to scale. factor: scale factor for the datalist, for example, factor=4.5, repeat the datalist 4 times and plus 50% of the original datalist. random_pick: whether to randomly pick data if scale factor has decimal part. seed: random seed to randomly pick data. gư>r))rrrr/r)rmodfrrrextendr rF)rrrr/rTrepeatsrrr]r]rcrK;s"zSequence[Iterable]r) partitionsfoldsr\csfddt|DS)a Select cross validation data based on data partitions and specified fold index. if a list of fold indices is provided, concatenate the partitions of these folds. Args: partitions: a sequence of datasets, each item is a iterable folds: the indices of the partitions to be combined. Returns: A list of combined datasets. Example:: >>> partitions = [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]] >>> select_cross_validation_folds(partitions, 2) [5, 6] >>> select_cross_validation_folds(partitions, [1, 2]) [3, 4, 5, 6] >>> select_cross_validation_folds(partitions, [-1, 2]) [9, 10, 5, 6] csg|]}|D]}|qqSr]r])r_Zfold_idZ data_itemrr]rcrjs z1select_cross_validation_folds..)r)rrr]rrcrLTsr)r\cCs\d}tjjdkr0ttj|ddd}n"tjtj|ddddd}|S)z_ Args: item: data item to be hashed Returns: the corresponding hash key r T) sort_keyszutf-8Fusedforsecurity) sys version_infominorhashlibmd5jsonrencode hexdigest)r cache_keyr]r]rcrAms    cCsXd}tjjdkr.ttjt||d}n tjtjt||ddd}| S)z Args: item: data item to be hashed protocol: protocol version used for pickling, defaults to `pickle.HIGHEST_PROTOCOL`. Returns: the corresponding hash key rr)protocolFr) rrrrrrWrrNrr)rrrr]r]rcrHs   cCs*t|ts|Sddt|||dDS)z/Return a new sorted dictionary from the `item`.cSs(i|] \}}|t|tr t|n|qSr])rrrNrr]r]rcrszsorted_dict..)rreverse)rrrr)rrrr]r]rcrNs zSequence[int | str] | NonezSequence[str] | Nonez'dict[str, dict[str, Any] | None] | Nonezdict[str, Sequence[str]] | Nonezlist[dict[str, Any]]) row_indices col_names col_types col_groupsr\c sRtfddt|}g}|dkr2t|jd}nT|D]N}t|ttfrzt|dkr\td| tt |d|dq6| |q6|dkr|j |n |j ||f} t|t rdd |D} | r| j| d } d d |D} | r| j| d d } | jdd} |dk rNi|D]\} }|j ||fj| <qfddt| D} | S)a- Utility to join pandas tables, select rows, columns and generate groups. Will return a list of dictionaries, every dictionary maps to a row of data in tables. Args: dfs: data table in pandas Dataframe format. if providing a list of tables, will join them. row_indices: indices of the expected rows to load. it should be a list, every item can be a int number or a range `[start, end)` for the indices. for example: `row_indices=[[0, 100], 200, 201, 202, 300]`. if None, load all the rows in the file. col_names: names of the expected columns to load. if None, load all the columns. col_types: `type` and `default value` to convert the loaded columns, if None, use original data. it should be a dictionary, every item maps to an expected column, the `key` is the column name and the `value` is None or a dictionary to define the default value and data type. the supported keys in dictionary are: ["type", "default"], and note that the value of `default` should not be `None`. for example:: col_types = { "subject_id": {"type": str}, "label": {"type": int, "default": 0}, "ehr_0": {"type": float, "default": 0.0}, "ehr_1": {"type": float, "default": 0.0}, } col_groups: args to group the loaded columns to generate a new column, it should be a dictionary, every item maps to a group, the `key` will be the new column name, the `value` is the names of columns to combine. for example: `col_groups={"ehr": [f"ehr_{i}" for i in range(10)], "meta": ["meta_1", "meta_2"]}` kwargs: additional arguments for `pandas.merge()` API to join tables. cstj||fSre)pdmerge)lr=)r+r]rcz)convert_tables_to_dicts..Nrr?z:range of row indices must contain 2 values: start and end.r)cSs0i|](\}}|dk r|ddk r||dqS)Ndefault)rMrr]r]rcrs z+convert_tables_to_dicts..)valuecSs*i|]"\}}|dk rd|kr||dqS)Nrr]rr]r]rcrs FrVrecords)orientcs.g|]&\}t|ffddDqS)csi|]\}}||qSr]r]rr r]rcrsz6convert_tables_to_dicts...)rrr})groupsr rcrsz+convert_tables_to_dicts..)r rrgrrrlrrrDrrrlocrrfillnarrto_dictr&r)dfsrrrrr+dfrowsrdata_defaultsrrr/colsr])rr+rcr6s2'       )r<r\cCst|jddd}ddgdddgddddgg}|t|dddg|d}t|tjrvtt|||St | |j |S)z Convert the ``affine`` between the `RAS` and `LPS` orientation by flipping the first two spatial dimensions. Args: affine: a 2D affine matrix. rr)rXr?r;) rrrrrrrZrrrirrrA)r<rsZflip_dZ flip_diagr]r]rcrDs   z list[str])rrr\cCs|D]}||d}qdS)z Remove keys from a dictionary. Operates in-place so nothing is returned. Args: data: dictionary to be modified. keys: keys to be deleted from dictionary. Returns: `None` N)pop)rrrrr]r]rcrRs )rr\cCst}t||ddS)z Remove extra metadata from the dictionary. Operates in-place so nothing is returned. Args: meta: dictionary containing metadata to be modified. Returns: `None` )rrN)rTrR)rrr]r]rcrS s c Cs*dd d tdDdd tdD}|S)z| Get a list of unnecessary keys for metadata that can be removed. Returns: List of keys to be removed. srow_xsrow_ysrow_z quatern_b quatern_c quatern_d qoffset_x qoffset_y qoffset_zrrQcSsg|]}d|dqS)zdim[]r]rr]r]rcr*sz+get_extra_metadata_keys..cSsg|]}d|dqS)zpixdim[rr]rr]r]rcr+s) rrrrrrrrrrrQ)r)rr]r]rcrTs  cCsLt|tjrtt|St|tr,|dkSt|rDtt|S|dkS)zPReturns whether `val` indicates "no_channel", for MetaKeys.ORIGINAL_CHANNEL_DIM.Z no_channelN)rrrrpisnanrriisscalar)valr]r]rcrV9s   )N)r]roT)T)r]roF)r)r)TTN)T)F)rTNT)NNFrFF)NNFrFF)Fr)NF)NNNN)w __future__rrrrrrrWr collectionsrrcollections.abcrrrrr rWr functoolsr itertoolsr rrpathlibrtypingrrrirZtorch.utils.data._utils.collatermonairmonai.config.type_definitionsrrrmonai.data.meta_objr monai.utilsrrrrrrrrr r!r"r#r$r%r&r'r(r+r,rrr.r__all__r2r1r;r@r:r?WRAPr>r<r KEY_SUFFIXrUrrr rBrr9 SYMMETRICrrErCrPrMrr3r7rIrQr5float64rOrJr8float32r4r=rFrGrKrLrAHIGHEST_PROTOCOLrHrNr6rDrRrSrTrVr]r]r]rc s$        L   *#.2V@:g %8?/M5qD M"