feat(lib): add gaussian_smooth to _postprocess
This commit is contained in:
31
src/ai_mouse/_postprocess.py
Normal file
31
src/ai_mouse/_postprocess.py
Normal file
@@ -0,0 +1,31 @@
|
||||
"""Pure-numpy post-processing primitives for trajectory generation.
|
||||
|
||||
All functions are pure (no I/O, no global state) and accept an explicit
|
||||
:class:`numpy.random.Generator` when randomness is involved.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def gaussian_smooth(x: np.ndarray, sigma: float = 1.0) -> np.ndarray:
|
||||
"""5-tap gaussian smoothing along a 1-D array; endpoints preserved.
|
||||
|
||||
Args:
|
||||
x: 1-D input array.
|
||||
sigma: gaussian std. Default 1.0 gives weights approximately
|
||||
[0.054, 0.244, 0.403, 0.244, 0.054].
|
||||
|
||||
Returns:
|
||||
Smoothed array of the same shape. ``x[0]`` and ``x[-1]`` unchanged.
|
||||
If ``len(x) < 5`` returns a copy of ``x`` (kernel won't fit).
|
||||
"""
|
||||
if len(x) < 5:
|
||||
return x.copy()
|
||||
kernel = np.exp(-0.5 * (np.arange(-2, 3) / sigma) ** 2)
|
||||
kernel /= kernel.sum()
|
||||
padded = np.pad(x, pad_width=2, mode="edge")
|
||||
smoothed = np.convolve(padded, kernel, mode="valid")
|
||||
smoothed[0] = x[0]
|
||||
smoothed[-1] = x[-1]
|
||||
return smoothed
|
||||
25
tests/unit/test_postprocess.py
Normal file
25
tests/unit/test_postprocess.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""Tests for trajectory post-processing primitives."""
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ai_mouse._postprocess import gaussian_smooth
|
||||
|
||||
|
||||
def test_gaussian_smooth_preserves_endpoints() -> None:
|
||||
x = np.array([1.0, 5.0, 3.0, 8.0, 2.0, 6.0, 4.0])
|
||||
result = gaussian_smooth(x, sigma=1.0)
|
||||
assert result[0] == 1.0
|
||||
assert result[-1] == 4.0
|
||||
|
||||
|
||||
def test_gaussian_smooth_short_input_unchanged() -> None:
|
||||
x = np.array([1.0, 2.0, 3.0])
|
||||
result = gaussian_smooth(x, sigma=1.0)
|
||||
assert np.array_equal(result, x)
|
||||
|
||||
|
||||
def test_gaussian_smooth_constant_unchanged() -> None:
|
||||
x = np.full(20, 7.5)
|
||||
result = gaussian_smooth(x, sigma=1.0)
|
||||
assert np.allclose(result, x, atol=1e-6)
|
||||
Reference in New Issue
Block a user