U Phjf @sddlmZddlZddlmZddlmZmZddlm Z ddl m Z ddl Z ddl mmZddlmZddlmZmZmZmZdd lmZd d lmZGd d d eZGdddeZGdddeZGdddeZGdddeZ dddddddZ!GdddeZ"GdddeZ#ddd d!dd"d#d$Z$d%e"j%d&d'fdddd d!d(d)d(d(d*d+ d,d-Z&Gd.d/d/eZ'd%e"j%d0d1d&d'd2fdddd(d)d3d4d(d(d!dd5 d6d7Z(dS)8) annotationsN)abstractmethod)CallableSequence)partial)Any)do_metric_reduction)MetricReductionStrEnumconvert_data_typeensure_tuple_rep)convert_to_dst_type)CumulativeIterationMetriccs~eZdZdZejdfddddfdd Zdd d d d dZddddddZe ddddddZ ddddddZ Z S)RegressionMetrica Base class for regression metrics. Input `y_pred` is compared with ground truth `y`. Both `y_pred` and `y` are expected to be real-valued, where `y_pred` is output from a regression model. `y_preds` and `y` can be a list of channel-first Tensor (CHW[D]) or a batch-first Tensor (BCHW[D]). Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. Args: reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). Here `not_nans` count the number of not nans for the metric, thus its shape equals to the shape of the metric. FMetricReduction | strboolNone reduction get_not_nansreturncst||_||_dSN)super__init__rrselfrr __class__M/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/metrics/regression.pyr0s zRegressionMetric.__init__NzMetricReduction | str | Nonez0torch.Tensor | tuple[torch.Tensor, torch.Tensor])rrcCsB|}t|tjstdt||p(|j\}}|jr>||fS|S)ao Args: reduction: define mode of reduction to the metrics, will only apply reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to `self.reduction`. if "none", will not do reduction. z-the data to aggregate must be PyTorch Tensor.) get_buffer isinstancetorchTensor ValueErrorrrr)rrdatafnot_nansrrr aggregate5s  zRegressionMetric.aggregate torch.Tensory_predyrcCs@|j|jkr&td|jd|jdt|jdkrrArrrr rszRMSEMetric.__init__r*r+cCst|||jd}t|SrD)rGrCr#sqrtrr,r-Zmse_outrrr r6szRMSEMetric._compute_metricrHrrrr rMsrMcsFeZdZdZejdfdddddfdd Zd d d d d dZZS) PSNRMetrica_Compute Peak Signal To Noise Ratio between two tensors using function: .. math:: \operatorname{PSNR}\left(Y, \hat{Y}\right) = 20 \cdot \log_{10} \left({\mathit{MAX}}_Y\right) \ -10 \cdot \log_{10}\left(\operatorname{MSE\left(Y, \hat{Y}\right)}\right) More info: https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio Help taken from: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/image_ops_impl.py line 4139 Input `y_pred` is compared with ground truth `y`. Both `y_pred` and `y` are expected to be real-valued, where `y_pred` is output from a regression model. Example of the typical execution steps of this metric class follows :py:class:`monai.metrics.metric.Cumulative`. Args: max_val: The dynamic range of the images/volumes (i.e., the difference between the maximum and the minimum allowed values e.g. 255 for a uint8 image). reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction. get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans). Fz int | floatrrr)max_valrrrcs*tj||d||_ttjdd|_dSr>)rrrQrr#rBrC)rrQrrrrr rszPSNRMetric.__init__r*rr+cCs.t|||jd}dt|jdt|S)NrE )rGrCmathlog10rQr#rOrrr r6szPSNRMetric._compute_metricrHrrrr rPs rPr*r)r,r-rFrcCs*ttjdd}tj||||dddS)Nr) start_dimT)dimkeepdim)rr#flattenmean)r,r-rFfltrrr rGsrGc@seZdZdZdZdS) KernelTypegaussianuniformN)r5r8r9GAUSSIANUNIFORMrrrr r]sr]c s`eZdZdZdejddddejdfdd d d d d d d ddd fdd ZddddddZ Z S) SSIMMetrica Computes the Structural Similarity Index Measure (SSIM). .. math:: \operatorname {SSIM}(x,y) =\frac {(2 \mu_x \mu_y + c_1)(2 \sigma_{xy} + c_2)}{((\mu_x^2 + \ \mu_y^2 + c_1)(\sigma_x^2 + \sigma_y^2 + c_2)} For more info, visit https://vicuesoft.com/glossary/term/ssim-ms-ssim/ SSIM reference paper: Wang, Zhou, et al. "Image quality assessment: from error visibility to structural similarity." IEEE transactions on image processing 13.4 (2004): 600-612. Args: spatial_dims: number of spatial dimensions of the input images. data_range: value range of input images. (usually 1.0 or 255) kernel_type: type of kernel, can be "gaussian" or "uniform". win_size: window size of kernel kernel_sigma: standard deviation for Gaussian kernel. k1: stability constant used in the luminance denominator k2: stability constant used in the contrast denominator reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans) ? ?{Gz?Q?FintfloatKernelType | strint | Sequence[int]float | Sequence[float]rrr) spatial_dims data_range kernel_typewin_size kernel_sigmak1k2rrrc sftj|| d||_||_||_t|ts6t||}||_t|tsPt||}||_ ||_ ||_ dSrJ) rrrmrnror"rr kernel_sizerqrrrs) rrmrnrorprqrrrsrrrrr rs     zSSIMMetric.__init__r*r+c Cs|}|jdkr2|dkr2td|jd|d|jdkr\|dkr\td|jd|dt|||j|j|j|j|j|j|j d \}}| |j d d j d d d}|S)aR Args: y_pred: Predicted image. It must be a 2D or 3D batch-first tensor [B,C,H,W] or [B,C,H,W,D]. y: Reference image. It must be a 2D or 3D batch-first tensor [B,C,H,W] or [B,C,H,W,D]. Raises: ValueError: when `y_pred` is not a 2D or 3D image. r/Ky_pred should have 4 dimensions (batch, channel, height, width) when using  spatial dimensions, got .zRy_pred should have 5 dimensions (batch, channel, height, width, depth) when using r,r-rmrnrortrqrrrsrrWrTrY) ndimensionrmr%compute_ssim_and_csrnrortrqrrrsviewr0r[)rr,r-dimsssim_value_full_image_Zssim_per_batchrrr r6s2  zSSIMMetric._compute_metric r5r8r9r:r]r`r r;rr6r<rrrr rbs&rbrhz Sequence[int]Sequence[float])rm num_channelsrtrqrc Csdddddd}||d|d}||d|d}t||}|d|d|df}|d kr||d |d d } t|d dd|d | |d|d|d }|d|d|d|d f}||S) aComputes 2D or 3D gaussian kernel. Args: spatial_dims: number of spatial dimensions of the input images. num_channels: number of channels in the image kernel_size: size of kernel kernel_sigma: standard deviation for Gaussian kernel. rhrir*)rtsigmarcSsPtjd|dd|ddd}tt||d d}||jddS)zComputes 1D gaussian kernel. Args: kernel_size: size of the gaussian kernel sigma: Standard deviation of the gaussian kernel rr/)startendsteprrX)r#arangeexprBsum unsqueeze)rtrdistgaussrrr gaussian_1dUs z%_gaussian_kernel..gaussian_1drrryr/rrW)r#matmultmulrrepeatexpand) rmrrtrqrZgaussian_kernel_xZgaussian_kernel_ykernelZkernel_dimensionsZgaussian_kernel_zrrr _gaussian_kernelIs  rrcrfrgrirjz!tuple[torch.Tensor, torch.Tensor]) r,r-rmrtrqrnrorrrsrc Cs|j|jkr&td|jd|jdt|tjtjdd}t|tjtjdd}|d} |tjkrvt || ||} n,|tj krt | df|t t |} t| |dd} ||d} ||d} ttd |d } | || | d }| || | d }| ||| | d }| ||| | d }| ||| | d }|||}|||}|||}d|| ||| }d||| |d|d| |}||fS) a Function to compute the Structural Similarity Index Measure (SSIM) and Contrast Sensitivity (CS) for a batch of images. Args: y_pred: batch of predicted images with shape (batch_size, channels, spatial_dim1, spatial_dim2[, spatial_dim3]) y: batch of target images with shape (batch_size, channels, spatial_dim1, spatial_dim2[, spatial_dim3]) kernel_size: the size of the kernel to use for the SSIM computation. kernel_sigma: the standard deviation of the kernel to use for the SSIM computation. spatial_dims: number of spatial dimensions of the images (2, 3) data_range: the data range of the images. kernel_type: the type of kernel to use for the SSIM computation. Can be either "gaussian" or "uniform". k1: the first stability constant. k2: the second stability constant. Returns: ssim: the Structural Similarity Index Measure score for the batch of images. cs: the Contrast Sensitivity for the batch of images. z*y_pred and y should have same shapes, got z and rx) output_typedtyperr)srcdstr/convd)groups)r0r%r r#r$risizer]r`rraonesprodtensorr getattrF)r,r-rmrtrqrnrorrrsrrc1c2Zconv_fnmu_xmu_yZmu_xxZmu_yyZmu_xysigma_xsigma_yZsigma_xyZcontrast_sensitivityrrrr r~qs0    "     (r~c sdeZdZdZdejdddddejdf d d d d d d d ddddd fdd ZddddddZ Z S)MultiScaleSSIMMetricaL Computes the Multi-Scale Structural Similarity Index Measure (MS-SSIM). MS-SSIM reference paper: Wang, Z., Simoncelli, E.P. and Bovik, A.C., 2003, November. "Multiscale structural similarity for image quality assessment." In The Thirty-Seventh Asilomar Conference on Signals, Systems & Computers, 2003 (Vol. 2, pp. 1398-1402). IEEE Args: spatial_dims: number of spatial dimensions of the input images. data_range: value range of input images. (usually 1.0 or 255) kernel_type: type of kernel, can be "gaussian" or "uniform". kernel_size: size of kernel kernel_sigma: standard deviation for Gaussian kernel. k1: stability constant used in the luminance denominator k2: stability constant used in the contrast denominator weights: parameters for image similarity and contrast sensitivity at different resolution scores. reduction: define the mode to reduce metrics, will only execute reduction on `not-nan` values, available reduction modes: {``"none"``, ``"mean"``, ``"sum"``, ``"mean_batch"``, ``"sum_batch"``, ``"mean_channel"``, ``"sum_channel"``}, default to ``"mean"``. if "none", will not do reduction get_not_nans: whether to return the `not_nans` count, if True, aggregate() returns (metric, not_nans) rcrdrerfrggǺ?g48EG?ga4?g??g9EGr?Frhrirjrkrlrrrr) rmrnrortrqrrrsweightsrrrc sltj| | d||_||_||_t|ts6t||}||_t|tsPt||}||_ ||_ ||_ ||_ dSrJ) rrrmrnror"rr rtrqrrrsr) rrmrnrortrqrrrsrrrrrr rs     zMultiScaleSSIMMetric.__init__r*r+c Cs,t|||j|j|j|j|j|j|j|jd S)N) r,r-rmrnrortrqrrrsr) compute_ms_ssimrmrnrortrqrrrsrr2rrr r6sz$MultiScaleSSIMMetric._compute_metricrrrrr rs(rrdrerrkrl) r,r-rmrnrortrqrrrsrrc  Cs|} |dkr.| dkr.td|d| d|dkrT| dkrTtd|d| dt|tsht||}t|ts|t||}td t| d d} |jdd } tt| D]L} | | | || d krtd t| d || d || d | dqt j | |j t j d}t td|d}g}tt|D]d}t|||||||||d \}}||jddd }|t |||dd}||dd}q0||jddd }t ||d<t |}t j||dd dd}||jddjd dd}|S)aQ Args: y_pred: Predicted image. It must be a 2D or 3D batch-first tensor [B,C,H,W] or [B,C,H,W,D]. y: Reference image. It must be a 2D or 3D batch-first tensor [B,C,H,W] or [B,C,H,W,D]. spatial_dims: number of spatial dimensions of the input images. data_range: value range of input images. (usually 1.0 or 255) kernel_type: type of kernel, can be "gaussian" or "uniform". kernel_size: size of kernel kernel_sigma: standard deviation for Gaussian kernel. k1: stability constant used in the luminance denominator k2: stability constant used in the contrast denominator weights: parameters for image similarity and contrast sensitivity at different resolution scores. Raises: ValueError: when `y_pred` is not a 2D or 3D image. r/rurvrwrxryrzzRy_pred should have 4 dimensions (batch, channel, height, width, depth) when using rNz+For a given number of `weights` parameters z and kernel size z', the image height must be larger than )deviceravg_poolrr{rrW)rtrTr|)r}r%r"rr maxr1r0ranger#rrrirrr~rr[appendrelustackr)r,r-rmrnrortrqrrrsrrZ weights_divZy_pred_spatial_dimsiweights_tensorrZmultiscale_listrZssimcsZ cs_per_batchZmultiscale_list_tensorZms_ssim_value_full_imageZms_ssim_per_batchrrr rs`    *   r)) __future__rrTabcrcollections.abcrr functoolsrtypingrr#torch.nn.functionalnn functionalrmonai.metrics.utilsr monai.utilsr r r r monai.utils.type_conversionr metricrrr=rIrMrPrGr]rbrr`r~rrrrrr  sD       :'e."AJ