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

import typing
import pathlib
from styxdefs import *

CIFTI_AVERAGE_METADATA = Metadata(
    id="f30740343235dc708940e806f82a27a090de7bc3.workbench",
    name="cifti-average",
    package="workbench",
    container_image_tag="nx10x/workbench:2.1.0",
)


_CiftiAverageExcludeOutliersParamsDictNoTag = typing.TypedDict('_CiftiAverageExcludeOutliersParamsDictNoTag', {
    "sigma-below": float,
    "sigma-above": float,
})
CiftiAverageExcludeOutliersParamsDictTagged = typing.TypedDict('CiftiAverageExcludeOutliersParamsDictTagged', {
    "@type": typing.Literal["exclude-outliers"],
    "sigma-below": float,
    "sigma-above": float,
})
CiftiAverageExcludeOutliersParamsDict = _CiftiAverageExcludeOutliersParamsDictNoTag | CiftiAverageExcludeOutliersParamsDictTagged


_CiftiAverageCiftiParamsDictNoTag = typing.TypedDict('_CiftiAverageCiftiParamsDictNoTag', {
    "cifti-in": InputPathType,
    "weight": typing.NotRequired[float | None],
})
CiftiAverageCiftiParamsDictTagged = typing.TypedDict('CiftiAverageCiftiParamsDictTagged', {
    "@type": typing.Literal["cifti"],
    "cifti-in": InputPathType,
    "weight": typing.NotRequired[float | None],
})
CiftiAverageCiftiParamsDict = _CiftiAverageCiftiParamsDictNoTag | CiftiAverageCiftiParamsDictTagged


_CiftiAverageParamsDictNoTag = typing.TypedDict('_CiftiAverageParamsDictNoTag', {
    "cifti-out": str,
    "exclude-outliers": typing.NotRequired[CiftiAverageExcludeOutliersParamsDict | None],
    "cifti": typing.NotRequired[list[CiftiAverageCiftiParamsDict] | None],
    "limit-GB": typing.NotRequired[float | None],
})
CiftiAverageParamsDictTagged = typing.TypedDict('CiftiAverageParamsDictTagged', {
    "@type": typing.Literal["workbench/cifti-average"],
    "cifti-out": str,
    "exclude-outliers": typing.NotRequired[CiftiAverageExcludeOutliersParamsDict | None],
    "cifti": typing.NotRequired[list[CiftiAverageCiftiParamsDict] | None],
    "limit-GB": typing.NotRequired[float | None],
})
CiftiAverageParamsDict = _CiftiAverageParamsDictNoTag | CiftiAverageParamsDictTagged


def cifti_average_exclude_outliers(
    sigma_below: float,
    sigma_above: float,
) -> CiftiAverageExcludeOutliersParamsDictTagged:
    """
    Build parameters.
    
    Args:
        sigma_below: number of standard deviations below the mean to include.
        sigma_above: number of standard deviations above the mean to include.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "exclude-outliers",
        "sigma-below": sigma_below,
        "sigma-above": sigma_above,
    }
    return params


def cifti_average_exclude_outliers_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `CiftiAverageExcludeOutliersParamsDict` 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("sigma-below", None) is None:
        raise StyxValidationError("`sigma-below` must not be None")
    if not isinstance(params["sigma-below"], (float, int)):
        raise StyxValidationError(f'`sigma-below` has the wrong type: Received `{type(params.get("sigma-below", None))}` expected `float`')
    if params.get("sigma-above", None) is None:
        raise StyxValidationError("`sigma-above` must not be None")
    if not isinstance(params["sigma-above"], (float, int)):
        raise StyxValidationError(f'`sigma-above` has the wrong type: Received `{type(params.get("sigma-above", None))}` expected `float`')


def cifti_average_exclude_outliers_cargs(
    params: CiftiAverageExcludeOutliersParamsDict,
    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([
        "-exclude-outliers",
        str(params.get("sigma-below", None)),
        str(params.get("sigma-above", None))
    ])
    return cargs


def cifti_average_cifti(
    cifti_in: InputPathType,
    weight: float | None = None,
) -> CiftiAverageCiftiParamsDictTagged:
    """
    Build parameters.
    
    Args:
        cifti_in: the input cifti file.
        weight: give a weight for this file\
            \
            the weight to use.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "cifti",
        "cifti-in": cifti_in,
    }
    if weight is not None:
        params["weight"] = weight
    return params


def cifti_average_cifti_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `CiftiAverageCiftiParamsDict` 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("cifti-in", None) is None:
        raise StyxValidationError("`cifti-in` must not be None")
    if not isinstance(params["cifti-in"], (pathlib.Path, str)):
        raise StyxValidationError(f'`cifti-in` has the wrong type: Received `{type(params.get("cifti-in", None))}` expected `InputPathType`')
    if params.get("weight", None) is not None:
        if not isinstance(params["weight"], (float, int)):
            raise StyxValidationError(f'`weight` has the wrong type: Received `{type(params.get("weight", None))}` expected `float | None`')


def cifti_average_cifti_cargs(
    params: CiftiAverageCiftiParamsDict,
    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([
        "-cifti",
        execution.input_file(params.get("cifti-in", None))
    ])
    if params.get("weight", None) is not None:
        cargs.extend([
            "-weight",
            str(params.get("weight", None))
        ])
    return cargs


class CiftiAverageOutputs(typing.NamedTuple):
    """
    Output object returned when calling `CiftiAverageParamsDict(...)`.
    """
    root: OutputPathType
    """Output root folder. This is the root folder for all outputs."""
    cifti_out: OutputPathType
    """output cifti file"""


def cifti_average_params(
    cifti_out: str,
    exclude_outliers: CiftiAverageExcludeOutliersParamsDict | None = None,
    cifti: list[CiftiAverageCiftiParamsDict] | None = None,
    limit_gb: float | None = None,
) -> CiftiAverageParamsDictTagged:
    """
    Build parameters.
    
    Args:
        cifti_out: output cifti file.
        exclude_outliers: exclude outliers by standard deviation of each\
            element across files.
        cifti: specify an input file.
        limit_gb: restrict memory used for file reading efficiency\
            \
            memory limit in gigabytes.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "workbench/cifti-average",
        "cifti-out": cifti_out,
    }
    if exclude_outliers is not None:
        params["exclude-outliers"] = exclude_outliers
    if cifti is not None:
        params["cifti"] = cifti
    if limit_gb is not None:
        params["limit-GB"] = limit_gb
    return params


def cifti_average_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `CiftiAverageParamsDict` 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("cifti-out", None) is None:
        raise StyxValidationError("`cifti-out` must not be None")
    if not isinstance(params["cifti-out"], str):
        raise StyxValidationError(f'`cifti-out` has the wrong type: Received `{type(params.get("cifti-out", None))}` expected `str`')
    if params.get("exclude-outliers", None) is not None:
        cifti_average_exclude_outliers_validate(params["exclude-outliers"])
    if params.get("cifti", None) is not None:
        if not isinstance(params["cifti"], list):
            raise StyxValidationError(f'`cifti` has the wrong type: Received `{type(params.get("cifti", None))}` expected `list[CiftiAverageCiftiParamsDict] | None`')
        for e in params["cifti"]:
            cifti_average_cifti_validate(e)
    if params.get("limit-GB", None) is not None:
        if not isinstance(params["limit-GB"], (float, int)):
            raise StyxValidationError(f'`limit-GB` has the wrong type: Received `{type(params.get("limit-GB", None))}` expected `float | None`')


def cifti_average_cargs(
    params: CiftiAverageParamsDict,
    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",
        "-cifti-average"
    ])
    cargs.append(params.get("cifti-out", None))
    if params.get("exclude-outliers", None) is not None or params.get("cifti", None) is not None:
        cargs.extend([
            *(cifti_average_exclude_outliers_cargs(params.get("exclude-outliers", None), execution) if (params.get("exclude-outliers", None) is not None) else []),
            *([a for c in [cifti_average_cifti_cargs(s, execution) for s in params.get("cifti", None)] for a in c] if (params.get("cifti", None) is not None) else [])
        ])
    if params.get("limit-GB", None) is not None:
        cargs.extend([
            "-mem-limit",
            str(params.get("limit-GB", None))
        ])
    return cargs


def cifti_average_outputs(
    params: CiftiAverageParamsDict,
    execution: Execution,
) -> CiftiAverageOutputs:
    """
    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 = CiftiAverageOutputs(
        root=execution.output_file("."),
        cifti_out=execution.output_file(params.get("cifti-out", None)),
    )
    return ret


def cifti_average_execute(
    params: CiftiAverageParamsDict,
    runner: Runner | None = None,
) -> CiftiAverageOutputs:
    """
    AVERAGE CIFTI FILES.
    
    Averages cifti files together. Files without -weight specified are given a
    weight of 1. If -exclude-outliers is specified, at each element, the data
    across all files is taken as a set, its unweighted mean and sample standard
    deviation are found, and values outside the specified number of standard
    deviations are excluded from the (potentially weighted) average at that
    element.
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `CiftiAverageOutputs`).
    """
    cifti_average_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(CIFTI_AVERAGE_METADATA)
    params = execution.params(params)
    cargs = cifti_average_cargs(params, execution)
    ret = cifti_average_outputs(params, execution)
    execution.run(cargs)
    return ret


def cifti_average(
    cifti_out: str,
    exclude_outliers: CiftiAverageExcludeOutliersParamsDict | None = None,
    cifti: list[CiftiAverageCiftiParamsDict] | None = None,
    limit_gb: float | None = None,
    runner: Runner | None = None,
) -> CiftiAverageOutputs:
    """
    AVERAGE CIFTI FILES.
    
    Averages cifti files together. Files without -weight specified are given a
    weight of 1. If -exclude-outliers is specified, at each element, the data
    across all files is taken as a set, its unweighted mean and sample standard
    deviation are found, and values outside the specified number of standard
    deviations are excluded from the (potentially weighted) average at that
    element.
    
    Args:
        cifti_out: output cifti file.
        exclude_outliers: exclude outliers by standard deviation of each\
            element across files.
        cifti: specify an input file.
        limit_gb: restrict memory used for file reading efficiency\
            \
            memory limit in gigabytes.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `CiftiAverageOutputs`).
    """
    params = cifti_average_params(
        cifti_out=cifti_out,
        exclude_outliers=exclude_outliers,
        cifti=cifti,
        limit_gb=limit_gb,
    )
    return cifti_average_execute(params, runner)


__all__ = [
    "CIFTI_AVERAGE_METADATA",
    "CiftiAverageCiftiParamsDict",
    "CiftiAverageCiftiParamsDictTagged",
    "CiftiAverageExcludeOutliersParamsDict",
    "CiftiAverageExcludeOutliersParamsDictTagged",
    "CiftiAverageOutputs",
    "CiftiAverageParamsDict",
    "CiftiAverageParamsDictTagged",
    "cifti_average",
    "cifti_average_cifti",
    "cifti_average_exclude_outliers",
    "cifti_average_execute",
    "cifti_average_params",
]
