
    h                    d   S r SSKJr  SSKJrJrJrJrJr  SSK	r
SSKJrJrJr  SSKJr  SSKJr  SSKJr  SSKJr  SS	KJrJr  SS
KJrJr  SSKJr  / SQr Sr! " S S\5      r" " S S\"5      r# " S S\"5      r$ " S S\5      r% " S S\%5      r& " S S\%5      r' " S S\5      r( " S S\5      r)g)a  Module containing 3D transformation classes for volumetric data augmentation.

This module provides a collection of transformation classes designed specifically for
3D volumetric data (such as medical CT/MRI scans). These transforms can manipulate properties
such as spatial dimensions, apply dropout effects, and perform symmetry operations on
3D volumes, masks, and keypoints. Each transformation inherits from a base transform
interface and implements specific 3D augmentation logic.
    )annotations)	AnnotatedAnyLiteralUnioncastN)AfterValidatorfield_validatormodel_validator)Self)
functional)KeypointsProcessor)check_range_boundsnondecreasing)BaseTransformInitSchemaTransform3D)Targets)CenterCrop3DCoarseDropout3DCubicSymmetryPad3DPadIfNeeded3DRandomCrop3D   c                     ^  \ rS rSrSr\R                  \R                  \R                  4r	 " S S\
R                  5      r   S
     SU 4S jjjr        SS jr        SS jrSS jrS	rU =r$ )	BasePad3D   aJ  Base class for 3D padding transforms.

This class serves as a foundation for all 3D transforms that perform padding operations
on volumetric data. It provides common functionality for padding 3D volumes, masks,
and processing 3D keypoints during padding operations.

The class handles different types of padding values (scalar or per-channel) and
provides separate fill values for volumes and masks.

Args:
    fill (tuple[float, ...] | float): Value to fill the padded voxels for volumes.
        Can be a single value for all channels or a tuple of values per channel.
    fill_mask (tuple[float, ...] | float): Value to fill the padded voxels for 3D masks.
        Can be a single value for all channels or a tuple of values per channel.
    p (float): Probability of applying the transform. Default: 1.0.

Targets:
    volume, mask3d, keypoints

Note:
    This is a base class and not intended to be used directly. Use its derivatives
    like Pad3D or PadIfNeeded3D instead, or create a custom padding transform
    by inheriting from this class.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>>
    >>> # Example of a custom padding transform inheriting from BasePad3D
    >>> class CustomPad3D(A.BasePad3D):
    ...     def __init__(self, padding_size: tuple[int, int, int] = (5, 5, 5), *args, **kwargs):
    ...         super().__init__(*args, **kwargs)
    ...         self.padding_size = padding_size
    ...
    ...     def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
    ...         # Create symmetric padding: same amount on all sides of each dimension
    ...         pad_d, pad_h, pad_w = self.padding_size
    ...         padding = (pad_d, pad_d, pad_h, pad_h, pad_w, pad_w)
    ...         return {"padding": padding}
    >>>
    >>> # Prepare sample data
    >>> volume = np.random.randint(0, 256, (10, 100, 100), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (10, 100, 100), dtype=np.uint8)    # (D, H, W)
    >>> keypoints = np.array([[20, 30, 5], [60, 70, 8]], dtype=np.float32)  # (x, y, z)
    >>> keypoint_labels = [1, 2]  # Labels for each keypoint
    >>>
    >>> # Use the custom transform in a pipeline
    >>> transform = A.Compose([
    ...     CustomPad3D(
    ...         padding_size=(2, 10, 10),
    ...         fill=0,
    ...         fill_mask=1,
    ...         p=1.0
    ...     )
    ... ], keypoint_params=A.KeypointParams(format='xyz', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> transformed = transform(
    ...     volume=volume,
    ...     mask3d=mask3d,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> transformed_volume = transformed["volume"]           # Shape: (14, 120, 120)
    >>> transformed_mask3d = transformed["mask3d"]           # Shape: (14, 120, 120)
    >>> transformed_keypoints = transformed["keypoints"]     # Keypoints shifted by padding offsets
    >>> transformed_keypoint_labels = transformed["keypoint_labels"]  # Labels remain unchanged

c                  *    \ rS rSr% S\S'   S\S'   Srg)BasePad3D.InitSchemai   tuple[float, ...] | floatfill	fill_mask N__name__
__module____qualname____firstlineno____annotations____static_attributes__r$       n/var/www/fran/franai/venv/lib/python3.13/site-packages/albumentations/augmentations/transforms3d/transforms.py
InitSchemar   i   s    '',,r,   r.   c                8   > [         TU ]  US9  Xl        X l        g N)p)super__init__r"   r#   )selfr"   r#   r1   	__class__s       r-   r3   BasePad3D.__init__m   s     	1	"r,   c                R    US:X  a  U$ [         R                  " UUU R                  S9$ )a  Apply padding to a 3D volume.

Args:
    volume (np.ndarray): Input volume with shape (depth, height, width) or (depth, height, width, channels)
    padding (tuple[int, int, int, int, int, int]): Padding values in format:
        (depth_front, depth_back, height_top, height_bottom, width_left, width_right)
    **params (Any): Additional parameters

Returns:
    np.ndarray: Padded volume with same number of dimensions as input

r   r   r   r   r   r   volumepaddingvalue)f3dpad_3d_with_paramsr"   )r4   r:   r;   paramss       r-   apply_to_volumeBasePad3D.apply_to_volumew   s2    $ ((M%%))
 	
r,   c                f    US:X  a  U$ [         R                  " UU[        SU R                  5      S9$ )a  Apply padding to a 3D mask.

Args:
    mask3d (np.ndarray): Input mask with shape (depth, height, width) or (depth, height, width, channels)
    padding (tuple[int, int, int, int, int, int]): Padding values in format:
        (depth_front, depth_back, height_top, height_bottom, width_left, width_right)
    **params (Any): Additional parameters

Returns:
    np.ndarray: Padded mask with same number of dimensions as input

r8   Union[tuple[float, ...], float]r9   )r=   r>   r   r#   )r4   mask3dr;   r?   s       r-   apply_to_mask3dBasePad3D.apply_to_mask3d   s:    $ ((M%%8$..I
 	
r,   c                |    US   n[         R                  " US   US   US   /5      n[        R                  " X5      $ )aH  Apply padding to keypoints.

Args:
    keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+).
                           The first three columns are x, y, z coordinates.
    **params (Any): Additional parameters containing padding values

Returns:
    np.ndarray: Shifted keypoints with same shape as input

r;         r   nparray
fgeometricshift_keypoints)r4   	keypointsr?   r;   shift_vectors        r-   apply_to_keypointsBasePad3D.apply_to_keypoints   s@     #xxWQZ DE)))BBr,   )r"   r#   r   r         ?)r"   r!   r#   r!   r1   float)r:   
np.ndarrayr;   #tuple[int, int, int, int, int, int]r?   r   returnrV   )rD   rV   r;   rW   r?   r   rX   rV   )rO   rV   r?   r   rX   rV   )r&   r'   r(   r)   __doc__r   VOLUMEMASK3D	KEYPOINTS_targetsr   r.   r3   r@   rE   rQ   r+   __classcell__r5   s   @r-   r   r      s    FP 0A0ABH-[++ - +,/0	#'# -# 	# #

 5
 	

 

4

 5
 	

 

4C Cr,   r   c                  |   ^  \ rS rSrSr " S S\R                  5      r   S       S	U 4S jjjrS
S jrSr	U =r
$ )r      aB	  Pad the sides of a 3D volume by specified number of voxels.

Args:
    padding (int, tuple[int, int, int] or tuple[int, int, int, int, int, int]): Padding values. Can be:
        * int - pad all sides by this value
        * tuple[int, int, int] - symmetric padding (depth, height, width) where each value
          is applied to both sides of the corresponding dimension
        * tuple[int, int, int, int, int, int] - explicit padding per side in order:
          (depth_front, depth_back, height_top, height_bottom, width_left, width_right)

    fill (tuple[float, ...] | float): Padding value for image
    fill_mask (tuple[float, ...] | float): Padding value for mask
    p (float): probability of applying the transform. Default: 1.0.

Targets:
    volume, mask3d, keypoints

Image types:
    uint8, float32

Note:
    Input volume should be a numpy array with dimensions ordered as (z, y, x) or (depth, height, width),
    with optional channel dimension as the last axis.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>>
    >>> # Prepare sample data
    >>> volume = np.random.randint(0, 256, (10, 100, 100), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (10, 100, 100), dtype=np.uint8)    # (D, H, W)
    >>> keypoints = np.array([[20, 30, 5], [60, 70, 8]], dtype=np.float32)  # (x, y, z)
    >>> keypoint_labels = [1, 2]  # Labels for each keypoint
    >>>
    >>> # Create the transform with symmetric padding
    >>> transform = A.Compose([
    ...     A.Pad3D(
    ...         padding=(2, 5, 10),  # (depth, height, width) applied symmetrically
    ...         fill=0,
    ...         fill_mask=1,
    ...         p=1.0
    ...     )
    ... ], keypoint_params=A.KeypointParams(format='xyz', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> transformed = transform(
    ...     volume=volume,
    ...     mask3d=mask3d,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> padded_volume = transformed["volume"]  # Shape: (14, 110, 120)
    >>> padded_mask3d = transformed["mask3d"]  # Shape: (14, 110, 120)
    >>> padded_keypoints = transformed["keypoints"]  # Keypoints shifted by padding
    >>> padded_keypoint_labels = transformed["keypoint_labels"]  # Labels remain unchanged

c                  R    \ rS rSr% S\S'   \" S5      \    SS j5       5       rSrg)Pad3D.InitSchema   @int | tuple[int, int, int] | tuple[int, int, int, int, int, int]r;   c                    [        U[        5      (       a  US:  a  [        S5      e[        U[        5      (       a"  [	        S U 5       5      (       d  [        S5      eU$ )a  Validate the padding parameter.

Args:
    cls (type): The class object
    v (int | tuple[int, int, int] | tuple[int, int, int, int, int, int]): The padding value to validate,
        can be an integer or tuple of integers

Returns:
    int | tuple[int, int, int] | tuple[int, int, int, int, int, int]: The validated padding value

Raises:
    ValueError: If padding is negative or contains negative values

r   z"Padding value must be non-negativec              3  Z   #    U  H!  n[        U[        5      =(       a    US :  v   M#     g7f)r   N)
isinstanceint).0is     r-   	<genexpr>4Pad3D.InitSchema.validate_padding.<locals>.<genexpr>  s&     /YWXRS
1c0B0MqAv0MWXs   )+z0Padding tuple must contain non-negative integers)rh   ri   
ValueErrortupleall)clsvs     r-   validate_padding!Pad3D.InitSchema.validate_padding   sR    ( !S!!a!e !EFF!U##C/YWX/Y,Y,Y !STTHr,   r$   N)rr   re   rX   re   )	r&   r'   r(   r)   r*   r
   classmethodrs   r+   r$   r,   r-   r.   rc      s:    QQ		#		O	 N	 
 
$	r,   r.   c                F   > [         TU ]  X#US9  Xl        X l        X0l        g N)r"   r#   r1   )r2   r3   r;   r"   r#   )r4   r;   r"   r#   r1   r5   s        r-   r3   Pad3D.__init__  s&     	d1=	"r,   c                    [        U R                  [        5      (       a  U R                  =n=pEX3XDXU4nSU0$ [        U R                  5      [        :X  a  U R                  u  p4nX3XDXU4nSU0$ U R                  nSU0$ )at  Get parameters dependent on input data.

Args:
    params (dict[str, Any]): Dictionary of existing parameters
    data (dict[str, Any]): Dictionary containing input data with volume, mask, etc.

Returns:
    dict[str, Any]: Dictionary containing the padding parameter tuple in format:
        (depth_front, depth_back, height_top, height_bottom, width_left, width_right)

r;   )rh   r;   ri   lenNUM_DIMENSIONS)r4   r?   datapad_dpad_hpad_wr;   s          r-   get_params_dependent_on_data"Pad3D.get_params_dependent_on_data#  s     dllC(($(LL0E0EU5@G 7## .0"&,,E%U5@G 7## llG7##r,   )r"   r#   r;   rS   )r;   re   r"   r!   r#   r!   r1   rU   r?   dict[str, Any]r|   r   rX   r   r&   r'   r(   r)   rY   r   r.   r3   r   r+   r^   r_   s   @r-   r   r      sa    :xY)) B +,/0
#Q
# (
# -	
#
 
# 
#$ $r,   r   c                     ^  \ rS rSrSr " S S\R                  5      r      S           S	U 4S jjjr      S
S jrSr	U =r
$ )r   i;  a  Pads the sides of a 3D volume if its dimensions are less than specified minimum dimensions.
If the pad_divisor_zyx is specified, the function additionally ensures that the volume
dimensions are divisible by these values.

Args:
    min_zyx (tuple[int, int, int] | None): Minimum desired size as (depth, height, width).
        Ensures volume dimensions are at least these values.
        If not specified, pad_divisor_zyx must be provided.
    pad_divisor_zyx (tuple[int, int, int] | None): If set, pads each dimension to make it
        divisible by corresponding value in format (depth_div, height_div, width_div).
        If not specified, min_zyx must be provided.
    position (Literal["center", "random"]): Position where the volume is to be placed after padding.
        Default is 'center'.
    fill (tuple[float, ...] | float): Value to fill the border voxels for volume. Default: 0
    fill_mask (tuple[float, ...] | float): Value to fill the border voxels for masks. Default: 0
    p (float): Probability of applying the transform. Default: 1.0

Targets:
    volume, mask3d, keypoints

Image types:
    uint8, float32

Note:
    Input volume should be a numpy array with dimensions ordered as (z, y, x) or (depth, height, width),
    with optional channel dimension as the last axis.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>>
    >>> # Prepare sample data
    >>> volume = np.random.randint(0, 256, (10, 100, 100), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (10, 100, 100), dtype=np.uint8)    # (D, H, W)
    >>> keypoints = np.array([[20, 30, 5], [60, 70, 8]], dtype=np.float32)  # (x, y, z)
    >>> keypoint_labels = [1, 2]  # Labels for each keypoint
    >>>
    >>> # Create a transform with both min_zyx and pad_divisor_zyx
    >>> transform = A.Compose([
    ...     A.PadIfNeeded3D(
    ...         min_zyx=(16, 128, 128),        # Minimum size (depth, height, width)
    ...         pad_divisor_zyx=(8, 16, 16),   # Make dimensions divisible by these values
    ...         position="center",              # Center the volume in the padded space
    ...         fill=0,                         # Fill value for volume
    ...         fill_mask=1,                    # Fill value for mask
    ...         p=1.0
    ...     )
    ... ], keypoint_params=A.KeypointParams(format='xyz', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> transformed = transform(
    ...     volume=volume,
    ...     mask3d=mask3d,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> padded_volume = transformed["volume"]           # Shape: (16, 128, 128)
    >>> padded_mask3d = transformed["mask3d"]           # Shape: (16, 128, 128)
    >>> padded_keypoints = transformed["keypoints"]     # Keypoints shifted by padding
    >>> padded_keypoint_labels = transformed["keypoint_labels"]  # Labels remain unchanged

c                  P    \ rS rSr% S\S'   S\S'   S\S'   \" SS	9SS
 j5       rSrg)PadIfNeeded3D.InitSchemai}  zSAnnotated[tuple[int, int, int] | None, AfterValidator(check_range_bounds(0, None))]min_zyxzSAnnotated[tuple[int, int, int] | None, AfterValidator(check_range_bounds(1, None))]pad_divisor_zyxLiteral['center', 'random']positionaftermodec                T    U R                   c  U R                  c  Sn[        U5      eU $ )zValidate that either min_zyx or pad_divisor_zyx is provided.

Returns:
    Self: Self reference for method chaining

Raises:
    ValueError: If both min_zyx and pad_divisor_zyx are None

z6At least one of min_zyx or pad_divisor_zyx must be set)r   r   rn   )r4   msgs     r-   validate_params(PadIfNeeded3D.InitSchema.validate_params  s-     ||#(<(<(DN o%Kr,   r$   NrX   r   )r&   r'   r(   r)   r*   r   r   r+   r$   r,   r-   r.   r   }  s+    ddll--	g	&	 
'	r,   r.   c                F   > [         TU ]  XEUS9  Xl        X l        X0l        g rw   )r2   r3   r   r   r   )r4   r   r   r   r"   r#   r1   r5   s          r-   r3   PadIfNeeded3D.__init__  s'     	d1=. r,   c           
        US   R                   SS u  p4nX4U4n[        U5       VVs/ s H[  u  px[        R                  " UU R                  (       a  U R                  U   OSU R
                  (       a  U R
                  U   OSS9PM]     n	nn[        R                  " U	U R                  U R                  S9n
SU
0$ s  snnf )a*  Calculate padding parameters based on input data dimensions.

Args:
    params (dict[str, Any]): Dictionary of existing parameters
    data (dict[str, Any]): Dictionary containing input data with volume, mask, etc.

Returns:
    dict[str, Any]: Dictionary containing calculated padding parameters

r:   Nr   )current_sizemin_sizedivisor)paddingsr   	py_randomr;   )
shape	enumeraterM   get_dimension_paddingr   r   r=   adjust_padding_by_position3dr   r   )r4   r?   r|   depthheightwidthsizesrk   sizer   r;   s              r-   r   *PadIfNeeded3D.get_params_dependent_on_data  s      $H~33BQ7u& %U+
 , ,,!,0LLad373G3G,,Q/T
 , 	 
 22]]nn
 7##
s   A"B;)r   r   r   )NNcenterr   r   rT   )r   tuple[int, int, int] | Noner   r   r   r   r"   r!   r#   r!   r1   rU   r   r   r_   s   @r-   r   r   ;  s    ?BY)) . 047;08*+/0!,! 5! .	!
 (! -! ! !!$!$ !$ 
	!$ !$r,   r   c                  <  ^  \ rS rSrSr\R                  \R                  \R                  4r	 " S S\
R                  5      r S         SU 4S jjjrSS jrSS jr      SS jr          SS	 jr          SS
 jr          SS jrSrU =r$ )BaseCropAndPad3Di  aN  Base class for 3D transforms that need both cropping and padding.

This class serves as a foundation for transforms that combine cropping and padding operations
on 3D volumetric data. It provides functionality for calculating padding parameters,
applying crop and pad operations to volumes, masks, and handling keypoint coordinate shifts.

Args:
    pad_if_needed (bool): Whether to pad if the volume is smaller than target dimensions
    fill (tuple[float, ...] | float): Value to fill the padded voxels for volume
    fill_mask (tuple[float, ...] | float): Value to fill the padded voxels for mask
    pad_position (Literal["center", "random"]): How to distribute padding when needed
        "center" - equal amount on both sides, "random" - random distribution
    p (float): Probability of applying the transform. Default: 1.0

Targets:
    volume, mask3d, keypoints

Note:
    This is a base class and not intended to be used directly. Use its derivatives
    like CenterCrop3D or RandomCrop3D instead, or create a custom transform
    by inheriting from this class.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>>
    >>> # Example of a custom crop transform inheriting from BaseCropAndPad3D
    >>> class CustomFixedCrop3D(A.BaseCropAndPad3D):
    ...     def __init__(self, crop_size: tuple[int, int, int] = (8, 64, 64), *args, **kwargs):
    ...         super().__init__(
    ...             pad_if_needed=True,
    ...             fill=0,
    ...             fill_mask=0,
    ...             pad_position="center",
    ...             *args,
    ...             **kwargs
    ...         )
    ...         self.crop_size = crop_size
    ...
    ...     def get_params_dependent_on_data(self, params: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
    ...         # Get the volume shape
    ...         volume = data["volume"]
    ...         z, h, w = volume.shape[:3]
    ...         target_z, target_h, target_w = self.crop_size
    ...
    ...         # Check if padding is needed and calculate parameters
    ...         pad_params = self._get_pad_params(
    ...             image_shape=(z, h, w),
    ...             target_shape=self.crop_size,
    ...         )
    ...
    ...         # Update dimensions if padding is applied
    ...         if pad_params is not None:
    ...             z = z + pad_params["pad_front"] + pad_params["pad_back"]
    ...             h = h + pad_params["pad_top"] + pad_params["pad_bottom"]
    ...             w = w + pad_params["pad_left"] + pad_params["pad_right"]
    ...
    ...         # Calculate fixed crop coordinates - always start at position (0,0,0)
    ...         crop_coords = (0, target_z, 0, target_h, 0, target_w)
    ...
    ...         return {
    ...             "crop_coords": crop_coords,
    ...             "pad_params": pad_params,
    ...         }
    >>>
    >>> # Prepare sample data
    >>> volume = np.random.randint(0, 256, (10, 100, 100), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (10, 100, 100), dtype=np.uint8)    # (D, H, W)
    >>> keypoints = np.array([[20, 30, 5], [60, 70, 8]], dtype=np.float32)  # (x, y, z)
    >>> keypoint_labels = [1, 2]  # Labels for each keypoint
    >>>
    >>> # Use the custom transform in a pipeline
    >>> transform = A.Compose([
    ...     CustomFixedCrop3D(
    ...         crop_size=(8, 64, 64),  # Crop first 8x64x64 voxels (with padding if needed)
    ...         p=1.0
    ...     )
    ... ], keypoint_params=A.KeypointParams(format='xyz', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> transformed = transform(
    ...     volume=volume,
    ...     mask3d=mask3d,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> cropped_volume = transformed["volume"]           # Shape: (8, 64, 64)
    >>> cropped_mask3d = transformed["mask3d"]           # Shape: (8, 64, 64)
    >>> cropped_keypoints = transformed["keypoints"]     # Keypoints shifted relative to crop
    >>> cropped_keypoint_labels = transformed["keypoint_labels"]  # Labels remain unchanged

c                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	rg
)BaseCropAndPad3D.InitSchemai&  boolpad_if_neededr!   r"   r#   r   pad_positionr$   Nr%   r$   r,   r-   r.   r   &  s    '',,11r,   r.   c                P   > [         TU ]  US9  Xl        X l        X0l        X@l        g r0   )r2   r3   r   r"   r#   r   )r4   r   r"   r#   r   r1   r5   s         r-   r3   BaseCropAndPad3D.__init__,  s+     	1*	"(r,   c                `    US:  a#  U R                   R                  SU5      nX-
  nX#4$ S=p#X#4$ )zGenerate random padding values.

Args:
    pad (int): Total padding value to distribute

Returns:
    tuple[int, int]: Random padding values (front, back)

r   )r   randintr4   pad	pad_startpad_ends       r-   _random_padBaseCropAndPad3D._random_pad:  sF     7..q#6IoG !! #$#I!!r,   c                    US-  nX-
  nX#4$ )zGenerate centered padding values.

Args:
    pad (int): Total padding value to distribute

Returns:
    tuple[int, int]: Centered padding values (front, back)

rI   r$   r   s       r-   _center_padBaseCropAndPad3D._center_padK  s     1H	/!!r,   c                   U R                   (       d  gUu  p4nUu  pgn[        SXc-
  5      n	[        SXt-
  5      n
[        SX-
  5      nU	S:X  a  U
S:X  a  US:X  a  gU R                  S:X  a;  U R                  U	5      u  pU R                  U
5      u  pU R                  U5      u  nnO:U R	                  U	5      u  pU R	                  U
5      u  pU R	                  U5      u  nnUUUUUUS.$ )a+  Calculate padding parameters to reach target shape.

Args:
    image_shape (tuple[int, int, int]): Current shape (depth, height, width)
    target_shape (tuple[int, int, int]): Target shape (depth, height, width)

Returns:
    dict[str, int] | None: Padding parameters or None if no padding needed

Nr   r   )	pad_frontpad_backpad_top
pad_bottompad_left	pad_right)r   maxr   r   r   )r4   image_shapetarget_shapezhwtarget_ztarget_htarget_wz_padh_padw_padz_frontz_backh_toph_bottomw_leftw_rights                     r-   _get_pad_params BaseCropAndPad3D._get_pad_paramsY  s    !!a'3$H Ax|$Ax|$Ax|$A:%1*! ("..u5OG"..u5OE"..u5OFG #..u5OG"..u5OE"..u5OFG !" 
 	
r,   c                    [         R                  " X5      nUb:  US   US   US   US   US   US   4n[         R                  " UUU R                  S9$ U$ )a  Apply cropping and padding to a 3D volume.

Args:
    volume (np.ndarray): Input volume with shape (depth, height, width) or (depth, height, width, channels)
    crop_coords (tuple[int, int, int, int, int, int]): Crop coordinates (z1, z2, y1, y2, x1, x2)
    pad_params (dict[str, int] | None): Padding parameters or None if no padding needed
    **params (Any): Additional parameters

Returns:
    np.ndarray: Cropped and padded volume with same number of dimensions as input

r   r   r   r   r   r   r;   r<   )r=   crop3dr>   r"   )r4   r:   crop_coords
pad_paramsr?   croppedr;   s          r-   r@    BaseCropAndPad3D.apply_to_volume  sz    ( **V1 !;':&9%<(:&;'G ))ii  r,   c                    [         R                  " X5      nUbD  US   US   US   US   US   US   4n[         R                  " UU[        SU R                  5      S9$ U$ )	a  Apply cropping and padding to a 3D mask.

Args:
    mask3d (np.ndarray): Input mask with shape (depth, height, width) or (depth, height, width, channels)
    crop_coords (tuple[int, int, int, int, int, int]): Crop coordinates (z1, z2, y1, y2, x1, x2)
    pad_params (dict[str, int] | None): Padding parameters or None if no padding needed
    **params (Any): Additional parameters

Returns:
    np.ndarray: Cropped and padded mask with same number of dimensions as input

r   r   r   r   r   r   rC   r   )r=   r   r>   r   r#   )r4   rD   r   r   r?   r   r;   s          r-   rE    BaseCropAndPad3D.apply_to_mask3d  s    ( **V1 !;':&9%<(:&;'G ))<dnnM  r,   c                    Uu  pVpvp[         R                  " U* U* U* /5      n	Ub%  U	[         R                  " US   US   US   /5      -  n	[        R                  " X5      $ )a  Apply cropping and padding to keypoints.

Args:
    keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+).
                           The first three columns are x, y, z coordinates.
    crop_coords (tuple[int, int, int, int, int, int]): Crop coordinates (z1, z2, y1, y2, x1, x2)
    pad_params (dict[str, int] | None): Padding parameters or None if no padding needed
    **params (Any): Additional parameters

Returns:
    np.ndarray: Shifted keypoints with same shape as input

r   r   r   rJ   )
r4   rO   r   r   r?   crop_z1_crop_y1crop_x1shifts
             r-   rQ   #BaseCropAndPad3D.apply_to_keypoints  s    * .9*G 
 !RXXz*y){+ E )));;r,   )r"   r#   r   r   rT   )
r   r   r"   r!   r#   r!   r   r   r1   rU   )r   ri   rX   tuple[int, int])r   tuple[int, int, int]r   r   rX   dict[str, int] | None)
r:   rV   r   rW   r   r   r?   r   rX   rV   )
rD   rV   r   rW   r   r   r?   r   rX   rV   )
rO   rV   r   rW   r   r   r?   r   rX   rV   )r&   r'   r(   r)   rY   r   rZ   r[   r\   r]   r   r.   r3   r   r   r   r@   rE   rQ   r+   r^   r_   s   @r-   r   r     sI   ]~ 0A0ABH2[++ 2 )) () -	)
 2) ) )"""/
)/
 +/
 
	/
b&& 9& *	&
 & 
&P&& 9& *	&
 & 
&P+<+< 9+< *	+<
 +< 
+< +<r,   r   c                  z   ^  \ rS rSrSr " S S\5      r    S         S	U 4S jjjr      S
S jrSr	U =r
$ )r   i  a  Crop the center of 3D volume.

Args:
    size (tuple[int, int, int]): Desired output size of the crop in format (depth, height, width)
    pad_if_needed (bool): Whether to pad if the volume is smaller than desired crop size. Default: False
    fill (tuple[float, float] | float): Padding value for image if pad_if_needed is True. Default: 0
    fill_mask (tuple[float, float] | float): Padding value for mask if pad_if_needed is True. Default: 0
    p (float): probability of applying the transform. Default: 1.0

Targets:
    volume, mask3d, keypoints

Image types:
    uint8, float32

Note:
    If you want to perform cropping only in the XY plane while preserving all slices along
    the Z axis, consider using CenterCrop instead. CenterCrop will apply the same XY crop
    to each slice independently, maintaining the full depth of the volume.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>>
    >>> # Prepare sample data
    >>> volume = np.random.randint(0, 256, (20, 200, 200), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (20, 200, 200), dtype=np.uint8)    # (D, H, W)
    >>> keypoints = np.array([[100, 100, 10], [150, 150, 15]], dtype=np.float32)  # (x, y, z)
    >>> keypoint_labels = [1, 2]  # Labels for each keypoint
    >>>
    >>> # Create the transform - crop to 16x128x128 from center
    >>> transform = A.Compose([
    ...     A.CenterCrop3D(
    ...         size=(16, 128, 128),        # Output size (depth, height, width)
    ...         pad_if_needed=True,         # Pad if input is smaller than crop size
    ...         fill=0,                     # Fill value for volume padding
    ...         fill_mask=1,                # Fill value for mask padding
    ...         p=1.0
    ...     )
    ... ], keypoint_params=A.KeypointParams(format='xyz', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> transformed = transform(
    ...     volume=volume,
    ...     mask3d=mask3d,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> cropped_volume = transformed["volume"]           # Shape: (16, 128, 128)
    >>> cropped_mask3d = transformed["mask3d"]           # Shape: (16, 128, 128)
    >>> cropped_keypoints = transformed["keypoints"]     # Keypoints shifted relative to center crop
    >>> cropped_keypoint_labels = transformed["keypoint_labels"]  # Labels remain unchanged
    >>>
    >>> # Example with a small volume that requires padding
    >>> small_volume = np.random.randint(0, 256, (10, 100, 100), dtype=np.uint8)
    >>> small_transform = A.Compose([
    ...     A.CenterCrop3D(
    ...         size=(16, 128, 128),
    ...         pad_if_needed=True,   # Will pad since the input is smaller
    ...         fill=0,
    ...         p=1.0
    ...     )
    ... ])
    >>> small_result = small_transform(volume=small_volume)
    >>> padded_and_cropped = small_result["volume"]  # Shape: (16, 128, 128), padded to size

c                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	rg
)CenterCrop3D.InitSchemaiO  LAnnotated[tuple[int, int, int], AfterValidator(check_range_bounds(1, None))]r   r   r   r!   r"   r#   r$   Nr%   r$   r,   r-   r.   r   O      ZZ'',,r,   r.   c                4   > [         TU ]  UUUSUS9  Xl        g )Nr   r   r"   r#   r   r1   r2   r3   r   r4   r   r   r"   r#   r1   r5   s         r-   r3   CenterCrop3D.__init__U  -     	'! 	 	
 	r,   c           	        US   nUR                   SS u  pEnU R                  u  pxn	U R                  XEU4U R                  S9n
U
b'  XJS   -   U
S   -   nXZS   -   U
S   -   nXjS	   -   U
S
   -   nXG:  d
  XX:  d  Xi:  a$  SU R                   SU SU SU S3	n[        U5      eXG-
  S-  nXX-
  S-  nXi-
  S-  nUX-   UX-   UX-   4nUU
S.$ )a0  Calculate crop coordinates for center cropping.

Args:
    params (dict[str, Any]): Dictionary of existing parameters
    data (dict[str, Any]): Dictionary containing input data with volume, mask, etc.

Returns:
    dict[str, Any]: Dictionary containing crop coordinates and optional padding parameters

r:   Nr   r   r   r   r   r   r   r   r   z
Crop size z# is larger than padded image size (z, z8). This should not happen - please report this as a bug.rI   r   r   )r   r   r   rn   )r4   r?   r|   r:   r   r   r   r   r   r   r   r   z_starth_startw_startr   s                   r-   r   )CenterCrop3D.get_params_dependent_on_dataf  sL    h,,r"a'+yy$H ))q	 * 

 !{++j.DDAy))J|,DDAz**Z-DDA <1<1<TYYK'J1#RPQsRTUVTW XH I  S/! <A%<A%<A% 
 '$
 	
r,   r   Fr   r   rT   
r   r   r   r   r"   r!   r#   r!   r1   rU   r   r&   r'   r(   r)   rY   r   r.   r3   r   r+   r^   r_   s   @r-   r   r     s    DL-, - $*+/0"  (	
 -  "8
8
 8
 
	8
 8
r,   r   c                  z   ^  \ rS rSrSr " S S\5      r    S         S	U 4S jjjr      S
S jrSr	U =r
$ )r   i  a	  Crop random part of 3D volume.

Args:
    size (tuple[int, int, int]): Desired output size of the crop in format (depth, height, width)
    pad_if_needed (bool): Whether to pad if the volume is smaller than desired crop size. Default: False
    fill (tuple[float, float] | float): Padding value for image if pad_if_needed is True. Default: 0
    fill_mask (tuple[float, float] | float): Padding value for mask if pad_if_needed is True. Default: 0
    p (float): probability of applying the transform. Default: 1.0

Targets:
    volume, mask3d, keypoints

Image types:
    uint8, float32

Note:
    If you want to perform random cropping only in the XY plane while preserving all slices along
    the Z axis, consider using RandomCrop instead. RandomCrop will apply the same XY crop
    to each slice independently, maintaining the full depth of the volume.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>>
    >>> # Prepare sample data
    >>> volume = np.random.randint(0, 256, (20, 200, 200), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (20, 200, 200), dtype=np.uint8)    # (D, H, W)
    >>> keypoints = np.array([[100, 100, 10], [150, 150, 15]], dtype=np.float32)  # (x, y, z)
    >>> keypoint_labels = [1, 2]  # Labels for each keypoint
    >>>
    >>> # Create the transform with random crop and padding if needed
    >>> transform = A.Compose([
    ...     A.RandomCrop3D(
    ...         size=(16, 128, 128),        # Output size (depth, height, width)
    ...         pad_if_needed=True,         # Pad if input is smaller than crop size
    ...         fill=0,                     # Fill value for volume padding
    ...         fill_mask=1,                # Fill value for mask padding
    ...         p=1.0
    ...     )
    ... ], keypoint_params=A.KeypointParams(format='xyz', label_fields=['keypoint_labels']))
    >>>
    >>> # Apply the transform
    >>> transformed = transform(
    ...     volume=volume,
    ...     mask3d=mask3d,
    ...     keypoints=keypoints,
    ...     keypoint_labels=keypoint_labels
    ... )
    >>>
    >>> # Get the transformed data
    >>> cropped_volume = transformed["volume"]           # Shape: (16, 128, 128)
    >>> cropped_mask3d = transformed["mask3d"]           # Shape: (16, 128, 128)
    >>> cropped_keypoints = transformed["keypoints"]     # Keypoints shifted relative to random crop
    >>> cropped_keypoint_labels = transformed["keypoint_labels"]  # Labels remain unchanged

c                  >    \ rS rSr% S\S'   S\S'   S\S'   S\S'   S	rg
)RandomCrop3D.InitSchemai  r   r   r   r   r!   r"   r#   r$   Nr%   r$   r,   r-   r.   r    r   r,   r.   c                4   > [         TU ]  UUUSUS9  Xl        g )Nrandomr   r   r   s         r-   r3   RandomCrop3D.__init__  r   r,   c                   US   nUR                   SS u  pEnU R                  u  pxn	U R                  XEU4U R                  S9n
U
b'  XJS   -   U
S   -   nXZS   -   U
S   -   nXjS	   -   U
S
   -   nU R                  R	                  S[        SXG-
  5      5      nU R                  R	                  S[        SXX-
  5      5      nU R                  R	                  S[        SXi-
  5      5      nUX-   UX-   UX-   4nUU
S.$ )a6  Calculate random crop coordinates.

Args:
    params (dict[str, Any]): Dictionary of existing parameters
    data (dict[str, Any]): Dictionary containing input data with volume, mask, etc.

Returns:
    dict[str, Any]: Dictionary containing randomly generated crop coordinates and optional padding parameters

r:   Nr   r   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   )r4   r?   r|   r:   r   r   r   r   r   r   r   r   r   r   r   s                  r-   r   )RandomCrop3D.get_params_dependent_on_data  s6    h,,r"a'+yy$H ))q	 * 

 !{++j.DDAy))J|,DDAz**Z-DDA ..((C1<,@A..((C1<,@A..((C1<,@A 
 '$
 	
r,   r   r   r   r   r   r_   s   @r-   r   r     s    7r-, - $*+/0"  (	
 -  "0
0
 0
 
	0
 0
r,   r   c                  &  ^  \ rS rSrSr\R                  \R                  \R                  4r	 " S S\
R                  5      r       S             SU 4S jjjr            SS jrSS jrSS jrSS	 jr        SS
 jrSrU =r$ )r   i%  a3
  CoarseDropout3D randomly drops out cuboid regions from a 3D volume and optionally,
the corresponding regions in an associated 3D mask, to simulate occlusion and
varied object sizes found in real-world volumetric data.

Args:
    num_holes_range (tuple[int, int]): Range (min, max) for the number of cuboid
        regions to drop out. Default: (1, 1)
    hole_depth_range (tuple[float, float]): Range (min, max) for the depth
        of dropout regions as a fraction of the volume depth (between 0 and 1). Default: (0.1, 0.2)
    hole_height_range (tuple[float, float]): Range (min, max) for the height
        of dropout regions as a fraction of the volume height (between 0 and 1). Default: (0.1, 0.2)
    hole_width_range (tuple[float, float]): Range (min, max) for the width
        of dropout regions as a fraction of the volume width (between 0 and 1). Default: (0.1, 0.2)
    fill (tuple[float, float] | float): Value for the dropped voxels. Can be:
        - int or float: all channels are filled with this value
        - tuple: tuple of values for each channel
        Default: 0
    fill_mask (tuple[float, float] | float | None): Fill value for dropout regions in the 3D mask.
        If None, mask regions corresponding to volume dropouts are unchanged. Default: None
    p (float): Probability of applying the transform. Default: 0.5

Targets:
    volume, mask3d, keypoints

Image types:
    uint8, float32

Note:
    - The actual number and size of dropout regions are randomly chosen within the specified ranges.
    - All values in hole_depth_range, hole_height_range and hole_width_range must be between 0 and 1.
    - If you want to apply dropout only in the XY plane while preserving the full depth dimension,
      consider using CoarseDropout instead. CoarseDropout will apply the same rectangular dropout
      to each slice independently, effectively creating cylindrical dropout regions that extend
      through the entire depth of the volume.

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> volume = np.random.randint(0, 256, (10, 100, 100), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (10, 100, 100), dtype=np.uint8)    # (D, H, W)
    >>> aug = A.CoarseDropout3D(
    ...     num_holes_range=(3, 6),
    ...     hole_depth_range=(0.1, 0.2),
    ...     hole_height_range=(0.1, 0.2),
    ...     hole_width_range=(0.1, 0.2),
    ...     fill=0,
    ...     p=1.0
    ... )
    >>> transformed = aug(volume=volume, mask3d=mask3d)
    >>> transformed_volume, transformed_mask3d = transformed["volume"], transformed["mask3d"]

c                      \ rS rSr% S\S'   S\S'   S\S'   S\S'   S\S	'   S
\S'   \SS j5       r\" SS9SS j5       rSr	g)CoarseDropout3D.InitSchemai]  zfAnnotated[tuple[int, int], AfterValidator(check_range_bounds(0, None)), AfterValidator(nondecreasing)]num_holes_rangezgAnnotated[tuple[float, float], AfterValidator(check_range_bounds(0, 1)), AfterValidator(nondecreasing)]hole_depth_rangehole_height_rangehole_width_ranger!   r"    tuple[float, ...] | float | Noner#   c                ^    SU S   s=::  a  U S   s=::  a  S::  d  O  [        SU SU  35      eg)a  Validate that range values are between 0 and 1 and in non-decreasing order.

Args:
    range_value (tuple[float, float]): Tuple of (min, max) values to check
    range_name (str): Name of the range for error reporting

Raises:
    ValueError: If range values are invalid

r      zAll values in z_ should be in [0, 1] range and first value should be less or equal than the second value. Got: N)rn   )range_value
range_names     r-   validate_range)CoarseDropout3D.InitSchema.validate_rangeu  sH     A=+a.=A= $ZL 1KKV-Y  >r,   r   r   c                    U R                  U R                  S5        U R                  U R                  S5        U R                  U R                  S5        U $ )Nr  r  r  )r  r  r  r  )r4   s    r-   _check_ranges(CoarseDropout3D.InitSchema._check_ranges  sL     5 57IJ 6 68KL 5 57IJKr,   r$   N)r  tuple[float, float]r  strrX   Noner   )
r&   r'   r(   r)   r*   staticmethodr  r   r  r+   r$   r,   r-   r.   r  ]  sc    
 	


 	


 	


 	

 ('33		 
	" 
g	&	 
'	r,   r.   c                h   > [         TU ]  US9  Xl        X l        X0l        X@l        XPl        X`l        g r0   )r2   r3   r  r  r  r  r"   r#   )	r4   r  r  r  r  r"   r#   r1   r5   s	           r-   r3   CoarseDropout3D.__init__  s7     	1. 0!2 0	"r,   c                6   USS u  pgn[         R                  " S[         R                  " X`R                  R                  " USU06-  5      5      R                  [        5      n	[         R                  " S[         R                  " XpR                  R                  " USU06-  5      5      R                  [        5      n
[         R                  " S[         R                  " XR                  R                  " USU06-  5      5      R                  [        5      nXU4$ )a(  Calculate dimensions for dropout holes.

Args:
    volume_shape (tuple[int, int, int]): Shape of the volume (depth, height, width)
    depth_range (tuple[float, float]): Range for hole depth as fraction of volume depth
    height_range (tuple[float, float]): Range for hole height as fraction of volume height
    width_range (tuple[float, float]): Range for hole width as fraction of volume width
    size (int): Number of holes to generate

Returns:
    tuple[np.ndarray, np.ndarray, np.ndarray]: Arrays of hole dimensions (depths, heights, widths)

Nr   r  r   )rK   maximumceilrandom_generatoruniformastyperi   )r4   volume_shapedepth_rangeheight_rangewidth_ranger   r   r   r   hole_depthshole_heightshole_widthss               r-   calculate_hole_dimensions)CoarseDropout3D.calculate_hole_dimensions  s    *  ,BQ/ujjBGGE4I4I4Q4QS^4jei4j,j$klsstwxzz!RWWV6K6K6S6SUa6mhl6m-m%novv
 jjBGGE4I4I4Q4QS^4jei4j,j$klsstwx+55r,   c                   US   R                   SS nU R                  R                  " U R                  6 nU R	                  UU R
                  U R                  U R                  US9u  pVnUSS u  pn
U R                  R                  SX-
  S-   US9nU R                  R                  SX-
  S-   US9nU R                  R                  SX-
  S-   US9nX-   nX-   nX-   n[        R                  " XXUU/SS9nS	U0$ )
a1  Generate parameters for coarse dropout based on input data.

Args:
    params (dict[str, Any]): Dictionary of existing parameters
    data (dict[str, Any]): Dictionary containing input data with volume, mask, etc.

Returns:
    dict[str, Any]: Dictionary containing generated hole parameters for dropout

r:   Nr   r   r   r  )axisholes)r   r   r   r  r-  r  r  r  r#  integersrK   stack)r4   r?   r|   r&  	num_holesr*  r+  r,  r   r   r   z_miny_minx_minz_maxy_maxx_maxr2  s                     r-   r   ,CoarseDropout3D.get_params_dependent_on_data  s1    H~++BQ/NN**D,@,@A	151O1O!!""!! 2P 2
.;  ,BQ/u%%..q%2E2IPY.Z%%..q&2G!2KR[.\%%..q%2E2IPY.Z#$#%eUC"Mr,   c                h    UR                   S:X  a  U$ [        R                  " XU R                  5      $ )a  Apply dropout to a 3D volume.

Args:
    volume (np.ndarray): Input volume with shape (depth, height, width) or (depth, height, width, channels)
    holes (np.ndarray): Array of holes with shape (num_holes, 6).
        Each hole is represented as [z1, y1, x1, z2, y2, x2]
    **params (Any): Additional parameters

Returns:
    np.ndarray: Volume with holes filled with the given value

r   )r   r=   cutout3dr"   )r4   r:   r2  r?   s       r-   r@   CoarseDropout3D.apply_to_volume  s)     ::?M||F49955r,   c                    U R                   b  UR                  S:X  a  U$ [        R                  " XU R                   5      $ )a{  Apply dropout to a 3D mask.

Args:
    mask (np.ndarray): Input mask with shape (depth, height, width) or (depth, height, width, channels)
    holes (np.ndarray): Array of holes with shape (num_holes, 6).
        Each hole is represented as [z1, y1, x1, z2, y2, x2]
    **params (Any): Additional parameters

Returns:
    np.ndarray: Mask with holes filled with the given value

r   )r#   r   r=   r>  )r4   maskr2  r?   s       r-   apply_to_maskCoarseDropout3D.apply_to_mask  s2     >>!UZZ1_K||D88r,   c                    UR                   S:X  a  U$ [        SU R                  S5      5      nUb  UR                  R                  (       d  U$ [
        R                  " X5      $ )a  Apply dropout to keypoints.

Args:
    keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+).
                           The first three columns are x, y, z coordinates.
    holes (np.ndarray): Array of holes with shape (num_holes, 6).
        Each hole is represented as [z1, y1, x1, z2, y2, x2]
    **params (Any): Additional parameters

Returns:
    np.ndarray: Filtered keypoints with same shape as input

r   r   rO   )r   r   get_processorr?   remove_invisibler=   filter_keypoints_in_holes3d)r4   rO   r2  r?   	processors        r-   rQ   "CoarseDropout3D.apply_to_keypoints  sX    & ::?-t/A/A+/NO	I$4$4$E$E..y@@r,   )r"   r#   r  r  r  r  ))r  r  g?g?rJ  rJ  r   Ng      ?)r  r   r  r  r  r  r  r  r"   r!   r#   r  r1   rU   )r&  r   r'  r  r(  r  r)  r  r   ri   rX   z)tuple[np.ndarray, np.ndarray, np.ndarray]r   )r:   rV   r2  rV   r?   r   rX   rV   )rA  rV   r2  rV   r?   r   rX   rV   )rO   rV   r2  rV   r?   r   rX   rV   )r&   r'   r(   r)   rY   r   rZ   r[   r\   r]   r   r.   r3   r-  r   r@   rB  rQ   r+   r^   r_   s   @r-   r   r   %  s"   3j 0A0ABH/[++ /f ,20:1;0:*+6:#(# .# /	#
 .# (# 4# # #$6*6 )6 *	6
 )6 6 
36>" H6$9$AA A 	A
 
A Ar,   r   c                     ^  \ rS rSrSr\R                  \R                  \R                  4r	 S S	U 4S jjjr
      S
S jrSS jrSS jrSrU =r$ )r   i#  at  Applies a random cubic symmetry transformation to a 3D volume.

This transform is a 3D extension of D4. While D4 handles the 8 symmetries
of a square (4 rotations x 2 reflections), CubicSymmetry handles all 48 symmetries of a cube.
Like D4, this transform does not create any interpolation artifacts as it only remaps voxels
from one position to another without any interpolation.

The 48 transformations consist of:
- 24 rotations (orientation-preserving):
    * 4 rotations around each face diagonal (6 face diagonals x 4 rotations = 24)
- 24 rotoreflections (orientation-reversing):
    * Reflection through a plane followed by any of the 24 rotations

For a cube, these transformations preserve:
- All face centers (6)
- All vertex positions (8)
- All edge centers (12)

works with 3D volumes and masks of the shape (D, H, W) or (D, H, W, C)

Args:
    p (float): Probability of applying the transform. Default: 1.0

Targets:
    volume, mask3d, keypoints

Image types:
    uint8, float32

Note:
    - This transform is particularly useful for data augmentation in 3D medical imaging,
      crystallography, and voxel-based 3D modeling where the object's orientation
      is arbitrary.
    - All transformations preserve the object's chirality (handedness) when using
      pure rotations (indices 0-23) and invert it when using rotoreflections
      (indices 24-47).

Examples:
    >>> import numpy as np
    >>> import albumentations as A
    >>> volume = np.random.randint(0, 256, (10, 100, 100), dtype=np.uint8)  # (D, H, W)
    >>> mask3d = np.random.randint(0, 2, (10, 100, 100), dtype=np.uint8)    # (D, H, W)
    >>> transform = A.CubicSymmetry(p=1.0)
    >>> transformed = transform(volume=volume, mask3d=mask3d)
    >>> transformed_volume = transformed["volume"]
    >>> transformed_mask3d = transformed["mask3d"]

See Also:
    - D4: The 2D version that handles the 8 symmetries of a square

c                    > [         TU ]  US9  g r0   )r2   r3   )r4   r1   r5   s     r-   r3   CubicSymmetry.__init__Z  s     	1r,   c                ^    US   R                   nU R                  R                  SS5      US.$ )a1  Generate parameters for cubic symmetry transformation.

Args:
    params (dict[str, Any]): Dictionary of existing parameters
    data (dict[str, Any]): Dictionary containing input data with volume, mask, etc.

Returns:
    dict[str, Any]: Dictionary containing the randomly selected transformation index

r:   r   /   )indexr&  )r   r   r   )r4   r?   r|   r&  s       r-   r   *CubicSymmetry.get_params_dependent_on_data`  s/      H~++//26UUr,   c                .    [         R                  " X5      $ )aU  Apply cubic symmetry transformation to a 3D volume.

Args:
    volume (np.ndarray): Input volume with shape (depth, height, width) or (depth, height, width, channels)
    index (int): Index of the transformation to apply (0-47)
    **params (Any): Additional parameters

Returns:
    np.ndarray: Transformed volume with same shape as input

)r=   transform_cube)r4   r:   rP  r?   s       r-   r@   CubicSymmetry.apply_to_volumes  s     !!&00r,   c                2    [         R                  " XUS   S9$ )a  Apply cubic symmetry transformation to keypoints.

Args:
    keypoints (np.ndarray): Array of keypoints with shape (num_keypoints, 3+).
                           The first three columns are x, y, z coordinates.
    index (int): Index of the transformation to apply (0-47)
    **params (Any): Additional parameters

Returns:
    np.ndarray: Transformed keypoints with same shape as input

r&  )r&  )r=   transform_cube_keypoints)r4   rO   rP  r?   s       r-   rQ    CubicSymmetry.apply_to_keypoints  s     ++I6R`Kabbr,   r$   r   )r1   rU   r   )r:   rV   rP  ri   r?   r   rX   rV   )rO   rV   rP  ri   r?   r   rX   rV   )r&   r'   r(   r)   rY   r   rZ   r[   r\   r]   r3   r   r@   rQ   r+   r^   r_   s   @r-   r   r   #  sr    2h 0A0ABH  VV V 
	V&1c cr,   r   )*rY   
__future__r   typingr   r   r   r   r   numpyrK   pydanticr	   r
   r   typing_extensionsr   &albumentations.augmentations.geometricr   rM   )albumentations.augmentations.transforms3dr=   #albumentations.core.keypoints_utilsr   albumentations.core.pydanticr   r   (albumentations.core.transforms_interfacer   r   $albumentations.core.type_definitionsr   __all__r{   r   r   r   r   r   r   r   r   r$   r,   r-   <module>rd     s    # 7 7  E E " K G B J Y 8
h[C [C||$I |$~F$I F$RA<{ A<H
V
# V
rA
# A
H{Ak {A|kcK kcr,   