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

import typing
import pathlib
from styxdefs import *

DWIDENOISE_METADATA = Metadata(
    id="82c3888900162dbe688e89a630bf3f397f859b0b.boutiques",
    name="dwidenoise",
    package="mrtrix",
    container_image_tag="mrtrix3/mrtrix3:3.0.4",
)


_DwidenoiseConfigParamsDictNoTag = typing.TypedDict('_DwidenoiseConfigParamsDictNoTag', {
    "key": str,
    "value": str,
})
DwidenoiseConfigParamsDictTagged = typing.TypedDict('DwidenoiseConfigParamsDictTagged', {
    "@type": typing.Literal["config"],
    "key": str,
    "value": str,
})
DwidenoiseConfigParamsDict = _DwidenoiseConfigParamsDictNoTag | DwidenoiseConfigParamsDictTagged


_DwidenoiseParamsDictNoTag = typing.TypedDict('_DwidenoiseParamsDictNoTag', {
    "mask": typing.NotRequired[InputPathType | None],
    "extent": typing.NotRequired[list[int] | None],
    "noise": typing.NotRequired[str | None],
    "datatype": typing.NotRequired[str | None],
    "estimator": typing.NotRequired[str | None],
    "info": bool,
    "quiet": bool,
    "debug": bool,
    "force": bool,
    "nthreads": typing.NotRequired[int | None],
    "config": typing.NotRequired[list[DwidenoiseConfigParamsDict] | None],
    "help": bool,
    "version": bool,
    "dwi": InputPathType,
    "out": str,
})
DwidenoiseParamsDictTagged = typing.TypedDict('DwidenoiseParamsDictTagged', {
    "@type": typing.Literal["mrtrix/dwidenoise"],
    "mask": typing.NotRequired[InputPathType | None],
    "extent": typing.NotRequired[list[int] | None],
    "noise": typing.NotRequired[str | None],
    "datatype": typing.NotRequired[str | None],
    "estimator": typing.NotRequired[str | None],
    "info": bool,
    "quiet": bool,
    "debug": bool,
    "force": bool,
    "nthreads": typing.NotRequired[int | None],
    "config": typing.NotRequired[list[DwidenoiseConfigParamsDict] | None],
    "help": bool,
    "version": bool,
    "dwi": InputPathType,
    "out": str,
})
DwidenoiseParamsDict = _DwidenoiseParamsDictNoTag | DwidenoiseParamsDictTagged


def dwidenoise_config(
    key: str,
    value: str,
) -> DwidenoiseConfigParamsDictTagged:
    """
    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 dwidenoise_config_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `DwidenoiseConfigParamsDict` 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 dwidenoise_config_cargs(
    params: DwidenoiseConfigParamsDict,
    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 DwidenoiseOutputs(typing.NamedTuple):
    """
    Output object returned when calling `DwidenoiseParamsDict(...)`.
    """
    root: OutputPathType
    """Output root folder. This is the root folder for all outputs."""
    out: OutputPathType
    """the output denoised DWI image."""
    noise: OutputPathType | None
    """The output noise map, i.e., the estimated noise level 'sigma' in the
    data. Note that on complex input data, this will be the total noise level
    across real and imaginary channels, so a scale factor sqrt(2) applies. """


def dwidenoise_params(
    dwi: InputPathType,
    out: str,
    mask: InputPathType | None = None,
    extent: list[int] | None = None,
    noise: str | None = None,
    datatype: str | None = None,
    estimator: str | None = None,
    info: bool = False,
    quiet: bool = False,
    debug: bool = False,
    force: bool = False,
    nthreads: int | None = None,
    config: list[DwidenoiseConfigParamsDict] | None = None,
    help_: bool = False,
    version: bool = False,
) -> DwidenoiseParamsDictTagged:
    """
    Build parameters.
    
    Args:
        dwi: the input diffusion-weighted image.
        out: the output denoised DWI image.
        mask: Only process voxels within the specified binary brain mask image.
        extent: Set the patch size of the denoising filter. By default, the\
            command will select the smallest isotropic patch size that exceeds the\
            number of DW images in the input data, e.g., 5x5x5 for data with <= 125\
            DWI volumes, 7x7x7 for data with <= 343 DWI volumes, etc.
        noise: The output noise map, i.e., the estimated noise level 'sigma' in\
            the data. Note that on complex input data, this will be the total noise\
            level across real and imaginary channels, so a scale factor sqrt(2)\
            applies.
        datatype: Datatype for the eigenvalue decomposition (single or double\
            precision). For complex input data, this will select complex float32 or\
            complex float64 datatypes.
        estimator: Select the noise level estimator (default = Exp2), either:\
            * Exp1: the original estimator used in Veraart et al. (2016), or\
            * Exp2: the improved estimator introduced in Cordero-Grande et al.\
            (2019).
        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/dwidenoise",
        "info": info,
        "quiet": quiet,
        "debug": debug,
        "force": force,
        "help": help_,
        "version": version,
        "dwi": dwi,
        "out": out,
    }
    if mask is not None:
        params["mask"] = mask
    if extent is not None:
        params["extent"] = extent
    if noise is not None:
        params["noise"] = noise
    if datatype is not None:
        params["datatype"] = datatype
    if estimator is not None:
        params["estimator"] = estimator
    if nthreads is not None:
        params["nthreads"] = nthreads
    if config is not None:
        params["config"] = config
    return params


def dwidenoise_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `DwidenoiseParamsDict` 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("mask", None) is not None:
        if not isinstance(params["mask"], (pathlib.Path, str)):
            raise StyxValidationError(f'`mask` has the wrong type: Received `{type(params.get("mask", None))}` expected `InputPathType | None`')
    if params.get("extent", None) is not None:
        if not isinstance(params["extent"], list):
            raise StyxValidationError(f'`extent` has the wrong type: Received `{type(params.get("extent", None))}` expected `list[int] | None`')
        for e in params["extent"]:
            if not isinstance(e, int):
                raise StyxValidationError(f'`extent` has the wrong type: Received `{type(params.get("extent", None))}` expected `list[int] | None`')
    if params.get("noise", None) is not None:
        if not isinstance(params["noise"], str):
            raise StyxValidationError(f'`noise` has the wrong type: Received `{type(params.get("noise", None))}` expected `str | None`')
    if params.get("datatype", None) is not None:
        if not isinstance(params["datatype"], str):
            raise StyxValidationError(f'`datatype` has the wrong type: Received `{type(params.get("datatype", None))}` expected `str | None`')
    if params.get("estimator", None) is not None:
        if not isinstance(params["estimator"], str):
            raise StyxValidationError(f'`estimator` has the wrong type: Received `{type(params.get("estimator", None))}` expected `str | 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[DwidenoiseConfigParamsDict] | None`')
        for e in params["config"]:
            dwidenoise_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("dwi", None) is None:
        raise StyxValidationError("`dwi` must not be None")
    if not isinstance(params["dwi"], (pathlib.Path, str)):
        raise StyxValidationError(f'`dwi` has the wrong type: Received `{type(params.get("dwi", None))}` expected `InputPathType`')
    if params.get("out", None) is None:
        raise StyxValidationError("`out` must not be None")
    if not isinstance(params["out"], str):
        raise StyxValidationError(f'`out` has the wrong type: Received `{type(params.get("out", None))}` expected `str`')


def dwidenoise_cargs(
    params: DwidenoiseParamsDict,
    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("dwidenoise")
    if params.get("mask", None) is not None:
        cargs.extend([
            "-mask",
            execution.input_file(params.get("mask", None))
        ])
    if params.get("extent", None) is not None:
        cargs.extend([
            "-extent",
            *map(str, params.get("extent", None))
        ])
    if params.get("noise", None) is not None:
        cargs.extend([
            "-noise",
            params.get("noise", None)
        ])
    if params.get("datatype", None) is not None:
        cargs.extend([
            "-datatype",
            params.get("datatype", None)
        ])
    if params.get("estimator", None) is not None:
        cargs.extend([
            "-estimator",
            params.get("estimator", 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 [dwidenoise_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("dwi", None)))
    cargs.append(params.get("out", None))
    return cargs


def dwidenoise_outputs(
    params: DwidenoiseParamsDict,
    execution: Execution,
) -> DwidenoiseOutputs:
    """
    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 = DwidenoiseOutputs(
        root=execution.output_file("."),
        out=execution.output_file(params.get("out", None)),
        noise=execution.output_file(params.get("noise", None)) if (params.get("noise") is not None) else None,
    )
    return ret


def dwidenoise_execute(
    params: DwidenoiseParamsDict,
    runner: Runner | None = None,
) -> DwidenoiseOutputs:
    """
    dwidenoise
    
    dMRI noise level estimation and denoising using Marchenko-Pastur PCA.
    
    DWI data denoising and noise map estimation by exploiting data redundancy in
    the PCA domain using the prior knowledge that the eigenspectrum of random
    covariance matrices is described by the universal Marchenko-Pastur (MP)
    distribution. Fitting the MP distribution to the spectrum of patch-wise
    signal matrices hence provides an estimator of the noise level 'sigma', as
    was first shown in Veraart et al. (2016) and later improved in
    Cordero-Grande et al. (2019). This noise level estimate then determines the
    optimal cut-off for PCA denoising.
    
    Important note: image denoising must be performed as the first step of the
    image processing pipeline. The routine will fail if interpolation or
    smoothing has been applied to the data prior to denoising.
    
    Note that this function does not correct for non-Gaussian noise biases
    present in magnitude-reconstructed MRI images. If available, including the
    MRI phase data can reduce such non-Gaussian biases, and the command now
    supports complex input data.
    
    References:
    
    Veraart, J.; Novikov, D.S.; Christiaens, D.; Ades-aron, B.; Sijbers, J. &
    Fieremans, E. Denoising of diffusion MRI using random matrix theory.
    NeuroImage, 2016, 142, 394-406, doi: 10.1016/j.neuroimage.2016.08.016
    
    Veraart, J.; Fieremans, E. & Novikov, D.S. Diffusion MRI noise mapping using
    random matrix theory. Magn. Res. Med., 2016, 76(5), 1582-1593, doi:
    10.1002/mrm.26059
    
    Cordero-Grande, L.; Christiaens, D.; Hutter, J.; Price, A.N.; Hajnal, J.V.
    Complex diffusion-weighted image estimation via matrix recovery under
    general noise models. NeuroImage, 2019, 200, 391-404, doi:
    10.1016/j.neuroimage.2019.06.039.
    
    Author: MRTrix3 Developers
    
    URL: https://www.mrtrix.org/
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `DwidenoiseOutputs`).
    """
    dwidenoise_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(DWIDENOISE_METADATA)
    params = execution.params(params)
    cargs = dwidenoise_cargs(params, execution)
    ret = dwidenoise_outputs(params, execution)
    execution.run(cargs)
    return ret


def dwidenoise(
    dwi: InputPathType,
    out: str,
    mask: InputPathType | None = None,
    extent: list[int] | None = None,
    noise: str | None = None,
    datatype: str | None = None,
    estimator: str | None = None,
    info: bool = False,
    quiet: bool = False,
    debug: bool = False,
    force: bool = False,
    nthreads: int | None = None,
    config: list[DwidenoiseConfigParamsDict] | None = None,
    help_: bool = False,
    version: bool = False,
    runner: Runner | None = None,
) -> DwidenoiseOutputs:
    """
    dwidenoise
    
    dMRI noise level estimation and denoising using Marchenko-Pastur PCA.
    
    DWI data denoising and noise map estimation by exploiting data redundancy in
    the PCA domain using the prior knowledge that the eigenspectrum of random
    covariance matrices is described by the universal Marchenko-Pastur (MP)
    distribution. Fitting the MP distribution to the spectrum of patch-wise
    signal matrices hence provides an estimator of the noise level 'sigma', as
    was first shown in Veraart et al. (2016) and later improved in
    Cordero-Grande et al. (2019). This noise level estimate then determines the
    optimal cut-off for PCA denoising.
    
    Important note: image denoising must be performed as the first step of the
    image processing pipeline. The routine will fail if interpolation or
    smoothing has been applied to the data prior to denoising.
    
    Note that this function does not correct for non-Gaussian noise biases
    present in magnitude-reconstructed MRI images. If available, including the
    MRI phase data can reduce such non-Gaussian biases, and the command now
    supports complex input data.
    
    References:
    
    Veraart, J.; Novikov, D.S.; Christiaens, D.; Ades-aron, B.; Sijbers, J. &
    Fieremans, E. Denoising of diffusion MRI using random matrix theory.
    NeuroImage, 2016, 142, 394-406, doi: 10.1016/j.neuroimage.2016.08.016
    
    Veraart, J.; Fieremans, E. & Novikov, D.S. Diffusion MRI noise mapping using
    random matrix theory. Magn. Res. Med., 2016, 76(5), 1582-1593, doi:
    10.1002/mrm.26059
    
    Cordero-Grande, L.; Christiaens, D.; Hutter, J.; Price, A.N.; Hajnal, J.V.
    Complex diffusion-weighted image estimation via matrix recovery under
    general noise models. NeuroImage, 2019, 200, 391-404, doi:
    10.1016/j.neuroimage.2019.06.039.
    
    Author: MRTrix3 Developers
    
    URL: https://www.mrtrix.org/
    
    Args:
        dwi: the input diffusion-weighted image.
        out: the output denoised DWI image.
        mask: Only process voxels within the specified binary brain mask image.
        extent: Set the patch size of the denoising filter. By default, the\
            command will select the smallest isotropic patch size that exceeds the\
            number of DW images in the input data, e.g., 5x5x5 for data with <= 125\
            DWI volumes, 7x7x7 for data with <= 343 DWI volumes, etc.
        noise: The output noise map, i.e., the estimated noise level 'sigma' in\
            the data. Note that on complex input data, this will be the total noise\
            level across real and imaginary channels, so a scale factor sqrt(2)\
            applies.
        datatype: Datatype for the eigenvalue decomposition (single or double\
            precision). For complex input data, this will select complex float32 or\
            complex float64 datatypes.
        estimator: Select the noise level estimator (default = Exp2), either:\
            * Exp1: the original estimator used in Veraart et al. (2016), or\
            * Exp2: the improved estimator introduced in Cordero-Grande et al.\
            (2019).
        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 `DwidenoiseOutputs`).
    """
    params = dwidenoise_params(
        mask=mask,
        extent=extent,
        noise=noise,
        datatype=datatype,
        estimator=estimator,
        info=info,
        quiet=quiet,
        debug=debug,
        force=force,
        nthreads=nthreads,
        config=config,
        help_=help_,
        version=version,
        dwi=dwi,
        out=out,
    )
    return dwidenoise_execute(params, runner)


__all__ = [
    "DWIDENOISE_METADATA",
    "DwidenoiseConfigParamsDict",
    "DwidenoiseConfigParamsDictTagged",
    "DwidenoiseOutputs",
    "DwidenoiseParamsDict",
    "DwidenoiseParamsDictTagged",
    "dwidenoise",
    "dwidenoise_config",
    "dwidenoise_execute",
    "dwidenoise_params",
]
