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

import typing
import pathlib
from styxdefs import *

CIFTI_CORRELATION_METADATA = Metadata(
    id="dcfca8ed7e2b49948aa64aa87d5693dc899aee50.workbench",
    name="cifti-correlation",
    package="workbench",
    container_image_tag="nx10x/workbench:2.1.0",
)


_CiftiCorrelationRoiOverrideParamsDictNoTag = typing.TypedDict('_CiftiCorrelationRoiOverrideParamsDictNoTag', {
    "roi-cifti": typing.NotRequired[InputPathType | None],
    "roi-vol": typing.NotRequired[InputPathType | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
})
CiftiCorrelationRoiOverrideParamsDictTagged = typing.TypedDict('CiftiCorrelationRoiOverrideParamsDictTagged', {
    "@type": typing.Literal["roi-override"],
    "roi-cifti": typing.NotRequired[InputPathType | None],
    "roi-vol": typing.NotRequired[InputPathType | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
    "roi-metric": typing.NotRequired[InputPathType | None],
})
CiftiCorrelationRoiOverrideParamsDict = _CiftiCorrelationRoiOverrideParamsDictNoTag | CiftiCorrelationRoiOverrideParamsDictTagged


_CiftiCorrelationParamsDictNoTag = typing.TypedDict('_CiftiCorrelationParamsDictNoTag', {
    "cifti": InputPathType,
    "cifti-out": str,
    "roi-override": typing.NotRequired[CiftiCorrelationRoiOverrideParamsDict | None],
    "limit-GB": typing.NotRequired[float | None],
    "weight-file": typing.NotRequired[str | None],
    "covariance": bool,
    "no-demean": bool,
    "fisher-z": bool,
})
CiftiCorrelationParamsDictTagged = typing.TypedDict('CiftiCorrelationParamsDictTagged', {
    "@type": typing.Literal["workbench/cifti-correlation"],
    "cifti": InputPathType,
    "cifti-out": str,
    "roi-override": typing.NotRequired[CiftiCorrelationRoiOverrideParamsDict | None],
    "limit-GB": typing.NotRequired[float | None],
    "weight-file": typing.NotRequired[str | None],
    "covariance": bool,
    "no-demean": bool,
    "fisher-z": bool,
})
CiftiCorrelationParamsDict = _CiftiCorrelationParamsDictNoTag | CiftiCorrelationParamsDictTagged


def cifti_correlation_roi_override(
    roi_cifti: InputPathType | None = None,
    roi_vol: InputPathType | None = None,
    roi_metric: InputPathType | None = None,
    roi_metric_: InputPathType | None = None,
    roi_metric_2: InputPathType | None = None,
) -> CiftiCorrelationRoiOverrideParamsDictTagged:
    """
    Build parameters.
    
    Args:
        roi_cifti: use a cifti file for combined rois\
            \
            the cifti roi file.
        roi_vol: use an roi for volume\
            \
            the volume roi file.
        roi_metric: use an roi for cerebellum\
            \
            the cerebellum roi as a metric file.
        roi_metric_: use an roi for right hempsphere\
            \
            the right roi as a metric file.
        roi_metric_2: use an roi for left hempsphere\
            \
            the left roi as a metric file.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "roi-override",
    }
    if roi_cifti is not None:
        params["roi-cifti"] = roi_cifti
    if roi_vol is not None:
        params["roi-vol"] = roi_vol
    if roi_metric is not None:
        params["roi-metric"] = roi_metric
    if roi_metric_ is not None:
        params["roi-metric"] = roi_metric_
    if roi_metric_2 is not None:
        params["roi-metric"] = roi_metric_2
    return params


def cifti_correlation_roi_override_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `CiftiCorrelationRoiOverrideParamsDict` 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("roi-cifti", None) is not None:
        if not isinstance(params["roi-cifti"], (pathlib.Path, str)):
            raise StyxValidationError(f'`roi-cifti` has the wrong type: Received `{type(params.get("roi-cifti", None))}` expected `InputPathType | None`')
    if params.get("roi-vol", None) is not None:
        if not isinstance(params["roi-vol"], (pathlib.Path, str)):
            raise StyxValidationError(f'`roi-vol` has the wrong type: Received `{type(params.get("roi-vol", None))}` expected `InputPathType | 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`')
    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`')
    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 cifti_correlation_roi_override_cargs(
    params: CiftiCorrelationRoiOverrideParamsDict,
    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.append("-roi-override")
    if params.get("roi-cifti", None) is not None:
        cargs.extend([
            "-cifti-roi",
            execution.input_file(params.get("roi-cifti", None))
        ])
    if params.get("roi-vol", None) is not None:
        cargs.extend([
            "-vol-roi",
            execution.input_file(params.get("roi-vol", None))
        ])
    if params.get("roi-metric", None) is not None:
        cargs.extend([
            "-cerebellum-roi",
            execution.input_file(params.get("roi-metric", None))
        ])
    if params.get("roi-metric", None) is not None:
        cargs.extend([
            "-right-roi",
            execution.input_file(params.get("roi-metric", None))
        ])
    if params.get("roi-metric", None) is not None:
        cargs.extend([
            "-left-roi",
            execution.input_file(params.get("roi-metric", None))
        ])
    return cargs


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


def cifti_correlation_params(
    cifti: InputPathType,
    cifti_out: str,
    roi_override: CiftiCorrelationRoiOverrideParamsDict | None = None,
    limit_gb: float | None = None,
    weight_file: str | None = None,
    covariance: bool = False,
    no_demean: bool = False,
    fisher_z: bool = False,
) -> CiftiCorrelationParamsDictTagged:
    """
    Build parameters.
    
    Args:
        cifti: input cifti file.
        cifti_out: output cifti file.
        roi_override: perform correlation from a subset of rows to all rows.
        limit_gb: restrict memory usage\
            \
            memory limit in gigabytes.
        weight_file: specify column weights\
            \
            text file containing one weight per column.
        covariance: compute covariance instead of correlation.
        no_demean: instead of correlation, do dot product of rows, then\
            normalize by diagonal.
        fisher_z: apply fisher small z transform (ie, artanh) to correlation.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "workbench/cifti-correlation",
        "cifti": cifti,
        "cifti-out": cifti_out,
        "covariance": covariance,
        "no-demean": no_demean,
        "fisher-z": fisher_z,
    }
    if roi_override is not None:
        params["roi-override"] = roi_override
    if limit_gb is not None:
        params["limit-GB"] = limit_gb
    if weight_file is not None:
        params["weight-file"] = weight_file
    return params


def cifti_correlation_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `CiftiCorrelationParamsDict` 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", None) is None:
        raise StyxValidationError("`cifti` must not be None")
    if not isinstance(params["cifti"], (pathlib.Path, str)):
        raise StyxValidationError(f'`cifti` has the wrong type: Received `{type(params.get("cifti", None))}` expected `InputPathType`')
    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("roi-override", None) is not None:
        cifti_correlation_roi_override_validate(params["roi-override"])
    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`')
    if params.get("weight-file", None) is not None:
        if not isinstance(params["weight-file"], str):
            raise StyxValidationError(f'`weight-file` has the wrong type: Received `{type(params.get("weight-file", None))}` expected `str | None`')
    if params.get("covariance", False) is None:
        raise StyxValidationError("`covariance` must not be None")
    if not isinstance(params["covariance"], bool):
        raise StyxValidationError(f'`covariance` has the wrong type: Received `{type(params.get("covariance", False))}` expected `bool`')
    if params.get("no-demean", False) is None:
        raise StyxValidationError("`no-demean` must not be None")
    if not isinstance(params["no-demean"], bool):
        raise StyxValidationError(f'`no-demean` has the wrong type: Received `{type(params.get("no-demean", False))}` expected `bool`')
    if params.get("fisher-z", False) is None:
        raise StyxValidationError("`fisher-z` must not be None")
    if not isinstance(params["fisher-z"], bool):
        raise StyxValidationError(f'`fisher-z` has the wrong type: Received `{type(params.get("fisher-z", False))}` expected `bool`')


def cifti_correlation_cargs(
    params: CiftiCorrelationParamsDict,
    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-correlation"
    ])
    cargs.append(execution.input_file(params.get("cifti", None)))
    cargs.append(params.get("cifti-out", None))
    if params.get("roi-override", None) is not None:
        cargs.extend(cifti_correlation_roi_override_cargs(params.get("roi-override", None), execution))
    if params.get("limit-GB", None) is not None:
        cargs.extend([
            "-mem-limit",
            str(params.get("limit-GB", None))
        ])
    if params.get("weight-file", None) is not None:
        cargs.extend([
            "-weights",
            params.get("weight-file", None)
        ])
    if params.get("covariance", False):
        cargs.append("-covariance")
    if params.get("no-demean", False):
        cargs.append("-no-demean")
    if params.get("fisher-z", False):
        cargs.append("-fisher-z")
    return cargs


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


def cifti_correlation_execute(
    params: CiftiCorrelationParamsDict,
    runner: Runner | None = None,
) -> CiftiCorrelationOutputs:
    """
    GENERATE CORRELATION OF ROWS IN A CIFTI FILE.
    
    For each row (or each row inside an roi if -roi-override is specified),
    correlate to all other rows. The -cifti-roi suboption to -roi-override may
    not be specified with any other -*-roi suboption, but you may specify the
    other -*-roi suboptions together.
    
    When using the -fisher-z option, the output is NOT a Z-score, it is
    artanh(r), to do further math on this output, consider using -cifti-math.
    
    Restricting the memory usage will make it calculate the output in chunks,
    and if the input file size is more than 70% of the memory limit, it will
    also read through the input file as rows are required, resulting in several
    passes through the input file (once per chunk). Memory limit does not need
    to be an integer, you may also specify 0 to calculate a single output row at
    a time (this may be very slow).
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `CiftiCorrelationOutputs`).
    """
    cifti_correlation_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(CIFTI_CORRELATION_METADATA)
    params = execution.params(params)
    cargs = cifti_correlation_cargs(params, execution)
    ret = cifti_correlation_outputs(params, execution)
    execution.run(cargs)
    return ret


def cifti_correlation(
    cifti: InputPathType,
    cifti_out: str,
    roi_override: CiftiCorrelationRoiOverrideParamsDict | None = None,
    limit_gb: float | None = None,
    weight_file: str | None = None,
    covariance: bool = False,
    no_demean: bool = False,
    fisher_z: bool = False,
    runner: Runner | None = None,
) -> CiftiCorrelationOutputs:
    """
    GENERATE CORRELATION OF ROWS IN A CIFTI FILE.
    
    For each row (or each row inside an roi if -roi-override is specified),
    correlate to all other rows. The -cifti-roi suboption to -roi-override may
    not be specified with any other -*-roi suboption, but you may specify the
    other -*-roi suboptions together.
    
    When using the -fisher-z option, the output is NOT a Z-score, it is
    artanh(r), to do further math on this output, consider using -cifti-math.
    
    Restricting the memory usage will make it calculate the output in chunks,
    and if the input file size is more than 70% of the memory limit, it will
    also read through the input file as rows are required, resulting in several
    passes through the input file (once per chunk). Memory limit does not need
    to be an integer, you may also specify 0 to calculate a single output row at
    a time (this may be very slow).
    
    Args:
        cifti: input cifti file.
        cifti_out: output cifti file.
        roi_override: perform correlation from a subset of rows to all rows.
        limit_gb: restrict memory usage\
            \
            memory limit in gigabytes.
        weight_file: specify column weights\
            \
            text file containing one weight per column.
        covariance: compute covariance instead of correlation.
        no_demean: instead of correlation, do dot product of rows, then\
            normalize by diagonal.
        fisher_z: apply fisher small z transform (ie, artanh) to correlation.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `CiftiCorrelationOutputs`).
    """
    params = cifti_correlation_params(
        cifti=cifti,
        cifti_out=cifti_out,
        roi_override=roi_override,
        limit_gb=limit_gb,
        weight_file=weight_file,
        covariance=covariance,
        no_demean=no_demean,
        fisher_z=fisher_z,
    )
    return cifti_correlation_execute(params, runner)


__all__ = [
    "CIFTI_CORRELATION_METADATA",
    "CiftiCorrelationOutputs",
    "CiftiCorrelationParamsDict",
    "CiftiCorrelationParamsDictTagged",
    "CiftiCorrelationRoiOverrideParamsDict",
    "CiftiCorrelationRoiOverrideParamsDictTagged",
    "cifti_correlation",
    "cifti_correlation_execute",
    "cifti_correlation_params",
    "cifti_correlation_roi_override",
]
