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

import typing
import pathlib
from styxdefs import *

TCKDFC_METADATA = Metadata(
    id="c08d7690e556dae567c956d830fbf83e42bf36aa.boutiques",
    name="tckdfc",
    package="mrtrix",
    container_image_tag="mrtrix3/mrtrix3:3.0.4",
)


_TckdfcDynamicParamsDictNoTag = typing.TypedDict('_TckdfcDynamicParamsDictNoTag', {
    "shape": str,
    "width": int,
})
TckdfcDynamicParamsDictTagged = typing.TypedDict('TckdfcDynamicParamsDictTagged', {
    "@type": typing.Literal["dynamic"],
    "shape": str,
    "width": int,
})
TckdfcDynamicParamsDict = _TckdfcDynamicParamsDictNoTag | TckdfcDynamicParamsDictTagged


_TckdfcConfigParamsDictNoTag = typing.TypedDict('_TckdfcConfigParamsDictNoTag', {
    "key": str,
    "value": str,
})
TckdfcConfigParamsDictTagged = typing.TypedDict('TckdfcConfigParamsDictTagged', {
    "@type": typing.Literal["config"],
    "key": str,
    "value": str,
})
TckdfcConfigParamsDict = _TckdfcConfigParamsDictNoTag | TckdfcConfigParamsDictTagged


_TckdfcParamsDictNoTag = typing.TypedDict('_TckdfcParamsDictNoTag', {
    "static": bool,
    "dynamic": typing.NotRequired[TckdfcDynamicParamsDict | None],
    "template": typing.NotRequired[InputPathType | None],
    "vox": typing.NotRequired[list[float] | None],
    "stat_vox": typing.NotRequired[str | None],
    "backtrack": bool,
    "upsample": typing.NotRequired[int | None],
    "info": bool,
    "quiet": bool,
    "debug": bool,
    "force": bool,
    "nthreads": typing.NotRequired[int | None],
    "config": typing.NotRequired[list[TckdfcConfigParamsDict] | None],
    "help": bool,
    "version": bool,
    "tracks": InputPathType,
    "fmri": InputPathType,
    "output": str,
})
TckdfcParamsDictTagged = typing.TypedDict('TckdfcParamsDictTagged', {
    "@type": typing.Literal["mrtrix/tckdfc"],
    "static": bool,
    "dynamic": typing.NotRequired[TckdfcDynamicParamsDict | None],
    "template": typing.NotRequired[InputPathType | None],
    "vox": typing.NotRequired[list[float] | None],
    "stat_vox": typing.NotRequired[str | None],
    "backtrack": bool,
    "upsample": typing.NotRequired[int | None],
    "info": bool,
    "quiet": bool,
    "debug": bool,
    "force": bool,
    "nthreads": typing.NotRequired[int | None],
    "config": typing.NotRequired[list[TckdfcConfigParamsDict] | None],
    "help": bool,
    "version": bool,
    "tracks": InputPathType,
    "fmri": InputPathType,
    "output": str,
})
TckdfcParamsDict = _TckdfcParamsDictNoTag | TckdfcParamsDictTagged


def tckdfc_dynamic(
    shape: str,
    width: int,
) -> TckdfcDynamicParamsDictTagged:
    """
    Build parameters.
    
    Args:
        shape: generate a "dynamic" (4D) output image; must additionally\
            provide the shape and width (in volumes) of the sliding window.
        width: generate a "dynamic" (4D) output image; must additionally\
            provide the shape and width (in volumes) of the sliding window.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "dynamic",
        "shape": shape,
        "width": width,
    }
    return params


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


def tckdfc_dynamic_cargs(
    params: TckdfcDynamicParamsDict,
    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("-dynamic")
    cargs.append(params.get("shape", None))
    cargs.append(str(params.get("width", None)))
    return cargs


def tckdfc_config(
    key: str,
    value: str,
) -> TckdfcConfigParamsDictTagged:
    """
    Build parameters.
    
    Args:
        key: temporarily set the value of an MRtrix config file entry.
        value: temporarily set the value of an MRtrix config file entry.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "config",
        "key": key,
        "value": value,
    }
    return params


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


def tckdfc_config_cargs(
    params: TckdfcConfigParamsDict,
    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("-config")
    cargs.append(params.get("key", None))
    cargs.append(params.get("value", None))
    return cargs


class TckdfcOutputs(typing.NamedTuple):
    """
    Output object returned when calling `TckdfcParamsDict(...)`.
    """
    root: OutputPathType
    """Output root folder. This is the root folder for all outputs."""
    output: OutputPathType
    """the output TW-dFC image"""


def tckdfc_params(
    tracks: InputPathType,
    fmri: InputPathType,
    output: str,
    static: bool = False,
    dynamic: TckdfcDynamicParamsDict | None = None,
    template: InputPathType | None = None,
    vox: list[float] | None = None,
    stat_vox: str | None = None,
    backtrack: bool = False,
    upsample: int | None = None,
    info: bool = False,
    quiet: bool = False,
    debug: bool = False,
    force: bool = False,
    nthreads: int | None = None,
    config: list[TckdfcConfigParamsDict] | None = None,
    help_: bool = False,
    version: bool = False,
) -> TckdfcParamsDictTagged:
    """
    Build parameters.
    
    Args:
        tracks: the input track file.
        fmri: the pre-processed fMRI time series.
        output: the output TW-dFC image.
        static: generate a "static" (3D) output image.
        dynamic: generate a "dynamic" (4D) output image; must additionally\
            provide the shape and width (in volumes) of the sliding window.
        template: an image file to be used as a template for the output (the\
            output image will have the same transform and field of view).
        vox: provide either an isotropic voxel size (in mm), or comma-separated\
            list of 3 voxel dimensions.
        stat_vox: define the statistic for choosing the final voxel intensities\
            for a given contrast type given the individual values from the tracks\
            passing through each voxel\
            Options are: sum, min, mean, max (default: mean).
        backtrack: if no valid timeseries is found at the streamline endpoint,\
            back-track along the streamline trajectory until a valid timeseries is\
            found.
        upsample: upsample the tracks by some ratio using Hermite interpolation\
            before mapping (if omitted, an appropriate ratio will be determined\
            automatically).
        info: display information messages.
        quiet: do not display information messages or progress status;\
            alternatively, this can be achieved by setting the MRTRIX_QUIET\
            environment variable to a non-empty string.
        debug: display debugging messages.
        force: force overwrite of output files (caution: using the same file as\
            input and output might cause unexpected behaviour).
        nthreads: use this number of threads in multi-threaded applications\
            (set to 0 to disable multi-threading).
        config: temporarily set the value of an MRtrix config file entry.
        help_: display this information page and exit.
        version: display version information and exit.
    Returns:
        Parameter dictionary
    """
    params = {
        "@type": "mrtrix/tckdfc",
        "static": static,
        "backtrack": backtrack,
        "info": info,
        "quiet": quiet,
        "debug": debug,
        "force": force,
        "help": help_,
        "version": version,
        "tracks": tracks,
        "fmri": fmri,
        "output": output,
    }
    if dynamic is not None:
        params["dynamic"] = dynamic
    if template is not None:
        params["template"] = template
    if vox is not None:
        params["vox"] = vox
    if stat_vox is not None:
        params["stat_vox"] = stat_vox
    if upsample is not None:
        params["upsample"] = upsample
    if nthreads is not None:
        params["nthreads"] = nthreads
    if config is not None:
        params["config"] = config
    return params


def tckdfc_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `TckdfcParamsDict` 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("static", False) is None:
        raise StyxValidationError("`static` must not be None")
    if not isinstance(params["static"], bool):
        raise StyxValidationError(f'`static` has the wrong type: Received `{type(params.get("static", False))}` expected `bool`')
    if params.get("dynamic", None) is not None:
        tckdfc_dynamic_validate(params["dynamic"])
    if params.get("template", None) is not None:
        if not isinstance(params["template"], (pathlib.Path, str)):
            raise StyxValidationError(f'`template` has the wrong type: Received `{type(params.get("template", None))}` expected `InputPathType | None`')
    if params.get("vox", None) is not None:
        if not isinstance(params["vox"], list):
            raise StyxValidationError(f'`vox` has the wrong type: Received `{type(params.get("vox", None))}` expected `list[float] | None`')
        for e in params["vox"]:
            if not isinstance(e, (float, int)):
                raise StyxValidationError(f'`vox` has the wrong type: Received `{type(params.get("vox", None))}` expected `list[float] | None`')
    if params.get("stat_vox", None) is not None:
        if not isinstance(params["stat_vox"], str):
            raise StyxValidationError(f'`stat_vox` has the wrong type: Received `{type(params.get("stat_vox", None))}` expected `str | None`')
    if params.get("backtrack", False) is None:
        raise StyxValidationError("`backtrack` must not be None")
    if not isinstance(params["backtrack"], bool):
        raise StyxValidationError(f'`backtrack` has the wrong type: Received `{type(params.get("backtrack", False))}` expected `bool`')
    if params.get("upsample", None) is not None:
        if not isinstance(params["upsample"], int):
            raise StyxValidationError(f'`upsample` has the wrong type: Received `{type(params.get("upsample", None))}` expected `int | None`')
    if params.get("info", False) is None:
        raise StyxValidationError("`info` must not be None")
    if not isinstance(params["info"], bool):
        raise StyxValidationError(f'`info` has the wrong type: Received `{type(params.get("info", False))}` expected `bool`')
    if params.get("quiet", False) is None:
        raise StyxValidationError("`quiet` must not be None")
    if not isinstance(params["quiet"], bool):
        raise StyxValidationError(f'`quiet` has the wrong type: Received `{type(params.get("quiet", False))}` expected `bool`')
    if params.get("debug", False) is None:
        raise StyxValidationError("`debug` must not be None")
    if not isinstance(params["debug"], bool):
        raise StyxValidationError(f'`debug` has the wrong type: Received `{type(params.get("debug", False))}` expected `bool`')
    if params.get("force", False) is None:
        raise StyxValidationError("`force` must not be None")
    if not isinstance(params["force"], bool):
        raise StyxValidationError(f'`force` has the wrong type: Received `{type(params.get("force", False))}` expected `bool`')
    if params.get("nthreads", None) is not None:
        if not isinstance(params["nthreads"], int):
            raise StyxValidationError(f'`nthreads` has the wrong type: Received `{type(params.get("nthreads", None))}` expected `int | None`')
    if params.get("config", None) is not None:
        if not isinstance(params["config"], list):
            raise StyxValidationError(f'`config` has the wrong type: Received `{type(params.get("config", None))}` expected `list[TckdfcConfigParamsDict] | None`')
        for e in params["config"]:
            tckdfc_config_validate(e)
    if params.get("help", False) is None:
        raise StyxValidationError("`help` must not be None")
    if not isinstance(params["help"], bool):
        raise StyxValidationError(f'`help` has the wrong type: Received `{type(params.get("help", False))}` expected `bool`')
    if params.get("version", False) is None:
        raise StyxValidationError("`version` must not be None")
    if not isinstance(params["version"], bool):
        raise StyxValidationError(f'`version` has the wrong type: Received `{type(params.get("version", False))}` expected `bool`')
    if params.get("tracks", None) is None:
        raise StyxValidationError("`tracks` must not be None")
    if not isinstance(params["tracks"], (pathlib.Path, str)):
        raise StyxValidationError(f'`tracks` has the wrong type: Received `{type(params.get("tracks", None))}` expected `InputPathType`')
    if params.get("fmri", None) is None:
        raise StyxValidationError("`fmri` must not be None")
    if not isinstance(params["fmri"], (pathlib.Path, str)):
        raise StyxValidationError(f'`fmri` has the wrong type: Received `{type(params.get("fmri", None))}` expected `InputPathType`')
    if params.get("output", None) is None:
        raise StyxValidationError("`output` must not be None")
    if not isinstance(params["output"], str):
        raise StyxValidationError(f'`output` has the wrong type: Received `{type(params.get("output", None))}` expected `str`')


def tckdfc_cargs(
    params: TckdfcParamsDict,
    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("tckdfc")
    if params.get("static", False):
        cargs.append("-static")
    if params.get("dynamic", None) is not None:
        cargs.extend(tckdfc_dynamic_cargs(params.get("dynamic", None), execution))
    if params.get("template", None) is not None:
        cargs.extend([
            "-template",
            execution.input_file(params.get("template", None))
        ])
    if params.get("vox", None) is not None:
        cargs.extend([
            "-vox",
            ",".join(map(str, params.get("vox", None)))
        ])
    if params.get("stat_vox", None) is not None:
        cargs.extend([
            "-stat_vox",
            params.get("stat_vox", None)
        ])
    if params.get("backtrack", False):
        cargs.append("-backtrack")
    if params.get("upsample", None) is not None:
        cargs.extend([
            "-upsample",
            str(params.get("upsample", None))
        ])
    if params.get("info", False):
        cargs.append("-info")
    if params.get("quiet", False):
        cargs.append("-quiet")
    if params.get("debug", False):
        cargs.append("-debug")
    if params.get("force", False):
        cargs.append("-force")
    if params.get("nthreads", None) is not None:
        cargs.extend([
            "-nthreads",
            str(params.get("nthreads", None))
        ])
    if params.get("config", None) is not None:
        cargs.extend([a for c in [tckdfc_config_cargs(s, execution) for s in params.get("config", None)] for a in c])
    if params.get("help", False):
        cargs.append("-help")
    if params.get("version", False):
        cargs.append("-version")
    cargs.append(execution.input_file(params.get("tracks", None)))
    cargs.append(execution.input_file(params.get("fmri", None)))
    cargs.append(params.get("output", None))
    return cargs


def tckdfc_outputs(
    params: TckdfcParamsDict,
    execution: Execution,
) -> TckdfcOutputs:
    """
    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 = TckdfcOutputs(
        root=execution.output_file("."),
        output=execution.output_file(params.get("output", None)),
    )
    return ret


def tckdfc_execute(
    params: TckdfcParamsDict,
    runner: Runner | None = None,
) -> TckdfcOutputs:
    """
    tckdfc
    
    Perform the Track-Weighted Dynamic Functional Connectivity (TW-dFC) method.
    
    This command generates a Track-Weighted Image (TWI), where the contribution
    from each streamline to the image is the Pearson correlation between the
    fMRI time series at the streamline endpoints.
    
    The output image can be generated in one of two ways (note that one of these
    two command-line options MUST be provided):
    
    - "Static" functional connectivity (-static option): Each streamline
    contributes to a static 3D output image based on the correlation between the
    signals at the streamline endpoints using the entirety of the input time
    series.
    
    - "Dynamic" functional connectivity (-dynamic option): The output image is a
    4D image, with the same number of volumes as the input fMRI time series. For
    each volume, the contribution from each streamline is calculated based on a
    finite-width sliding time window, centred at the timepoint corresponding to
    that volume.
    
    Note that the -backtrack option in this command is similar, but not
    precisely equivalent, to back-tracking as can be used with
    Anatomically-Constrained Tractography (ACT) in the tckgen command. However,
    here the feature does not change the streamlines trajectories in any way; it
    simply enables detection of the fact that the input fMRI image may not
    contain a valid timeseries underneath the streamline endpoint, and where
    this occurs, searches from the streamline endpoint inwards along the
    streamline trajectory in search of a valid timeseries to sample from the
    input image.
    
    References:
    
    Calamante, F.; Smith, R.E.; Liang, X.; Zalesky, A.; Connelly, A
    Track-weighted dynamic functional connectivity (TW-dFC): a new method to
    study time-resolved functional connectivity. Brain Struct Funct, 2017, doi:
    10.1007/s00429-017-1431-1.
    
    Author: MRTrix3 Developers
    
    URL: https://www.mrtrix.org/
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `TckdfcOutputs`).
    """
    tckdfc_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(TCKDFC_METADATA)
    params = execution.params(params)
    cargs = tckdfc_cargs(params, execution)
    ret = tckdfc_outputs(params, execution)
    execution.run(cargs)
    return ret


def tckdfc(
    tracks: InputPathType,
    fmri: InputPathType,
    output: str,
    static: bool = False,
    dynamic: TckdfcDynamicParamsDict | None = None,
    template: InputPathType | None = None,
    vox: list[float] | None = None,
    stat_vox: str | None = None,
    backtrack: bool = False,
    upsample: int | None = None,
    info: bool = False,
    quiet: bool = False,
    debug: bool = False,
    force: bool = False,
    nthreads: int | None = None,
    config: list[TckdfcConfigParamsDict] | None = None,
    help_: bool = False,
    version: bool = False,
    runner: Runner | None = None,
) -> TckdfcOutputs:
    """
    tckdfc
    
    Perform the Track-Weighted Dynamic Functional Connectivity (TW-dFC) method.
    
    This command generates a Track-Weighted Image (TWI), where the contribution
    from each streamline to the image is the Pearson correlation between the
    fMRI time series at the streamline endpoints.
    
    The output image can be generated in one of two ways (note that one of these
    two command-line options MUST be provided):
    
    - "Static" functional connectivity (-static option): Each streamline
    contributes to a static 3D output image based on the correlation between the
    signals at the streamline endpoints using the entirety of the input time
    series.
    
    - "Dynamic" functional connectivity (-dynamic option): The output image is a
    4D image, with the same number of volumes as the input fMRI time series. For
    each volume, the contribution from each streamline is calculated based on a
    finite-width sliding time window, centred at the timepoint corresponding to
    that volume.
    
    Note that the -backtrack option in this command is similar, but not
    precisely equivalent, to back-tracking as can be used with
    Anatomically-Constrained Tractography (ACT) in the tckgen command. However,
    here the feature does not change the streamlines trajectories in any way; it
    simply enables detection of the fact that the input fMRI image may not
    contain a valid timeseries underneath the streamline endpoint, and where
    this occurs, searches from the streamline endpoint inwards along the
    streamline trajectory in search of a valid timeseries to sample from the
    input image.
    
    References:
    
    Calamante, F.; Smith, R.E.; Liang, X.; Zalesky, A.; Connelly, A
    Track-weighted dynamic functional connectivity (TW-dFC): a new method to
    study time-resolved functional connectivity. Brain Struct Funct, 2017, doi:
    10.1007/s00429-017-1431-1.
    
    Author: MRTrix3 Developers
    
    URL: https://www.mrtrix.org/
    
    Args:
        tracks: the input track file.
        fmri: the pre-processed fMRI time series.
        output: the output TW-dFC image.
        static: generate a "static" (3D) output image.
        dynamic: generate a "dynamic" (4D) output image; must additionally\
            provide the shape and width (in volumes) of the sliding window.
        template: an image file to be used as a template for the output (the\
            output image will have the same transform and field of view).
        vox: provide either an isotropic voxel size (in mm), or comma-separated\
            list of 3 voxel dimensions.
        stat_vox: define the statistic for choosing the final voxel intensities\
            for a given contrast type given the individual values from the tracks\
            passing through each voxel\
            Options are: sum, min, mean, max (default: mean).
        backtrack: if no valid timeseries is found at the streamline endpoint,\
            back-track along the streamline trajectory until a valid timeseries is\
            found.
        upsample: upsample the tracks by some ratio using Hermite interpolation\
            before mapping (if omitted, an appropriate ratio will be determined\
            automatically).
        info: display information messages.
        quiet: do not display information messages or progress status;\
            alternatively, this can be achieved by setting the MRTRIX_QUIET\
            environment variable to a non-empty string.
        debug: display debugging messages.
        force: force overwrite of output files (caution: using the same file as\
            input and output might cause unexpected behaviour).
        nthreads: use this number of threads in multi-threaded applications\
            (set to 0 to disable multi-threading).
        config: temporarily set the value of an MRtrix config file entry.
        help_: display this information page and exit.
        version: display version information and exit.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `TckdfcOutputs`).
    """
    params = tckdfc_params(
        static=static,
        dynamic=dynamic,
        template=template,
        vox=vox,
        stat_vox=stat_vox,
        backtrack=backtrack,
        upsample=upsample,
        info=info,
        quiet=quiet,
        debug=debug,
        force=force,
        nthreads=nthreads,
        config=config,
        help_=help_,
        version=version,
        tracks=tracks,
        fmri=fmri,
        output=output,
    )
    return tckdfc_execute(params, runner)


__all__ = [
    "TCKDFC_METADATA",
    "TckdfcConfigParamsDict",
    "TckdfcConfigParamsDictTagged",
    "TckdfcDynamicParamsDict",
    "TckdfcDynamicParamsDictTagged",
    "TckdfcOutputs",
    "TckdfcParamsDict",
    "TckdfcParamsDictTagged",
    "tckdfc",
    "tckdfc_config",
    "tckdfc_dynamic",
    "tckdfc_execute",
    "tckdfc_params",
]
