# This file was auto generated by Styx.
# Do not edit this file directly.

import typing
import pathlib
from styxdefs import *

VOLUME_FIND_CLUSTERS_METADATA = Metadata(
    id="80ccd8653d75a12acc8bcc204d1a6379b0a31cfe.workbench",
    name="volume-find-clusters",
    package="workbench",
    container_image_tag="nx10x/workbench:2.1.0",
)


_VolumeFindClustersParamsDictNoTag = typing.TypedDict('_VolumeFindClustersParamsDictNoTag', {
    "volume-in": InputPathType,
    "value-threshold": float,
    "minimum-volume": float,
    "volume-out": str,
    "startval": typing.NotRequired[int | None],
    "distance": typing.NotRequired[float | None],
    "ratio": typing.NotRequired[float | None],
    "subvol": typing.NotRequired[str | None],
    "roi-volume": typing.NotRequired[InputPathType | None],
    "less-than": bool,
})
VolumeFindClustersParamsDictTagged = typing.TypedDict('VolumeFindClustersParamsDictTagged', {
    "@type": typing.Literal["workbench/volume-find-clusters"],
    "volume-in": InputPathType,
    "value-threshold": float,
    "minimum-volume": float,
    "volume-out": str,
    "startval": typing.NotRequired[int | None],
    "distance": typing.NotRequired[float | None],
    "ratio": typing.NotRequired[float | None],
    "subvol": typing.NotRequired[str | None],
    "roi-volume": typing.NotRequired[InputPathType | None],
    "less-than": bool,
})
VolumeFindClustersParamsDict = _VolumeFindClustersParamsDictNoTag | VolumeFindClustersParamsDictTagged


class VolumeFindClustersOutputs(typing.NamedTuple):
    """
    Output object returned when calling `VolumeFindClustersParamsDict(...)`.
    """
    root: OutputPathType
    """Output root folder. This is the root folder for all outputs."""
    volume_out: OutputPathType
    """the output volume"""


def volume_find_clusters_params(
    volume_in: InputPathType,
    value_threshold: float,
    minimum_volume: float,
    volume_out: str,
    startval: int | None = None,
    distance: float | None = None,
    ratio: float | None = None,
    subvol: str | None = None,
    roi_volume: InputPathType | None = None,
    less_than: bool = False,
) -> VolumeFindClustersParamsDictTagged:
    """
    Build parameters.
    
    Args:
        volume_in: the input volume.
        value_threshold: threshold for data values.
        minimum_volume: threshold for cluster volume, in mm^3.
        volume_out: the output volume.
        startval: start labeling clusters from a value other than 1\
            \
            the value to give the first cluster found.
        distance: ignore clusters further than a given distance from the\
            largest cluster\
            \
            how far from the largest cluster a cluster can be, edge to edge, in\
            mm.
        ratio: ignore clusters smaller than a given fraction of the largest\
            cluster in map\
            \
            fraction of the largest cluster's volume.
        subvol: select a single subvolume\
            \
            the subvolume number or name.
        roi_volume: select a region of interest\
            \
            the roi, as a volume file.
        less_than: find values less than <value-threshold>, rather than greater.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "workbench/volume-find-clusters",
        "volume-in": volume_in,
        "value-threshold": value_threshold,
        "minimum-volume": minimum_volume,
        "volume-out": volume_out,
        "less-than": less_than,
    }
    if startval is not None:
        params["startval"] = startval
    if distance is not None:
        params["distance"] = distance
    if ratio is not None:
        params["ratio"] = ratio
    if subvol is not None:
        params["subvol"] = subvol
    if roi_volume is not None:
        params["roi-volume"] = roi_volume
    return params


def volume_find_clusters_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `VolumeFindClustersParamsDict` object.
    
    Args:
        params: The parameters object to validate.
    """
    if params is None or not isinstance(params, dict):
        raise StyxValidationError(f'Params object has the wrong type \'{type(params)}\'')
    if params.get("volume-in", None) is None:
        raise StyxValidationError("`volume-in` must not be None")
    if not isinstance(params["volume-in"], (pathlib.Path, str)):
        raise StyxValidationError(f'`volume-in` has the wrong type: Received `{type(params.get("volume-in", None))}` expected `InputPathType`')
    if params.get("value-threshold", None) is None:
        raise StyxValidationError("`value-threshold` must not be None")
    if not isinstance(params["value-threshold"], (float, int)):
        raise StyxValidationError(f'`value-threshold` has the wrong type: Received `{type(params.get("value-threshold", None))}` expected `float`')
    if params.get("minimum-volume", None) is None:
        raise StyxValidationError("`minimum-volume` must not be None")
    if not isinstance(params["minimum-volume"], (float, int)):
        raise StyxValidationError(f'`minimum-volume` has the wrong type: Received `{type(params.get("minimum-volume", None))}` expected `float`')
    if params.get("volume-out", None) is None:
        raise StyxValidationError("`volume-out` must not be None")
    if not isinstance(params["volume-out"], str):
        raise StyxValidationError(f'`volume-out` has the wrong type: Received `{type(params.get("volume-out", None))}` expected `str`')
    if params.get("startval", None) is not None:
        if not isinstance(params["startval"], int):
            raise StyxValidationError(f'`startval` has the wrong type: Received `{type(params.get("startval", None))}` expected `int | None`')
    if params.get("distance", None) is not None:
        if not isinstance(params["distance"], (float, int)):
            raise StyxValidationError(f'`distance` has the wrong type: Received `{type(params.get("distance", None))}` expected `float | None`')
    if params.get("ratio", None) is not None:
        if not isinstance(params["ratio"], (float, int)):
            raise StyxValidationError(f'`ratio` has the wrong type: Received `{type(params.get("ratio", None))}` expected `float | None`')
    if params.get("subvol", None) is not None:
        if not isinstance(params["subvol"], str):
            raise StyxValidationError(f'`subvol` has the wrong type: Received `{type(params.get("subvol", None))}` expected `str | None`')
    if params.get("roi-volume", None) is not None:
        if not isinstance(params["roi-volume"], (pathlib.Path, str)):
            raise StyxValidationError(f'`roi-volume` has the wrong type: Received `{type(params.get("roi-volume", None))}` expected `InputPathType | None`')
    if params.get("less-than", False) is None:
        raise StyxValidationError("`less-than` must not be None")
    if not isinstance(params["less-than"], bool):
        raise StyxValidationError(f'`less-than` has the wrong type: Received `{type(params.get("less-than", False))}` expected `bool`')


def volume_find_clusters_cargs(
    params: VolumeFindClustersParamsDict,
    execution: Execution,
) -> list[str]:
    """
    Build command-line arguments from parameters.
    
    Args:
        params: The parameters.
        execution: The execution object for resolving input paths.
    Returns:
        Command-line arguments.
    """
    cargs = []
    cargs.extend([
        "wb_command",
        "-volume-find-clusters"
    ])
    cargs.append(execution.input_file(params.get("volume-in", None)))
    cargs.append(str(params.get("value-threshold", None)))
    cargs.append(str(params.get("minimum-volume", None)))
    cargs.append(params.get("volume-out", None))
    if params.get("startval", None) is not None:
        cargs.extend([
            "-start",
            str(params.get("startval", None))
        ])
    if params.get("distance", None) is not None:
        cargs.extend([
            "-distance",
            str(params.get("distance", None))
        ])
    if params.get("ratio", None) is not None:
        cargs.extend([
            "-size-ratio",
            str(params.get("ratio", None))
        ])
    if params.get("subvol", None) is not None:
        cargs.extend([
            "-subvolume",
            params.get("subvol", None)
        ])
    if params.get("roi-volume", None) is not None:
        cargs.extend([
            "-roi",
            execution.input_file(params.get("roi-volume", None))
        ])
    if params.get("less-than", False):
        cargs.append("-less-than")
    return cargs


def volume_find_clusters_outputs(
    params: VolumeFindClustersParamsDict,
    execution: Execution,
) -> VolumeFindClustersOutputs:
    """
    Build outputs object containing output file paths and possibly stdout/stderr.
    
    Args:
        params: The parameters.
        execution: The execution object for resolving input paths.
    Returns:
        Outputs object.
    """
    ret = VolumeFindClustersOutputs(
        root=execution.output_file("."),
        volume_out=execution.output_file(params.get("volume-out", None)),
    )
    return ret


def volume_find_clusters_execute(
    params: VolumeFindClustersParamsDict,
    runner: Runner | None = None,
) -> VolumeFindClustersOutputs:
    """
    FILTER CLUSTERS BY VOLUME.
    
    Outputs a volume with nonzero integers for all voxels within a large enough
    cluster, and zeros elsewhere. The integers denote cluster membership (by
    default, first cluster found will use value 1, second cluster 2, etc).
    Cluster values are not reused across frames of the output, but instead keep
    counting up. By default, values greater than <value-threshold> are
    considered to be in a cluster, use -less-than to test for values less than
    the threshold. To apply this as a mask to the data, or to do more
    complicated thresholding, see -volume-math.
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `VolumeFindClustersOutputs`).
    """
    volume_find_clusters_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(VOLUME_FIND_CLUSTERS_METADATA)
    params = execution.params(params)
    cargs = volume_find_clusters_cargs(params, execution)
    ret = volume_find_clusters_outputs(params, execution)
    execution.run(cargs)
    return ret


def volume_find_clusters(
    volume_in: InputPathType,
    value_threshold: float,
    minimum_volume: float,
    volume_out: str,
    startval: int | None = None,
    distance: float | None = None,
    ratio: float | None = None,
    subvol: str | None = None,
    roi_volume: InputPathType | None = None,
    less_than: bool = False,
    runner: Runner | None = None,
) -> VolumeFindClustersOutputs:
    """
    FILTER CLUSTERS BY VOLUME.
    
    Outputs a volume with nonzero integers for all voxels within a large enough
    cluster, and zeros elsewhere. The integers denote cluster membership (by
    default, first cluster found will use value 1, second cluster 2, etc).
    Cluster values are not reused across frames of the output, but instead keep
    counting up. By default, values greater than <value-threshold> are
    considered to be in a cluster, use -less-than to test for values less than
    the threshold. To apply this as a mask to the data, or to do more
    complicated thresholding, see -volume-math.
    
    Args:
        volume_in: the input volume.
        value_threshold: threshold for data values.
        minimum_volume: threshold for cluster volume, in mm^3.
        volume_out: the output volume.
        startval: start labeling clusters from a value other than 1\
            \
            the value to give the first cluster found.
        distance: ignore clusters further than a given distance from the\
            largest cluster\
            \
            how far from the largest cluster a cluster can be, edge to edge, in\
            mm.
        ratio: ignore clusters smaller than a given fraction of the largest\
            cluster in map\
            \
            fraction of the largest cluster's volume.
        subvol: select a single subvolume\
            \
            the subvolume number or name.
        roi_volume: select a region of interest\
            \
            the roi, as a volume file.
        less_than: find values less than <value-threshold>, rather than greater.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `VolumeFindClustersOutputs`).
    """
    params = volume_find_clusters_params(
        volume_in=volume_in,
        value_threshold=value_threshold,
        minimum_volume=minimum_volume,
        volume_out=volume_out,
        startval=startval,
        distance=distance,
        ratio=ratio,
        subvol=subvol,
        roi_volume=roi_volume,
        less_than=less_than,
    )
    return volume_find_clusters_execute(params, runner)


__all__ = [
    "VOLUME_FIND_CLUSTERS_METADATA",
    "VolumeFindClustersOutputs",
    "VolumeFindClustersParamsDict",
    "VolumeFindClustersParamsDictTagged",
    "volume_find_clusters",
    "volume_find_clusters_execute",
    "volume_find_clusters_params",
]
