o  ijf@shddlmZddlZddlmZddlmZmZddlm Z ddl m Z ddl Z ddl mmZddlmZddlmZmZmZmZdd lmZd d lmZGd d d eZGdddeZGdddeZGdddeZGdddeZ dAddZ!GdddeZ"Gd d!d!eZ#dBd)d*Z$d+e"j%d,d-fdCd5d6Z&Gd7d8d8eZ'd+e"j%d9d:d,d-d;fdDd?d@Z(dS)E) annotationsN)abstractmethod)CallableSequence)partial)Any)do_metric_reduction)MetricReductionStrEnumconvert_data_typeensure_tuple_rep)convert_to_dst_type)CumulativeIterationMetriccsZeZdZdZejdfdfd d Z ddddZdddZe dddZ dddZ 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. F reductionMetricReduction | str get_not_nansboolreturnNonecst||_||_dSN)super__init__rrselfrr __class__Z/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/metrics/regression.pyr0s  zRegressionMetric.__init__NMetricReduction | str | None0torch.Tensor | tuple[torch.Tensor, torch.Tensor]cCsB|}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.aggregatey_pred torch.TensorycCs@|j|jkrtd|jd|jdt|jdkrtddS)Nz2y_pred and y shapes dont match, received y_pred: [z ] and y: []zIeither channel or spatial dimensions required, found only batch dimension)shaper&lenrr+r-rrr _check_shapeEs zRegressionMetric._check_shapecCstd|jjd)Nz Subclass z must implement this method.)NotImplementedErrorr__name__r2rrr_compute_metricMsz RegressionMetric._compute_metriccCs8t|tjr t|tjstd||||||S)Nz$y_pred and y must be PyTorch Tensor.)r#r$r%r&r3r6r2rrr_compute_tensorQs  z RegressionMetric._compute_tensorrrrrrrr)rr rr!)r+r,r-r,rrr+r,r-r,rr,) r5 __module__ __qualname____doc__r MEANrr*r3rr6r7 __classcell__rrrrrs  rc4eZdZdZejdfdfd d ZdddZZS) MSEMetricaCompute Mean Squared Error between two tensors using function: .. math:: \operatorname {MSE}\left(Y, \hat{Y}\right) =\frac {1}{n}\sum _{i=1}^{n}\left(y_i-\hat{y_i} \right)^{2}. More info: https://en.wikipedia.org/wiki/Mean_squared_error 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: 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). Frrrrrrc$tj||dttjdd|_dSNrrg@)exponentrrrr$powsq_funcrrrrrmzMSEMetric.__init__r+r,r-cCt|||jdSNfunc)compute_mean_error_metricsrGr2rrrr6qzMSEMetric._compute_metricr8r9 r5r:r;r<r r=rr6r>rrrrr@Xr@cr?) MAEMetricaCompute Mean Absolute Error between two tensors using function: .. math:: \operatorname {MAE}\left(Y, \hat{Y}\right) =\frac {1}{n}\sum _{i=1}^{n}\left|y_i-\hat{y_i}\right|. More info: https://en.wikipedia.org/wiki/Mean_absolute_error 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: 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). Frrrrrrcstj||dtj|_dSNrC)rrr$absabs_funcrrrrrs zMAEMetric.__init__r+r,r-cCrIrJ)rMrTr2rrrr6rNzMAEMetric._compute_metricr8r9rOrrrrrQurPrQcr?) RMSEMetrica/Compute Root Mean Squared Error between two tensors using function: .. math:: \operatorname {RMSE}\left(Y, \hat{Y}\right) ={ \sqrt{ \frac {1}{n}\sum _{i=1}^{n}\left(y_i-\hat{y_i}\right)^2 } } \ = \sqrt {\operatorname{MSE}\left(Y, \hat{Y}\right)}. More info: https://en.wikipedia.org/wiki/Root-mean-square_deviation 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: 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). FrrrrrrcrArBrErrrrrrHzRMSEMetric.__init__r+r,r-cCst|||jd}t|SrJ)rMrGr$sqrtrr+r-Zmse_outrrrr6s zRMSEMetric._compute_metricr8r9rOrrrrrUsrUcs4eZdZdZejdfdfd d ZdddZZS) 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). Fmax_val int | floatrrrrrrcs*tj||d||_ttjdd|_dSrB)rrrYrr$rFrG)rrYrrrrrrszPSNRMetric.__init__r+r,r-rcCs.t|||jd}dt|jdt|S)NrK )rMrGmathlog10rYr$rWrrrr6szPSNRMetric._compute_metric)rYrZrrrrrr)r+r,r-r,rrrOrrrrrXs rXr+r,r-rLrrcCs*ttjdd}tj||||dddS)Nr) start_dimT)dimkeepdim)rr$flattenmean)r+r-rLfltrrrrMsrMc@seZdZdZdZdS) KernelTypegaussianuniformN)r5r:r;GAUSSIANUNIFORMrrrrrfsrfcsBeZdZdZdejddddejdfd!fdd Zd"dd Z 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?F spatial_dimsint data_rangefloat kernel_typeKernelType | strwin_sizeint | Sequence[int] kernel_sigmafloat | Sequence[float]k1k2rrrrrrc sftj|| d||_||_||_t|tst||}||_t|ts(t||}||_ ||_ ||_ dSrR) rrrqrsrur#rr kernel_sizeryr{r|) rrqrsrurwryr{r|rrrrrrs      zSSIMMetric.__init__r+r,r-c Cs|}|jdkr|dkrtd|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-rqrsrur}ryr{r|rr`rTrb) ndimensionrqr&compute_ssim_and_csrsrur}ryr{r|viewr0rd)rr+r-dimsssim_value_full_image_Zssim_per_batchrrrr6s8     zSSIMMetric._compute_metric)rqrrrsrtrurvrwrxryrzr{rtr|rtrrrrrrr9 r5r:r;r<rfrir r=rr6r>rrrrrksrkrqrr num_channelsr} Sequence[int]rySequence[float]c Csddd}||d |d }||d |d }t||}|d |d |d f}|d kr`||d |d d } t|dd d |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. r}rrsigmartrr,cSsPtjd|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/)startendsteprra)r$arangeexprFsum unsqueeze)r}rdistgaussrrr gaussian_1dUs z%_gaussian_kernel..gaussian_1drrrr/rr`N)r}rrrrtrr,)r$matmultmulrrepeatexpand) rqrr}ryrZgaussian_kernel_xZgaussian_kernel_ykernelZkernel_dimensionsZgaussian_kernel_zrrr_gaussian_kernelIs   rrlrorprsrtrurvr{r|!tuple[torch.Tensor, torch.Tensor]c Cs|j|jkrtd|jd|jdt|tjtjdd}t|tjtjdd}|d} |tjkr;t || ||} n|tj krRt | dg|Rt 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 r) output_typedtyperr)srcdstr/convd)groups)r0r&r r$r%rtsizerfrirrjonesprodtensorr getattrF)r+r-rqr}ryrsrur{r|rrc1c2conv_fnmu_xmu_yZmu_xxZmu_yyZmu_xysigma_xsigma_yZsigma_xyZcontrast_sensitivityrrrrrqs0    $     (rc sDeZdZdZdejdddddejdf d$fdd Zd%d"d#Z 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) rlrmrnrorpgǺ?g48EG?ga4?g??g9EGr?Frqrrrsrtrurvr}rxryrzr{r|weightsrrrrrrrc sltj| | d||_||_||_t|tst||}||_t|ts(t||}||_ ||_ ||_ ||_ dSrR) rrrqrsrur#rr r}ryr{r|r) rrqrsrur}ryr{r|rrrrrrrs      zMultiScaleSSIMMetric.__init__r+r,r-c Cs,t|||j|j|j|j|j|j|j|jd S)N) r+r-rqrsrur}ryr{r|r) compute_ms_ssimrqrsrur}ryr{r|rr2rrrr6sz$MultiScaleSSIMMetric._compute_metric)rqrrrsrtrurvr}rxryrzr{rtr|rtrrrrrrrrr9rrrrrrsrrmrnrrxrzrc  Cs|} |dkr| dkrtd|d| d|dkr*| dkr*td|d| dt|ts4t||}t|ts>t||}td t| d d} |jdd } tt| D]&} | | | || d kr|td t| d || d || d | dqVt j | |j t j d}t td|d}g}tt|D]1}t|||||||||d \}}||jddd }|t |||dd}||dd}q||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/r~rrrrrzRy_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_poolrrrr`)r}rTr)rr&r#rr maxr1r0ranger$rrrtrrrrrdappendrelustackr)r+r-rqrsrur}ryr{r|rrZ weights_divZy_pred_spatial_dimsiweights_tensorrZmultiscale_listrZssimcsZ cs_per_batchZmultiscale_list_tensorZms_ssim_value_full_imageZms_ssim_per_batchrrrrsp         r)r+r,r-r,rLrrr,) rqrrrrrr}rryrrr,)r+r,r-r,rqrrr}rryrrsrtrurvr{rtr|rtrr)r+r,r-r,rqrrrsrtrurvr}rxryrzr{rtr|rtrrrr,)) __future__rr]abcrcollections.abcrr functoolsrtypingrr$torch.nn.functionalnn functionalrmonai.metrics.utilsr monai.utilsr r r r monai.utils.type_conversionr metricrrr@rQrUrXrMrfrkrrirrrrrrrsF       : ' e. AJ