File: checks.py

package info (click to toggle)
python-sigima 1.0.3-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 24,956 kB
  • sloc: python: 33,326; makefile: 3
file content (290 lines) | stat: -rw-r--r-- 9,932 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
# Copyright (c) DataLab Platform Developers, BSD 3-Clause license, see LICENSE file.

"""
.. Checks for 1D and 2D NumPy arrays used in tools (:mod:`sigima.tools.checks`).
"""

from __future__ import annotations

from dataclasses import dataclass
from functools import wraps
from typing import Any, Callable

import numpy as np


@dataclass(frozen=True)
class ArrayValidationRules:
    """Hold 1-D array validation rules."""

    #: Label used in error messages (e.g., "x" or "y")
    label: str
    #: Whether to enforce 1-D.
    require_1d: bool = True
    #: Check minimum size
    min_size: int | None = None
    #: Expected dtype (np.issubdtype). Use None to skip.
    dtype: type | None = None
    #: Whether to enforce finite values only.
    finite_only: bool = False
    #: Whether to enforce non-decreasing order.
    sorted_: bool = False
    #: Whether to enforce constant spacing (within rtol).
    evenly_spaced: bool = False
    #: Relative tolerance for regular spacing.
    rtol: float = 1e-5


def _validate_array_1d(arr: np.ndarray, *, rules: ArrayValidationRules) -> None:
    """Validate a single 1D NumPy array according to the provided rules.

    Args:
        arr: Array to validate.
        rules: Validation rules to apply.

    Raises:
        ValueError: If shape constraint is violated.
        ValueError: If size constraint is violated.
        ValueError: If finite constraint is violated.
        ValueError: If order constraint is violated.
        ValueError: If spacing constraint is violated.
        TypeError: If dtype does not match.
    """
    if rules.require_1d and arr.ndim != 1:
        raise ValueError(f"{rules.label} must be 1-D.")
    if rules.min_size is not None and arr.size < rules.min_size:
        raise ValueError(f"{rules.label} must have at least {rules.min_size} elements.")
    if rules.dtype is not None and not np.issubdtype(arr.dtype, rules.dtype):
        raise TypeError(
            f"{rules.label} must be of type {rules.dtype}, but got {arr.dtype}."
        )
    if rules.finite_only and not np.all(np.isfinite(arr)):
        raise ValueError(f"{rules.label} must contain only finite values.")
    if rules.sorted_ and arr.size > 1 and not np.all(np.diff(arr) > 0.0):
        raise ValueError(f"{rules.label} must be sorted in ascending order.")
    if rules.evenly_spaced and arr.size > 1:
        dx = np.diff(arr)
        if not np.allclose(dx, np.mean(dx), rtol=rules.rtol):
            raise ValueError(f"{rules.label} must be evenly spaced.")


def check_1d_array(
    func: Callable[..., Any] | None = None,
    *,
    require_1d: bool = True,
    min_size: int | None = None,
    dtype: type | None = np.inexact,
    finite_only: bool = False,
    sorted_: bool = False,
    evenly_spaced: bool = False,
    rtol: float = 1e-5,
    label: str = "array",
) -> Callable:
    """Decorator to check a single 1D NumPy array.

    Can be used with or without parentheses.

    Args:
        require_1d: Whether to check if the array is 1-D.
        min_size: Minimum size of the array.
        dtype: Expected dtype of the array (np.issubdtype). Use None to skip.
        finite_only: Whether to check if the array contains only finite values.
        sorted_: Whether to check if the array is sorted in ascending order.
        evenly_spaced: Whether to check if the array is evenly spaced.
        rtol: Relative tolerance for regular spacing.
        label: Label for error messages (e.g., "x", "y").

    Returns:
        Decorated function with pre-checks on the single array.
    """

    def decorator(inner_func: Callable[..., Any]) -> Callable[..., Any]:
        @wraps(inner_func)
        def wrapper(arr: np.ndarray, *args: Any, **kwargs: Any) -> Any:
            _validate_array_1d(
                arr,
                rules=ArrayValidationRules(
                    label=label,
                    require_1d=require_1d,
                    min_size=min_size,
                    dtype=dtype,
                    finite_only=finite_only,
                    sorted_=sorted_,
                    evenly_spaced=evenly_spaced,
                    rtol=rtol,
                ),
            )
            return inner_func(arr, *args, **kwargs)

        return wrapper

    if func is not None:
        return decorator(func)
    return decorator


def check_1d_arrays(
    func: Callable[..., Any] | None = None,
    *,
    x_require_1d: bool = True,
    x_min_size: int | None = None,
    x_dtype: type | None = np.floating,
    x_finite_only: bool = False,
    x_sorted: bool = False,
    x_evenly_spaced: bool = False,
    y_require_1d: bool = True,
    y_min_size: int | None = None,
    y_dtype: type | None = np.inexact,
    y_finite_only: bool = False,
    same_size: bool = True,
    rtol: float = 1e-5,
) -> Callable:
    """Decorator to check paired 1D NumPy arrays (x, y).

    Can be used with or without parentheses.

    Args:
        func: Function to decorate.
        x_require_1d: Whether to check if x is 1-D.
        x_min_size: Minimum size of x.
        x_dtype: Expected dtype of x (np.issubdtype). Use None to skip.
        x_finite_only: Whether to check if x contains only finite values.
        x_sorted: Whether to check if x is sorted in ascending order.
        x_evenly_spaced: Whether to check if x is evenly spaced.
        y_require_1d: Whether to check if y is 1-D.
        y_min_size: Minimum size of y.
        y_dtype: Expected dtype of y (np.issubdtype). Use None to skip.
        y_finite_only: Whether to check if y contains only finite values.
        same_size: Whether to check that x and y have the same size.
        rtol: Relative tolerance for regular spacing (used for x).

    Returns:
        Decorated function with pre-checks on x/y.
    """

    def decorator(inner_func: Callable[..., Any]) -> Callable[..., Any]:
        @wraps(inner_func)
        def wrapper(x: np.ndarray, y: np.ndarray, *args: Any, **kwargs: Any) -> Any:
            _validate_array_1d(
                x,
                rules=ArrayValidationRules(
                    label="x",
                    require_1d=x_require_1d,
                    min_size=x_min_size,
                    dtype=x_dtype,
                    finite_only=x_finite_only,
                    sorted_=x_sorted,
                    evenly_spaced=x_evenly_spaced,
                    rtol=rtol,
                ),
            )
            _validate_array_1d(
                y,
                rules=ArrayValidationRules(
                    label="y",
                    require_1d=y_require_1d,
                    min_size=y_min_size,
                    dtype=y_dtype,
                    finite_only=y_finite_only,
                    sorted_=False,
                    evenly_spaced=False,
                    rtol=rtol,
                ),
            )
            if same_size and x.size != y.size:
                raise ValueError("x and y must have the same size.")
            return inner_func(x, y, *args, **kwargs)

        return wrapper

    if func is not None:
        return decorator(func)
    return decorator


def check_2d_array(
    func: Callable[..., Any] | None = None,
    *,
    ndim: int = 2,
    dtype: type | None = None,
    non_constant: bool = False,
    finite_only: bool = False,
) -> Callable:
    """
    Decorator to check input for functions operating on 2D NumPy arrays (e.g. images).

    Can be used with parentheses:

    .. code-block:: python

        @check_2d_array(ndim=3, dtype=np.uint8)
        def process_image(image: np.ndarray) -> np.ndarray:
            # Process the image
            return image

    Or without parentheses (default arguments):

    .. code-block:: python

        @check_2d_array
        def process_image(image: np.ndarray) -> np.ndarray:
            # Process the image
            return image

    Args:
        ndim: Expected number of dimensions.
        dtype: Expected dtype.
        non_constant: Whether to check that the array has dynamic range.
        finite_only: Whether to check that all values are finite.

    Returns:
        Decorated function with pre-checks on data.
    """

    def decorator(inner_func: Callable[..., Any]) -> Callable[..., Any]:
        @wraps(inner_func)
        def wrapper(data: np.ndarray, *args: Any, **kwargs: Any) -> Any:
            # === Check input array
            if data.ndim != ndim:
                raise ValueError(f"Input array must be {ndim}D, got {data.ndim}D.")
            if dtype is not None and not np.issubdtype(data.dtype, dtype):
                raise TypeError(
                    f"Input array must be of type {dtype}, got {data.dtype}."
                )
            if non_constant:
                dmin, dmax = np.nanmin(data), np.nanmax(data)
                if dmin == dmax:
                    raise ValueError("Input array has no dynamic range.")
            if finite_only and not np.all(np.isfinite(data)):
                raise ValueError("Input array contains non-finite values.")
            # === Call the original function
            return inner_func(data, *args, **kwargs)

        return wrapper

    if func is not None:
        # Usage: `@check_2d_array`
        return decorator(func)
    # Usage: `@check_2d_array(...)`
    return decorator


def normalize_kernel(kernel: np.ndarray) -> np.ndarray:
    """Normalize a convolution/deconvolution kernel if needed.

    This utility function can normalize the kernel to sum to 1.0.

    Args:
        kernel: The kernel array to normalize.

    Returns:
        The normalized kernel if it's not already normalized and if its sum is not
        zero, otherwise the original kernel.

    Note:
        A kernel is considered normalized if ``np.isclose(sum(kernel), 1.0)``.
    """
    kernel_sum = np.sum(kernel)
    if not np.isclose(kernel_sum, 1.0) and kernel_sum != 0.0:
        return kernel / kernel_sum
    return kernel