<tool id="ip_superdsm" name="Perform segmentation using deformable shape models" version="@TOOL_VERSION@+galaxy@VERSION_SUFFIX@" profile="20.05">
    <description>with SuperDSM</description>
    <macros>
        <import>creators.xml</import>
        <import>tests.xml</import>
        <token name="@TOOL_VERSION@">0.2.0</token>
        <token name="@VERSION_SUFFIX@">2</token>
    </macros>
    <creator>
        <expand macro="creators/bmcv"/>
    </creator>
    <edam_operations>
        <edam_operation>operation_3443</edam_operation>
    </edam_operations>
    <xrefs>
        <xref type="bio.tools">superdsm</xref>
        <xref type="biii">superdsm</xref>
    </xrefs>
    <requirements>

        <requirement type="package" version="@TOOL_VERSION@">superdsm</requirement>
        <requirement type="package" version="0.1.1">giatools</requirement>

        <!--
        Pin the dependencies to specific versions for reproducibility:
        https://github.com/BMCV/SuperDSM#dependency-version-considerations
        -->
        <requirement type="package" version="1.20">numpy</requirement>
        <requirement type="package" version="1.6.3">scipy</requirement>
        <requirement type="package" version="0.18.1">scikit-image</requirement>
        <requirement type="package" version="1.2.6">cvxopt</requirement>
        <requirement type="package" version="1.1.13">cvxpy</requirement>
        <requirement type="package" version="1.6.0">ray-core</requirement>

        <!--
        2020.0 is the last version of MKL which supports the "MKL_DEBUG_CPU_TYPE" environment variable.
        -->
        <requirement type="package" version="2020.0">mkl</requirement>

        <!--
        Using MKL instead of other BLAS can significantly improve performance on some hardware:
        https://stackoverflow.com/questions/62783262/why-is-numpy-with-ryzen-threadripper-so-much-slower-than-xeon

        Pinning BLAS to version 1.0 is required for reproducibility:
        https://github.com/BMCV/SuperDSM#dependency-version-considerations
        -->
        <requirement type="package" version="1.0=mkl">blas</requirement>

    </requirements>
    <command detect_errors="aggressive">
    <![CDATA[
    python '$__tool_directory__/run-superdsm.py'
    '${dataset}'
    \${GALAXY_SLOTS:-4}
    #if 'masks' in $outputs:
        --do-masks 'masks.png'
    #end if
    #if 'cfg' in $outputs:
        --do-cfg 'cfg.tsv'
    #end if
    #if 'overlay' in $outputs:
        --do-overlay 'overlay.png'
        #if $seg_border.value % 2 == 1:
            #set $seg_border = "%d" % ($seg_border.value + 1)
            --do-overlay-border $seg_border
        #else:
            --do-overlay-border $seg_border
        #end if
    #end if
    #if str($config.AF_scale) != '':
        --AF_scale '${config.AF_scale}'
    #end if
    #if str($config.c2f_region_analysis_min_atom_radius) != '':
        --c2f_region_analysis_min_atom_radius '${config.c2f_region_analysis_min_atom_radius}'
    #end if
    #if str($config.c2f_region_analysis_min_norm_energy_improvement) != '':
        --c2f_region_analysis_min_norm_energy_improvement '${config.c2f_region_analysis_min_norm_energy_improvement}'
    #end if
    #if str($config.c2f_region_analysis_max_atom_norm_energy) != '':
        --c2f_region_analysis_max_atom_norm_energy '${config.c2f_region_analysis_max_atom_norm_energy}'
    #end if
    #if str($config.c2f_region_analysis_max_cluster_marker_irregularity) != '':
        --c2f_region_analysis_max_cluster_marker_irregularity '${config.c2f_region_analysis_max_cluster_marker_irregularity}'
    #end if
    #if str($config.dsm_alpha) != '':
        --dsm_alpha '${config.dsm_alpha}'
    #end if
    #if str($config.dsm_AF_alpha) != '':
        --dsm_AF_alpha '${config.dsm_AF_alpha}'
    #end if
    --global_energy_minimization_pruning '${global_energy_minimization_pruning}'
    #if str($config.global_energy_minimization_beta) != '':
        --global_energy_minimization_beta '${config.global_energy_minimization_beta}'
    #end if
    #if str($config.global_energy_minimization_AF_beta) != '':
        --global_energy_minimization_AF_beta '${config.global_energy_minimization_AF_beta}'
    #end if
    #if str($config.postprocess_mask_max_distance) != '':
        --postprocess_mask_max_distance '${config.postprocess_mask_max_distance}'
    #end if
    #if str($config.postprocess_mask_stdamp) != '':
        --postprocess_mask_stdamp '${config.postprocess_mask_stdamp}'
    #end if
    #if str($config.postprocess_max_norm_energy) != '':
        --postprocess_max_norm_energy '${config.postprocess_max_norm_energy}'
    #end if
    #if str($config.postprocess_min_contrast) != '':
        --postprocess_min_contrast '${config.postprocess_min_contrast}'
    #end if
    #if str($config.postprocess_min_object_radius) != '':
        --postprocess_min_object_radius '${config.postprocess_min_object_radius}'
    #end if
    ]]>
    </command>
    <environment_variables>

        <!--
        This enables accelerated CPU instruction sets on AMD hardware, does nothing in Intel hardware, thus no need to change this:
        -->
        <environment_variable name="MKL_DEBUG_CPU_TYPE">5</environment_variable>

    </environment_variables>
    <inputs>
        <param name="dataset" type="data" format="tiff,png" label="Dataset" />
        <param argument="--global_energy_minimization_pruning" type="select" label="Graph pruning for global energy minimization" help="Exact graph pruning corresponds to the original algorithm, which provably yields globally optimal results. Robust graph pruning is more greedy and has a provably bounded approximation error. Depending on the data, this can be significantly faster than exact graph pruning, without degrading the segmentation or cluster splitting performance.">
            <option value="exact">Exact graph pruning (Kostrykin and Rohr, TPAMI 2023)</option>
            <option value="isbi24" selected="true">Robust graph pruning (Kostrykin and Rohr, ISBI 2024)</option>
        </param>
        <param name="outputs" type="select" label="Tool outputs" multiple="true" optional="false" help="Note that if neither a segmentation overlay nor a label map is created, segmentation and cluster splitting will not be performed. As a consequence, hyperparameters which are determined automatically during segmentation and cluster splitting will not be reported, even if &quot;Report all hyperparameters&quot; is selected.">
            <option value="overlay" selected="true">Create a segmentation overlay</option>
            <option value="masks">Create a label map (e.g., for further processing)</option>
            <option value="cfg">Report all hyperparameters (manually set and automatically determined values)</option>
        </param>
        <param name="seg_border" type="integer" min="1" value="8" label="Width of the outlines (in pixels)" help="This parameter is only used for segmentation overlays (see above)." />
        <section name="config" title="Hyperparameters" expanded="false">
            <param argument="--AF_scale" optional="true" type="float" value="" min="0" label="scale σ" help="The scale of the objects to be segmented. Leave empty to use the automatically determined value." />
            <param argument="--c2f_region_analysis_min_atom_radius" optional="true" type="float" value="" min="0" label="min_atom_radius" help="No region determined by the Coarse-to-fine region analysis scheme is smaller than a circle of this radius (in terms of the surface area). Leave empty to use the automatically determined value." />
            <param argument="--c2f_region_analysis_min_norm_energy_improvement" type="float" value="0.1" min="0" label="min_norm_energy_improvement" help="Each split performed during the computation of the atomic image regions must improve the normalized energy 𝑟(𝜔) of an image region 𝜔 by at least this factor. Given that an image region is split into the sub-regions 𝜔₁, 𝜔₂, the improvement of the split is defined by the fraction max{𝑟(𝜔)₁, 𝑟(𝜔₂)} / 𝑟(𝜔₁ ∪ 𝜔₂). Lower values of the fraction correspond to better improvements." />
            <param argument="--c2f_region_analysis_max_atom_norm_energy" type="float" value="0.05" min="0" label="max_norm_energy1" help="No atomic image region 𝜔 determined by the Coarse-to-fine region analysis has a normalized energy 𝑟(𝜔) smaller than this value." />
            <param argument="--c2f_region_analysis_max_cluster_marker_irregularity" type="float" value="0.2" min="0" label="max_pa_ratio" help="Threshold for the “irregularity” of image regions. Image regions with an “irregularity” higher than this value are masked as “empty” image regions and discarded from further considerations." />
            <param argument="--dsm_alpha" type="float" value="" optional="true" min="0" label="regularization of the deformations 𝛼" help="Governs the regularization of the deformations. Increasing this value leads to a smoother segmentation result. Leave empty to use the automatically determined value." />
            <param argument="--dsm_AF_alpha" type="float" value="0.0005" min="0" label="factor used for automatic computation of 𝛼" />
            <param argument="--global_energy_minimization_beta" type="float" value="" optional="true" min="0" label="sparsity 𝛽" help="Increasing this value leads to a sparser segmentation result. Leave empty to use the automatically determined value." />
            <param argument="--global_energy_minimization_AF_beta" type="float" value="0.66" min="0" label="factor used for automatic computation of 𝛽" />
            <param argument="--postprocess_mask_max_distance" type="integer" value="1" min="0" label="mask_max_distance" help="Image points within this maximum distance of the boundary of the original segmentation mask are subject to refinement in post-processing. Image points further away from the boundary are neither added to nor removed from the segmentation mask." />
            <param argument="--postprocess_mask_stdamp" type="float" value="2" min="0" label="mask_stdamp" help="An image point adjacent to the boundary of the original segmentation mask is added to the segmentation mask in post-processing, if its Gaussian-smoothed intensity is sufficiently similar to the mean intensity of the mask. The image point is removed otherwise. The lower the value set, the stricter the similarity must be." />
            <param argument="--postprocess_max_norm_energy" type="float" value="0.2" label="max_norm_energy2" help="Objects with a normalized energy larger than this value are discarded in post-processing." />
            <param argument="--postprocess_min_contrast" type="float" value="1.35" label="min_contrast" help="A segmented object is discarded in post-processing, if the contrast as defined above is below this threshold." />
            <param argument="--postprocess_min_object_radius" type="float" value="0" label="min_object_radius" help="Objects smaller than a circle of this radius are discarded in post-processing (in terms of the surface area)." />
        </section>
    </inputs>
    <outputs>
        <data format="png" name="masks" from_work_dir="masks.png" label="${tool.name} on ${on_string}: masks">
            <filter>'masks' in outputs</filter>
        </data>
        <data format="tsv" name="cfg" from_work_dir="cfg.tsv" label="${tool.name} on ${on_string}: cfg">
            <filter>'cfg' in outputs</filter>
        </data>
        <data format="png" name="overlay" from_work_dir="overlay.png" label="${tool.name} on ${on_string}: overlay">
            <filter>'overlay' in outputs</filter>
        </data>
    </outputs>
    <tests>
        <test expect_num_outputs="3">
            <param name="dataset" value="BBBC033_C2_z28.png" />
            <param name="global_energy_minimization_pruning" value="exact" />
            <param name="outputs" value="overlay,masks,cfg" />
            <expand macro="tests/intensity_image_diff" name="overlay" value="overlay.png" ftype="png"/>
            <output name="cfg" value="cfg-full.tsv" ftype="tsv" compare="diff" />
            <output name="masks" ftype="png">
                <assert_contents>

                    <has_image_width width="1024"/>
                    <has_image_height height="1344"/>
                    <has_image_channels channels="1"/>
                    <has_image_n_labels n="16"/><!-- 15 objects plus the background -->

                </assert_contents>
            </output>
        </test>
        <test expect_num_outputs="1">
            <param name="dataset" value="BBBC033_C2_z28.png" />
            <param name="global_energy_minimization_pruning" value="exact" />
            <param name="outputs" value="cfg" />
            <output name="cfg" value="cfg.tsv" ftype="tsv" compare="diff" />
        </test>
    </tests>
    <help>

        **Performs segmentation of 2-D fluorescence microscopy images using deformable shape models and superadditivity.**

        SuperDSM is a globally optimal method for cell nuclei segmentation using deformable shape models and their inherent law of superadditivity.

        You can either use an individual input image (PNG, TIFF) or a collection of such images.

    </help>
    <citations>
        <citation type="bibtex">
        @inproceedings{kostrykin2024,
          author = {Kostrykin, L. and Rohr, K.},
          title = {Robust Graph Pruning for Efficient Segmentation and Cluster Splitting of Cell Nuclei using Deformable Shape Models},
          booktitle = {Proc. IEEE International Symposium on Biomedical Imaging (ISBI'24)},
          pages = {accepted for presentation},
          year = {2024},
        }
        </citation>
        <citation type="doi">10.1109/TPAMI.2022.3185583</citation>
    </citations>
</tool>
