Skip to content

armgit / manim

Public Imported from GitHub
0

A community-maintained Python framework for creating mathematical animations.

Implement logarithmic scaling for :class:`~.NumberLine`/:class:`~.Axes` (#1812)

Laith Bahodi5397d38e101a
diff --git a/docs/source/reference_index/utilities_misc.rst b/docs/source/reference_index/utilities_misc.rst
index ebd02ed33..0cec0a083 100644
--- a/docs/source/reference_index/utilities_misc.rst
+++ b/docs/source/reference_index/utilities_misc.rst
@@ -21,6 +21,7 @@ Module Index
~utils.iterables
~utils.paths
~utils.rate_functions
+ ~utils.scale
~utils.simple_functions
~utils.sounds
~utils.space_ops
diff --git a/manim/__init__.py b/manim/__init__.py
index 9adb2002c..1dd9f91e4 100644
--- a/manim/__init__.py
+++ b/manim/__init__.py
@@ -103,6 +103,7 @@ from .utils.images import *
from .utils.iterables import *
from .utils.paths import *
from .utils.rate_functions import *
+from .utils.scale import *
from .utils.simple_functions import *
from .utils.sounds import *
from .utils.space_ops import *
diff --git a/manim/mobject/coordinate_systems.py b/manim/mobject/coordinate_systems.py
index a4595c43e..52c3915e0 100644
--- a/manim/mobject/coordinate_systems.py
+++ b/manim/mobject/coordinate_systems.py
@@ -18,6 +18,7 @@ import numpy as np
from colour import Color
from manim.mobject.opengl_compatibility import ConvertToOpenGL
+from manim.utils.scale import LinearBase
from .. import config
from ..constants import *
@@ -443,6 +444,12 @@ class CoordinateSystem:
if isinstance(values, dict):
axis.add_labels(values, **kwargs)
labels = axis.labels
+ elif values is None and axis.scaling.custom_labels:
+ tick_range = axis.get_tick_range()
+ axis.add_labels(
+ dict(zip(tick_range, axis.scaling.get_custom_labels(tick_range)))
+ )
+ labels = axis.labels
else:
axis.add_numbers(values, **kwargs)
labels = axis.numbers
@@ -692,8 +699,12 @@ class CoordinateSystem:
# For axes, the third coordinate of x_range indicates
# tick frequency. But for functions, it indicates a
# sample frequency
+
graph = ParametricFunction(
- lambda t: self.coords_to_point(t, function(t)), t_range=t_range, **kwargs
+ lambda t: self.coords_to_point(t, function(t)),
+ t_range=t_range,
+ scaling=self.x_axis.scaling,
+ **kwargs,
)
graph.underlying_function = function
return graph
@@ -1553,12 +1564,32 @@ class CoordinateSystem:
class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
"""Creates a set of axes.
+ Examples
+ --------
+
+ .. manim:: LogScalingExample
+ :save_last_frame:
+
+ class LogScalingExample(Scene):
+ def construct(self):
+ ax = Axes(
+ x_range=[0, 10, 1],
+ y_range=[-2, 6, 1],
+ tips=False,
+ axis_config={"include_numbers": True},
+ y_axis_config={"scaling": LogBase(custom_labels=True)},
+ )
+
+ # x_min must be > 0 because log is undefined at 0.
+ graph = ax.get_graph(lambda x: x ** 2, x_range=[0.001, 10], use_smoothing=False)
+ self.add(ax, graph)
+
Parameters
----------
x_range
- The :code:`[x_min, x_max, x_step]` values of the x-axis.
+ The ``(x_min, x_max, x_step)`` values of the x-axis.
y_range
- The :code:`[y_min, y_max, y_step]` values of the y-axis.
+ The ``(y_min, y_max, y_step)`` values of the y-axis.
x_length
The length of the x-axis.
y_length
@@ -1593,7 +1624,6 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
self.axis_config = {
"include_tip": tips,
"numbers_to_exclude": [0],
- "exclude_origin_tick": True,
}
self.x_axis_config = {}
self.y_axis_config = {"rotation": 90 * DEGREES, "label_direction": LEFT}
@@ -1612,6 +1642,28 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
self.y_axis_config,
)
+ # excluding the origin tick removes a tick at the 0-point of the axis
+ # This is desired for LinearBase because the 0 point is always the x-axis
+ # For non-LinearBase, the "0-point" does not have this quality, so it must be included.
+
+ # i.e. with LogBase range [-2, 4]:
+ # it would remove the "0" tick, which is actually 10^0,
+ # not the lowest tick on the graph (which is 10^-2).
+
+ if self.x_axis_config.get("scaling") is None or isinstance(
+ self.x_axis_config.get("scaling"), LinearBase
+ ):
+ self.x_axis_config["exclude_origin_tick"] = True
+ else:
+ self.x_axis_config["exclude_origin_tick"] = False
+
+ if self.y_axis_config.get("scaling") is None or isinstance(
+ self.y_axis_config.get("scaling"), LinearBase
+ ):
+ self.y_axis_config["exclude_origin_tick"] = True
+ else:
+ self.y_axis_config["exclude_origin_tick"] = False
+
self.x_axis = self._create_axis(self.x_range, self.x_axis_config, self.x_length)
self.y_axis = self._create_axis(self.y_range, self.y_axis_config, self.y_length)
@@ -1622,7 +1674,10 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
self.add(*self.axes)
# finds the middle-point on each axis
- lines_center_point = [((axis.x_max + axis.x_min) / 2) for axis in self.axes]
+ lines_center_point = [
+ axis.scaling.function((axis.x_range[1] + axis.x_range[0]) / 2)
+ for axis in self.axes
+ ]
self.shift(-self.coords_to_point(*lines_center_point))
@@ -1643,23 +1698,23 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
Parameters
----------
range_terms
- The range of the the axis : `(x_min, x_max, x_step)`.
+ The range of the the axis : ``(x_min, x_max, x_step)``.
axis_config
- Additional parameters that are passed to :class:`NumberLine`.
+ Additional parameters that are passed to :class:`~.NumberLine`.
length
The length of the axis.
Returns
-------
:class:`NumberLine`
- Returns a number line with the provided x and y axis range.
+ Returns a number line based on ``range_terms``.
"""
axis_config["length"] = length
axis = NumberLine(range_terms, **axis_config)
# without the call to _origin_shift, graph does not exist when min > 0 or max < 0
# shifts the axis so that 0 is centered
- axis.shift(-axis.number_to_point(self._origin_shift(range_terms)))
+ 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:
@@ -1696,8 +1751,9 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
np.ndarray
A point with respect to the scene's coordinate system.
"""
-
- origin = self.x_axis.number_to_point(self._origin_shift(self.x_range))
+ 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
@@ -1850,8 +1906,10 @@ class Axes(VGroup, CoordinateSystem, metaclass=ConvertToOpenGL):
The range of the axis : ``(x_min, x_max, x_step)``.
"""
if axis_range[0] > 0:
+ # min greater than 0
return axis_range[0]
if axis_range[1] < 0:
+ # max less than 0
return axis_range[1]
else:
return 0
@@ -1863,11 +1921,11 @@ class ThreeDAxes(Axes):
Parameters
----------
x_range
- The :code:`[x_min, x_max, x_step]` values of the x-axis.
+ The ``[x_min, x_max, x_step]`` values of the x-axis.
y_range
- The :code:`[y_min, y_max, y_step]` values of the y-axis.
+ The ``[y_min, y_max, y_step]`` values of the y-axis.
z_range
- The :code:`[z_min, z_max, z_step]` values of the z-axis.
+ The ``[z_min, z_max, z_step]`` values of the z-axis.
x_length
The length of the x-axis.
y_length
@@ -1933,11 +1991,22 @@ class ThreeDAxes(Axes):
self.dimension = 3
+ if self.z_axis_config.get("scaling") is None or isinstance(
+ self.z_axis_config.get("scaling"), LinearBase
+ ):
+ self.z_axis_config["exclude_origin_tick"] = True
+ else:
+ self.z_axis_config["exclude_origin_tick"] = False
+
z_axis = self._create_axis(self.z_range, self.z_axis_config, self.z_length)
z_axis.rotate_about_zero(-PI / 2, UP)
z_axis.rotate_about_zero(angle_of_vector(self.z_normal))
- z_axis.shift(self.x_axis.number_to_point(self._origin_shift(x_range)))
+ z_axis.shift(
+ self.x_axis.number_to_point(
+ self._origin_shift([z_axis.x_min, z_axis.x_max]),
+ ),
+ )
self.axes.add(z_axis)
self.add(z_axis)
@@ -2027,9 +2096,9 @@ class NumberPlane(Axes):
Parameters
----------
x_range
- The :code:`[x_min, x_max, x_step]` values of the plane in the horizontal direction.
+ The ``[x_min, x_max, x_step]`` values of the plane in the horizontal direction.
y_range
- The :code:`[y_min, y_max, y_step]` values of the plane in the vertical direction.
+ The ``[y_min, y_max, y_step]`` values of the plane in the vertical direction.
x_length
The width of the plane.
y_length
@@ -2045,7 +2114,6 @@ class NumberPlane(Axes):
kwargs : Any
Additional arguments to be passed to :class:`Axes`.
-
.. note::
If :attr:`x_length` or :attr:`y_length` are not defined, the plane automatically adjusts its lengths based
@@ -2088,7 +2156,7 @@ class NumberPlane(Axes):
background_line_style: Optional[dict] = None,
faded_line_style: Optional[dict] = None,
faded_line_ratio: int = 1,
- make_smooth_after_applying_functions=True,
+ make_smooth_after_applying_functions: bool = True,
**kwargs,
):
@@ -2161,7 +2229,8 @@ class NumberPlane(Axes):
)
def _get_lines(self) -> Tuple[VGroup, VGroup]:
- """Generate all the lines, faded and not faded. Two sets of lines are generated: one parallel to the X-axis, and parallel to the Y-axis.
+ """Generate all the lines, faded and not faded.
+ Two sets of lines are generated: one parallel to the X-axis, and parallel to the Y-axis.
Returns
-------
@@ -2174,14 +2243,14 @@ class NumberPlane(Axes):
x_lines1, x_lines2 = self._get_lines_parallel_to_axis(
x_axis,
y_axis,
- self.y_axis.x_step,
+ self.y_axis.x_range[2],
self.faded_line_ratio,
)
y_lines1, y_lines2 = self._get_lines_parallel_to_axis(
y_axis,
x_axis,
- self.x_axis.x_step,
+ self.x_axis.x_range[2],
self.faded_line_ratio,
)
@@ -2220,7 +2289,8 @@ class NumberPlane(Axes):
Returns
-------
Tuple[:class:`~.VGroup`, :class:`~.VGroup`]
- The first (i.e the non-faded lines parallel to `axis_parallel_to`) and second (i.e the faded lines parallel to `axis_parallel_to`) sets of lines, respectively.
+ The first (i.e the non-faded lines parallel to `axis_parallel_to`) and second
+ (i.e the faded lines parallel to `axis_parallel_to`) sets of lines, respectively.
"""
line = Line(axis_parallel_to.get_start(), axis_parallel_to.get_end())
@@ -2231,25 +2301,20 @@ class NumberPlane(Axes):
lines2 = VGroup()
unit_vector_axis_perp_to = axis_perpendicular_to.get_unit_vector()
+ # need to unpack all three values
+ x_min, x_max, _ = axis_perpendicular_to.x_range
+
+ # account for different axis scalings (logarithmic), where
+ # negative values do not exist and [-2 , 4] should output lines
+ # similar to [0, 6]
+ if axis_perpendicular_to.x_min > 0 and x_min < 0:
+ x_min, x_max = (0, np.abs(x_min) + np.abs(x_max))
+
# min/max used in case range does not include 0. i.e. if (2,6):
- # the range becomes (0,4), not (0,6), to produce the correct number of lines
+ # the range becomes (0,4), not (0,6).
ranges = (
- np.arange(
- 0,
- min(
- axis_perpendicular_to.x_max - axis_perpendicular_to.x_min,
- axis_perpendicular_to.x_max,
- ),
- step,
- ),
- np.arange(
- 0,
- max(
- axis_perpendicular_to.x_min - axis_perpendicular_to.x_max,
- axis_perpendicular_to.x_min,
- ),
- -step,
- ),
+ np.arange(0, min(x_max - x_min, x_max), step),
+ np.arange(0, max(x_min - x_max, x_min), -step),
)
for inputs in ranges:
@@ -2493,14 +2558,14 @@ class PolarPlane(Axes):
if ratio_faded_lines == 0: # don't show faded lines
ratio_faded_lines = 1 # i.e. set ratio to 1
- rstep = (1 / ratio_faded_lines) * self.x_axis.x_step
+ rstep = (1 / ratio_faded_lines) * self.x_axis.x_range[2]
astep = (1 / ratio_faded_lines) * (TAU * (1 / self.azimuth_step))
rlines1 = VGroup()
rlines2 = VGroup()
alines1 = VGroup()
alines2 = VGroup()
- rinput = np.arange(0, self.x_axis.x_max + rstep, rstep)
+ rinput = np.arange(0, self.x_axis.x_range[1] + rstep, rstep)
ainput = np.arange(0, TAU, astep)
unit_vector = self.x_axis.get_unit_vector()[0]
diff --git a/manim/mobject/functions.py b/manim/mobject/functions.py
index 204183b13..22d84fc26 100644
--- a/manim/mobject/functions.py
+++ b/manim/mobject/functions.py
@@ -12,12 +12,26 @@ from .. import config
from ..constants import *
from ..mobject.types.vectorized_mobject import VMobject
from ..utils.color import YELLOW
+from ..utils.scale import LinearBase, _ScaleBase
from .opengl_compatibility import ConvertToOpenGL
class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
"""A parametric curve.
+ Parameters
+ ----------
+ function
+ The function to be plotted in the form of ``(lambda x: x**2)``
+ t_range
+ Determines the length that the function spans. By default ``[0, 1]``
+ scaling
+ Scaling class applied to the points of the function. Default of :class:`~.LinearBase`.
+ 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)
+
+
Examples
--------
@@ -52,11 +66,12 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
def __init__(
self,
- function=None,
- t_range=None,
- dt=1e-8,
- discontinuities=None,
- use_smoothing=True,
+ function: Callable[[float, float], float],
+ t_range: Optional[Sequence[float]] = None,
+ scaling: _ScaleBase = LinearBase(),
+ dt: float = 1e-8,
+ discontinuities: bool = None,
+ use_smoothing: bool = True,
**kwargs
):
self.function = function
@@ -64,6 +79,8 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
if len(t_range) == 2:
t_range = np.array([*t_range, 0.01])
+ self.scaling = scaling
+
self.dt = dt
self.discontinuities = [] if discontinuities is None else discontinuities
self.use_smoothing = use_smoothing
@@ -79,22 +96,28 @@ class ParametricFunction(VMobject, metaclass=ConvertToOpenGL):
def generate_points(self):
- discontinuities = filter(
- lambda t: self.t_min <= t <= self.t_max,
- self.discontinuities,
- )
- discontinuities = np.array(list(discontinuities))
- boundary_times = np.array(
- [
- self.t_min,
- self.t_max,
- *(discontinuities - self.dt),
- *(discontinuities + self.dt),
- ],
- )
- boundary_times.sort()
+ if self.discontinuities:
+ discontinuities = filter(
+ lambda t: self.t_min <= t <= self.t_max,
+ self.discontinuities,
+ )
+ discontinuities = np.array(list(discontinuities))
+ boundary_times = np.array(
+ [
+ self.t_min,
+ self.t_max,
+ *(discontinuities - self.dt),
+ *(discontinuities + self.dt),
+ ],
+ )
+ boundary_times.sort()
+ else:
+ boundary_times = [self.t_min, self.t_max]
+
for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]):
- t_range = np.array([*np.arange(t1, t2, self.t_step), t2])
+ t_range = np.array(
+ [*self.scaling.function(np.arange(t1, t2, self.t_step)), t2],
+ )
points = np.array([self.function(t) for t in t_range])
self.start_new_path(points[0])
self.add_points_as_corners(points[1:])
diff --git a/manim/mobject/number_line.py b/manim/mobject/number_line.py
index ecf637124..1958230fd 100644
--- a/manim/mobject/number_line.py
+++ b/manim/mobject/number_line.py
@@ -8,6 +8,7 @@ import numpy as np
from colour import Color
from manim.mobject.svg.tex_mobject import MathTex, Tex
+from manim.utils.scale import LinearBase, _ScaleBase
from .. import config
from ..constants import *
@@ -26,9 +27,7 @@ if TYPE_CHECKING:
class NumberLine(Line):
- """Creates a number line with tick marks. Number ranges that include both negative and
- positive values will be generated from the 0 point, and may not include a tick at the min / max
- values as the tick locations are dependent on the step size.
+ """Creates a number line with tick marks.
Parameters
----------
@@ -61,6 +60,8 @@ class NumberLine(Line):
include_numbers
Whether to add numbers to the tick marks. The number of decimal places is determined
by the step size, this default can be overridden by ``decimal_number_config``.
+ scaling
+ The way the ``x_range`` is value is scaled, i.e. :class:`~.LogBase` for a logarithmic numberline. Defaults to :class:`~.LinearBase`.
font size
The size of the label mobjects. Defaults to 36.
label_direction
@@ -98,9 +99,8 @@ class NumberLine(Line):
include_numbers=True,
font_size=24,
)
- [num6] = [num for num in l1.numbers if num.number == 6]
+ num6 = l1.numbers[8]
num6.set_color(RED)
- l1.add(num6)
l2 = NumberLine(
x_range=[-2.5, 2.5 + 0.5, 0.5],
@@ -120,10 +120,11 @@ class NumberLine(Line):
line_group = VGroup(l0, l1, l2, l3).arrange(DOWN, buff=1)
self.add(line_group)
- Returns
- -------
- NumberLine
- The constructed number line.
+ .. note::
+
+ Number ranges that include both negative and positive values will be generated
+ from the 0 point, and may not include a tick at the min / max
+ values as the tick locations are dependent on the step size.
"""
@deprecated_params(
@@ -155,6 +156,7 @@ class NumberLine(Line):
include_numbers: bool = False,
font_size: float = 36,
label_direction: Sequence[float] = DOWN,
+ scaling: _ScaleBase = LinearBase(),
line_to_number_buff: float = MED_SMALL_BUFF,
decimal_number_config: Optional[Dict] = None,
numbers_to_exclude: Optional[Iterable[float]] = None,
@@ -184,12 +186,15 @@ class NumberLine(Line):
# adds x_step if not specified. not sure how to feel about this. a user can't know default without peeking at source code
x_range = [*x_range, 1]
- self.x_min, self.x_max, self.x_step = x_range
if decimal_number_config is None:
decimal_number_config = {
- "num_decimal_places": self.decimal_places_from_step(),
+ "num_decimal_places": self._decimal_places_from_step(x_range[2]),
}
+ # turn into into an np array to scale by just applying the function
+ self.x_range = np.array(x_range, dtype=float)
+ self.x_min, self.x_max, self.x_step = scaling.function(self.x_range)
+
self.length = length
self.unit_size = unit_size
# ticks
@@ -213,9 +218,10 @@ class NumberLine(Line):
self.numbers_to_exclude = numbers_to_exclude
self.numbers_to_include = numbers_to_include
+ self.scaling = scaling
super().__init__(
- self.x_min * RIGHT,
- self.x_max * RIGHT,
+ self.x_range[0] * RIGHT,
+ self.x_range[1] * RIGHT,
stroke_width=stroke_width,
color=self.color,
**kwargs,
@@ -237,11 +243,29 @@ class NumberLine(Line):
self.rotate(self.rotation)
if self.include_numbers or self.numbers_to_include is not None:
- self.add_numbers(
- x_values=self.numbers_to_include,
- excluding=self.numbers_to_exclude,
- font_size=self.font_size,
- )
+ if self.scaling.custom_labels:
+ tick_range = self.get_tick_range()
+
+ self.add_labels(
+ dict(
+ zip(
+ tick_range,
+ self.scaling.get_custom_labels(
+ tick_range,
+ unit_decimal_places=decimal_number_config[
+ "num_decimal_places"
+ ],
+ ),
+ )
+ ),
+ )
+
+ else:
+ self.add_numbers(
+ x_values=self.numbers_to_include,
+ excluding=self.numbers_to_exclude,
+ font_size=self.font_size,
+ )
def rotate_about_zero(self, angle: float, axis: Sequence[float] = OUT, **kwargs):
return self.rotate_about_number(0, angle, axis, **kwargs)
@@ -252,6 +276,8 @@ class NumberLine(Line):
return self.rotate(angle, axis, about_point=self.n2p(number), **kwargs)
def add_ticks(self):
+ """Adds ticks to the number line. Ticks can be accessed after creation
+ via ``self.ticks``."""
ticks = VGroup()
elongated_tick_size = self.tick_size * self.longer_tick_multiple
for x in self.get_tick_range():
@@ -263,6 +289,20 @@ class NumberLine(Line):
self.ticks = ticks
def get_tick(self, x: float, size: Optional[float] = None) -> Line:
+ """Generates a tick and positions it along the number line.
+
+ Parameters
+ ----------
+ x
+ The position of the tick.
+ size
+ The factor by which the tick is scaled.
+
+ Returns
+ -------
+ :class:`~.Line`
+ A positioned tick.
+ """
if size is None:
size = self.tick_size
result = Line(size * DOWN, size * UP)
@@ -272,34 +312,70 @@ class NumberLine(Line):
return result
def get_tick_marks(self) -> VGroup:
- return VGroup(self.ticks)
+ return self.ticks
def get_tick_range(self) -> np.ndarray:
- if self.include_tip:
- x_max = self.x_max
- else:
- x_max = self.x_max + 1e-6
+ """Generates the range of values on which labels are plotted based on the
+ ``x_range`` attribute of the number line.
+
+ Returns
+ -------
+ np.ndarray
+ A numpy array of floats represnting values along the number line.
+ """
+ x_min, x_max, x_step = self.x_range
+ if not self.include_tip:
+ x_max += 1e-6
# Handle cases where min and max are both positive or both negative
- if self.x_min < x_max < 0 or self.x_max > self.x_min > 0:
- return np.arange(self.x_min, x_max, self.x_step)
+ if x_min < x_max < 0 or x_max > x_min > 0:
+ tick_range = np.arange(x_min, x_max, x_step)
+ else:
+ start_point = 0
+ if self.exclude_origin_tick:
+ start_point += x_step
- start_point = 0
- if self.exclude_origin_tick:
- start_point += self.x_step
+ x_min_segment = np.arange(start_point, np.abs(x_min) + 1e-6, x_step) * -1
+ x_max_segment = np.arange(start_point, x_max, x_step)
- x_min_segment = (
- np.arange(start_point, np.abs(self.x_min) + 1e-6, self.x_step) * -1
- )
- x_max_segment = np.arange(start_point, x_max, self.x_step)
+ tick_range = np.unique(np.concatenate((x_min_segment, x_max_segment)))
- return np.unique(np.concatenate((x_min_segment, x_max_segment)))
+ return self.scaling.function(tick_range)
def number_to_point(self, number: float) -> np.ndarray:
- alpha = float(number - self.x_min) / (self.x_max - self.x_min)
- return interpolate(self.get_start(), self.get_end(), alpha)
+ """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.
+
+ Returns
+ -------
+ np.ndarray
+ A point with respect to the scene's coordinate system.
+ """
+
+ 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)
+ return val
def point_to_number(self, point: Sequence[float]) -> float:
+ """Accepts a point with respect to the scene and returns
+ a float along the number line.
+
+ Parameters
+ ----------
+ point
+ A sequence of values consisting of ``(x_coord, y_coord, z_coord)``.
+
+ Returns
+ -------
+ float
+ A float representing a value along the number line.
+ """
start, end = self.get_start_and_end()
unit_vect = normalize(end - start)
proportion = fdiv(
@@ -309,15 +385,15 @@ class NumberLine(Line):
return interpolate(self.x_min, self.x_max, proportion)
def n2p(self, number: float) -> np.ndarray:
- """Abbreviation for number_to_point"""
+ """Abbreviation for :meth:`~.NumberLine.number_to_point`."""
return self.number_to_point(number)
def p2n(self, point: Sequence[float]) -> float:
- """Abbreviation for point_to_number"""
+ """Abbreviation for :meth:`~.NumberLine.point_to_number`."""
return self.point_to_number(point)
def get_unit_size(self) -> float:
- return self.get_length() / (self.x_max - self.x_min)
+ return self.get_length() / (self.x_range[1] - self.x_range[0])
def get_unit_vector(self) -> np.ndarray:
return super().get_unit_vector() * self.unit_size
@@ -330,6 +406,24 @@ class NumberLine(Line):
font_size: Optional[float] = None,
**number_config,
) -> DecimalNumber:
+ """Generates a positioned :class:`~.DecimalNumber` mobject representing a number label.
+
+ Parameters
+ ----------
+ x
+ The x-value at which the tick should be positioned.
+ direction
+ Determines the direction at which the label is positioned next to the line.
+ buff
+ The distance of the label from the line.
+ font_size
+ The font size of the :class:`~.DecimalNumber` mobject.
+
+ Returns
+ -------
+ :class:`~.DecimalNumber`
+ The positioned mobject.
+ """
number_config = merge_dicts_recursively(
self.decimal_number_config,
number_config,
@@ -363,7 +457,23 @@ class NumberLine(Line):
excluding: Optional[Iterable[float]] = None,
font_size: Optional[float] = None,
**kwargs,
- ) -> VGroup:
+ ):
+ """Adds :class:`~.DecimalNumber` mobjects representing their position
+ at each tick of the number line. The numbers can be accessed after creation
+ via ``self.numbers``.
+
+ Parameters
+ ----------
+ x_values
+ An iterable of the values used to position and create the labels.
+ Defaults to the output produced by :meth:`~.NumberLine.get_tick_range`
+ excluding
+ A list of values to exclude from :attr:`x_values`.
+ font_size
+ The font size of the labels. Defaults to the ``font_size`` attribute
+ of the number line.
+
+ """
if x_values is None:
x_values = self.get_tick_range()
@@ -386,18 +496,37 @@ class NumberLine(Line):
def add_labels(
self,
dict_values: Dict[float, Union[str, float, "Mobject"]],
- direction=None,
- buff=None,
- font_size=None,
+ direction: Sequence[float] = None,
+ buff: float = None,
+ font_size: float = None,
):
- """Adds specifically positioned labels to the :class:`~.NumberLine` using a ``dict``."""
+ """Adds specifically positioned labels to the :class:`~.NumberLine` using a ``dict``.
+ The labels can be accessed after creation via ``self.labels``.
+
+ Parameters
+ ----------
+ dict_values
+ A dictionary consisting of the position along the number line and the mobject to be added:
+ ``{1: Tex("Monday"), 3: Tex("Tuesday")}``.
+ direction
+ Determines the direction at which the label is positioned next to the line.
+ buff
+ The distance of the label from the line.
+ font_size
+ The font size of the mobject to be positioned.
+
+ Raises
+ ------
+ AttributeError
+ If the label does not have a ``font_size`` attribute, an ``AttributeError`` is raised.
+ """
direction = self.label_direction if direction is None else direction
buff = self.line_to_number_buff if buff is None else buff
font_size = self.font_size if font_size is None else font_size
labels = VGroup()
for x, label in dict_values.items():
- label = self.create_label_tex(label)
+ label = self._create_label_tex(label)
if hasattr(label, "font_size"):
label.font_size = font_size
else:
@@ -410,7 +539,7 @@ class NumberLine(Line):
return self
@staticmethod
- def create_label_tex(label_tex) -> "Mobject":
+ def _create_label_tex(label_tex) -> "Mobject":
"""Checks if the label is a ``float``, ``int`` or a ``str`` and creates a :class:`~.MathTex`/:class:`~.Tex` label accordingly.
Parameters
@@ -429,11 +558,12 @@ class NumberLine(Line):
label_tex = Tex(label_tex)
return label_tex
- def decimal_places_from_step(self) -> int:
- step_as_str = str(self.x_step)
- if "." not in step_as_str:
+ @staticmethod
+ def _decimal_places_from_step(step) -> int:
+ step = str(step)
+ if "." not in step:
return 0
- return len(step_as_str.split(".")[-1])
+ return len(step.split(".")[-1])
class UnitInterval(NumberLine):
diff --git a/manim/utils/scale.py b/manim/utils/scale.py
new file mode 100644
index 000000000..e692d6537
--- /dev/null
+++ b/manim/utils/scale.py
@@ -0,0 +1,178 @@
+import math
+from typing import TYPE_CHECKING, Any, Dict, Iterable, List
+
+__all__ = ["LogBase", "LinearBase"]
+
+from ..mobject.numbers import Integer
+
+if TYPE_CHECKING:
+ from manim.mobject.mobject import Mobject
+
+
+class _ScaleBase:
+ """Scale baseclass for graphing/functions."""
+
+ def __init__(self, custom_labels: bool = False):
+ """
+ Parameters
+ ----------
+ custom_labels
+ Whether to create custom labels when plotted on a :class:`~.NumberLine`.
+ """
+ self.custom_labels = custom_labels
+
+ def function(self, value: float) -> float:
+ """The function that will be used to scale the values.
+
+ Parameters
+ ----------
+ value
+ The number/``np.ndarray`` to be scaled.
+
+ Returns
+ -------
+ float
+ The value after it has undergone the scaling.
+
+ Raises
+ ------
+ NotImplementedError
+ Must be subclassed.
+ """
+ raise NotImplementedError
+
+ def inverse_function(self, value: float) -> float:
+ """The inverse of ``function``. Used for plotting on a particular axis.
+
+ Raises
+ ------
+ NotImplementedError
+ Must be subclassed.
+ """
+ raise NotImplementedError
+
+ def get_custom_labels(
+ self,
+ val_range: Iterable[float],
+ ) -> Iterable["Mobject"]:
+ """Custom instructions for generating labels along an axis.
+
+ Parameters
+ ----------
+ val_range
+ The position of labels. Also used for defining the content of the labels.
+
+ Returns
+ -------
+ Dict
+ A list consisting of the labels.
+ Can be passed to :meth:`~.NumberLine.add_labels() along with ``val_range``.
+
+ Raises
+ ------
+ NotImplementedError
+ Can be subclassed, optional.
+ """
+ raise NotImplementedError
+
+
+class LinearBase(_ScaleBase):
+ def __init__(self, scale_factor: float = 1.0):
+ """The default scaling class.
+
+ Parameters
+ ----------
+ scale_factor
+ The slope of the linear function, by default 1.0
+ """
+
+ super().__init__()
+ self.scale_factor = scale_factor
+
+ def function(self, value: float) -> float:
+ """Multiplies the value by the scale factor.
+
+ Parameters
+ ----------
+ value
+ Value to be multiplied by the scale factor.
+ """
+ return self.scale_factor * value
+
+ def inverse_function(self, value: float) -> float:
+ """Inverse of function. Divides the value by the scale factor.
+
+ Parameters
+ ----------
+ value
+ value to be divided by the scale factor.
+ """
+ return value / self.scale_factor
+
+
+class LogBase(_ScaleBase):
+ def __init__(self, base: float = 10, custom_labels: bool = True):
+ """Scale for logarithmic graphs/functions.
+
+ Parameters
+ ----------
+ base
+ The base of the log, by default 10.
+ custom_labels : bool, optional
+ For use with :class:`~.Axes`:
+ Whetherer or not to include ``LaTeX`` axis labels, by default True.
+
+ Examples
+ --------
+
+ .. code-block:: python
+
+ func = ParametricFunction(lambda x: x, scaling=LogBase(base=2))
+
+ """
+ super().__init__()
+ self.base = base
+ self.custom_labels = custom_labels
+
+ def function(self, value: float) -> float:
+ """Scales the value to fit it to a logarithmic scale.``self.function(5)==10**5``"""
+ return self.base ** value
+
+ def inverse_function(self, value: float) -> float:
+ """Inverse of ``function``. The value must be greater than 0"""
+ if value <= 0:
+ raise ValueError(
+ "log(0) is undefined. Make sure the value is in the domain of the function"
+ )
+ value = math.log(value, self.base)
+ return value
+
+ def get_custom_labels(
+ self,
+ val_range: Iterable[float],
+ unit_decimal_places: int = 0,
+ **base_config: Dict[str, Any],
+ ) -> List["Mobject"]:
+ """Produces custom :class:`~.Integer` labels in the form of ``10^2``.
+
+ Parameters
+ ----------
+
+ val_range
+ The iterable of values used to create the labels. Determines the exponent.
+ units_decimal_places
+ The number of decimal places to include in the exponent
+ base_config
+ Additional arguments to be passed to :class:`~.Integer`.
+ """
+
+ # uses `format` syntax to control the number of decimal places.
+ tex_labels = [
+ Integer(
+ self.base,
+ unit="^{%s}" % (f"{self.inverse_function(i):.{unit_decimal_places}f}"),
+ **base_config,
+ )
+ for i in val_range
+ ]
+ return tex_labels
diff --git a/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz b/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz
index bc61eb4ca..3ca51a4ad 100644
Binary files a/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz and b/tests/control_data/graphical_units_data/coordinate_system/number_plane.npz differ
diff --git a/tests/control_data/graphical_units_data/coordinate_system/number_plane_log.npz b/tests/control_data/graphical_units_data/coordinate_system/number_plane_log.npz
new file mode 100644
index 000000000..dc9c4f0a6
Binary files /dev/null and b/tests/control_data/graphical_units_data/coordinate_system/number_plane_log.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/axes.npz b/tests/control_data/graphical_units_data/plot/axes.npz
index 7a5cc0cde..17ecaab9f 100644
Binary files a/tests/control_data/graphical_units_data/plot/axes.npz and b/tests/control_data/graphical_units_data/plot/axes.npz differ
diff --git a/tests/control_data/graphical_units_data/plot/log_scaling_graph.npz b/tests/control_data/graphical_units_data/plot/log_scaling_graph.npz
new file mode 100644
index 000000000..28b07d999
Binary files /dev/null and b/tests/control_data/graphical_units_data/plot/log_scaling_graph.npz differ
diff --git a/tests/control_data/graphical_units_data/threed/Axes.npz b/tests/control_data/graphical_units_data/threed/Axes.npz
index 8a4b21157..2fdbe0f2b 100644
Binary files a/tests/control_data/graphical_units_data/threed/Axes.npz and b/tests/control_data/graphical_units_data/threed/Axes.npz differ
diff --git a/tests/test_graphical_units/test_axes.py b/tests/test_graphical_units/test_axes.py
index 589037fa6..6183d7802 100644
--- a/tests/test_graphical_units/test_axes.py
+++ b/tests/test_graphical_units/test_axes.py
@@ -12,7 +12,6 @@ def test_axes(scene):
x_length=6,
y_length=6,
color=WHITE,
- axis_config={"exclude_origin_tick": False},
)
labels = graph.get_axis_labels()
scene.add(graph, labels)
@@ -243,3 +242,18 @@ def test_get_z_axis_label(scene):
lab = ax.get_z_axis_label(Tex("$z$-label"))
scene.set_camera_orientation(phi=2 * PI / 5, theta=PI / 5)
scene.add(ax, lab)
+
+
+@frames_comparison
+def test_log_scaling_graph(scene):
+ ax = Axes(
+ x_range=[0, 8],
+ y_range=[-2, 4],
+ x_length=10,
+ y_axis_config={"scaling": LogBase()},
+ )
+ ax.add_coordinates()
+
+ gr = ax.get_graph(lambda x: x, use_smoothing=False, x_range=[0.01, 8])
+
+ scene.add(ax, gr)
diff --git a/tests/test_graphical_units/test_coordinate_systems.py b/tests/test_graphical_units/test_coordinate_systems.py
index 754516370..740e282e5 100644
--- a/tests/test_graphical_units/test_coordinate_systems.py
+++ b/tests/test_graphical_units/test_coordinate_systems.py
@@ -40,3 +40,36 @@ def test_implicit_graph(scene):
ax = Axes()
graph = ax.get_implicit_curve(lambda x, y: x ** 2 + y ** 2 - 4)
scene.add(ax, graph)
+
+
+@frames_comparison
+def test_number_plane_log(scene):
+ """Test that NumberPlane generates its lines properly with a LogBase"""
+ # y_axis log
+ plane1 = (
+ NumberPlane(
+ x_range=[0, 8, 1],
+ y_range=[-2, 5],
+ y_length=6,
+ x_length=10,
+ y_axis_config={"scaling": LogBase()},
+ )
+ .add_coordinates()
+ .scale(1 / 2)
+ )
+
+ # x_axis log
+ plane2 = (
+ NumberPlane(
+ x_range=[0, 8, 1],
+ y_range=[-2, 5],
+ y_length=6,
+ x_length=10,
+ x_axis_config={"scaling": LogBase()},
+ faded_line_ratio=4,
+ )
+ .add_coordinates()
+ .scale(1 / 2)
+ )
+
+ scene.add(VGroup(plane1, plane2).arrange())
diff --git a/tests/test_graphical_units/test_threed.py b/tests/test_graphical_units/test_threed.py
index ccbf27acf..a7f8ef266 100644
--- a/tests/test_graphical_units/test_threed.py
+++ b/tests/test_graphical_units/test_threed.py
@@ -49,7 +49,7 @@ def test_Torus(scene):
@frames_comparison(base_scene=ThreeDScene)
def test_Axes(scene):
- scene.add(ThreeDAxes(axis_config={"exclude_origin_tick": False}))
+ scene.add(ThreeDAxes())
@frames_comparison(base_scene=ThreeDScene)