o  i#@sddlmZddlmZddlmZmZddlZddl Z ddl m m Z ddlmZddlmZddlmZmZmZdgZGd ddeZdS) ) annotations)Sequence)AnyCallableN)SlidingWindowInferer)sliding_window_inference) BlendModePytorchPadModelook_up_optionSlidingWindowHoVerNetInfererc sReZdZdZddejdejdddddddf d/fd!d" Zd#d$Zd0d-d.Z Z S)1r 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?gNFroi_sizeSequence[int] | int sw_batch_sizeintoverlapfloatmodeBlendMode | str sigma_scaleSequence[float] | float padding_modePytorchPadMode | strcval sw_devicetorch.device | str | Nonedeviceprogressboolcache_roi_weight_map cpu_thresh int | Noneextra_input_paddingtuple[int] | NonereturnNonecs.tj||||||||| | | | d | |_dS)N) r rrrrrrrrrrr )super__init__r")selfr rrrrrrrrrrr r" __class__g/home/dell461/cl/sdc2/last_ska_mid/HISourceFinder-master-l/src/monai/apps/pathology/inferers/inferer.pyr'Ms z%SlidingWindowHoVerNetInferer.__init__c s|jdd}|djdd}gg}t||D]$\}}t||d} | d} | | } | | g|t| || qtj||j|j d} ||| |<t fdd|D}|| fS)Nr)dtyperc3s*|]}tj|tjjdVqdS)padrvalueN)Fr0tuplerr).0Zseg_probr(Zwindow_pad_sizer+r, ~s  z>SlidingWindowHoVerNetInferer.process_output..) shapezipmaxextendappendslicetorchzerosr.rr3) r(Zseg_prob_tupleZ window_dataimportance_map_ window_shape seg_shapeZwindow_pad_slicesZwindow_sZoutput_s pad_widthZ pad_half_1Z pad_half_2importance_mapr+r5r,process_outputms  z+SlidingWindowHoVerNetInferer.process_outputinputs torch.TensornetworkNCallable[..., torch.Tensor | Sequence[torch.Tensor] | dict[Any, torch.Tensor]]argsrkwargsAtorch.Tensor | tuple[torch.Tensor, ...] | dict[Any, torch.Tensor]cs|j}|dur|jdur|jdd|jkrd}|jr9|jdd}t|}tj|t|jt |j t |j d}t ||j|j||j|j|j|j |j |j||j|j|j|j|jdg|Ri|}|jrgt|jd} t| D]} t|j| d||| d|j| d} d| qqtt|j| D] } dtdqt|tr|D] \} }||| <q|St|ttfrt |fdd |D}|St|t!j"t#j$fr|}|St%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+)r4resZ extra_slicingr+r, sz9SlidingWindowHoVerNetInferer.__call__..z The output [zC] should be either dict, list, tuple, torch.Tensor, or numpy array.)&rr r7numelr"lenr2r0r3r rr rrr rrrrrrroi_weight_maprD buffer_steps buffer_dimranger<insert isinstancedictitemslisttyper=Tensornpndarray ValueError)r(rErGrIrJrZimage_size_originalnum_spatial_dimsresultsZnum_padded_dimssp slice_dim_kvr+rNr,__call__sx*     z%SlidingWindowHoVerNetInferer.__call__)r rrrrrrrrrrrrrrrrrrrrrr r!r"r#r$r%) rErFrGrHrIrrJrr$rK) __name__ __module__ __qualname____doc__rCONSTANTr r'rDrg __classcell__r+r+r)r,r s"3 ) __future__rcollections.abcrtypingrrnumpyr]r=torch.nn.functionalnn functionalr2monai.inferersrmonai.inferers.utilsr monai.utilsrr r __all__r r+r+r+r,s