Skip to content

pixano_inference.schemas.nd_array

Pydantic models for N-dimensional arrays.

NDArray(**data)

Bases: BaseModel, Generic[T], ABC

Represents an N-dimensional array.

Attributes:

Name Type Description
values list[T]

The list of values.

shape list[int]

The shape of the array, represented as a list of integers.

np_dtype dtype

The NumPy data type of the array.

Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )

from_numpy(arr) classmethod

Create an instance of the class from a NumPy array.

Parameters:

Name Type Description Default
arr ndarray

The NumPy array to convert.

required

Returns:

Type Description
Self

An instance of the class with values and shape derived from the input array.

Source code in pixano_inference/schemas/nd_array.py
@classmethod
def from_numpy(cls, arr: np.ndarray) -> Self:
    """Create an instance of the class from a NumPy array.

    Args:
        arr: The NumPy array to convert.

    Returns:
        An instance of the class with values and shape derived from
            the input array.
    """
    shape = list(arr.shape)
    arr = arr.astype(dtype=cls.np_dtype)
    return cls(
        values=arr.reshape(-1).tolist(),
        shape=shape,
    )

from_torch(tensor) classmethod

Create an instance of the class from a PyTorch tensor.

Parameters:

Name Type Description Default
tensor Tensor

The PyTorch tensor to convert.

required

Returns:

Type Description
Self

An instance of the class with values and shape derived from the input tensor.

Source code in pixano_inference/schemas/nd_array.py
@classmethod
def from_torch(cls, tensor: "Tensor") -> Self:
    """Create an instance of the class from a PyTorch tensor.

    Args:
        tensor: The PyTorch tensor to convert.

    Returns:
        An instance of the class with values and shape derived from
            the input tensor.
    """
    assert_torch_installed()
    return cls.from_numpy(tensor.cpu().numpy())

to_numpy()

Convert the instance to a NumPy array.

Returns:

Type Description
ndarray

A NumPy array with values and shape derived from the instance.

Source code in pixano_inference/schemas/nd_array.py
def to_numpy(self) -> np.ndarray:
    """Convert the instance to a NumPy array.

    Returns:
        A NumPy array with values and shape derived from the instance.
    """
    array = np.array(self.values, dtype=self.np_dtype).reshape(self.shape)
    return array

to_torch()

Convert the instance to a PyTorch tensor.

Returns:

Type Description
Tensor

A PyTorch tensor with values and shape derived from the instance.

Source code in pixano_inference/schemas/nd_array.py
def to_torch(self) -> "Tensor":
    """Convert the instance to a PyTorch tensor.

    Returns:
        A PyTorch tensor with values and shape derived from the instance.
    """
    import torch

    assert_torch_installed()
    return torch.from_numpy(self.to_numpy())

NDArrayFloat(**data)

Bases: NDArray[float]

Represents an N-dimensional array of 32-bit floating-point values.

Attributes:

Name Type Description
values list[T]

The list of 32-bit floating-point values in the array.

shape list[int]

The shape of the array, represented as a list of integers.

np_dtype dtype

The NumPy data type of the array.

Source code in pydantic/main.py
def __init__(self, /, **data: Any) -> None:
    """Create a new model by parsing and validating input data from keyword arguments.

    Raises [`ValidationError`][pydantic_core.ValidationError] if the input data cannot be
    validated to form a valid model.

    `self` is explicitly positional-only to allow `self` as a field name.
    """
    # `__tracebackhide__` tells pytest and some other tools to omit this function from tracebacks
    __tracebackhide__ = True
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
    if self is not validated_self:
        warnings.warn(
            'A custom validator is returning a value other than `self`.\n'
            "Returning anything other than `self` from a top level model validator isn't supported when validating via `__init__`.\n"
            'See the `model_validator` docs (https://docs.pydantic.dev/latest/concepts/validators/#model-validators) for more details.',
            stacklevel=2,
        )