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

import typing
import pathlib
from styxdefs import *

N3_BIAS_FIELD_CORRECTION_METADATA = Metadata(
    id="12e6ca015aa736902ad4369af67b842768a91549.boutiques",
    name="N3BiasFieldCorrection",
    package="ants",
    container_image_tag="antsx/ants:v2.5.3",
)


N3BiasFieldCorrectionParameters = typing.TypedDict('N3BiasFieldCorrectionParameters', {
    "__STYX_TYPE__": typing.Literal["N3BiasFieldCorrection"],
    "image_dimensionality": typing.NotRequired[typing.Literal[2, 3, 4] | None],
    "input_image": InputPathType,
    "mask_image": typing.NotRequired[InputPathType | None],
    "rescale_intensities": typing.NotRequired[typing.Literal[0, 1] | None],
    "weight_image": typing.NotRequired[InputPathType | None],
    "shrink_factor": typing.NotRequired[int | None],
    "convergence": typing.NotRequired[str | None],
    "bspline_fitting": typing.NotRequired[str | None],
    "histogram_sharpening": typing.NotRequired[str | None],
    "output": str,
    "verbose": typing.NotRequired[typing.Literal[0, 1] | None],
})


def dyn_cargs(
    t: str,
) -> typing.Any:
    """
    Get build cargs function by command type.
    
    Args:
        t: Command type.
    Returns:
        Build cargs function.
    """
    return {
        "N3BiasFieldCorrection": n3_bias_field_correction_cargs,
    }.get(t)


def dyn_outputs(
    t: str,
) -> typing.Any:
    """
    Get build outputs function by command type.
    
    Args:
        t: Command type.
    Returns:
        Build outputs function.
    """
    return {
        "N3BiasFieldCorrection": n3_bias_field_correction_outputs,
    }.get(t)


class N3BiasFieldCorrectionOutputs(typing.NamedTuple):
    """
    Output object returned when calling `n3_bias_field_correction(...)`.
    """
    root: OutputPathType
    """Output root folder. This is the root folder for all outputs."""
    corrected_image: OutputPathType
    """The bias-corrected version of the input image."""
    bias_field: OutputPathType
    """The estimated bias field, if specified in the output."""


def n3_bias_field_correction_params(
    input_image: InputPathType,
    output: str,
    image_dimensionality: typing.Literal[2, 3, 4] | None = None,
    mask_image: InputPathType | None = None,
    rescale_intensities: typing.Literal[0, 1] | None = None,
    weight_image: InputPathType | None = None,
    shrink_factor: int | None = None,
    convergence: str | None = None,
    bspline_fitting: str | None = None,
    histogram_sharpening: str | None = None,
    verbose: typing.Literal[0, 1] | None = None,
) -> N3BiasFieldCorrectionParameters:
    """
    Build parameters.
    
    Args:
        input_image: A scalar image is expected as input for bias correction.\
            Since N3 log transforms the intensities, negative values or values\
            close to zero should be processed prior to correction.
        output: The bias-corrected version of the input image and optionally\
            the estimated bias field.
        image_dimensionality: This option forces the image to be treated as a\
            specified-dimensional image. If not specified, N3 tries to infer the\
            dimensionality from the input image.
        mask_image: If a mask image is specified, the final bias correction is\
            only performed in the mask region. If a mask image is not specified,\
            the entire image region will be used as the mask region. Note: this\
            differs from the original N3 implementation.
        rescale_intensities: This option rescales the intensity range within\
            the user-specified mask to the original [min, max] range.
        weight_image: The weight image allows the user to perform a relative\
            weighting of specific voxels during the B-spline fitting.
        shrink_factor: Shrink factor to resample the input image. Commonly used\
            values are <= 4.
        convergence: Describes the convergence criteria with default value as\
            [50,0.0].
        bspline_fitting: Describes the parameters for B-Spline fitting.\
            Defaults are [splineDistance,4,3].
        histogram_sharpening: Describes histogram sharpening parameters;\
            defaults are [0.15,0.01,200].
        verbose: Verbose output.
    Returns:
        Parameter dictionary
    """
    params = {
        "__STYXTYPE__": "N3BiasFieldCorrection",
        "input_image": input_image,
        "output": output,
    }
    if image_dimensionality is not None:
        params["image_dimensionality"] = image_dimensionality
    if mask_image is not None:
        params["mask_image"] = mask_image
    if rescale_intensities is not None:
        params["rescale_intensities"] = rescale_intensities
    if weight_image is not None:
        params["weight_image"] = weight_image
    if shrink_factor is not None:
        params["shrink_factor"] = shrink_factor
    if convergence is not None:
        params["convergence"] = convergence
    if bspline_fitting is not None:
        params["bspline_fitting"] = bspline_fitting
    if histogram_sharpening is not None:
        params["histogram_sharpening"] = histogram_sharpening
    if verbose is not None:
        params["verbose"] = verbose
    return params


def n3_bias_field_correction_cargs(
    params: N3BiasFieldCorrectionParameters,
    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("N3BiasFieldCorrection")
    if params.get("image_dimensionality") is not None:
        cargs.extend([
            "--image-dimensionality",
            str(params.get("image_dimensionality"))
        ])
    cargs.extend([
        "--input-image",
        execution.input_file(params.get("input_image"))
    ])
    if params.get("mask_image") is not None:
        cargs.extend([
            "--mask-image",
            execution.input_file(params.get("mask_image"))
        ])
    if params.get("rescale_intensities") is not None:
        cargs.extend([
            "--rescale-intensities",
            str(params.get("rescale_intensities"))
        ])
    if params.get("weight_image") is not None:
        cargs.extend([
            "--weight-image",
            execution.input_file(params.get("weight_image"))
        ])
    if params.get("shrink_factor") is not None:
        cargs.extend([
            "--shrink-factor",
            str(params.get("shrink_factor"))
        ])
    if params.get("convergence") is not None:
        cargs.extend([
            "--convergence",
            params.get("convergence")
        ])
    if params.get("bspline_fitting") is not None:
        cargs.extend([
            "--bspline-fitting",
            params.get("bspline_fitting")
        ])
    if params.get("histogram_sharpening") is not None:
        cargs.extend([
            "--histogram-sharpening",
            params.get("histogram_sharpening")
        ])
    cargs.extend([
        "--output",
        params.get("output")
    ])
    if params.get("verbose") is not None:
        cargs.extend([
            "--verbose",
            str(params.get("verbose"))
        ])
    return cargs


def n3_bias_field_correction_outputs(
    params: N3BiasFieldCorrectionParameters,
    execution: Execution,
) -> N3BiasFieldCorrectionOutputs:
    """
    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 = N3BiasFieldCorrectionOutputs(
        root=execution.output_file("."),
        corrected_image=execution.output_file(params.get("output")),
        bias_field=execution.output_file("[BIS_FIELD]"),
    )
    return ret


def n3_bias_field_correction_execute(
    params: N3BiasFieldCorrectionParameters,
    execution: Execution,
) -> N3BiasFieldCorrectionOutputs:
    """
    This N3 is a variant of the popular N3 (nonparametric nonuniform normalization)
    retrospective bias correction algorithm. Based on the assumption that the
    corruption of the low frequency bias field can be modeled as a convolution of
    the intensity histogram by a Gaussian, the basic algorithmic protocol is to
    iterate between deconvolving the intensity histogram by a Gaussian, remapping
    the intensities, and then spatially smoothing this result by a B-spline modeling
    of the bias field itself.
    
    Author: ANTs Developers
    
    URL: https://github.com/ANTsX/ANTs
    
    Args:
        params: The parameters.
        execution: The execution object.
    Returns:
        NamedTuple of outputs (described in `N3BiasFieldCorrectionOutputs`).
    """
    params = execution.params(params)
    cargs = n3_bias_field_correction_cargs(params, execution)
    ret = n3_bias_field_correction_outputs(params, execution)
    execution.run(cargs)
    return ret


def n3_bias_field_correction(
    input_image: InputPathType,
    output: str,
    image_dimensionality: typing.Literal[2, 3, 4] | None = None,
    mask_image: InputPathType | None = None,
    rescale_intensities: typing.Literal[0, 1] | None = None,
    weight_image: InputPathType | None = None,
    shrink_factor: int | None = None,
    convergence: str | None = None,
    bspline_fitting: str | None = None,
    histogram_sharpening: str | None = None,
    verbose: typing.Literal[0, 1] | None = None,
    runner: Runner | None = None,
) -> N3BiasFieldCorrectionOutputs:
    """
    This N3 is a variant of the popular N3 (nonparametric nonuniform normalization)
    retrospective bias correction algorithm. Based on the assumption that the
    corruption of the low frequency bias field can be modeled as a convolution of
    the intensity histogram by a Gaussian, the basic algorithmic protocol is to
    iterate between deconvolving the intensity histogram by a Gaussian, remapping
    the intensities, and then spatially smoothing this result by a B-spline modeling
    of the bias field itself.
    
    Author: ANTs Developers
    
    URL: https://github.com/ANTsX/ANTs
    
    Args:
        input_image: A scalar image is expected as input for bias correction.\
            Since N3 log transforms the intensities, negative values or values\
            close to zero should be processed prior to correction.
        output: The bias-corrected version of the input image and optionally\
            the estimated bias field.
        image_dimensionality: This option forces the image to be treated as a\
            specified-dimensional image. If not specified, N3 tries to infer the\
            dimensionality from the input image.
        mask_image: If a mask image is specified, the final bias correction is\
            only performed in the mask region. If a mask image is not specified,\
            the entire image region will be used as the mask region. Note: this\
            differs from the original N3 implementation.
        rescale_intensities: This option rescales the intensity range within\
            the user-specified mask to the original [min, max] range.
        weight_image: The weight image allows the user to perform a relative\
            weighting of specific voxels during the B-spline fitting.
        shrink_factor: Shrink factor to resample the input image. Commonly used\
            values are <= 4.
        convergence: Describes the convergence criteria with default value as\
            [50,0.0].
        bspline_fitting: Describes the parameters for B-Spline fitting.\
            Defaults are [splineDistance,4,3].
        histogram_sharpening: Describes histogram sharpening parameters;\
            defaults are [0.15,0.01,200].
        verbose: Verbose output.
        runner: Command runner.
    Returns:
        NamedTuple of outputs (described in `N3BiasFieldCorrectionOutputs`).
    """
    runner = runner or get_global_runner()
    execution = runner.start_execution(N3_BIAS_FIELD_CORRECTION_METADATA)
    params = n3_bias_field_correction_params(
        image_dimensionality=image_dimensionality,
        input_image=input_image,
        mask_image=mask_image,
        rescale_intensities=rescale_intensities,
        weight_image=weight_image,
        shrink_factor=shrink_factor,
        convergence=convergence,
        bspline_fitting=bspline_fitting,
        histogram_sharpening=histogram_sharpening,
        output=output,
        verbose=verbose,
    )
    return n3_bias_field_correction_execute(params, execution)


__all__ = [
    "N3BiasFieldCorrectionOutputs",
    "N3BiasFieldCorrectionParameters",
    "N3_BIAS_FIELD_CORRECTION_METADATA",
    "n3_bias_field_correction",
    "n3_bias_field_correction_params",
]
