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

import typing
import pathlib
from styxdefs import *

METRIC_TFCE_METADATA = Metadata(
    id="08ff0e7a57ecc93cc6a3d034347b01fa26e0507a.workbench",
    name="metric-tfce",
    package="workbench",
    container_image_tag="nx10x/workbench:2.1.0",
)


_MetricTfcePresmoothParamsDictNoTag = typing.TypedDict('_MetricTfcePresmoothParamsDictNoTag', {
    "kernel": float,
    "fwhm": bool,
})
MetricTfcePresmoothParamsDictTagged = typing.TypedDict('MetricTfcePresmoothParamsDictTagged', {
    "@type": typing.Literal["presmooth"],
    "kernel": float,
    "fwhm": bool,
})
MetricTfcePresmoothParamsDict = _MetricTfcePresmoothParamsDictNoTag | MetricTfcePresmoothParamsDictTagged


_MetricTfceParametersParamsDictNoTag = typing.TypedDict('_MetricTfceParametersParamsDictNoTag', {
    "E": float,
    "H": float,
})
MetricTfceParametersParamsDictTagged = typing.TypedDict('MetricTfceParametersParamsDictTagged', {
    "@type": typing.Literal["parameters"],
    "E": float,
    "H": float,
})
MetricTfceParametersParamsDict = _MetricTfceParametersParamsDictNoTag | MetricTfceParametersParamsDictTagged


_MetricTfceParamsDictNoTag = typing.TypedDict('_MetricTfceParamsDictNoTag', {
    "surface": InputPathType,
    "metric-in": InputPathType,
    "metric-out": str,
    "presmooth": typing.NotRequired[MetricTfcePresmoothParamsDict | None],
    "parameters": typing.NotRequired[MetricTfceParametersParamsDict | None],
    "area-metric": typing.NotRequired[InputPathType | None],
    "column": typing.NotRequired[str | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
})
MetricTfceParamsDictTagged = typing.TypedDict('MetricTfceParamsDictTagged', {
    "@type": typing.Literal["workbench/metric-tfce"],
    "surface": InputPathType,
    "metric-in": InputPathType,
    "metric-out": str,
    "presmooth": typing.NotRequired[MetricTfcePresmoothParamsDict | None],
    "parameters": typing.NotRequired[MetricTfceParametersParamsDict | None],
    "area-metric": typing.NotRequired[InputPathType | None],
    "column": typing.NotRequired[str | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
})
MetricTfceParamsDict = _MetricTfceParamsDictNoTag | MetricTfceParamsDictTagged


def metric_tfce_presmooth(
    kernel: float,
    fwhm: bool = False,
) -> MetricTfcePresmoothParamsDictTagged:
    """
    Build parameters.
    
    Args:
        kernel: the size of the gaussian smoothing kernel in mm, as sigma by\
            default.
        fwhm: kernel size is FWHM, not sigma.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "presmooth",
        "kernel": kernel,
        "fwhm": fwhm,
    }
    return params


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


def metric_tfce_presmooth_cargs(
    params: MetricTfcePresmoothParamsDict,
    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([
        "-presmooth",
        str(params.get("kernel", None))
    ])
    if params.get("fwhm", False):
        cargs.append("-fwhm")
    return cargs


def metric_tfce_parameters(
    e: float,
    h: float,
) -> MetricTfceParametersParamsDictTagged:
    """
    Build parameters.
    
    Args:
        e: exponent for cluster area (default 1.0).
        h: exponent for threshold value (default 2.0).
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "parameters",
        "E": e,
        "H": h,
    }
    return params


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


def metric_tfce_parameters_cargs(
    params: MetricTfceParametersParamsDict,
    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([
        "-parameters",
        str(params.get("E", None)),
        str(params.get("H", None))
    ])
    return cargs


class MetricTfceOutputs(typing.NamedTuple):
    """
    Output object returned when calling `MetricTfceParamsDict(...)`.
    """
    root: OutputPathType
    """Output root folder. This is the root folder for all outputs."""
    metric_out: OutputPathType
    """the output metric"""


def metric_tfce_params(
    surface: InputPathType,
    metric_in: InputPathType,
    metric_out: str,
    presmooth: MetricTfcePresmoothParamsDict | None = None,
    parameters: MetricTfceParametersParamsDict | None = None,
    area_metric: InputPathType | None = None,
    column: str | None = None,
    roi_metric: InputPathType | None = None,
) -> MetricTfceParamsDictTagged:
    """
    Build parameters.
    
    Args:
        surface: the surface to compute on.
        metric_in: the metric to run TFCE on.
        metric_out: the output metric.
        presmooth: smooth the metric before running TFCE.
        parameters: set parameters for TFCE integral.
        area_metric: vertex areas to use instead of computing them from the\
            surface\
            \
            the corrected vertex areas, as a metric.
        column: select a single column\
            \
            the column number or name.
        roi_metric: select a region of interest to run TFCE on\
            \
            the area to run TFCE on, as a metric.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "workbench/metric-tfce",
        "surface": surface,
        "metric-in": metric_in,
        "metric-out": metric_out,
    }
    if presmooth is not None:
        params["presmooth"] = presmooth
    if parameters is not None:
        params["parameters"] = parameters
    if area_metric is not None:
        params["area-metric"] = area_metric
    if column is not None:
        params["column"] = column
    if roi_metric is not None:
        params["roi-metric"] = roi_metric
    return params


def metric_tfce_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `MetricTfceParamsDict` 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("surface", None) is None:
        raise StyxValidationError("`surface` must not be None")
    if not isinstance(params["surface"], (pathlib.Path, str)):
        raise StyxValidationError(f'`surface` has the wrong type: Received `{type(params.get("surface", None))}` expected `InputPathType`')
    if params.get("metric-in", None) is None:
        raise StyxValidationError("`metric-in` must not be None")
    if not isinstance(params["metric-in"], (pathlib.Path, str)):
        raise StyxValidationError(f'`metric-in` has the wrong type: Received `{type(params.get("metric-in", None))}` expected `InputPathType`')
    if params.get("metric-out", None) is None:
        raise StyxValidationError("`metric-out` must not be None")
    if not isinstance(params["metric-out"], str):
        raise StyxValidationError(f'`metric-out` has the wrong type: Received `{type(params.get("metric-out", None))}` expected `str`')
    if params.get("presmooth", None) is not None:
        metric_tfce_presmooth_validate(params["presmooth"])
    if params.get("parameters", None) is not None:
        metric_tfce_parameters_validate(params["parameters"])
    if params.get("area-metric", None) is not None:
        if not isinstance(params["area-metric"], (pathlib.Path, str)):
            raise StyxValidationError(f'`area-metric` has the wrong type: Received `{type(params.get("area-metric", None))}` expected `InputPathType | None`')
    if params.get("column", None) is not None:
        if not isinstance(params["column"], str):
            raise StyxValidationError(f'`column` has the wrong type: Received `{type(params.get("column", None))}` expected `str | None`')
    if params.get("roi-metric", None) is not None:
        if not isinstance(params["roi-metric"], (pathlib.Path, str)):
            raise StyxValidationError(f'`roi-metric` has the wrong type: Received `{type(params.get("roi-metric", None))}` expected `InputPathType | None`')


def metric_tfce_cargs(
    params: MetricTfceParamsDict,
    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",
        "-metric-tfce"
    ])
    cargs.append(execution.input_file(params.get("surface", None)))
    cargs.append(execution.input_file(params.get("metric-in", None)))
    cargs.append(params.get("metric-out", None))
    if params.get("presmooth", None) is not None or params.get("parameters", None) is not None:
        cargs.extend([
            *(metric_tfce_presmooth_cargs(params.get("presmooth", None), execution) if (params.get("presmooth", None) is not None) else []),
            *(metric_tfce_parameters_cargs(params.get("parameters", None), execution) if (params.get("parameters", None) is not None) else [])
        ])
    if params.get("area-metric", None) is not None:
        cargs.extend([
            "-corrected-areas",
            execution.input_file(params.get("area-metric", None))
        ])
    if params.get("column", None) is not None:
        cargs.extend([
            "-column",
            params.get("column", None)
        ])
    if params.get("roi-metric", None) is not None:
        cargs.extend([
            "-roi",
            execution.input_file(params.get("roi-metric", None))
        ])
    return cargs


def metric_tfce_outputs(
    params: MetricTfceParamsDict,
    execution: Execution,
) -> MetricTfceOutputs:
    """
    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 = MetricTfceOutputs(
        root=execution.output_file("."),
        metric_out=execution.output_file(params.get("metric-out", None)),
    )
    return ret


def metric_tfce_execute(
    params: MetricTfceParamsDict,
    runner: Runner | None = None,
) -> MetricTfceOutputs:
    """
    DO TFCE ON A METRIC FILE.
    
    This command does not do any statistical analysis. Please use something like
    PALM if you are just trying to do statistics on your data.
    
    Threshold-free cluster enhancement is a method to increase the relative
    value of regions that would form clusters in a standard thresholding test.
    This is accomplished by evaluating the integral of:
    
    e(h, p)^E * h^H * dh
    
    at each vertex p, where h ranges from 0 to the maximum value in the data,
    and e(h, p) is the extent of the cluster containing vertex p at threshold h.
    Negative values are similarly enhanced by negating the data, running the
    same process, and negating the result.
    
    When using -presmooth with -corrected-areas, note that it is an approximate
    correction within the smoothing algorithm (the TFCE correction is exact).
    Doing smoothing on individual surfaces before averaging/TFCE is preferred,
    when possible, in order to better tie the smoothing kernel size to the
    original feature size.
    
    The TFCE method is explained in: Smith SM, Nichols TE., "Threshold-free
    cluster enhancement: addressing problems of smoothing, threshold dependence
    and localisation in cluster inference." Neuroimage. 2009 Jan 1;44(1):83-98.
    PMID: 18501637.
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `MetricTfceOutputs`).
    """
    metric_tfce_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(METRIC_TFCE_METADATA)
    params = execution.params(params)
    cargs = metric_tfce_cargs(params, execution)
    ret = metric_tfce_outputs(params, execution)
    execution.run(cargs)
    return ret


def metric_tfce(
    surface: InputPathType,
    metric_in: InputPathType,
    metric_out: str,
    presmooth: MetricTfcePresmoothParamsDict | None = None,
    parameters: MetricTfceParametersParamsDict | None = None,
    area_metric: InputPathType | None = None,
    column: str | None = None,
    roi_metric: InputPathType | None = None,
    runner: Runner | None = None,
) -> MetricTfceOutputs:
    """
    DO TFCE ON A METRIC FILE.
    
    This command does not do any statistical analysis. Please use something like
    PALM if you are just trying to do statistics on your data.
    
    Threshold-free cluster enhancement is a method to increase the relative
    value of regions that would form clusters in a standard thresholding test.
    This is accomplished by evaluating the integral of:
    
    e(h, p)^E * h^H * dh
    
    at each vertex p, where h ranges from 0 to the maximum value in the data,
    and e(h, p) is the extent of the cluster containing vertex p at threshold h.
    Negative values are similarly enhanced by negating the data, running the
    same process, and negating the result.
    
    When using -presmooth with -corrected-areas, note that it is an approximate
    correction within the smoothing algorithm (the TFCE correction is exact).
    Doing smoothing on individual surfaces before averaging/TFCE is preferred,
    when possible, in order to better tie the smoothing kernel size to the
    original feature size.
    
    The TFCE method is explained in: Smith SM, Nichols TE., "Threshold-free
    cluster enhancement: addressing problems of smoothing, threshold dependence
    and localisation in cluster inference." Neuroimage. 2009 Jan 1;44(1):83-98.
    PMID: 18501637.
    
    Args:
        surface: the surface to compute on.
        metric_in: the metric to run TFCE on.
        metric_out: the output metric.
        presmooth: smooth the metric before running TFCE.
        parameters: set parameters for TFCE integral.
        area_metric: vertex areas to use instead of computing them from the\
            surface\
            \
            the corrected vertex areas, as a metric.
        column: select a single column\
            \
            the column number or name.
        roi_metric: select a region of interest to run TFCE on\
            \
            the area to run TFCE on, as a metric.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `MetricTfceOutputs`).
    """
    params = metric_tfce_params(
        surface=surface,
        metric_in=metric_in,
        metric_out=metric_out,
        presmooth=presmooth,
        parameters=parameters,
        area_metric=area_metric,
        column=column,
        roi_metric=roi_metric,
    )
    return metric_tfce_execute(params, runner)


__all__ = [
    "METRIC_TFCE_METADATA",
    "MetricTfceOutputs",
    "MetricTfceParametersParamsDict",
    "MetricTfceParametersParamsDictTagged",
    "MetricTfceParamsDict",
    "MetricTfceParamsDictTagged",
    "MetricTfcePresmoothParamsDict",
    "MetricTfcePresmoothParamsDictTagged",
    "metric_tfce",
    "metric_tfce_execute",
    "metric_tfce_parameters",
    "metric_tfce_params",
    "metric_tfce_presmooth",
]
