U Ph#@sddlmZddlmZmZmZddlZddlZddl m m Z ddl mZddlmZddlmZmZmZdgZGdddeZdS) ) annotations)AnyCallableSequenceN)SlidingWindowInferer)sliding_window_inference) BlendModePytorchPadModelook_up_optionSlidingWindowHoVerNetInferercs|eZdZdZddejdejdddddddf dd d d d d d ddddddddfdd ZddZddddddddZ Z S)r a Sliding window method for HoVerNet model inference, with `sw_batch_size` windows for every model.forward(). Usage example can be found in the :py:class:`monai.inferers.Inferer` base class. Args: roi_size: the window size to execute SlidingWindow evaluation. If it has non-positive components, the corresponding `inputs` size will be used. if the components of the `roi_size` are non-positive values, the transform will use the corresponding components of img size. For example, `roi_size=(32, -1)` will be adapted to `(32, 64)` if the second spatial dimension size of img is `64`. sw_batch_size: the batch size to run window slices. overlap: Amount of overlap between scans. mode: {``"constant"``, ``"gaussian"``} How to blend output of overlapping windows. Defaults to ``"constant"``. - ``"constant``": gives equal weight to all predictions. - ``"gaussian``": gives less weight to predictions on edges of windows. sigma_scale: the standard deviation coefficient of the Gaussian window when `mode` is ``"gaussian"``. Default: 0.125. Actual window sigma is ``sigma_scale`` * ``dim_size``. When sigma_scale is a sequence of floats, the values denote sigma_scale at the corresponding spatial dimensions. padding_mode: {``"constant"``, ``"reflect"``, ``"replicate"``, ``"circular"``} Padding mode when ``roi_size`` is larger than inputs. Defaults to ``"constant"`` See also: https://pytorch.org/docs/stable/generated/torch.nn.functional.pad.html cval: fill value for 'constant' padding mode. Default: 0 sw_device: device for the window data. By default the device (and accordingly the memory) of the `inputs` is used. Normally `sw_device` should be consistent with the device where `predictor` is defined. device: device for the stitched output prediction. By default the device (and accordingly the memory) of the `inputs` is used. If for example set to device=torch.device('cpu') the gpu memory consumption is less and independent of the `inputs` and `roi_size`. Output is on the `device`. progress: whether to print a tqdm progress bar. cache_roi_weight_map: whether to pre-compute the ROI weight map. cpu_thresh: when provided, dynamically switch to stitching on cpu (to save gpu memory) when input image volume is larger than this threshold (in pixels/voxels). Otherwise use ``"device"``. Thus, the output may end-up on either cpu or gpu. extra_input_padding: the amount of padding for the input image, which is a tuple of even number of pads. Refer to to the `pad` argument of `torch.nn.functional.pad` for more details. Note: ``sw_batch_size`` denotes the max number of windows per network inference iteration, not the batch size of inputs. g?g?gNFzSequence[int] | intintfloatzBlendMode | strzSequence[float] | floatzPytorchPadMode | strztorch.device | str | Noneboolz int | Noneztuple[int] | NoneNone)roi_size sw_batch_sizeoverlapmode sigma_scale padding_modecval sw_devicedeviceprogresscache_roi_weight_map cpu_threshextra_input_paddingreturncs.tj||||||||| | | | d | |_dS)N) rrrrrrrrrrrr)super__init__r)selfrrrrrrrrrrrrr __class__Z/home/dell461/cl/sdc2/HISourceFinder-master-l/src/monai/apps/pathology/inferers/inferer.pyr Lsz%SlidingWindowHoVerNetInferer.__init__c s|jdd}|djdd}gg}t||D]H\}}t||d} | d} | | } | | g|t| || q2tj||j|j d} ||| |<t fdd|D}|| fS)Nr)dtyperc3s(|] }tj|tjjdVqdS)padrvalueN)Fr)tuplerr).0Zseg_probr!Zwindow_pad_sizer$r% }sz>SlidingWindowHoVerNetInferer.process_output..) shapezipmaxextendappendslicetorchzerosr'rr,) r!Zseg_prob_tupleZ window_dataimportance_map_ window_shape seg_shapeZwindow_pad_slicesZwindow_sZoutput_s pad_widthZ pad_half_1Z pad_half_2importance_mapr$r.r%process_outputls  z+SlidingWindowHoVerNetInferer.process_outputz torch.TensorzNCallable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]]rzAtorch.Tensor | tuple[torch.Tensor, ...] | dict[Any, torch.Tensor])inputsnetworkargskwargsrcs|j}|dkr4|jdk r4|jdd|jkr4d}|jrr|jdd}t|}tj|t|jt |j t |j d}t ||j|j||j|j|j|j |j |j||j|j|j|j|jdf||}|jrgt|jd} t| D]>} t|j| d||| d|j| d} d| qtt|j| D]} dtdq0t|trv|D]\} }||| <q\n^t|ttfrt |fdd |D}n2t|t!j"t#j$fr|}nt%d t |d |S) ag Args: inputs: model input data for inference. network: target model to execute inference. supports callables such as ``lambda x: my_torch_model(x, additional_config)`` args: optional args to be passed to ``network``. kwargs: optional keyword args to be passed to ``network``. Nr&cpur(Fr rcsg|] }|qSr$r$)r-resZ extra_slicingr$r% sz9SlidingWindowHoVerNetInferer.__call__..z The output [zC] should be either dict, list, tuple, torch.Tensor, or numpy array.)&rrr0numelrlenr+r)r,r rr rrrrrrrrrroi_weight_mapr= buffer_steps buffer_dimranger5insert isinstancedictitemslisttyper6Tensornpndarray ValueError)r!r>r?r@rArZimage_size_originalnum_spatial_dimsresultsZnum_padded_dimssp slice_dim_kvr$rDr%__call__sr*     z%SlidingWindowHoVerNetInferer.__call__) __name__ __module__ __qualname____doc__rCONSTANTr r r=r] __classcell__r$r$r"r%r s 3. ) __future__rtypingrrrnumpyrSr6torch.nn.functionalnn functionalr+monai.inferersrmonai.inferers.utilsr monai.utilsrr r __all__r r$r$r$r% s