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

import typing
import pathlib
from styxdefs import *

METRIC_REGRESSION_METADATA = Metadata(
    id="112cf7b9fc8784489485c6275842f1d2dadef8d8.workbench",
    name="metric-regression",
    package="workbench",
    container_image_tag="nx10x/workbench:2.1.0",
)


_MetricRegressionRemoveParamsDictNoTag = typing.TypedDict('_MetricRegressionRemoveParamsDictNoTag', {
    "metric": InputPathType,
    "column": typing.NotRequired[str | None],
})
MetricRegressionRemoveParamsDictTagged = typing.TypedDict('MetricRegressionRemoveParamsDictTagged', {
    "@type": typing.Literal["remove"],
    "metric": InputPathType,
    "column": typing.NotRequired[str | None],
})
MetricRegressionRemoveParamsDict = _MetricRegressionRemoveParamsDictNoTag | MetricRegressionRemoveParamsDictTagged


_MetricRegressionKeepParamsDictNoTag = typing.TypedDict('_MetricRegressionKeepParamsDictNoTag', {
    "metric": InputPathType,
    "column": typing.NotRequired[str | None],
})
MetricRegressionKeepParamsDictTagged = typing.TypedDict('MetricRegressionKeepParamsDictTagged', {
    "@type": typing.Literal["keep"],
    "metric": InputPathType,
    "column": typing.NotRequired[str | None],
})
MetricRegressionKeepParamsDict = _MetricRegressionKeepParamsDictNoTag | MetricRegressionKeepParamsDictTagged


_MetricRegressionParamsDictNoTag = typing.TypedDict('_MetricRegressionParamsDictNoTag', {
    "metric-in": InputPathType,
    "metric-out": str,
    "remove": typing.NotRequired[list[MetricRegressionRemoveParamsDict] | None],
    "keep": typing.NotRequired[list[MetricRegressionKeepParamsDict] | None],
    "column": typing.NotRequired[str | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
})
MetricRegressionParamsDictTagged = typing.TypedDict('MetricRegressionParamsDictTagged', {
    "@type": typing.Literal["workbench/metric-regression"],
    "metric-in": InputPathType,
    "metric-out": str,
    "remove": typing.NotRequired[list[MetricRegressionRemoveParamsDict] | None],
    "keep": typing.NotRequired[list[MetricRegressionKeepParamsDict] | None],
    "column": typing.NotRequired[str | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
})
MetricRegressionParamsDict = _MetricRegressionParamsDictNoTag | MetricRegressionParamsDictTagged


def metric_regression_remove(
    metric: InputPathType,
    column: str | None = None,
) -> MetricRegressionRemoveParamsDictTagged:
    """
    Build parameters.
    
    Args:
        metric: the metric file to use.
        column: select a column to use, rather than all\
            \
            the column number or name.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "remove",
        "metric": metric,
    }
    if column is not None:
        params["column"] = column
    return params


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


def metric_regression_remove_cargs(
    params: MetricRegressionRemoveParamsDict,
    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([
        "-remove",
        execution.input_file(params.get("metric", None))
    ])
    if params.get("column", None) is not None:
        cargs.extend([
            "-remove-column",
            params.get("column", None)
        ])
    return cargs


def metric_regression_keep(
    metric: InputPathType,
    column: str | None = None,
) -> MetricRegressionKeepParamsDictTagged:
    """
    Build parameters.
    
    Args:
        metric: the metric file to use.
        column: select a column to use, rather than all\
            \
            the column number or name.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "keep",
        "metric": metric,
    }
    if column is not None:
        params["column"] = column
    return params


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


def metric_regression_keep_cargs(
    params: MetricRegressionKeepParamsDict,
    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([
        "-keep",
        execution.input_file(params.get("metric", None))
    ])
    if params.get("column", None) is not None:
        cargs.extend([
            "-keep-column",
            params.get("column", None)
        ])
    return cargs


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


def metric_regression_params(
    metric_in: InputPathType,
    metric_out: str,
    remove: list[MetricRegressionRemoveParamsDict] | None = None,
    keep: list[MetricRegressionKeepParamsDict] | None = None,
    column: str | None = None,
    roi_metric: InputPathType | None = None,
) -> MetricRegressionParamsDictTagged:
    """
    Build parameters.
    
    Args:
        metric_in: the metric to regress from.
        metric_out: the output metric.
        remove: specify a metric to regress out.
        keep: specify a metric to include in regression, but not remove.
        column: select a single column to regress from\
            \
            the column number or name.
        roi_metric: only regress inside an roi\
            \
            the area to use for regression, as a metric.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "workbench/metric-regression",
        "metric-in": metric_in,
        "metric-out": metric_out,
    }
    if remove is not None:
        params["remove"] = remove
    if keep is not None:
        params["keep"] = keep
    if column is not None:
        params["column"] = column
    if roi_metric is not None:
        params["roi-metric"] = roi_metric
    return params


def metric_regression_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `MetricRegressionParamsDict` 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("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("remove", None) is not None:
        if not isinstance(params["remove"], list):
            raise StyxValidationError(f'`remove` has the wrong type: Received `{type(params.get("remove", None))}` expected `list[MetricRegressionRemoveParamsDict] | None`')
        for e in params["remove"]:
            metric_regression_remove_validate(e)
    if params.get("keep", None) is not None:
        if not isinstance(params["keep"], list):
            raise StyxValidationError(f'`keep` has the wrong type: Received `{type(params.get("keep", None))}` expected `list[MetricRegressionKeepParamsDict] | None`')
        for e in params["keep"]:
            metric_regression_keep_validate(e)
    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_regression_cargs(
    params: MetricRegressionParamsDict,
    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-regression"
    ])
    cargs.append(execution.input_file(params.get("metric-in", None)))
    cargs.append(params.get("metric-out", None))
    if params.get("remove", None) is not None or params.get("keep", None) is not None:
        cargs.extend([
            *([a for c in [metric_regression_remove_cargs(s, execution) for s in params.get("remove", None)] for a in c] if (params.get("remove", None) is not None) else []),
            *([a for c in [metric_regression_keep_cargs(s, execution) for s in params.get("keep", None)] for a in c] if (params.get("keep", None) is not None) else [])
        ])
    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_regression_outputs(
    params: MetricRegressionParamsDict,
    execution: Execution,
) -> MetricRegressionOutputs:
    """
    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 = MetricRegressionOutputs(
        root=execution.output_file("."),
        metric_out=execution.output_file(params.get("metric-out", None)),
    )
    return ret


def metric_regression_execute(
    params: MetricRegressionParamsDict,
    runner: Runner | None = None,
) -> MetricRegressionOutputs:
    """
    REGRESS SPATIAL MAP OUT OF A METRIC FILE.
    
    For each regressor, its mean across the surface is subtracted from its data.
    Each input map is then regressed against these, and a constant term. The
    resulting regressed slopes of all regressors specified with -remove are
    multiplied with their respective regressor maps, and these are subtracted
    from the input map.
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `MetricRegressionOutputs`).
    """
    metric_regression_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(METRIC_REGRESSION_METADATA)
    params = execution.params(params)
    cargs = metric_regression_cargs(params, execution)
    ret = metric_regression_outputs(params, execution)
    execution.run(cargs)
    return ret


def metric_regression(
    metric_in: InputPathType,
    metric_out: str,
    remove: list[MetricRegressionRemoveParamsDict] | None = None,
    keep: list[MetricRegressionKeepParamsDict] | None = None,
    column: str | None = None,
    roi_metric: InputPathType | None = None,
    runner: Runner | None = None,
) -> MetricRegressionOutputs:
    """
    REGRESS SPATIAL MAP OUT OF A METRIC FILE.
    
    For each regressor, its mean across the surface is subtracted from its data.
    Each input map is then regressed against these, and a constant term. The
    resulting regressed slopes of all regressors specified with -remove are
    multiplied with their respective regressor maps, and these are subtracted
    from the input map.
    
    Args:
        metric_in: the metric to regress from.
        metric_out: the output metric.
        remove: specify a metric to regress out.
        keep: specify a metric to include in regression, but not remove.
        column: select a single column to regress from\
            \
            the column number or name.
        roi_metric: only regress inside an roi\
            \
            the area to use for regression, as a metric.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `MetricRegressionOutputs`).
    """
    params = metric_regression_params(
        metric_in=metric_in,
        metric_out=metric_out,
        remove=remove,
        keep=keep,
        column=column,
        roi_metric=roi_metric,
    )
    return metric_regression_execute(params, runner)


__all__ = [
    "METRIC_REGRESSION_METADATA",
    "MetricRegressionKeepParamsDict",
    "MetricRegressionKeepParamsDictTagged",
    "MetricRegressionOutputs",
    "MetricRegressionParamsDict",
    "MetricRegressionParamsDictTagged",
    "MetricRegressionRemoveParamsDict",
    "MetricRegressionRemoveParamsDictTagged",
    "metric_regression",
    "metric_regression_execute",
    "metric_regression_keep",
    "metric_regression_params",
    "metric_regression_remove",
]
