Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Add vectorized plotting functionality to improve performance (#2739)

Tristan Schulz9359331effff
diff --git a/manim/_config/utils.py b/manim/_config/utils.py
index cedf0a9fc..98bc88609 100644
--- a/manim/_config/utils.py
+++ b/manim/_config/utils.py
@@ -150,12 +150,22 @@ class ManimConfig(MutableMapping):
Examples
--------
+ We use a copy of the global configuration object in the following
+ examples for the sake of demonstration; you can skip these lines
+ and just import ``config`` directly if you actually want to modify
+ the configuration:
+
+ .. code-block:: pycon
+
+ >>> from manim import config as global_config
+ >>> config = global_config.copy()
+
Each config option allows for dict syntax and attribute syntax. For
example, the following two lines are equivalent,
.. code-block:: pycon
- >>> from manim import config, WHITE
+ >>> from manim import WHITE
>>> config.background_color = WHITE
>>> config["background_color"] = WHITE
@@ -1326,7 +1336,8 @@ class ManimConfig(MutableMapping):
.. code-block:: pycon
- >>> from manim import config
+ >>> from manim import config as globalconfig
+ >>> config = globalconfig.copy()
>>> config.tex_dir
'{media_dir}/Tex'
>>> config.media_dir
diff --git a/manim/mobject/graphing/coordinate_systems.py b/manim/mobject/graphing/coordinate_systems.py
index 8b5e7cd32..73e398bbe 100644
--- a/manim/mobject/graphing/coordinate_systems.py
+++ b/manim/mobject/graphing/coordinate_systems.py
@@ -629,6 +629,7 @@ class CoordinateSystem:
self,
function: Callable[[float], float],
x_range: Sequence[float] | None = None,
+ use_vectorized: bool = False,
**kwargs,
):
"""Generates a curve based on a function.
@@ -639,6 +640,9 @@ class CoordinateSystem:
The function used to construct the :class:`~.ParametricFunction`.
x_range
The range of the curve along the axes. ``x_range = [x_min, x_max, x_step]``.
+ use_vectorized
+ Whether to pass in the generated t value array to the function. Only use this if your function supports it.
+ Output should be a numpy array of shape ``[y_0, y_1, ...]``
kwargs
Additional parameters to be passed to :class:`~.ParametricFunction`.
@@ -714,6 +718,7 @@ class CoordinateSystem:
lambda t: self.coords_to_point(t, function(t)),
t_range=t_range,
scaling=self.x_axis.scaling,
+ use_vectorized=use_vectorized,
**kwargs,
)
graph.underlying_function = function
@@ -767,10 +772,12 @@ class CoordinateSystem:
)
return graph
- def plot_parametric_curve(self, function, **kwargs):
+ def plot_parametric_curve(self, function, use_vectorized=False, **kwargs):
dim = self.dimension
graph = ParametricFunction(
- lambda t: self.coords_to_point(*function(t)[:dim]), **kwargs
+ lambda t: self.coords_to_point(*function(t)[:dim]),
+ use_vectorized=use_vectorized,
+ **kwargs,
)
graph.underlying_function = function
return graph
@@ -1342,6 +1349,7 @@ class CoordinateSystem:
graph: ParametricFunction,
y_intercept: float = 0,
samples: int = 50,
+ use_vectorized: bool = False,
**kwargs,
):
"""Plots an antiderivative graph.
@@ -1354,6 +1362,10 @@ class CoordinateSystem:
The y-value at which the graph intercepts the y-axis.
samples
The number of points to take the area under the graph.
+ use_vectorized
+ Whether to use the vectorized version of the antiderivative. This means
+ to pass in the generated t value array to the function. Only use this if your function supports it.
+ Output should be a numpy array of shape ``[y_0, y_1, ...]``
kwargs
Any valid keyword argument of :class:`~.ParametricFunction`.
@@ -1385,12 +1397,12 @@ class CoordinateSystem:
"""
def antideriv(x):
- x_vals = np.linspace(0, x, samples)
+ x_vals = np.linspace(0, x, samples, axis=1 if use_vectorized else 0)
f_vec = np.vectorize(graph.underlying_function)
y_vals = f_vec(x_vals)
return np.trapz(y_vals, x_vals) + y_intercept
- return self.plot(antideriv, **kwargs)
+ return self.plot(antideriv, use_vectorized=use_vectorized, **kwargs)
def get_secant_slope_group(
self,
@@ -1829,7 +1841,9 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
axis.shift(-axis.number_to_point(self._origin_shift([axis.x_min, axis.x_max])))
return axis
- def coords_to_point(self, *coords: Sequence[float]) -> np.ndarray:
+ def coords_to_point(
+ self, *coords: Sequence[float] | Sequence[Sequence[float]] | np.ndarray
+ ) -> np.ndarray:
"""Accepts coordinates from the axes and returns a point with respect to the scene.
Parameters
@@ -1837,13 +1851,39 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
coords
The coordinates. Each coord is passed as a separate argument: ``ax.coords_to_point(1, 2, 3)``.
+ Also accepts a list of coordinates
+
+ ``ax.coords_to_point( [x_0, x_1, ...], [y_0, y_1, ...], ... )``
+
+ ``ax.coords_to_point( [[x_0, y_0, z_0], [x_1, y_1, z_1]] )``
+
Returns
-------
np.ndarray
A point with respect to the scene's coordinate system.
+ The shape of the array will be similar to the shape of the input.
Examples
--------
+
+ .. code-block:: pycon
+
+ >>> from manim import Axes
+ >>> import numpy as np
+ >>> ax = Axes()
+ >>> np.around(ax.coords_to_point(1, 0, 0), 2)
+ array([0.86, 0. , 0. ])
+ >>> np.around(ax.coords_to_point([[0, 1], [1, 1], [1, 0]]), 2)
+ array([[0. , 0.75, 0. ],
+ [0.86, 0.75, 0. ],
+ [0.86, 0. , 0. ]])
+ >>> np.around(
+ ... ax.coords_to_point([0, 1, 1], [1, 1, 0]), 2
+ ... ) # Transposed version of the above
+ array([[0. , 0.86, 0.86],
+ [0.75, 0.75, 0. ],
+ [0. , 0. , 0. ]])
+
.. manim:: CoordsToPointExample
:save_last_frame:
@@ -1865,26 +1905,68 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
origin = self.x_axis.number_to_point(
self._origin_shift([self.x_axis.x_min, self.x_axis.x_max]),
)
- result = np.array(origin)
- for axis, coord in zip(self.get_axes(), coords):
- result += axis.number_to_point(coord) - origin
- return result
- def point_to_coords(self, point: Sequence[float]) -> tuple[float]:
+ coords = np.asarray(coords)
+
+ # if called like coords_to_point(1, 2, 3), then coords is a 1x3 array
+ transposed = False
+ if coords.ndim == 1:
+ # original implementation of coords_to_point for performance in the legacy case
+ result = np.array(origin)
+ for axis, number in zip(self.get_axes(), coords):
+ result += axis.number_to_point(number) - origin
+ return result
+ # if called like coords_to_point([1, 2, 3],[4, 5, 6]), then it shall be used as [1,4], [2,5], [3,6] and return the points as ([x_0,x_1],[y_0,y_1],[z_0,z_1])
+ elif coords.ndim == 2:
+ coords = coords.T
+ transposed = True
+ # if called like coords_to_point(np.array([[1, 2, 3],[4,5,6]])), reduce dimension by 1
+ elif coords.ndim == 3:
+ coords = np.squeeze(coords)
+ # else the coords is a Nx1, Nx2, Nx3 array so we do not need to modify the array
+
+ points = origin + np.sum(
+ [
+ axis.number_to_point(number) - origin
+ for number, axis in zip(coords.T, self.get_axes())
+ ],
+ axis=0,
+ )
+ # if called with single coord, then return a point instead of a list of points
+ if transposed:
+ return points.T
+ return points
+
+ def point_to_coords(self, point: Sequence[float]) -> np.ndarray:
"""Accepts a point from the scene and returns its coordinates with respect to the axes.
Parameters
----------
point
The point, i.e. ``RIGHT`` or ``[0, 1, 0]``.
+ Also accepts a list of points as ``[RIGHT, [0, 1, 0]]``.
Returns
-------
- Tuple[float]
- The coordinates on the axes, i.e. ``(4.0, 7.0)``.
+ np.ndarray[float]
+ The coordinates on the axes, i.e. ``[4.0, 7.0]``.
+ Or a list of coordinates if `point` is a list of points.
Examples
--------
+
+ .. code-block:: pycon
+
+ >>> from manim import Axes, RIGHT
+ >>> import numpy as np
+ >>> ax = Axes(x_range=[0, 10, 2])
+ >>> np.around(ax.point_to_coords(RIGHT), 2)
+ array([5.83, 0. ])
+ >>> np.around(ax.point_to_coords([[0, 0, 1], [1, 0, 0]]), 2)
+ array([[5. , 0. ],
+ [5.83, 0. ]])
+
+
.. manim:: PointToCoordsExample
:save_last_frame:
@@ -1902,7 +1984,11 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
self.add(ax, circ, label, Dot(circ.get_right()))
"""
- return tuple(axis.point_to_number(point) for axis in self.get_axes())
+ point = np.asarray(point)
+ result = np.asarray([axis.point_to_number(point) for axis in self.get_axes()])
+ if point.ndim == 2:
+ return result.T
+ return result
def get_axes(self) -> VGroup:
"""Gets the axes.
diff --git a/manim/mobject/graphing/functions.py b/manim/mobject/graphing/functions.py
index e93742057..4e40d463b 100644
--- a/manim/mobject/graphing/functions.py
+++ b/manim/mobject/graphing/functions.py
@@ -31,6 +31,11 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
use_smoothing
Whether to interpolate between the points of the function after they have been created.
(Will have odd behaviour with a low number of points)
+ use_vectorized
+ Whether to pass in the generated t value array to the function as ``[t_0, t_1, ...]``.
+ Only use this if your function supports it. Output should be a numpy array
+ of shape ``[[x_0, x_1, ...], [y_0, y_1, ...], [z_0, z_1, ...]]`` but ``z`` can
+ also be 0 if the Axes is 2D
discontinuities
Values of t at which the function experiences discontinuity.
dt
@@ -98,6 +103,7 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
dt: float = 1e-8,
discontinuities: Iterable[float] | None = None,
use_smoothing: bool = True,
+ use_vectorized: bool = False,
**kwargs,
):
self.function = function
@@ -110,6 +116,7 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
self.dt = dt
self.discontinuities = discontinuities
self.use_smoothing = use_smoothing
+ self.use_vectorized = use_vectorized
self.t_min, self.t_max, self.t_step = t_range
super().__init__(**kwargs)
@@ -147,7 +154,15 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
self.scaling.function(t2),
],
)
- points = np.array([self.function(t) for t in t_range])
+
+ if self.use_vectorized:
+ x, y, z = self.function(t_range)
+ if not isinstance(z, np.ndarray):
+ z = np.zeros_like(x)
+ points = np.stack(zip(x, y, z), axis=0)
+ else:
+ points = np.array([self.function(t) for t in t_range])
+
self.start_new_path(points[0])
self.add_points_as_corners(points[1:])
if self.use_smoothing:
diff --git a/manim/mobject/graphing/number_line.py b/manim/mobject/graphing/number_line.py
index 78f61e4b6..cafea17c9 100644
--- a/manim/mobject/graphing/number_line.py
+++ b/manim/mobject/graphing/number_line.py
@@ -324,24 +324,40 @@ class NumberLine(Line):
return self.scaling.function(tick_range)
- def number_to_point(self, number: float) -> np.ndarray:
+ def number_to_point(self, number: float | np.ndarray) -> np.ndarray:
"""Accepts a value along the number line and returns a point with
respect to the scene.
Parameters
----------
number
- The value to be transformed into a coordinate.
+ The value to be transformed into a coordinate. Or a list of values.
Returns
-------
np.ndarray
- A point with respect to the scene's coordinate system.
+ A point with respect to the scene's coordinate system. Or a list of points.
+
+ Examples
+ --------
+
+ >>> from manim import NumberLine
+ >>> number_line = NumberLine()
+ >>> number_line.number_to_point(0)
+ array([0., 0., 0.])
+ >>> number_line.number_to_point(1)
+ array([1., 0., 0.])
+ >>> number_line.number_to_point([1,2,3])
+ array([[1., 0., 0.],
+ [2., 0., 0.],
+ [3., 0., 0.]])
"""
-
+ number = np.asarray(number)
+ scalar = number.ndim == 0
number = self.scaling.inverse_function(number)
- alpha = float(number - self.x_range[0]) / (self.x_range[1] - self.x_range[0])
- val = interpolate(self.get_start(), self.get_end(), alpha)
+ alphas = (number - self.x_range[0]) / (self.x_range[1] - self.x_range[0])
+ alphas = float(alphas) if scalar else np.vstack(alphas)
+ val = interpolate(self.get_start(), self.get_end(), alphas)
return val
def point_to_number(self, point: Sequence[float]) -> float:
@@ -357,13 +373,27 @@ class NumberLine(Line):
-------
float
A float representing a value along the number line.
+
+ Examples
+ --------
+
+ >>> from manim import NumberLine
+ >>> number_line = NumberLine()
+ >>> number_line.point_to_number((0,0,0))
+ 0.0
+ >>> number_line.point_to_number((1,0,0))
+ 1.0
+ >>> number_line.point_to_number([[0.5,0,0],[1,0,0],[1.5,0,0]])
+ array([0.5, 1. , 1.5])
+
"""
+ point = np.asarray(point)
start, end = self.get_start_and_end()
unit_vect = normalize(end - start)
proportion = np.dot(point - start, unit_vect) / np.dot(end - start, unit_vect)
return interpolate(self.x_min, self.x_max, proportion)
- def n2p(self, number: float) -> np.ndarray:
+ def n2p(self, number: float | np.ndarray) -> np.ndarray:
"""Abbreviation for :meth:`~.NumberLine.number_to_point`."""
return self.number_to_point(number)
diff --git a/manim/mobject/graphing/scale.py b/manim/mobject/graphing/scale.py
index 2aaae7a5a..0e570a6a1 100644
--- a/manim/mobject/graphing/scale.py
+++ b/manim/mobject/graphing/scale.py
@@ -3,6 +3,8 @@ from __future__ import annotations
import math
from typing import TYPE_CHECKING, Any, Iterable
+import numpy as np
+
__all__ = ["LogBase", "LinearBase"]
from manim.mobject.text.numbers import Integer
@@ -141,11 +143,18 @@ class LogBase(_ScaleBase):
def inverse_function(self, value: float) -> float:
"""Inverse of ``function``. The value must be greater than 0"""
- if value <= 0:
+ if isinstance(value, np.ndarray):
+ condition = value.any() <= 0
+ func = lambda value, base: np.log(value) / np.log(base)
+ else:
+ condition = value <= 0
+ func = math.log
+
+ if condition:
raise ValueError(
"log(0) is undefined. Make sure the value is in the domain of the function"
)
- value = math.log(value, self.base)
+ value = func(value, self.base)
return value
def get_custom_labels(
diff --git a/manim/mobject/types/vectorized_mobject.py b/manim/mobject/types/vectorized_mobject.py
index fd2140ef3..b524822de 100644
--- a/manim/mobject/types/vectorized_mobject.py
+++ b/manim/mobject/types/vectorized_mobject.py
@@ -649,6 +649,9 @@ class VMobject(Mobject):
# TODO, check the len(self.points) % 4 == 0?
self.append_points([anchor1, handle1, handle2, anchor2])
+ def add_cubic_bezier_curves(self, curves):
+ self.append_points(curves.flatten())
+
def add_cubic_bezier_curve_to(
self,
handle1: np.ndarray,
diff --git a/manim/utils/space_ops.py b/manim/utils/space_ops.py
index 7f14c2750..d74a6dd59 100644
--- a/manim/utils/space_ops.py
+++ b/manim/utils/space_ops.py
@@ -301,7 +301,7 @@ def z_to_vector(vector: np.ndarray) -> np.ndarray:
return np.array([axis_x, axis_y, axis_z]).T
-def angle_of_vector(vector: Sequence[float]) -> float:
+def angle_of_vector(vector: Sequence[float] | np.ndarray) -> float:
"""Returns polar coordinate theta when vector is projected on xy plane.
Parameters
@@ -314,6 +314,13 @@ def angle_of_vector(vector: Sequence[float]) -> float:
float
The angle of the vector projected.
"""
+ if isinstance(vector, np.ndarray) and len(vector.shape) > 1:
+ if vector.shape[0] < 2:
+ raise ValueError("Vector must have the correct dimensions. (2, n)")
+ c_vec = np.empty(vector.shape[1], dtype=np.complex128)
+ c_vec.real = vector[0]
+ c_vec.imag = vector[1]
+ return np.angle(c_vec)
return np.angle(complex(*vector[:2]))
diff --git a/manim/utils/testing/frames_comparison.py b/manim/utils/testing/frames_comparison.py
index 05a771f5e..775219a87 100644
--- a/manim/utils/testing/frames_comparison.py
+++ b/manim/utils/testing/frames_comparison.py
@@ -94,7 +94,7 @@ def frames_comparison(
# Example: if "length" is parametrized from 0 to 20, the kwargs
# will be once with {"length" : 1}, etc.
test_name_with_param = test_name + "_".join(
- [f"{str(tup[0])}:{str(tup[1])}" for tup in kwargs.items()],
+ f"_{str(tup[0])}[{str(tup[1])}]" for tup in kwargs.items()
)
config_tests = _config_test(last_frame)
diff --git a/tests/test_coordinate_system.py b/tests/test_coordinate_system.py
index e463ef166..c01946322 100644
--- a/tests/test_coordinate_system.py
+++ b/tests/test_coordinate_system.py
@@ -102,6 +102,19 @@ def test_point_to_coords():
np.testing.assert_array_equal(coords, (7.0833, 2.6667))
+def test_point_to_coords_vectorized():
+ ax = Axes(x_range=[0, 10, 2])
+ circ = Circle(radius=0.5).shift(UR * 2)
+ points = np.array(
+ [circ.get_right(), circ.get_left(), circ.get_bottom(), circ.get_top()]
+ )
+ # get the coordinates of the circle with respect to the axes
+ expected = [np.around(ax.point_to_coords(point), decimals=4) for point in points]
+ actual = np.around(ax.point_to_coords(points), decimals=4)
+
+ np.testing.assert_array_equal(expected, actual)
+
+
def test_coords_to_point():
ax = Axes()
@@ -110,6 +123,41 @@ def test_coords_to_point():
np.testing.assert_array_equal(c2p_coord, (1.7143, 1.5, 0))
+def test_coords_to_point_vectorized():
+ plane = NumberPlane(x_range=[2, 4])
+
+ origin = plane.x_axis.number_to_point(
+ plane._origin_shift([plane.x_axis.x_min, plane.x_axis.x_max]),
+ )
+
+ def ref_func(*coords):
+ result = np.array(origin)
+ for axis, number in zip(plane.get_axes(), coords):
+ result += axis.number_to_point(number) - origin
+ return result
+
+ coords = [[1], [1, 2], [2, 2], [3, 4]]
+
+ print(f"\n\nTesting coords_to_point {coords}")
+ expected = np.round([ref_func(*coord) for coord in coords], 4)
+ actual1 = np.round([plane.coords_to_point(*coord) for coord in coords], 4)
+ coords[0] = [
+ 1,
+ 0,
+ ] # Extend the first coord because you can't vectorize items with different dimensions
+ actual2 = np.round(
+ plane.coords_to_point(coords), 4
+ ) # Test [x_0,y_0,z_0], [x_1,y_1,z_1], ...
+ actual3 = np.round(
+ plane.coords_to_point(*np.array(coords).T), 4
+ ) # Test [x_0,x_1,...], [y_0,y_1,...], ...
+ print(actual3)
+
+ np.testing.assert_array_equal(expected, actual1)
+ np.testing.assert_array_equal(expected, actual2)
+ np.testing.assert_array_equal(expected, actual3.T)
+
+
def test_input_to_graph_point():
ax = Axes()
curve = ax.plot(lambda x: np.cos(x))
diff --git a/tests/test_graphical_units/conftest.py b/tests/test_graphical_units/conftest.py
index 01bec579d..9a00b0264 100644
--- a/tests/test_graphical_units/conftest.py
+++ b/tests/test_graphical_units/conftest.py
@@ -6,3 +6,8 @@ import pytest
@pytest.fixture
def show_diff(request):
return request.config.getoption("show_diff")
+
+
[email protected](params=[True, False])
+def use_vectorized(request):
+ yield request.param
diff --git a/tests/test_graphical_units/control_data/coordinate_system/plot_log_x_axis_vectorized.npz b/tests/test_graphical_units/control_data/coordinate_system/plot_log_x_axis_vectorized.npz
new file mode 100644
index 000000000..f215752d0
Binary files /dev/null and b/tests/test_graphical_units/control_data/coordinate_system/plot_log_x_axis_vectorized.npz differ
diff --git a/tests/test_graphical_units/control_data/plot/get_riemann_rectangles.npz b/tests/test_graphical_units/control_data/plot/get_riemann_rectangles_use_vectorized[False].npz
similarity index 100%
rename from tests/test_graphical_units/control_data/plot/get_riemann_rectangles.npz
rename to tests/test_graphical_units/control_data/plot/get_riemann_rectangles_use_vectorized[False].npz
diff --git a/tests/test_graphical_units/control_data/plot/get_riemann_rectangles_use_vectorized[True].npz b/tests/test_graphical_units/control_data/plot/get_riemann_rectangles_use_vectorized[True].npz
new file mode 100644
index 000000000..f756d2544
Binary files /dev/null and b/tests/test_graphical_units/control_data/plot/get_riemann_rectangles_use_vectorized[True].npz differ
diff --git a/tests/test_graphical_units/control_data/plot/plot_derivative_graph.npz b/tests/test_graphical_units/control_data/plot/plot_derivative_graph_use_vectorized[False].npz
similarity index 100%
rename from tests/test_graphical_units/control_data/plot/plot_derivative_graph.npz
rename to tests/test_graphical_units/control_data/plot/plot_derivative_graph_use_vectorized[False].npz
diff --git a/tests/test_graphical_units/control_data/plot/plot_derivative_graph_use_vectorized[True].npz b/tests/test_graphical_units/control_data/plot/plot_derivative_graph_use_vectorized[True].npz
new file mode 100644
index 000000000..bf393eb22
Binary files /dev/null and b/tests/test_graphical_units/control_data/plot/plot_derivative_graph_use_vectorized[True].npz differ
diff --git a/tests/test_graphical_units/control_data/plot/plot_functions.npz b/tests/test_graphical_units/control_data/plot/plot_functions_use_vectorized[False].npz
similarity index 100%
rename from tests/test_graphical_units/control_data/plot/plot_functions.npz
rename to tests/test_graphical_units/control_data/plot/plot_functions_use_vectorized[False].npz
diff --git a/tests/test_graphical_units/control_data/plot/plot_functions_use_vectorized[True].npz b/tests/test_graphical_units/control_data/plot/plot_functions_use_vectorized[True].npz
new file mode 100644
index 000000000..1411fbf70
Binary files /dev/null and b/tests/test_graphical_units/control_data/plot/plot_functions_use_vectorized[True].npz differ
diff --git a/tests/test_graphical_units/control_data/plot/plot.npz b/tests/test_graphical_units/control_data/plot/plot_use_vectorized[False].npz
similarity index 100%
rename from tests/test_graphical_units/control_data/plot/plot.npz
rename to tests/test_graphical_units/control_data/plot/plot_use_vectorized[False].npz
diff --git a/tests/test_graphical_units/control_data/plot/plot_use_vectorized[True].npz b/tests/test_graphical_units/control_data/plot/plot_use_vectorized[True].npz
new file mode 100644
index 000000000..b88654332
Binary files /dev/null and b/tests/test_graphical_units/control_data/plot/plot_use_vectorized[True].npz differ
diff --git a/tests/test_graphical_units/test_axes.py b/tests/test_graphical_units/test_axes.py
index 20843f1da..3faea3f46 100644
--- a/tests/test_graphical_units/test_axes.py
+++ b/tests/test_graphical_units/test_axes.py
@@ -20,9 +20,9 @@ def test_axes(scene):
@frames_comparison
-def test_plot_functions(scene):
+def test_plot_functions(scene, use_vectorized):
ax = Axes(x_range=(-10, 10.3), y_range=(-1.5, 1.5))
- graph = ax.plot(lambda x: x**2)
+ graph = ax.plot(lambda x: x**2, use_vectorized=use_vectorized)
scene.add(ax, graph)
@@ -92,18 +92,18 @@ def test_axis_tip_custom_width_height(scene):
@frames_comparison
-def test_plot_derivative_graph(scene):
+def test_plot_derivative_graph(scene, use_vectorized):
ax = NumberPlane(y_range=[-1, 7], background_line_style={"stroke_opacity": 0.4})
- curve_1 = ax.plot(lambda x: x**2, color=PURPLE_B)
- curve_2 = ax.plot_derivative_graph(curve_1)
- curve_3 = ax.plot_antiderivative_graph(curve_1)
+ curve_1 = ax.plot(lambda x: x**2, color=PURPLE_B, use_vectorized=use_vectorized)
+ curve_2 = ax.plot_derivative_graph(curve_1, use_vectorized=use_vectorized)
+ curve_3 = ax.plot_antiderivative_graph(curve_1, use_vectorized=use_vectorized)
curves = VGroup(curve_1, curve_2, curve_3)
scene.add(ax, curves)
@frames_comparison
-def test_plot(scene):
+def test_plot(scene, use_vectorized):
# construct the axes
ax_1 = Axes(
x_range=[0.001, 6],
@@ -126,15 +126,22 @@ def test_plot(scene):
return np.log(x)
# a curve without adjustments; poor interpolation.
- curve_1 = ax_1.plot(log_func, color=PURE_RED)
+ curve_1 = ax_1.plot(log_func, color=PURE_RED, use_vectorized=use_vectorized)
# disabling interpolation makes the graph look choppy as not enough
# inputs are available
- curve_2 = ax_2.plot(log_func, use_smoothing=False, color=ORANGE)
+ curve_2 = ax_2.plot(
+ log_func, use_smoothing=False, color=ORANGE, use_vectorized=use_vectorized
+ )
# taking more inputs of the curve by specifying a step for the
# x_range yields expected results, but increases rendering time.
- curve_3 = ax_3.plot(log_func, x_range=(0.001, 6, 0.001), color=PURE_GREEN)
+ curve_3 = ax_3.plot(
+ log_func,
+ x_range=(0.001, 6, 0.001),
+ color=PURE_GREEN,
+ use_vectorized=use_vectorized,
+ )
curves = VGroup(curve_1, curve_2, curve_3)
@@ -238,9 +245,9 @@ def test_get_area_with_boundary_and_few_plot_points(scene):
@frames_comparison
-def test_get_riemann_rectangles(scene):
+def test_get_riemann_rectangles(scene, use_vectorized):
ax = Axes(y_range=[-2, 10])
- quadratic = ax.plot(lambda x: 0.5 * x**2 - 0.5)
+ quadratic = ax.plot(lambda x: 0.5 * x**2 - 0.5, use_vectorized=use_vectorized)
# the rectangles are constructed from their top right corner.
# passing an iterable to `color` produces a gradient
diff --git a/tests/test_graphical_units/test_coordinate_systems.py b/tests/test_graphical_units/test_coordinate_systems.py
index 3a62b3107..db214c7c5 100644
--- a/tests/test_graphical_units/test_coordinate_systems.py
+++ b/tests/test_graphical_units/test_coordinate_systems.py
@@ -56,6 +56,20 @@ def test_plot_log_x_axis(scene):
scene.add(ax, graph)
+@frames_comparison
+def test_plot_log_x_axis_vectorized(scene):
+ ax = Axes(
+ x_range=[-1, 4],
+ y_range=[0, 3],
+ x_axis_config={"scaling": LogBase()},
+ )
+
+ graph = ax.plot(
+ lambda x: np.where(x < 10, 2, 1), x_range=[-1, 4], use_vectorized=True
+ )
+ scene.add(ax, graph)
+
+
@frames_comparison
def test_number_plane_log(scene):
"""Test that NumberPlane generates its lines properly with a LogBase"""
diff --git a/tests/test_number_line.py b/tests/test_number_line.py
index 4092e4bfd..3fededfab 100644
--- a/tests/test_number_line.py
+++ b/tests/test_number_line.py
@@ -66,3 +66,58 @@ def test_add_labels():
assert (
actual_label_length == expected_label_length
), f"Expected a VGroup with {expected_label_length} integers but got {actual_label_length}."
+
+
+def test_number_to_point():
+ line = NumberLine()
+ numbers = [1, 2, 3, 4, 5]
+ numbers_np = np.array(numbers)
+ expected = np.array(
+ [
+ [1.0, 0.0, 0.0],
+ [2.0, 0.0, 0.0],
+ [3.0, 0.0, 0.0],
+ [4.0, 0.0, 0.0],
+ [5.0, 0.0, 0.0],
+ ]
+ )
+ vec_1 = np.array([line.number_to_point(x) for x in numbers])
+ vec_2 = line.number_to_point(numbers)
+ vec_3 = line.number_to_point(numbers_np)
+
+ np.testing.assert_equal(
+ np.round(vec_1, 4),
+ np.round(expected, 4),
+ f"Expected {expected} but got {vec_1} with input as scalar",
+ )
+ np.testing.assert_equal(
+ np.round(vec_2, 4),
+ np.round(expected, 4),
+ f"Expected {expected} but got {vec_2} with input as params",
+ )
+ np.testing.assert_equal(
+ np.round(vec_2, 4),
+ np.round(expected, 4),
+ f"Expected {expected} but got {vec_3} with input as ndarray",
+ )
+
+
+def test_point_to_number():
+ line = NumberLine()
+ points = [
+ [1.0, 0.0, 0.0],
+ [2.0, 0.0, 0.0],
+ [3.0, 0.0, 0.0],
+ [4.0, 0.0, 0.0],
+ [5.0, 0.0, 0.0],
+ ]
+ points_np = np.array(points)
+ expected = [1, 2, 3, 4, 5]
+
+ num_1 = [line.point_to_number(point) for point in points]
+ num_2 = line.point_to_number(points)
+ num_3 = line.point_to_number(points_np)
+
+ np.testing.assert_array_equal(np.round(num_1, 4), np.round(expected, 4))
+ np.testing.assert_array_equal(np.round(num_2, 4), np.round(expected, 4))
+ np.testing.assert_array_equal(np.round(num_3, 4), np.round(expected, 4))
diff --git a/tests/test_space_ops.py b/tests/test_space_ops.py
index 8ca826d0a..eef307b4b 100644
--- a/tests/test_space_ops.py
+++ b/tests/test_space_ops.py
@@ -60,7 +60,13 @@ def test_angle_of_vector():
np.round(angle_between_vectors(np.array([1, 1, 1]), np.array([-1, 1, 1])), 5)
== 1.23096
)
- assert angle_of_vector(np.zeros(3)) == 0.0
+ np.testing.assert_equal(angle_of_vector(np.zeros(3)), 0.0)
+
+
+def test_angle_of_vector_vectorized():
+ vec = np.random.randn(4, 10)
+ ref = [np.angle(complex(*v[:2])) for v in vec.T]
+ np.testing.assert_array_equal(ref, angle_of_vector(vec))
def test_center_of_mass():