o
     id                     @  sN  d dl m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Zd dlZd dlmZmZmZ d dlmZmZ d d	lmZ d d
lmZmZmZmZmZmZmZ d dlm Z  eddd\Z!Z"eddd\Z#Z"g dZ$G dd deZ%G dd de%Z&eddG dd de%Z'eddG dd de%Z(eddG dd de%Z)dS )    )annotationsN)abstractmethod)Sequence)abspath)Any)	DtypeLikeNdarrayOrTensorPathLike)ImageReader_stack_images)is_supported_format)WSIPatchKeysdtype_numpy_to_torchdtype_torch_to_numpyensure_tupleensure_tuple_repoptional_importrequire_pkg)ConvertUnits	openslide	OpenSlidenametifffileTiffFile)BaseWSIReader	WSIReaderCuCIMWSIReaderOpenSlideWSIReaderTiffFileWSIReaderc                      s   e Zd ZU dZg Zded< dZddddddddejdd	fdR fddZ	dd Z
d d! ZedSd$d%ZdTd-d.ZdUd/d0ZedVd1d2ZedWd3d4ZedXd5d6ZedYd8d9ZedWd:d;ZedZd@dAZd[dEdFZ	G					d\d]dKdLZd^dPdQZ  ZS )_r   a  
    An abstract class that defines APIs to load patches from whole slide image files.

    Args:
        level: the whole slide image level at which the patches are extracted.
        mpp: the resolution in micron per pixel at which the patches are extracted.
        mpp_rtol: the acceptable relative tolerance for resolution in micro per pixel.
        mpp_atol: the acceptable absolute tolerance for resolution in micro per pixel.
        power: the objective power at which the patches are extracted.
        power_rtol: the acceptable relative tolerance for objective power.
        power_atol: the acceptable absolute tolerance for objective power.
        channel_dim: the desired dimension for color channel.
        dtype: the data type of output image.
        device: target device to put the extracted patch. Note that if device is "cuda"",
            the output will be converted to torch tenor and sent to the gpu even if the dtype is numpy.
        mode: the output image color mode, e.g., "RGB" or "RGBA".
        kwargs: additional args for the reader

        Notes:
            Only one of resolution parameters, `level`, `mpp`, or `power`, should be provided.
            If such parameters are provided in `get_data` method, those will override the values provided here.
            If none of them are provided here or in `get_data`, `level=0` will be used.

    Typical usage of a concrete implementation of this class is:

    .. code-block:: python

        image_reader = MyWSIReader()
        wsi = image_reader.read(filepath, **kwargs)
        img_data, meta_data = image_reader.get_data(wsi)

    - The `read` call converts an image filename into whole slide image object,
    - The `get_data` call fetches the image data, as well as metadata.

    The following methods needs to be implemented for any concrete implementation of this class:

    - `read` reads a whole slide image object from a given file
    - `get_size` returns the size of the whole slide image of a given wsi object at a given level.
    - `get_level_count` returns the number of levels in the whole slide image
    - `_get_patch` extracts and returns a patch image form the whole slide image
    - `_get_metadata` extracts and returns metadata for a whole slide image and a specific patch.


    z	list[str]supported_suffixes N皙?        r   RGBlevel
int | Nonempp"float | tuple[float, float] | Nonempp_rtolfloatmpp_atolpower
power_rtol
power_atolchannel_dimintdtypeDtypeLike | torch.dtypedevicetorch.device | str | Nonemodestrc                   sv   t    || _|| _| |	 | |
 || _|| _|d ur$t|dnd | _	|| _
|| _|| _|| _|| _i | _d S )N   )super__init__r%   r/   	set_dtype
set_devicer5   kwargsr   r'   r,   r)   r+   r-   r.   metadata)selfr%   r'   r)   r+   r,   r-   r.   r/   r1   r3   r5   r<   	__class__ W/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/data/wsi_reader.pyr9   \   s   



zBaseWSIReader.__init__c                 C  s*   |  t |tjr|| _d S t|| _d S )N)
isinstancetorchr1   np)r>   r1   rA   rA   rB   r:   z   s   
zBaseWSIReader.set_dtypec                 C  s6   |d u st |tjtfr|| _d S tdt| d)Nz5`device` must be `torch.device`, `str` or `None` but z
 is given.)rC   rD   r3   r6   
ValueErrortype)r>   r3   rA   rA   rB   r;      s   
zBaseWSIReader.set_devicereturntuple[int, int]c                 C     t d| jj d)
        Returns the size (height, width) of the whole slide image at a given level.

        Args:
            wsi: a whole slide image object loaded from a file.
            level: the level number where the size is calculated.

        	Subclass  must implement this method.NotImplementedErrorr@   __name__r>   wsir%   rA   rA   rB   get_size      
zBaseWSIReader.get_sizer   valuetuplevalue_at_levelsSequence[tuple]atolrtolc                   s    |v r	|  S t| fddd}tt D ]<}t||  |  ||t |   krUtd| d  d| d| d| d	| d
| d| d| d| d| dq| |S )a  Find the level corresponding to the value of the quantity in the list of values at each level.
        Args:
            name: the name of the requested quantity
            value: the value of requested quantity
            value_at_levels: list of value of the quantity at each level
            atol: the tolerance for the value
            rtol: relative tolerance for the value
        c                   s   t dd t|  D S )Nc                 S  s   g | ]
\}}t || qS rA   )abs).0xyrA   rA   rB   
<listcomp>       zGBaseWSIReader._find_closest_level.<locals>.<lambda>.<locals>.<listcomp>)sumzip)a_valuerU   rA   rB   <lambda>       z3BaseWSIReader._find_closest_level.<locals>.<lambda>keyzThe requested z < z2 > does not exist in this whole slide image (with z_rtol=z and z_atol=z!). Here is the list of available z: z!. The closest matching available z is z8.Please consider changing the tolerances or use another .)indexminrangelenr[   rF   )r>   r   rU   rW   rY   rZ   Zclosest_valueirA   rd   rB   _find_closest_level   s8   
(
z!BaseWSIReader._find_closest_levelc                   s(  |du r|du r|du r j } j} j}dd d|fd|fd|ffD }t|dkr3td| d	 }|durZt|d
} fddt|D } d|| j	 j
}|S |dur{t|}	 fddt|D }
 d|	|
 j j}|S |du rd}||krtd|d  d| d|S )a4  
        Returns the level associated to the resolution parameters in the whole slide image.

        Args:
            wsi: a whole slide image object loaded from a file.
            level: the level number.
            mpp: the micron-per-pixel resolution.
            power: the objective power.

        Nc                 S  s    g | ]}|d  dur|d qS )   Nr   rA   )r\   valrA   rA   rB   r_      s     z1BaseWSIReader.get_valid_level.<locals>.<listcomp>r%   r'   r,   rp   z;Only one of `level`, `mpp`, or `power` should be provided. z are provided.r7   c                   s   g | ]}  |qS rA   )get_mppr\   r%   r>   rR   rA   rB   r_      rf   c                   s   g | ]	}  |fqS rA   )	get_powerrs   rt   rA   rB   r_      s    r   z#The maximum level of this image is z while level=z is requested)!)r'   r,   r%   rm   rF   get_level_countr   rl   ro   r+   r)   r   r.   r-   )r>   rR   r%   r'   r,   
resolutionn_levelsmpp_Zavailable_mppsZpower_Zavailable_powersrA   rt   rB   get_valid_level   s.    

zBaseWSIReader.get_valid_levelc                 C  rJ   )
        Returns the number of levels in the whole slide image.

        Args:
            wsi: a whole slide image object loaded from a file.

        rL   rM   rN   rt   rA   rA   rB   rv      s   	zBaseWSIReader.get_level_countc                 C  rJ   )
        Returns the down-sampling ratio of the whole slide image at a given level.

        Args:
            wsi: a whole slide image object loaded from a file.
            level: the level number where the downsample ratio is calculated.

        rL   rM   rN   rQ   rA   rA   rB   get_downsample_ratio   rT   z"BaseWSIReader.get_downsample_ratioc                 C  rJ   )'Return the file path for the WSI objectrL   rM   rN   rt   rA   rA   rB   get_file_path   s   zBaseWSIReader.get_file_pathtuple[float, float]c                 C  rJ   )
        Returns the micro-per-pixel resolution of the whole slide image at a given level.

        Args:
            wsi: a whole slide image object loaded from a file.
            level: the level number where the mpp is calculated.

        rL   rM   rN   rQ   rA   rA   rB   rr      rT   zBaseWSIReader.get_mppc                 C  rJ   )
        Returns the objective power of the whole slide image at a given level.

        Args:
            wsi: a whole slide image object loaded from a file.
            level: the level number where the objective power is calculated.

        rL   rM   rN   rQ   rA   rA   rB   ru     rT   zBaseWSIReader.get_powerlocationsizer   
np.ndarrayc                 C  rJ   )i  
        Extracts and returns a patch image form the whole slide image.

        Args:
            wsi: a whole slide image object loaded from a file or a lis of such objects
            location: (top, left) tuple giving the top left pixel in the level 0 reference frame. Defaults to (0, 0).
            size: (height, width) tuple giving the patch size at the given level (`level`).
                If None, it is set to the full image size at the given level.
            level: the level number.
            dtype: the data type of output image.
            mode: the output image mode, 'RGB' or 'RGBA'.

        rL   rM   rN   r>   rR   r   r   r%   r1   r5   rA   rA   rB   
_get_patch  s   zBaseWSIReader._get_patchpatchr   dictc                 C  s   | j t|jks| j t|j k rtd| j  d|j | j | j dk r)t|jnd }d| jd|dt|jd| |j|d d  tjj	dtj
j	| |tjj	t|tjj	t|tjj	|i}|S )	a4  
        Returns metadata of the extracted patch from the whole slide image.

        Args:
            wsi: the whole slide image object, from which the patch is loaded.
            patch: extracted patch from whole slide image.
            location: (top, left) tuple giving the top left pixel in the level 0 reference frame. Defaults to (0, 0).
            size: (height, width) tuple giving the patch size at the given level (`level`).
                If None, it is set to the full image size at the given level.
            level: the level number.

        zThe desired channel_dim (z#) is out of bound for image shape: r   backendoriginal_channel_dimspatial_shapeNrp   )r/   rm   shaperF   r   rE   arrayr   COUNTrU   PATHr   LOCATIONasarraySIZELEVEL)r>   rR   r   r   r   r%   r/   r=   rA   rA   rB   _get_metadata   s   "&
zBaseWSIReader._get_metadatar   r   tuple[int, int] | None
str | Nonetuple[np.ndarray, dict]c              	     s  |du r| j }g }g }	t|ttfs|f}t|D ]}
| |
|||}|du r*d}| |
d}|d |d ks@|d |d krJtd| d| |du r]|dkrVtd| |
|}n|d dksi|d dkrptd| t| jt	jr|t
| jn| j}| j|
|||||d	}t| jt	js| jdurt	| jjd
krt| jt	jst| jn| j}|jd rt	j||| jd}n	t	j||| jd}|jdkrtd|j d|dkr|j| j dkrtd| d|j| j  dn|dv r|j| j dkrtd| d|j| j  d| j|
||||d}|| |	| qt|dkrZtdd |	D dkr9tdtdd |	D dkrItdtD ]  fdd|	D | < qKt|||fS ) a;  
        Verifies inputs, extracts patches from WSI image and generates metadata.

        Args:
            wsi: a whole slide image object loaded from a file or a list of such objects.
            location: (top, left) tuple giving the top left pixel in the level 0 reference frame. Defaults to (0, 0).
            size: (height, width) tuple giving the patch size at the given level (`level`).
                If not provided or None, it is set to the full image size at the given level.
            level: the whole slide image level at which the patches are extracted.
            mpp: the resolution in micron per pixel at which the patches are extracted.
            power: the objective power at which the patches are extracted.
            dtype: the data type of output image.
            mode: the output image mode, 'RGB' or 'RGBA'.

        Returns:
            a tuples, where the first element is an image patch [CxHxW] or stack of patches,
                and second element is a dictionary of metadata.

        Notes:
            Only one of resolution parameters, `level`, `mpp`, or `power`, should be provided.
            If none of them are provided, it uses the defaults that are set during class instantiation.
            If none of them are set here or during class instantiation, `level=0` will be used.
        Nr   r   rp   z+Location is outside of the image: location=z, image size=z0Patch size should be defined to extract patches.z?Patch size should be greater than zero, provided: patch size = )r   r   r%   r1   r5   cuda	WRITEABLE)r1   r3      z(The image dimension should be 3 but has zI. `WSIReader` is designed to work only with 2D images with color channel.RGBA   z6The image is expected to have four color channels in '' mode but has ri   r$   z7The image is expected to have three color channels in '. )rR   r   r   r   r%   c                 S  s   h | ]}|d  qS )r   rA   r\   mrA   rA   rB   	<setcomp>      z)BaseWSIReader.get_data.<locals>.<setcomp>z:original_channel_dim is not consistent across wsi objects.c                 S  s   h | ]}t |d  qS )r   )rV   r   rA   rA   rB   r     rf   z3spatial_shape is not consistent across wsi objects.c                   s   g | ]}|  qS rA   rA   r   rg   rA   rB   r_     r   z*BaseWSIReader.get_data.<locals>.<listcomp>)r5   rC   listrV   r   rz   rS   rF   r1   rD   r   r   r3   rG   r   flags	as_tensortensorndimr   r/   r   appendrm   r   r   )r>   rR   r   r   r%   r'   r,   r5   
patch_listmetadata_listZeach_wsiwsi_sizedtype_npr   Zdtype_torchr=   rA   rg   rB   get_data@  sr   ! 




zBaseWSIReader.get_datafilenameSequence[PathLike] | PathLikeboolc                 C  s   t || jS )z
        Verify whether the specified file or files format is supported by WSI reader.

        The list of supported suffixes are read from `self.supported_suffixes`.

        Args:
            filename: filename or a list of filenames to read.

        )r   r    )r>   r   rA   rA   rB   verify_suffix  s   
zBaseWSIReader.verify_suffixr%   r&   r'   r(   r)   r*   r+   r*   r,   r&   r-   r*   r.   r*   r/   r0   r1   r2   r3   r4   r5   r6   r%   r0   rH   rI   )r   r6   rU   rV   rW   rX   rY   r*   rZ   r*   rH   r0   )r%   r&   r'   r(   r,   r&   rH   r0   rH   r0   r%   r0   rH   r*   rH   r6   r%   r0   rH   r   r   rI   r   rI   r%   r0   r1   r   r5   r6   rH   r   )
r   r   r   rI   r   rI   r%   r0   rH   r   )r   NNNNN)r   rI   r   r   r%   r&   r'   r(   r,   r&   r5   r   rH   r   )r   r   rH   r   )rP   
__module____qualname____doc__r    __annotations__r   rE   uint8r9   r:   r;   r   rS   ro   rz   rv   r}   r   rr   ru   r   r   r   r   __classcell__rA   rA   r?   rB   r   +   sV   
 -

,

#rr   c                   @  s   e Zd ZdZg dZdddddddddejddfd6ddZd7ddZd8d!d"Z	d9d#d$Z
d:d%d&Zd;d(d)Zd9d*d+Zd<d0d1Zd=d4d5ZdS )>r   a}  
    Read whole slide images and extract patches using different backend libraries

    Args:
        backend: the name of backend whole slide image reader library, the default is cuCIM.
        level: the whole slide image level at which the patches are extracted.
        mpp: the resolution in micron per pixel at which the patches are extracted.
        mpp_rtol: the acceptable relative tolerance for resolution in micro per pixel.
        mpp_atol: the acceptable absolute tolerance for resolution in micro per pixel.
        power: the objective power at which the patches are extracted.
        power_rtol: the acceptable relative tolerance for objective power.
        power_atol: the acceptable absolute tolerance for objective power.
        channel_dim: the desired dimension for color channel. Default to 0 (channel first).
        dtype: the data type of output image. Defaults to `np.uint8`.
        device: target device to put the extracted patch. Note that if device is "cuda"",
            the output will be converted to torch tenor and sent to the gpu even if the dtype is numpy.
        mode: the output image color mode, "RGB" or "RGBA". Defaults to "RGB".
        num_workers: number of workers for multi-thread image loading (cucim backend only).
        kwargs: additional arguments to be passed to the backend library

        Notes:
            Only one of resolution parameters, `level`, `mpp`, or `power`, should be provided.
            If such parameters are provided in `get_data` method, those will override the values provided here.
            If none of them are provided here or in `get_data`, `level=0` will be used.

    )cucimr   r   r   Nr"   r#   r   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   c                 K  sL  |  | _|  | jdkr!td||||||||	|
||d|| _n=| jdkr;td||||||||	|
||d|| _n#| jdkrUtd||||||||	|
||d|| _n	td| j d| jj| _| jj| _| jj	| _	| jj
| _
| jj| _| jj| _| jj| _| jj| _| jj| _| jj| _| jj| _| jj| _| jj| _| jj| _d S )Nr   )r%   r'   r)   r+   r,   r-   r.   r/   r1   r3   r5   r   r   z?The supported backends are cucim, openslide, and tifffile but 'z' was given.rA   )lowerr   r   readerr   r   rF   r    r%   r)   r+   r,   r-   r.   r/   r1   r3   r5   r<   r=   r'   )r>   r   r%   r'   r)   r+   r,   r-   r.   r/   r1   r3   r5   r<   rA   rA   rB   r9     s   



















zWSIReader.__init__rH   c                 C     | j |S r{   )r   rv   rt   rA   rA   rB   rv   /  s   zWSIReader.get_level_countrI   c                 C     | j ||S rK   )r   rS   rQ   rA   rA   rB   rS   9     	zWSIReader.get_sizec                 C  r   r|   )r   r}   rQ   rA   rA   rB   r}   D  r   zWSIReader.get_downsample_ratioc                 C  r   r~   )r   r   rt   rA   rA   rB   r   O  s   zWSIReader.get_file_pathr   c                 C  r   )r   )r   rr   rQ   rA   rA   rB   rr   S  r   zWSIReader.get_mppc                 C  r   )a   
        Returns the micro-per-pixel resolution of the whole slide image at a given level.

        Args:
            wsi: a whole slide image object loaded from a file.
            level: the level number where the objective power is calculated.

        )r   ru   rQ   rA   rA   rB   ru   ^  r   zWSIReader.get_powerr   r   r   r   c                 C  s   | j j||||||dS )ai  
        Extracts and returns a patch image form the whole slide image.

        Args:
            wsi: a whole slide image object loaded from a file or a lis of such objects.
            location: (top, left) tuple giving the top left pixel in the level 0 reference frame. Defaults to (0, 0).
            size: (height, width) tuple giving the patch size at the given level (`level`).
                If None, it is set to the full image size at the given level.
            level: the level number.
            dtype: the data type of output image
            mode: the output image mode, 'RGB' or 'RGBA'.

        )rR   r   r   r%   r1   r5   )r   r   r   rA   rA   rB   r   i  s   zWSIReader._get_patchdata*Sequence[PathLike] | PathLike | np.ndarrayc                 K  s   | j jdd|i|S )aV  
        Read whole slide image objects from given file or list of files.

        Args:
            data: file name or a list of file names to read.
            kwargs: additional args for the reader module (overrides `self.kwargs` for existing keys).

        Returns:
            whole slide image object or list of such objects.

        r   NrA   )r   read)r>   r   r<   rA   rA   rB   r   {  s   zWSIReader.readr   r   r   r   r   r   r   r   r   )rP   r   r   r   supported_backendsrE   r   r9   rv   rS   r}   r   rr   ru   r   r   rA   rA   rA   rB   r     s0    
R






r   r   )pkg_namec                      s   e Zd ZdZg dZdZd'd( fddZed)d
dZd*ddZ	d+ddZ
ed,ddZd-ddZd+ddZd.ddZd/d%d&Z  ZS )0r   aE  
    Read whole slide images and extract patches using cuCIM library.

    Args:
        level: the whole slide image level at which the patches are extracted.
        mpp: the resolution in micron per pixel at which the patches are extracted.
        mpp_rtol: the acceptable relative tolerance for resolution in micro per pixel.
        mpp_atol: the acceptable absolute tolerance for resolution in micro per pixel.
        power: the objective power at which the patches are extracted.
        power_rtol: the acceptable relative tolerance for objective power.
        power_atol: the acceptable absolute tolerance for objective power.
        channel_dim: the desired dimension for color channel. Default to 0 (channel first).
        dtype: the data type of output image. Defaults to `np.uint8`.
        device: target device to put the extracted patch. Note that if device is "cuda"",
            the output will be converted to torch tenor and sent to the gpu even if the dtype is numpy.
        mode: the output image color mode, "RGB" or "RGBA". Defaults to "RGB".
        num_workers: number of workers for multi-thread image loading.
        kwargs: additional args for `cucim.CuImage` module:
            https://github.com/rapidsai/cucim/blob/main/cpp/include/cucim/cuimage.h

        Notes:
            Only one of resolution parameters, `level`, `mpp`, or `power`, should be provided.
            If such parameters are provided in `get_data` method, those will override the values provided here.
            If none of them are provided here or in `get_data`, `level=0` will be used.

    tiftiffZsvsr   r   num_workersr0   c                   s   t  jdi | || _d S NrA   )r8   r9   r   )r>   r   r<   r?   rA   rB   r9     s   
zCuCIMWSIReader.__init__rH   c                 C  s
   | j d S )r{   level_countresolutionsrR   rA   rA   rB   rv        
	zCuCIMWSIReader.get_level_countr%   rI   c                 C  s$   |j d | d |j d | d fS )rK   level_dimensionsrp   r   r   rQ   rA   rA   rB   rS     s   $	zCuCIMWSIReader.get_sizer*   c                 C  s   t |jd | S )r|   level_downsamples)r*   r   rQ   rA   rA   rB   r}     s   	z#CuCIMWSIReader.get_downsample_ratior6   c                 C     t t| jS r   )r6   r   pathr   rA   rA   rB   r        zCuCIMWSIReader.get_file_pathr   c                 C  s   |  ||}d|jv r|jd d}|r|t| fd S d|jv rL|jd d}|rLt|trLt|dkrL|d rL|d rL||d  ||d  fS td)	r   aperioZMPPr7   r   spacingr   rp   C`mpp` cannot be obtained for this file. Please use `level` instead.)r}   r=   getr*   rC   r   rm   rF   )r>   rR   r%   downsample_ratiory   rA   rA   rB   rr     s   	

zCuCIMWSIReader.get_mppc                 C  s>   d|j v r|j d d}|r| ||}t|| S td)r   r   ZAppMagzCurrently, cuCIM backend can obtain the objective power only for Aperio images. Please use `level` (or `mpp`) instead, or try OpenSlide backend.)r=   r   r}   r*   rF   r>   rR   r%   Zobjective_powerr   rA   rA   rB   ru     s   
	zCuCIMWSIReader.get_powerr   r   c           
      K  sl   t ddd\}}g }t|}| j }|| |D ]}||fi |}	||	 qt|dkr2|S |d S )a  
        Read whole slide image objects from given file or list of files.

        Args:
            data: file name or a list of file names to read.
            kwargs: additional args that overrides `self.kwargs` for existing keys.
                For more details look at https://github.com/rapidsai/cucim/blob/main/cpp/include/cucim/cuimage.h

        Returns:
            whole slide image object or list of such objects.

        r   ZCuImager   rp   r   )r   r   r<   copyupdater   rm   )
r>   r   r<   Zcuimage_cls_wsi_list	filenameskwargs_r   rR   rA   rA   rB   r     s   

zCuCIMWSIReader.readr   r   r1   r   r5   r   c                 C  s   |j |ddd |ddd || jd}tj||d}t|d| j}|dv rH|j| j dvr>td| d|j| j  d	t|g d
| j}|S )aj  
        Extracts and returns a patch image form the whole slide image.

        Args:
            wsi: a whole slide image object loaded from a file or a lis of such objects.
            location: (top, left) tuple giving the top left pixel in the level 0 reference frame. Defaults to (0, 0).
            size: (height, width) tuple giving the patch size at the given level (`level`).
                If None, it is set to the full image size at the given level.
            level: the level number.
            dtype: the data type of output image.
            mode: the output image mode, 'RGB' or 'RGBA'.

        N)r   r   r%   r   r1   r$   r   r   ?The image is expected to have three or four color channels in 'r   r   r   rp   r7   )	read_regionr   rE   r   moveaxisr/   r   rF   take)r>   rR   r   r   r%   r1   r5   r   rA   rA   rB   r     s   
zCuCIMWSIReader._get_patch)r   )r   r0   r   r   r   r   r   r   r   rP   r   r   r   r    r   r9   staticmethodrv   rS   r}   r   rr   ru   r   r   r   rA   rA   r?   rB   r     s    





r   c                         e Zd ZdZg dZdZ fddZed%dd	Zd&ddZ	d'ddZ
ed(ddZd)ddZd'ddZd*ddZd+d#d$Z  ZS ),r   a  
    Read whole slide images and extract patches using OpenSlide library.

    Args:
        level: the whole slide image level at which the patches are extracted.
        mpp: the resolution in micron per pixel at which the patches are extracted.
        mpp_rtol: the acceptable relative tolerance for resolution in micro per pixel.
        mpp_atol: the acceptable absolute tolerance for resolution in micro per pixel.
        power: the objective power at which the patches are extracted.
        power_rtol: the acceptable relative tolerance for objective power.
        power_atol: the acceptable absolute tolerance for objective power.
        channel_dim: the desired dimension for color channel. Default to 0 (channel first).
        dtype: the data type of output image. Defaults to `np.uint8`.
        device: target device to put the extracted patch. Note that if device is "cuda"",
            the output will be converted to torch tenor and sent to the gpu even if the dtype is numpy.
        mode: the output image color mode, "RGB" or "RGBA". Defaults to "RGB".
        kwargs: additional args for `openslide.OpenSlide` module.

        Notes:
            Only one of resolution parameters, `level`, `mpp`, or `power`, should be provided.
            If such parameters are provided in `get_data` method, those will override the values provided here.
            If none of them are provided here or in `get_data`, `level=0` will be used.

    r   r   c                      t  jdi | d S r   r8   r9   r>   r<   r?   rA   rB   r9   ^     zOpenSlideWSIReader.__init__rH   r0   c                 C  s   | j S r   )r   r   rA   rA   rB   rv   a  s   	z"OpenSlideWSIReader.get_level_countr%   rI   c                 C  s   |j | d |j | d fS )rK   rp   r   )r   rQ   rA   rA   rB   rS   l  s   	zOpenSlideWSIReader.get_sizer*   c                 C  s
   |j | S r   )r   rQ   rA   rA   rB   r}   w  r   z'OpenSlideWSIReader.get_downsample_ratior6   c                 C  r   r   )r6   r   	_filenamer   rA   rA   rB   r     r   z OpenSlideWSIReader.get_file_pathr   c                 C  s   |  ||}d|jv r,d|jv r,|jd r,|jd r,|t|jd  |t|jd  fS d|jv rld|jv rl|jd rl|jd rl|jd}|du rQtd d}t|d}||t|jd  ||t|jd  fS td	)
r   zopenslide.mpp-xzopenslide.mpp-yztiff.XResolutionztiff.YResolutionztiff.ResolutionUnitNzEThe resolution unit is missing, `micrometer` will be used as default.
micrometerr   )r}   
propertiesr*   r   warningswarnr   rF   )r>   rR   r%   r   unitconvert_to_micronrA   rA   rB   rr     s2   	





zOpenSlideWSIReader.get_mppc                 C  s0   |j d}|r| ||}t|| S td)r   zopenslide.objective-powerzZObjective `power` cannot be obtained for this file. Please use `level` (or `mpp`) instead.)r   r   r}   r*   rF   r   rA   rA   rB   ru     s
   	zOpenSlideWSIReader.get_powerr   r   c                 K  \   g }t |}| j }|| |D ]}t|fi |}|| qt|dkr*|S |d S aC  
        Read whole slide image objects from given file or list of files.

        Args:
            data: file name or a list of file names to read.
            kwargs: additional args that overrides `self.kwargs` for existing keys.

        Returns:
            whole slide image object or list of such objects.

        rp   r   )r   r<   r   r   r   r   rm   r>   r   r<   r   r   r   r   rR   rA   rA   rB   r        

zOpenSlideWSIReader.readr   r   r1   r   r5   r   c           	      C  sP   |j |ddd |ddd |d}||}tj||d}t|d| j}|S )r   Nr   )r   r   r%   r   )r   convertrE   r   r   r/   )	r>   rR   r   r   r%   r1   r5   Z	pil_patchr   rA   rA   rB   r     s
   $
zOpenSlideWSIReader._get_patchr   r   r   r   r   r   r   r   rA   rA   r?   rB   r   @  s    




(
r   c                      r   ),r   a  
    Read whole slide images and extract patches using TiffFile library.

    Args:
        level: the whole slide image level at which the patches are extracted.
        mpp: the resolution in micron per pixel at which the patches are extracted.
        mpp_rtol: the acceptable relative tolerance for resolution in micro per pixel.
        mpp_atol: the acceptable absolute tolerance for resolution in micro per pixel.
        channel_dim: the desired dimension for color channel. Default to 0 (channel first).
        dtype: the data type of output image. Defaults to `np.uint8`.
        device: target device to put the extracted patch. Note that if device is "cuda"",
            the output will be converted to torch tenor and sent to the gpu even if the dtype is numpy.
        mode: the output image color mode, "RGB" or "RGBA". Defaults to "RGB".
        kwargs: additional args for `tifffile.TiffFile` module.

        Notes:
            - Objective power cannot be obtained via TiffFile backend.
            - Only one of resolution parameters, `level` or `mpp`, should be provided.
                If such parameters are provided in `get_data` method, those will override the values provided here.
                If none of them are provided here or in `get_data`, `level=0` will be used.

    r   r   c                   r   r   r   r   r?   rA   rB   r9     r   zTiffFileWSIReader.__init__rH   r0   c                 C  s
   t | jS r   )rm   pagesr   rA   rA   rB   rv     r   z!TiffFileWSIReader.get_level_countr%   rI   c                 C  s   |j | j|j | jfS r   )r  imagelengthZ
imagewidthrQ   rA   rA   rB   rS      s   	zTiffFileWSIReader.get_sizer*   c                 C  s    t |jd jt |j| j S )r|   r   )r*   r  r	  rQ   rA   rA   rB   r}   +  s    	z&TiffFileWSIReader.get_downsample_ratior6   c                 C  s   t t| jjS r   )r6   r   Z
filehandler   r   rA   rA   rB   r   6  s   zTiffFileWSIReader.get_file_pathr   c                 C  s   d|j | jv rqd|j | jv rq|j | jd jrq|j | jd jrq|j | jd}|dur5t|jj}|du s?t|dkrFtd d}t	|d}|j | jd j}|j | jd j}||d |d  ||d |d  fS t
d	)
r   XResolutionYResolutionResolutionUnitNr   zEThe resolution unit is missing. `micrometer` will be used as default.r   rp   zD`mpp`  cannot be obtained for this file. Please use `level` instead.)r  tagsrU   r   r6   r   rm   r   r   r   rF   )r>   rR   r%   r  r  ZyresZxresrA   rA   rB   rr   ;  s"   


(zTiffFileWSIReader.get_mppc                 C  s   t d)r   zCurrently, TiffFile does not provide a general API to obtain objective power.Please use `level` (or `mpp`) instead, or try other backends.)rF   rQ   rA   rA   rB   ru   Y  s   	zTiffFileWSIReader.get_powerr   r   c                 K  r  r  )r   r<   r   r   r   r   rm   r  rA   rA   rB   r   g  r  zTiffFileWSIReader.readr   r   r1   r   r5   r   c           
        s   |j |d|}t|jdk r|d }| j||d  fddttD }||d |d |d  |d |d |d  d	d	f }	t|	d
| j}	|dv rs|	j| j dvrit	d| d|	j| j  dt
|	g d| j}	|	S )r   )r%   r   ).N)rR   r%   c                   s   g | ]
}t |   qS rA   )round)r\   rn   Zdownsampling_ratior   rA   rB   r_     r`   z0TiffFileWSIReader._get_patch.<locals>.<listcomp>r   rp   Nr   r$   r   r   r   r   r   )r   astyperm   r   r}   rl   rE   r   r/   rF   r   )
r>   rR   r   r   r%   r1   r5   Z	wsi_imageZ	location_r   rA   r  rB   r   ~  s    :
zTiffFileWSIReader._get_patchr   r   r   r   r   r   r   r   rA   rA   r?   rB   r     s    





r   )*
__future__r   r   abcr   collections.abcr   os.pathr   typingr   numpyrE   rD   monai.configr   r   r	   monai.data.image_readerr
   r   monai.data.utilsr   monai.utilsr   r   r   r   r   r   r   monai.utils.miscr   r   r   r   __all__r   r   r   r   r   rA   rA   rA   rB   <module>   s<   $	    L 6 6