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

import typing
import pathlib
from styxdefs import *

DIRGEN_METADATA = Metadata(
    id="cda69ea8a57022773ddb6022ca8ca9caa5cc0e2b.boutiques",
    name="dirgen",
    package="mrtrix",
    container_image_tag="mrtrix3/mrtrix3:3.0.4",
)


_DirgenConfigParamsDictNoTag = typing.TypedDict('_DirgenConfigParamsDictNoTag', {
    "key": str,
    "value": str,
})
DirgenConfigParamsDictTagged = typing.TypedDict('DirgenConfigParamsDictTagged', {
    "@type": typing.Literal["config"],
    "key": str,
    "value": str,
})
DirgenConfigParamsDict = _DirgenConfigParamsDictNoTag | DirgenConfigParamsDictTagged


_DirgenParamsDictNoTag = typing.TypedDict('_DirgenParamsDictNoTag', {
    "power": typing.NotRequired[int | None],
    "niter": typing.NotRequired[int | None],
    "restarts": typing.NotRequired[int | None],
    "unipolar": bool,
    "cartesian": bool,
    "info": bool,
    "quiet": bool,
    "debug": bool,
    "force": bool,
    "nthreads": typing.NotRequired[int | None],
    "config": typing.NotRequired[list[DirgenConfigParamsDict] | None],
    "help": bool,
    "version": bool,
    "ndir": int,
    "dirs": str,
})
DirgenParamsDictTagged = typing.TypedDict('DirgenParamsDictTagged', {
    "@type": typing.Literal["mrtrix/dirgen"],
    "power": typing.NotRequired[int | None],
    "niter": typing.NotRequired[int | None],
    "restarts": typing.NotRequired[int | None],
    "unipolar": bool,
    "cartesian": bool,
    "info": bool,
    "quiet": bool,
    "debug": bool,
    "force": bool,
    "nthreads": typing.NotRequired[int | None],
    "config": typing.NotRequired[list[DirgenConfigParamsDict] | None],
    "help": bool,
    "version": bool,
    "ndir": int,
    "dirs": str,
})
DirgenParamsDict = _DirgenParamsDictNoTag | DirgenParamsDictTagged


def dirgen_config(
    key: str,
    value: str,
) -> DirgenConfigParamsDictTagged:
    """
    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 dirgen_config_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `DirgenConfigParamsDict` 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 dirgen_config_cargs(
    params: DirgenConfigParamsDict,
    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 DirgenOutputs(typing.NamedTuple):
    """
    Output object returned when calling `DirgenParamsDict(...)`.
    """
    root: OutputPathType
    """Output root folder. This is the root folder for all outputs."""
    dirs: OutputPathType
    """the text file to write the directions to, as [ az el ] pairs."""


def dirgen_params(
    ndir: int,
    dirs: str,
    power: int | None = None,
    niter: int | None = None,
    restarts: int | None = None,
    unipolar: bool = False,
    cartesian: bool = False,
    info: bool = False,
    quiet: bool = False,
    debug: bool = False,
    force: bool = False,
    nthreads: int | None = None,
    config: list[DirgenConfigParamsDict] | None = None,
    help_: bool = False,
    version: bool = False,
) -> DirgenParamsDictTagged:
    """
    Build parameters.
    
    Args:
        ndir: the number of directions to generate.
        dirs: the text file to write the directions to, as [ az el ] pairs.
        power: specify exponent to use for repulsion power law (default: 1).\
            This must be a power of 2 (i.e. 1, 2, 4, 8, 16, ...).
        niter: specify the maximum number of iterations to perform (default:\
            10000).
        restarts: specify the number of restarts to perform (default: 10).
        unipolar: optimise assuming a unipolar electrostatic repulsion model\
            rather than the bipolar model normally assumed in DWI.
        cartesian: Output the directions in Cartesian coordinates [x y z]\
            instead of [az el].
        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/dirgen",
        "unipolar": unipolar,
        "cartesian": cartesian,
        "info": info,
        "quiet": quiet,
        "debug": debug,
        "force": force,
        "help": help_,
        "version": version,
        "ndir": ndir,
        "dirs": dirs,
    }
    if power is not None:
        params["power"] = power
    if niter is not None:
        params["niter"] = niter
    if restarts is not None:
        params["restarts"] = restarts
    if nthreads is not None:
        params["nthreads"] = nthreads
    if config is not None:
        params["config"] = config
    return params


def dirgen_validate(
    params: typing.Any,
) -> None:
    """
    Validate parameters. Throws an error if `params` is not a valid
    `DirgenParamsDict` 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("power", None) is not None:
        if not isinstance(params["power"], int):
            raise StyxValidationError(f'`power` has the wrong type: Received `{type(params.get("power", None))}` expected `int | None`')
    if params.get("niter", None) is not None:
        if not isinstance(params["niter"], int):
            raise StyxValidationError(f'`niter` has the wrong type: Received `{type(params.get("niter", None))}` expected `int | None`')
    if params.get("restarts", None) is not None:
        if not isinstance(params["restarts"], int):
            raise StyxValidationError(f'`restarts` has the wrong type: Received `{type(params.get("restarts", None))}` expected `int | None`')
    if params.get("unipolar", False) is None:
        raise StyxValidationError("`unipolar` must not be None")
    if not isinstance(params["unipolar"], bool):
        raise StyxValidationError(f'`unipolar` has the wrong type: Received `{type(params.get("unipolar", False))}` expected `bool`')
    if params.get("cartesian", False) is None:
        raise StyxValidationError("`cartesian` must not be None")
    if not isinstance(params["cartesian"], bool):
        raise StyxValidationError(f'`cartesian` has the wrong type: Received `{type(params.get("cartesian", False))}` expected `bool`')
    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[DirgenConfigParamsDict] | None`')
        for e in params["config"]:
            dirgen_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("ndir", None) is None:
        raise StyxValidationError("`ndir` must not be None")
    if not isinstance(params["ndir"], int):
        raise StyxValidationError(f'`ndir` has the wrong type: Received `{type(params.get("ndir", None))}` expected `int`')
    if params.get("dirs", None) is None:
        raise StyxValidationError("`dirs` must not be None")
    if not isinstance(params["dirs"], str):
        raise StyxValidationError(f'`dirs` has the wrong type: Received `{type(params.get("dirs", None))}` expected `str`')


def dirgen_cargs(
    params: DirgenParamsDict,
    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("dirgen")
    if params.get("power", None) is not None:
        cargs.extend([
            "-power",
            str(params.get("power", None))
        ])
    if params.get("niter", None) is not None:
        cargs.extend([
            "-niter",
            str(params.get("niter", None))
        ])
    if params.get("restarts", None) is not None:
        cargs.extend([
            "-restarts",
            str(params.get("restarts", None))
        ])
    if params.get("unipolar", False):
        cargs.append("-unipolar")
    if params.get("cartesian", False):
        cargs.append("-cartesian")
    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 [dirgen_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(str(params.get("ndir", None)))
    cargs.append(params.get("dirs", None))
    return cargs


def dirgen_outputs(
    params: DirgenParamsDict,
    execution: Execution,
) -> DirgenOutputs:
    """
    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 = DirgenOutputs(
        root=execution.output_file("."),
        dirs=execution.output_file(params.get("dirs", None)),
    )
    return ret


def dirgen_execute(
    params: DirgenParamsDict,
    runner: Runner | None = None,
) -> DirgenOutputs:
    """
    dirgen
    
    Generate a set of uniformly distributed directions using a bipolar
    electrostatic repulsion model.
    
    Directions are distributed by analogy to an electrostatic repulsion system,
    with each direction corresponding to a single electrostatic charge (for
    -unipolar), or a pair of diametrically opposed charges (for the default
    bipolar case). The energy of the system is determined based on the Coulomb
    repulsion, which assumes the form 1/r^power, where r is the distance between
    any pair of charges, and p is the power assumed for the repulsion law
    (default: 1). The minimum energy state is obtained by gradient descent.
    
    References:
    
    Jones, D.; Horsfield, M. & Simmons, A. Optimal strategies for measuring
    diffusion in anisotropic systems by magnetic resonance imaging. Magnetic
    Resonance in Medicine, 1999, 42: 515-525
    
    Papadakis, N. G.; Murrills, C. D.; Hall, L. D.; Huang, C. L.-H. & Adrian
    Carpenter, T. Minimal gradient encoding for robust estimation of diffusion
    anisotropy. Magnetic Resonance Imaging, 2000, 18: 671-679.
    
    Author: MRTrix3 Developers
    
    URL: https://www.mrtrix.org/
    
    Args:
        params: The parameters.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `DirgenOutputs`).
    """
    dirgen_validate(params)
    runner = runner or get_global_runner()
    execution = runner.start_execution(DIRGEN_METADATA)
    params = execution.params(params)
    cargs = dirgen_cargs(params, execution)
    ret = dirgen_outputs(params, execution)
    execution.run(cargs)
    return ret


def dirgen(
    ndir: int,
    dirs: str,
    power: int | None = None,
    niter: int | None = None,
    restarts: int | None = None,
    unipolar: bool = False,
    cartesian: bool = False,
    info: bool = False,
    quiet: bool = False,
    debug: bool = False,
    force: bool = False,
    nthreads: int | None = None,
    config: list[DirgenConfigParamsDict] | None = None,
    help_: bool = False,
    version: bool = False,
    runner: Runner | None = None,
) -> DirgenOutputs:
    """
    dirgen
    
    Generate a set of uniformly distributed directions using a bipolar
    electrostatic repulsion model.
    
    Directions are distributed by analogy to an electrostatic repulsion system,
    with each direction corresponding to a single electrostatic charge (for
    -unipolar), or a pair of diametrically opposed charges (for the default
    bipolar case). The energy of the system is determined based on the Coulomb
    repulsion, which assumes the form 1/r^power, where r is the distance between
    any pair of charges, and p is the power assumed for the repulsion law
    (default: 1). The minimum energy state is obtained by gradient descent.
    
    References:
    
    Jones, D.; Horsfield, M. & Simmons, A. Optimal strategies for measuring
    diffusion in anisotropic systems by magnetic resonance imaging. Magnetic
    Resonance in Medicine, 1999, 42: 515-525
    
    Papadakis, N. G.; Murrills, C. D.; Hall, L. D.; Huang, C. L.-H. & Adrian
    Carpenter, T. Minimal gradient encoding for robust estimation of diffusion
    anisotropy. Magnetic Resonance Imaging, 2000, 18: 671-679.
    
    Author: MRTrix3 Developers
    
    URL: https://www.mrtrix.org/
    
    Args:
        ndir: the number of directions to generate.
        dirs: the text file to write the directions to, as [ az el ] pairs.
        power: specify exponent to use for repulsion power law (default: 1).\
            This must be a power of 2 (i.e. 1, 2, 4, 8, 16, ...).
        niter: specify the maximum number of iterations to perform (default:\
            10000).
        restarts: specify the number of restarts to perform (default: 10).
        unipolar: optimise assuming a unipolar electrostatic repulsion model\
            rather than the bipolar model normally assumed in DWI.
        cartesian: Output the directions in Cartesian coordinates [x y z]\
            instead of [az el].
        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 `DirgenOutputs`).
    """
    params = dirgen_params(
        power=power,
        niter=niter,
        restarts=restarts,
        unipolar=unipolar,
        cartesian=cartesian,
        info=info,
        quiet=quiet,
        debug=debug,
        force=force,
        nthreads=nthreads,
        config=config,
        help_=help_,
        version=version,
        ndir=ndir,
        dirs=dirs,
    )
    return dirgen_execute(params, runner)


__all__ = [
    "DIRGEN_METADATA",
    "DirgenConfigParamsDict",
    "DirgenConfigParamsDictTagged",
    "DirgenOutputs",
    "DirgenParamsDict",
    "DirgenParamsDictTagged",
    "dirgen",
    "dirgen_config",
    "dirgen_execute",
    "dirgen_params",
]
