o
    !i(                     @  s   d dl mZ d dlZd dlmZ d dlZd dlZd dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZmZmZ e ZG dd dZdS )    )annotationsN)chain)KeysCollection)
DataLoader)Dataset)
MetaTensor)affine_to_spacing)concatenate)PostFixconvert_data_typeconvert_to_tensorc                   @  s\   e Zd ZdZdddedfd,ddZdd Zd-d.ddZd/d0dd Z		!	"	#	$d1d2d*d+Z	dS )3DatasetSummarya  
    This class provides a way to calculate a reasonable output voxel spacing according to
    the input dataset. The achieved values can used to resample the input in 3d segmentation tasks
    (like using as the `pixdim` parameter in `monai.transforms.Spacingd`).
    In addition, it also supports to compute the mean, std, min and max intensities of the input,
    and these statistics are helpful for image normalization
    (as parameters of `monai.transforms.ScaleIntensityRanged` and `monai.transforms.NormalizeIntensityd`).

    The algorithm for calculation refers to:
    `Automated Design of Deep Learning Methods for Biomedical Image Segmentation <https://arxiv.org/abs/1904.08128>`_.

    imagelabelNr   datasetr   	image_key
str | None	label_keymeta_keyKeysCollection | Nonemeta_key_postfixstrnum_workersintc                 K  sB   t d|d|d|| _|| _|| _|p| d| | _g | _dS )a  
        Args:
            dataset: dataset from which to load the data.
            image_key: key name of images (default: ``image``).
            label_key: key name of labels (default: ``label``).
            meta_key: explicitly indicate the key of the corresponding metadata dictionary.
                for example, for data with key `image`, the metadata by default is in `image_meta_dict`.
                the metadata is a dictionary object which contains: filename, affine, original_shape, etc.
                if None, will try to construct meta_keys by `{image_key}_{meta_key_postfix}`.
                This is not required if `data[image_key]` is a MetaTensor.
            meta_key_postfix: use `{image_key}_{meta_key_postfix}` to fetch the metadata from dict,
                the metadata is a dictionary object (default: ``meta_dict``).
            num_workers: how many subprocesses to use for data loading.
                ``0`` means that the data will be loaded in the main process (default: ``0``).
            kwargs: other parameters (except `batch_size` and `num_workers`) for DataLoader,
                this class forces to use ``batch_size=1``.

           )r   
batch_sizer   _N )r   data_loaderr   r   r   all_meta_data)selfr   r   r   r   r   r   kwargsr   r   \/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/data/dataset_summary.py__init__-   s
   
zDatasetSummary.__init__c                 C  sh   | j D ].}i }t|| j tr|| j j}n| j|v r!|| j }n
td| j d | j	| qdS )z^
        This function is used to collect the metadata for all images of the dataset.
        z&To collect metadata for the dataset, `z` or `data.meta` must exist.N)
r   
isinstancer   r   metar   warningswarnr   append)r    data	meta_dictr   r   r"   collect_meta_dataQ   s   

z DatasetSummary.collect_meta_dataaffine         $@spacing_keyanisotropic_threshold
percentilefloatc                 C  s  t | jdkr|   || jd vrtdg }| jD ]1}t|| d ddd}|jdkr9||dd d  q|jd	krI|t|dd  qtd
t|dd}t	|t
jdd^}}t
j|dd}	t|	t|	 |krt
|	}
t
|dd|
f ||	|
< t|	}t|S )a  
        Calculate the target spacing according to all spacings.
        If the target spacing is very anisotropic,
        decrease the spacing value of the maximum axis according to percentile.
        The spacing is computed from `affine_to_spacing(data[spacing_key][0], 3)` if `data[spacing_key]` is a matrix,
        otherwise, the `data[spacing_key]` must be a vector of pixdim values.

        Args:
            spacing_key: key of the affine used to compute spacing in metadata (default: ``affine``).
            anisotropic_threshold: threshold to decide if the target spacing is anisotropic (default: ``3``).
            percentile: for anisotropic target spacing, use the percentile of all spacings of the anisotropic axis to
                replace that axis.

        r   z6The provided spacing_key is not in self.all_meta_data.FT)
track_metawrap_sequencer   Nr-      z/data[spacing_key] must be a vector or a matrix.)to_cataxis)r)   output_typer4   )r7   )lenr   r+   
ValueErrorr   ndimr(   r   r	   r   npndarraymedianmaxminargmaxr1   listtuple)r    r/   r0   r1   Zspacingsr)   Zspacing_valsZall_spacingsr   Ztarget_spacingZlargest_axisoutputr   r   r"   get_target_spacing`   s(   



z!DatasetSummary.get_target_spacingforeground_thresholdc                 C  s$  t d}t d}g g }}d}| jD ]Z}| jr(| jr(|| j || j }}	n|\}}	t|t jd^}}
t|	t jd^}	}
|t |	|k }||	 
  || 
  |t|7 }|| 7 }|t | 7 }qt	|t|| _| _|| 
 | _t || | jd  
 | _dS )a?  
        This function is used to calculate the maximum, minimum, mean and standard deviation of intensities of
        the input dataset.

        Args:
            foreground_threshold: the threshold to distinguish if a voxel belongs to foreground, this parameter
                is used to select the foreground of images for calculation. Normally, `label > 0` means the corresponding
                voxel belongs to foreground, thus if you need to calculate the statistics for whole images, you can set
                the threshold to ``-1`` (default: ``0``).

        g        r   r)   r8   r5   N)torch	as_tensorr   r   r   r   Tensorwherer(   r?   itemr@   r9   sumsquaredata_maxdata_minZ	data_meansqrtZdata_std)r    rF   Z	voxel_sumZvoxel_square_sumZ	voxel_maxZ	voxel_minZvoxel_ctr)   r   r   r   Zimage_foregroundr   r   r"   calculate_statistics   s&   



"z#DatasetSummary.calculate_statisticsT
         ?     X@sampling_flagboolintervalmin_percentilemax_percentilec                 C  s   g }| j D ]C}| jr| jr|| j || j }}	n|\}}	t|tjd^}}
t|	tjd^}	}
|t|	|k  }|rC|dd| }|| qt	t
| }t|||g\| _| _t|| _dS )a  
        This function is used to calculate the percentiles of intensities (and median) of the input dataset. To get
        the required values, all voxels need to be accumulated. To reduce the memory used, this function can be set
        to accumulate only a part of the voxels.

        Args:
            foreground_threshold: the threshold to distinguish if a voxel belongs to foreground, this parameter
                is used to select the foreground of images for calculation. Normally, `label > 0` means the corresponding
                voxel belongs to foreground, thus if you need to calculate the statistics for whole images, you can set
                the threshold to ``-1`` (default: ``0``).
            sampling_flag: whether to sample only a part of the voxels (default: ``True``).
            interval: the sampling interval for accumulating voxels (default: ``10``).
            min_percentile: minimal percentile (default: ``0.5``).
            max_percentile: maximal percentile (default: ``99.5``).

        rG   N)r   r   r   r   rH   rJ   rK   tolistr(   rB   r   r<   r1   Zdata_min_percentileZdata_max_percentiler>   Zdata_median)r    rF   rV   rX   rY   rZ   Zall_intensitiesr)   r   r   r   Zintensitiesr   r   r"   calculate_percentiles   s    
z$DatasetSummary.calculate_percentiles)r   r   r   r   r   r   r   r   r   r   r   r   )r,   r-   r.   )r/   r   r0   r   r1   r2   )r   )rF   r   )r   TrS   rT   rU   )
rF   r   rV   rW   rX   r   rY   r2   rZ   r2   )
__name__
__module____qualname____doc__DEFAULT_POST_FIXr#   r+   rE   rR   r\   r   r   r   r"   r      s"    $('r   )
__future__r   r&   	itertoolsr   numpyr<   rH   monai.configr   Zmonai.data.dataloaderr   Zmonai.data.datasetr   monai.data.meta_tensorr   monai.data.utilsr   monai.transformsr	   monai.utilsr
   r   r   r%   ra   r   r   r   r   r"   <module>   s   