A community-maintained Python framework for creating mathematical animations.
Fix: Make `normalize` properly check for a fallback when vector norm is 0 (#5001)
nikolajmunkaebf3574e8a0
diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.pyindex d55c623c5..d1b2e7293 100644--- a/manim/utils/space_ops.py+++ b/manim/utils/space_ops.py@@ -360,11 +360,22 @@ def angle_between_vectors(v1: np.ndarray, v2: np.ndarray) -> float:def normalize(vect: np.ndarray | tuple[float], fall_back: np.ndarray | None = None) -> np.ndarray:+ """Normalizes a vector to unit length while preserving its direction. If the vector+ has norm 0, a fallback vector is returned instead.++ Parameters+ ----------+ vect+ The vector to be normalized.+ fall_back+ The vector to be returned if ``vect`` has norm 0. If ``None``, a zero vector of+ the same length as ``vect`` is returned.+ """norm = np.linalg.norm(vect)if norm > 0:return np.array(vect) / normelse:- return fall_back or np.zeros(len(vect))+ return np.zeros(len(vect)) if fall_back is None else fall_backdef normalize_along_axis(array: np.ndarray, axis: np.ndarray) -> np.ndarray:diff --git a/tests/module/utils/test_space_ops.py b/tests/module/utils/test_space_ops.pyindex bcaf8168f..5d8a30344 100644--- a/tests/module/utils/test_space_ops.py+++ b/tests/module/utils/test_space_ops.py@@ -148,3 +148,46 @@ def test_triangulation_ring_connection():assert len(triangulation) % 3 == 0assert min(triangulation) >= 0assert max(triangulation) < len(verts)+++ ("vec", "expected"),+ [+ (np.array([1, 2, 3]), [0.26726124, 0.53452248, 0.80178373]),+ ((-1, -2, -3), [-0.26726124, -0.53452248, -0.80178373]),+ ((0.1, 0.1, 0), [0.70710678, 0.70710678, 0]),+ (np.array([10]), [1]),+ (+ np.array([0, 1, 2, 3, 4, 5]),+ [0, 0.13483997, 0.26967994, 0.40451992, 0.53935989, 0.67419986],+ ),+ ],+)+def test_normalize_nonzero_vector(vec, expected):+ normalized_vec = normalize(vec)+ assert np.allclose(normalized_vec, expected)++ # check that fallback vector is ignored when the input vector is non-zero+ fallback_vec = np.array([1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])+ normalized_vec_with_fallback = normalize(vec, fall_back=fallback_vec)+ assert np.all(normalized_vec_with_fallback == normalized_vec)+++ "vec",+ [+ np.array([0, 0, 0]),+ np.array([-0, -0, -0]),+ (0, 0, 0),+ np.array([0]),+ np.array([0, 0, 0, 0, 0]),+ ],+)+def test_normalize_zero_vector(vec):+ normalized_zero_vec = normalize(vec)+ assert np.allclose(normalized_zero_vec, np.zeros(len(vec)))++ # check that fallback vector is returned when the input vector is zero+ fallback_vec = np.array([1, 0, 0])+ normalized_zero_vec_with_fallback = normalize(vec, fall_back=fallback_vec)+ assert np.allclose(normalized_zero_vec_with_fallback, fallback_vec)