A community-maintained Python framework for creating mathematical animations.
Upgrades to CoordinateSystem and graphing. (#1161)
hydrobeam9e88b64cd4af
diff --git a/manim/mobject/coordinate_systems.py b/manim/mobject/coordinate_systems.pyindex 12025c640..90568b453 100644--- a/manim/mobject/coordinate_systems.py+++ b/manim/mobject/coordinate_systems.py@@ -3,6 +3,7 @@__all__ = ["CoordinateSystem", "Axes", "ThreeDAxes", "NumberPlane", "ComplexPlane"]+import mathimport numbersfrom typing import Iterable, Optional@@ -11,7 +12,7 @@ import numpy as npfrom .. import configfrom ..constants import *from ..mobject.functions import ParametricFunction-from ..mobject.geometry import Arrow, Dot, Line+from ..mobject.geometry import Arrow, DashedLine, Dot, Linefrom ..mobject.number_line import NumberLinefrom ..mobject.svg.tex_mobject import MathTexfrom ..mobject.types.vectorized_mobject import VDict, VGroup, VMobject@@ -28,12 +29,34 @@ class CoordinateSystem:Abstract class for Axes and NumberPlane"""- def __init__(self, x_min=None, x_max=None, y_min=None, y_max=None, dim=2):- self.dimension = dim- self.x_min = -config["frame_x_radius"] if x_min is None else x_min- self.x_max = config["frame_x_radius"] if x_max is None else x_max- self.y_min = -config["frame_y_radius"] if y_min is None else y_min- self.y_max = config["frame_y_radius"] if y_max is None else y_max+ def __init__(+ self,+ x_range=None,+ y_range=None,+ x_length=None,+ y_length=None,+ dimension=2,+ ):+ self.dimension = dimension++ if x_range is None:+ x_range = [+ round(-config["frame_x_radius"]),+ round(config["frame_x_radius"]),+ 1.0,+ ]+ if y_range is None:+ y_range = [+ round(-config["frame_y_radius"]),+ round(config["frame_y_radius"]),+ 1.0,+ ]++ self.x_range = np.array(x_range)+ self.y_range = np.array(y_range)+ self.x_length = x_length+ self.y_length = y_length+ self.num_sampled_graph_points_per_tick = 10def coords_to_point(self, *coords):raise NotImplementedError()@@ -64,17 +87,19 @@ class CoordinateSystem:def get_z_axis(self):return self.get_axis(2)- def get_x_axis_label(self, label_tex, edge=RIGHT, direction=DL, **kwargs):+ def get_x_axis_label(+ self, label_tex, edge=RIGHT, direction=UP * 4 + RIGHT, **kwargs+ ):return self.get_axis_label(label_tex, self.get_x_axis(), edge, direction, **kwargs)- def get_y_axis_label(self, label_tex, edge=UP, direction=DR, **kwargs):+ def get_y_axis_label(self, label_tex, edge=UP, direction=UP + RIGHT * 2, **kwargs):return self.get_axis_label(label_tex, self.get_y_axis(), edge, direction, **kwargs)- def get_axis_label(self, label_tex, axis, edge, direction, buff=MED_SMALL_BUFF):+ def get_axis_label(self, label_tex, axis, edge, direction, buff=SMALL_BUFF):label = MathTex(label_tex)label.next_to(axis.get_edge_center(edge), direction, buff=buff)label.shift_onto_screen(buff=MED_SMALL_BUFF)@@ -87,14 +112,33 @@ class CoordinateSystem:)return self.axis_labels+ def get_line_from_axis_to_point(+ self, index, point, line_func=DashedLine, color=LIGHT_GREY, stroke_width=2+ ):+ axis = self.get_axis(index)+ line = line_func(axis.get_projection(point), point)+ line.set_stroke(color, stroke_width)+ return line++ def get_vertical_line(self, point, **kwargs):+ return self.get_line_from_axis_to_point(0, point, **kwargs)++ def get_horizontal_line(self, point, **kwargs):+ return self.get_line_from_axis_to_point(1, point, **kwargs)++ # graphing+def get_graph(self, function, **kwargs):- x_min = kwargs.pop("x_min", self.x_min)- x_max = kwargs.pop("x_max", self.x_max)+ t_range = self.x_range++ if len(t_range) == 3:+ # if t_range has a defined step size, increase the number of sample points per tick+ t_range[2] /= self.num_sampled_graph_points_per_tick+ # For axes, the third coordinate of x_range indicates+ # tick frequency. But for functions, it indicates a+ # sample frequencygraph = ParametricFunction(- lambda t: self.coords_to_point(t, function(t)),- t_min=x_min,- t_max=x_max,- **kwargs,+ lambda t: self.coords_to_point(t, function(t)), t_range=t_range, **kwargs)graph.underlying_function = functionreturn graph@@ -116,8 +160,8 @@ class CoordinateSystem:0],target=x,- lower_bound=self.x_min,- upper_bound=self.x_max,+ lower_bound=self.x_range[0],+ upper_bound=self.x_range[1],)if alpha is not None:return graph.point_from_proportion(alpha)@@ -126,49 +170,59 @@ class CoordinateSystem:class Axes(VGroup, CoordinateSystem):+ """Creates a set of axes.++ Parameters+ ----------+ x_range : Optional[Union[:class:`list`, :class:`numpy.ndarray`]]+ The :code:`[x_min, x_max, x_step]` values of the x-axis.+ y_range : Optional[Union[:class:`list`, :class:`numpy.ndarray`]]+ The :code:`[y_min, y_max, y_step]` values of the y-axis.+ x_length : Optional[:class:`float`]+ The length of the x-axis.+ y_length : Optional[:class:`float`]+ The length of the y-axis.+ axis_config : Optional[:class:`dict`]+ Arguments to be passed to :class:`~.NumberLine` that influences both axes.+ x_axis_config : Optional[:class:`dict`]+ Arguments to be passed to :class:`~.NumberLine` that influence the x-axis.+ y_axis_config : Optional[:class:`dict`]+ Arguments to be passed to :class:`~.NumberLine` that influence the y-axis.+ kwargs : Any+ Additional arguments to be passed to :class:`CoordinateSystem` and :class:`~.VGroup`.+ """+def __init__(self,- x_min=None,- x_max=None,- y_min=None,- y_max=None,+ x_range=None,+ y_range=None,+ x_length=round(config.frame_width) - 2,+ y_length=round(config.frame_height) - 2,axis_config=None,x_axis_config=None,y_axis_config=None,- center_point=ORIGIN,- **kwargs+ **kwargs,):- CoordinateSystem.__init__(- self, x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max- )VGroup.__init__(self, **kwargs)+ CoordinateSystem.__init__(self, x_range, y_range, x_length, y_length)- self.axis_config = {- "color": LIGHT_GREY,- "include_tip": True,- "exclude_zero_from_default_numbers": True,- }- self.x_axis_config = {"x_min": self.x_min, "x_max": self.x_max}- self.y_axis_config = {- "x_min": self.y_min,- "x_max": self.y_max,- "label_direction": LEFT,- "rotation": 90 * DEGREES,- }+ self.axis_config = {"include_tip": True, "numbers_to_exclude": [0]}+ self.x_axis_config = {}+ self.y_axis_config = {"rotation": 90 * DEGREES, "label_direction": LEFT}self.update_default_configs((self.axis_config, self.x_axis_config, self.y_axis_config),(axis_config, x_axis_config, y_axis_config),)- self.center_point = center_point- self.x_axis = self.create_axis(self.x_axis_config)- self.y_axis = self.create_axis(self.y_axis_config)+ 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)+# Add as a separate group in case various other# mobjects are added to self, as for example in# NumberPlane below- self.axes = VGroup(self.x_axis, self.y_axis, dim=self.dim)+ self.axes = VGroup(self.x_axis, self.y_axis)self.add(*self.axes)- self.shift(self.center_point)+ self.center()@staticmethoddef update_default_configs(default_configs, passed_configs):@@ -176,8 +230,31 @@ class Axes(VGroup, CoordinateSystem):if passed_config is not None:update_dict_recursively(default_config, passed_config)- def create_axis(self, axis_config):- return NumberLine(**merge_dicts_recursively(self.axis_config, axis_config))+ def create_axis(self, range_terms, axis_config, length):+ """Creates an axis and dynamically adjusts its position depending on where 0 is located on the line.++ Parameters+ ----------+ range_terms : Union[:class:`list`, :class:`numpy.ndarray`]+ The range of the the axis : `(x_min, x_max, x_step)`.+ axis_config : :class:`dict`+ Additional parameters that are passed to :class:`NumberLine`.+ length : :class:`float`+ The length of the axis.+ """+ new_config = merge_dicts_recursively(self.axis_config, axis_config)+ new_config["length"] = length+ axis = NumberLine(range_terms, **new_config)++ # without the if/elif, graph does not exist when min > 0 or max < 0+ # shifts the axis so that 0 is centered+ if range_terms[0] > 0:+ axis.shift(-axis.number_to_point(range_terms[0]))+ elif range_terms[1] < 0:+ axis.shift(-axis.number_to_point(range_terms[1]))+ else:+ axis.shift(-axis.number_to_point(0))+ return axisdef coords_to_point(self, *coords):origin = self.x_axis.number_to_point(0)@@ -186,31 +263,22 @@ class Axes(VGroup, CoordinateSystem):result += axis.number_to_point(coord) - originreturn result- def c2p(self, *coords):- return self.coords_to_point(*coords)-def point_to_coords(self, point):return tuple([axis.point_to_number(point) for axis in self.get_axes()])- def p2c(self, point):- return self.point_to_coords(point)-def get_axes(self):return self.axes- def get_coordinate_labels(self, x_vals=None, y_vals=None):- if x_vals is None:- x_vals = []- if y_vals is None:- y_vals = []- x_mobs = self.get_x_axis().get_number_mobjects(*x_vals)- y_mobs = self.get_y_axis().get_number_mobjects(*y_vals)-- self.coordinate_labels = VGroup(x_mobs, y_mobs)+ def get_coordinate_labels(self, x_values=None, y_values=None, **kwargs):+ axes = self.get_axes()+ self.coordinate_labels = VGroup()+ for axis, values in zip(axes, [x_values, y_values]):+ labels = axis.add_numbers(values, **kwargs)+ self.coordinate_labels.add(labels)return self.coordinate_labels- def add_coordinates(self, x_vals=None, y_vals=None):- self.add(self.get_coordinate_labels(x_vals, y_vals))+ def add_coordinates(self, x_values=None, y_values=None):+ self.add(self.get_coordinate_labels(x_values, y_values))return selfdef get_line_graph(@@ -222,7 +290,7 @@ class Axes(VGroup, CoordinateSystem):add_vertex_dots: bool = True,vertex_dot_radius: float = DEFAULT_DOT_RADIUS,vertex_dot_style: Optional[dict] = None,- **kwargs+ **kwargs,) -> VDict:"""Draws a line graph.@@ -296,37 +364,86 @@ class Axes(VGroup, CoordinateSystem):class ThreeDAxes(Axes):+ """A 3-dimensional set of axes.++ Parameters+ ----------+ x_range : Optional[Union[:class:`list`, :class:`numpy.ndarray`]]+ The :code:`[x_min, x_max, x_step]` values of the x-axis.+ y_range : Optional[Union[:class:`list`, :class:`numpy.ndarray`]]+ The :code:`[y_min, y_max, y_step]` values of the y-axis.+ z_range : Optional[Union[:class:`list`, :class:`numpy.ndarray`]]+ The :code:`[z_min, z_max, z_step]` values of the z-axis.+ x_length : Optional[:class:`float`]+ The length of the x-axis.+ y_length : Optional[:class:`float`]+ The length of the y-axis.+ z_length : Optional[:class:`float`]+ The length of the z-axis.+ z_axis_config : Optional[:class:`dict`]+ Arguments to be passed to :class:`~.NumberLine` that influence the z-axis.+ z_normal : Union[:class:`list`, :class:`numpy.ndarray`]+ The direction of the normal.+ num_axis_pieces : :class:`int`+ The number of pieces used to construct the axes.+ light_source : Union[:class:`list`, :class:`numpy.ndarray`]+ The direction of the light source.+ depth+ Currently non-functional.+ gloss+ Currently non-functional.+ kwargs : Any+ Additional arguments to be passed to :class:`Axes`.+ """+def __init__(self,- x_min=-5.5,- x_max=5.5,- y_min=-5.5,- y_max=5.5,- z_min=-3.5,- z_max=3.5,+ x_range=np.array((-5.5, 5.5, 1)),+ y_range=np.array((-5.5, 5.5, 1)),+ z_range=np.array((-3.5, 3.5, 1)),+ x_length=config.frame_height + 2.5,+ y_length=config.frame_height + 2.5,+ z_length=config.frame_height - 1.5,z_axis_config=None,z_normal=DOWN,num_axis_pieces=20,light_source=9 * DOWN + 7 * LEFT + 10 * OUT,- **kwargs+ # opengl stuff (?)+ depth=None,+ gloss=0.5,+ **kwargs,):+Axes.__init__(- self, x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, **kwargs+ self,+ x_range=x_range,+ x_length=x_length,+ y_range=y_range,+ y_length=y_length,+ **kwargs,)- self.z_min = z_min- self.z_max = z_max- self.z_axis_config = {"x_min": self.z_min, "x_max": self.z_max}++ self.z_range = z_range+ self.z_length = z_length++ self.z_axis_config = {}self.update_default_configs((self.z_axis_config,), (z_axis_config,))+self.z_normal = z_normalself.num_axis_pieces = num_axis_pieces+self.light_source = light_source+self.dimension = 3- z_axis = self.z_axis = self.create_axis(self.z_axis_config)- z_axis.shift(self.center_point)- z_axis.rotate_about_zero(-np.pi / 2, UP)++ 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.n2p(0))+self.axes.add(z_axis)self.add(z_axis)+ self.z_axis = z_axisself.add_3d_pieces()self.set_axis_shading()@@ -354,18 +471,53 @@ class ThreeDAxes(Axes):class NumberPlane(Axes):+ """Creates a cartesian plane with background lines.++ Parameters+ ----------+ x_range : Optional[Union[:class:`list`, :class:`numpy.ndarray`]]+ The :code:`[x_min, x_max, x_step]` values of the plane in the horizontal direction.+ y_range : Optional[Union[:class:`list`, :class:`numpy.ndarray`]]+ The :code:`[y_min, y_max, y_step]` values of the plane in the vertical direction.+ x_length : Optional[:class:`float`]+ The width of the plane.+ y_length : Optional[:class:`float`]+ The height of the plane.+ axis_config : Optional[:class:`dict`]+ Arguments to be passed to :class:`~.NumberLine` that influences both axes.+ y_axis_config : Optional[:class:`dict`]+ Arguments to be passed to :class:`~.NumberLine` that influence the y-axis.+ background_line_style : Optional[:class:`dict`]+ Arguments that influence the construction of the background lines of the plane.+ faded_line_style : Optional[:class:`dict`]+ Similar to :attr:`background_line_style`, affects the construction of the scene's background lines.+ faded_line_ratio : Optional[:class:`int`]+ Determines the number of boxes within the background lines: :code:`2` = 4 boxes, :code:`3` = 9 boxes.+ make_smooth_after_applying_functions+ Currently non-functional.+ 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+ on the :attr:`x_range` and :attr:`y_range` values to set the unit_size to 1.+ """+def __init__(self,+ x_range=np.array((-6, 6, 1)),+ y_range=np.array((-3, 3, 1)),+ x_length=None,+ y_length=None,axis_config=None,y_axis_config=None,background_line_style=None,faded_line_style=None,- x_line_frequency=1,- y_line_frequency=1,faded_line_ratio=1,make_smooth_after_applying_functions=True,- **kwargs+ **kwargs,):++ # configsself.axis_config = {"stroke_color": WHITE,"stroke_width": 2,@@ -373,7 +525,7 @@ class NumberPlane(Axes):"include_tip": False,"line_to_number_buff": SMALL_BUFF,"label_direction": DR,- "number_scale_val": 0.5,+ "number_scale_value": 0.5,}self.y_axis_config = {"label_direction": DR}self.background_line_style = {@@ -389,16 +541,27 @@ class NumberPlane(Axes):# Defaults to a faded version of line_configself.faded_line_style = faded_line_style- self.x_line_frequency = x_line_frequency- self.y_line_frequency = y_line_frequencyself.faded_line_ratio = faded_line_ratioself.make_smooth_after_applying_functions = make_smooth_after_applying_functions+ # init+super().__init__(+ x_range=x_range,+ y_range=y_range,+ x_length=x_length,+ y_length=y_length,axis_config=self.axis_config,y_axis_config=self.y_axis_config,**kwargs,)++ # dynamically adjusts x_length and y_length so that the unit_size is one by default+ if x_length is None:+ x_length = self.x_range[1] - self.x_range[0]+ if y_length is None:+ y_length = self.y_range[1] - self.y_range[0]+self.init_background_lines()def init_background_lines(self):@@ -434,19 +597,17 @@ class NumberPlane(Axes):"""x_axis = self.get_x_axis()y_axis = self.get_y_axis()- x_freq = self.x_line_frequency- y_freq = self.y_line_frequencyx_lines1, x_lines2 = self.get_lines_parallel_to_axis(x_axis,y_axis,- x_freq,+ self.x_axis.x_step,self.faded_line_ratio,)y_lines1, y_lines2 = self.get_lines_parallel_to_axis(y_axis,x_axis,- y_freq,+ self.y_axis.x_step,self.faded_line_ratio,)lines1 = VGroup(*x_lines1, *y_lines1)@@ -477,25 +638,23 @@ class NumberPlane(Axes):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."""+line = Line(axis_parallel_to.get_start(), axis_parallel_to.get_end())if ratio_faded_lines == 0: # don't show faded linesratio_faded_lines = 1 # i.e. set ratio to 1step = (1 / ratio_faded_lines) * freqlines1 = VGroup()lines2 = VGroup()- unit_vector_axis_perp_to = axis_perpendicular_to.get_unit_vector()- ranges = (- np.arange(0, axis_perpendicular_to.x_max, step),- np.arange(0, axis_perpendicular_to.x_min, -step),+ inputs = np.arange(+ axis_perpendicular_to.x_min, axis_perpendicular_to.x_max + step, step)- for inputs in ranges:- for k, x in enumerate(inputs):- new_line = line.copy()- new_line.shift(unit_vector_axis_perp_to * x)- if k % ratio_faded_lines == 0:- lines1.add(new_line)- else:- lines2.add(new_line)+ for k, x in enumerate(inputs):+ new_line = line.copy()+ new_line.shift(axis_perpendicular_to.n2p(x) - axis_perpendicular_to.n2p(0))+ if k % ratio_faded_lines == 0:+ lines1.add(new_line)+ else:+ lines2.add(new_line)return lines1, lines2def get_center_point(self):@@ -525,11 +684,9 @@ class NumberPlane(Axes):class ComplexPlane(NumberPlane):- def __init__(self, color=BLUE, x_line_frequency=1, y_line_frequency=1, **kwargs):+ def __init__(self, color=BLUE, **kwargs):super().__init__(color=color,- x_line_frequency=x_line_frequency,- y_line_frequency=y_line_frequency,**kwargs,)@@ -548,8 +705,8 @@ class ComplexPlane(NumberPlane):return self.point_to_number(point)def get_default_coordinate_values(self):- x_numbers = self.get_x_axis().default_numbers_to_display()- y_numbers = self.get_y_axis().default_numbers_to_display()+ x_numbers = self.get_x_axis().get_tick_range()+ y_numbers = self.get_y_axis().get_tick_range()y_numbers = [complex(0, y) for y in y_numbers if y != 0]return [*x_numbers, *y_numbers]@@ -563,10 +720,7 @@ class ComplexPlane(NumberPlane):if abs(z.imag) > abs(z.real):axis = self.get_y_axis()value = z.imag- kwargs = merge_dicts_recursively(- kwargs,- {"number_config": {"unit": "i"}},- )+ kwargs["unit"] = "i"else:axis = self.get_x_axis()value = z.realdiff --git a/manim/mobject/functions.py b/manim/mobject/functions.pyindex 00c9ce46f..eed380af8 100644--- a/manim/mobject/functions.py+++ b/manim/mobject/functions.py@@ -49,19 +49,22 @@ class ParametricFunction(VMobject):def __init__(self,function=None,- t_min=0,- t_max=1,- step_size=0.01,+ t_range=None,dt=1e-8,discontinuities=None,+ use_smoothing=True,**kwargs):self.function = function- self.t_min = t_min- self.t_max = t_max- self.step_size = step_size+ t_range = np.array([0, 1, 0.01]) if t_range is None else t_range+ if len(t_range) == 2:+ t_range = [*t_range, 0.01]+self.dt = dtself.discontinuities = [] if discontinuities is None else discontinuities+ self.use_smoothing = use_smoothing+ self.t_min, self.t_max, self.t_step = t_range+VMobject.__init__(self, **kwargs)def get_function(self):@@ -70,72 +73,40 @@ class ParametricFunction(VMobject):def get_point_from_function(self, t):return self.function(t)- def get_step_size(self, t=None):- if self.step_size == "auto":- """- for x between -1 to 1, return 0.01- else, return log10(x) (rounded)- e.g.: 10.5 -> 0.1 ; 1040 -> 10- """- if t == 0:- scale = 0- else:- scale = math.log10(abs(t))- if scale < 0:- scale = 0-- scale = math.floor(scale)-- scale -= 2- return math.pow(10, scale)- else:- return self.step_size-def generate_points(self):- t_min, t_max = self.t_min, self.t_max- dt = self.dt- discontinuities = filter(lambda t: t_min <= t <= t_max, self.discontinuities)+ discontinuities = filter(+ lambda t: self.t_min <= t <= self.t_max, self.discontinuities+ )discontinuities = np.array(list(discontinuities))boundary_times = [self.t_min,self.t_max,- *(discontinuities - dt),- *(discontinuities + dt),+ *(discontinuities - self.dt),+ *(discontinuities + self.dt),]boundary_times.sort()for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]):- t_range = list(np.arange(t1, t2, self.get_step_size(t1)))- if t_range[-1] != t2:- t_range.append(t2)+ t_range = [*np.arange(t1, t2, self.t_step), t2]points = np.array([self.function(t) for t in t_range])- valid_indices = np.apply_along_axis(np.all, 1, np.isfinite(points))- points = points[valid_indices]- if len(points) > 0:- self.start_new_path(points[0])- self.add_points_as_corners(points[1:])- self.make_smooth()+ self.start_new_path(points[0])+ self.add_points_as_corners(points[1:])+ if self.use_smoothing:+ # TODO: not in line with upstream, approx_smooth does not exist+ self.make_smooth()return selfclass FunctionGraph(ParametricFunction):- def __init__(self, function, x_min=None, x_max=None, color=YELLOW, **kwargs):- if x_min is None:- x_min = -config["frame_x_radius"]- if x_max is None:- x_max = config["frame_x_radius"]- self.x_min = x_min- self.x_max = x_max+ def __init__(self, function, x_range=None, color=YELLOW, **kwargs):++ if x_range is None:+ x_range = np.array([-config["frame_x_radius"], config["frame_x_radius"]])++ self.x_range = x_rangeself.parametric_function = lambda t: np.array([t, function(t), 0])- ParametricFunction.__init__(- self,- self.parametric_function,- t_min=self.x_min,- t_max=self.x_max,- color=color,- **kwargs- )self.function = function+ super().__init__(self.parametric_function, self.x_range, color=color, **kwargs)def get_function(self):return self.functiondiff --git a/manim/mobject/geometry.py b/manim/mobject/geometry.pyindex bb0d2c09e..3a1a319d6 100644--- a/manim/mobject/geometry.py+++ b/manim/mobject/geometry.py@@ -852,6 +852,21 @@ class Line(TipableVMobject):def get_angle(self):return angle_of_vector(self.get_vector())+ def get_projection(self, point):+ """Return the projection of a point onto the line.++ Examples+ --------+ ::+ >>> import numpy as np+ >>> line = Line(LEFT, RIGHT)+ >>> line.get_projection(np.array([0, 1, 0]))+ array([0., 0., 0.])+ """+ unit_vect = self.get_unit_vector()+ start = self.get_start()+ return start + np.dot(point - start, unit_vect) * unit_vect+def get_slope(self):return np.tan(self.get_angle())diff --git a/manim/mobject/number_line.py b/manim/mobject/number_line.pyindex 07c0a386a..4c99d8d6e 100644--- a/manim/mobject/number_line.py+++ b/manim/mobject/number_line.py@@ -1,11 +1,13 @@"""Mobject representing a number line."""-__all__ = ["NumberLine", "UnitInterval"]+__all__ = ["NumberLine", "UnitInterval", "NumberLineOld"]import operator as op+import numpy as np+from .. import configfrom ..constants import *from ..mobject.geometry import Line@@ -19,6 +21,288 @@ from ..utils.space_ops import normalizeclass NumberLine(Line):+ """Creates a number line with tick marks.++ Parameters+ ----------+ x_range : Union[:class:`list`, :class:`numpy.ndarray`]+ The :code:`[x_min, x_max, x_step]` values to create the line.+ length : :class:`float`+ The length of the number line.+ unit_size : class:`float`+ The distance between each tick of the line.+ include_ticks : :class:`bool`+ Determines whether ticks are included.+ tick_size : :class:`float`+ The vertical length of each tick mark.+ numbers_with_elongated_ticks : Union[:class:`list`, :class:`numpy.ndarray`]+ A list of specific values with elongated ticks.+ longer_tick_multiple : :class:`float`+ Influences how many times larger elongated ticks are than regular ticks (2 = 2x).+ color : :class:`~.Colors`+ The color of the line.+ rotation : :class:`float`+ The angle (in radians) at which the line is rotated.+ stroke_width : :class:`float`+ The thickness of the line.+ include_tip : :class:`bool`+ Determines whether a tip is added to the end of the line.+ tip_width : :class:`float`+ The width of the tip.+ tip_height : :class:`float`+ The height of the tip.+ include_numbers : :class:`bool`+ Determines whether numbers are added to tick marks.+ label_direction : Union[:class:`list`, :class:`numpy.ndarray`]+ The specific position to which number mobjects are added on the line.+ line_to_number_buff : :class:`float`+ The distance between the line and the number mobject.+ decimal_number_config : :class:`dict`+ Arguments that can be passed to :class:`~.numbers.DecimalNumber` to influence number mobjects.+ numbers_to_exclude : Union[:class:`list`, :class:`numpy.ndarray`]+ An explicit list of numbers to not be added to the line.+ number_scale_value : :class:`float`+ The size scaling factor for the number mobjects.+ kwargs : Any+ Additional arguments to be passed to :class:`~.Line`.++ Returns+ -------+ NumberLine+ The constructed number line.+ """++ def __init__(+ self,+ x_range=None, # must be first+ length=None,+ unit_size=1,+ # ticks+ include_ticks=True,+ tick_size=0.1,+ numbers_with_elongated_ticks=[],+ longer_tick_multiple=2,+ # visuals+ color=LIGHT_GREY,+ rotation=0,+ stroke_width=2.0,+ # tip+ include_tip=False,+ tip_width=0.25,+ tip_height=0.25,+ # numbers+ include_numbers=False,+ label_direction=DOWN,+ line_to_number_buff=MED_SMALL_BUFF,+ decimal_number_config={"num_decimal_places": 0, "font_size": 24},+ numbers_to_exclude=[],+ # temp, because DecimalNumber() needs to be updated+ number_scale_value=0.75,+ **kwargs+ ):+ if x_range is None:+ x_range = [-config["frame_x_radius"], config["frame_x_radius"], 1.0]+ if len(x_range) == 2:+ # 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+ self.length = length+ self.unit_size = unit_size+ # ticks+ self.include_ticks = include_ticks+ self.tick_size = tick_size+ self.numbers_with_elongated_ticks = numbers_with_elongated_ticks+ self.longer_tick_multiple = longer_tick_multiple+ # visuals+ self.stroke_width = stroke_width+ self.rotation = rotation+ self.color = color+ # tip+ self.include_tip = include_tip+ self.tip_width = tip_width+ self.tip_height = tip_height+ # numbers+ self.include_numbers = include_numbers+ self.label_direction = label_direction+ self.line_to_number_buff = line_to_number_buff+ self.decimal_number_config = decimal_number_config+ self.numbers_to_exclude = numbers_to_exclude+ self.number_scale_value = number_scale_value++ super().__init__(+ self.x_min * RIGHT,+ self.x_max * RIGHT,+ stroke_width=self.stroke_width,+ color=self.color,+ **kwargs,+ )+ if self.length:+ self.set_length(self.length)+ self.unit_size = self.get_unit_size()+ else:+ self.scale(self.unit_size)++ self.center()++ if self.include_tip:+ self.add_tip()+ self.tip.set_stroke(self.stroke_color, self.stroke_width)++ if self.include_ticks:+ self.add_ticks()++ self.rotate(self.rotation)+ if self.include_numbers:+ self.add_numbers(excluding=self.numbers_to_exclude)++ def rotate_about_zero(self, angle, axis=OUT, **kwargs):+ return self.rotate_about_number(0, angle, axis, **kwargs)++ def rotate_about_number(self, number, angle, axis=OUT, **kwargs):+ return self.rotate(angle, axis, about_point=self.n2p(number), **kwargs)++ def add_ticks(self):+ ticks = VGroup()+ elongated_tick_size = self.tick_size * self.longer_tick_multiple+ for x in self.get_tick_range():+ size = self.tick_size+ if x in self.numbers_with_elongated_ticks:+ size = elongated_tick_size+ ticks.add(self.get_tick(x, size))+ self.add(ticks)+ self.ticks = ticks++ def get_tick(self, x, size=None):+ if size is None:+ size = self.tick_size+ result = Line(size * DOWN, size * UP)+ result.rotate(self.get_angle())+ result.move_to(self.number_to_point(x))+ result.match_style(self)+ return result++ def get_tick_marks(self):+ return VGroup(self.ticks)++ def get_tick_range(self):+ if self.include_tip:+ x_max = self.x_max+ else:+ x_max = self.x_max + 1e-6+ return np.arange(self.x_min, x_max, self.x_step)++ def number_to_point(self, number):+ alpha = float(number - self.x_min) / (self.x_max - self.x_min)+ return interpolate(self.get_start(), self.get_end(), alpha)++ def point_to_number(self, point):+ start, end = self.get_start_and_end()+ unit_vect = normalize(end - start)+ proportion = fdiv(+ 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):+ """Abbreviation for number_to_point"""+ return self.number_to_point(number)++ def p2n(self, point):+ """Abbreviation for point_to_number"""+ return self.point_to_number(point)++ def get_unit_size(self):+ return self.get_length() / (self.x_max - self.x_min)++ def get_unit_vector(self):+ return super().get_unit_vector() * self.unit_size++ def get_number_mobject(self, x, direction=None, buff=None, **number_config):+ number_config = merge_dicts_recursively(+ self.decimal_number_config, number_config+ )+ if direction is None:+ direction = self.label_direction+ if buff is None:+ buff = self.line_to_number_buff++ num_mob = DecimalNumber(x, **number_config)+ # font_size does not exist yet in decimal number+ num_mob.scale(self.number_scale_value)++ num_mob.next_to(self.number_to_point(x), direction=direction, buff=buff)+ if x < 0 and self.label_direction[0] == 0:+ # Align without the minus sign+ num_mob.shift(num_mob[0].get_width() * LEFT / 2)+ return num_mob++ def get_number_mobjects(self, *numbers, **kwargs):+ if len(numbers) == 0:+ numbers = self.default_numbers_to_display()+ return VGroup([self.get_number_mobject(number, **kwargs) for number in numbers])++ def get_labels(self):+ return self.get_number_mobjects()++ def add_numbers(self, x_values=None, excluding=None, font_size=24, **kwargs):+ if x_values is None:+ x_values = self.get_tick_range()++ kwargs["font_size"] = font_size++ numbers = VGroup()+ for x in x_values:+ if x in self.numbers_to_exclude:+ continue+ if excluding is not None and x in excluding:+ continue+ numbers.add(self.get_number_mobject(x, **kwargs))+ self.add(numbers)+ self.numbers = numbers+ return numbers+++class UnitInterval(NumberLine):+ def __init__(+ self,+ unit_size=10,+ tick_frequency=0.1,+ numbers_with_elongated_ticks=None,+ decimal_number_config=None,+ **kwargs+ ):+ numbers_with_elongated_ticks = (+ [0, 1]+ if numbers_with_elongated_ticks is None+ else numbers_with_elongated_ticks+ )++ decimal_number_config = (+ {+ "num_decimal_places": 1,+ }+ if decimal_number_config is None+ else decimal_number_config+ )++ NumberLine.__init__(+ self,+ x_range=[0, 1, 0.1],+ unit_size=unit_size,+ numbers_with_elongated_ticks=numbers_with_elongated_ticks,+ decimal_number_config=decimal_number_config,+ **kwargs,+ )+++class NumberLineOld(Line):+ """The old version of :class:`NumberLine`.++ Exists for compatibility with :class:`~.GraphScene`.+ """+def __init__(self,color=LIGHT_GREY,@@ -235,28 +519,3 @@ class NumberLine(Line):self.numbers = self.get_number_mobjects(*numbers, **kwargs)self.add(self.numbers)return self---class UnitInterval(NumberLine):- def __init__(- self,- unit_size=6,- tick_frequency=0.1,- numbers_with_elongated_ticks=[0, 1],- number_at_center=0.5,- decimal_number_config={- "num_decimal_places": 1,- },- **kwargs- ):- NumberLine.__init__(- self,- unit_size=unit_size,- tick_frequency=tick_frequency,- numbers_with_elongated_ticks=numbers_with_elongated_ticks,- number_at_center=number_at_center,- decimal_number_config=decimal_number_config,- x_min=0,- x_max=1,- **kwargs,- )diff --git a/manim/scene/graph_scene.py b/manim/scene/graph_scene.pyindex e00395a79..f4467bbfd 100644--- a/manim/scene/graph_scene.py+++ b/manim/scene/graph_scene.py@@ -48,14 +48,14 @@ __all__ = ["GraphScene"]import itertools as it-from .. import config+from .. import config, loggerfrom ..animation.creation import Create, DrawBorderThenFill, Writefrom ..animation.transform import Transformfrom ..animation.update import UpdateFromAlphaFuncfrom ..constants import *from ..mobject.functions import ParametricFunctionfrom ..mobject.geometry import Line, Rectangle, RegularPolygon-from ..mobject.number_line import NumberLine+from ..mobject.number_line import NumberLineOldfrom ..mobject.svg.tex_mobject import MathTex, Texfrom ..mobject.types.vectorized_mobject import VectorizedPoint, VGroupfrom ..scene.scene import Scene@@ -79,6 +79,10 @@ from ..utils.space_ops import angle_of_vectorclass GraphScene(Scene):+ """+ Deprecated - GraphScene+ """+def __init__(self,x_min=-1,@@ -112,6 +116,10 @@ class GraphScene(Scene):y_axis_config=None,**kwargs,):+ logger.warning(+ "GraphScene has been deprecated and will be removed in a future release. "+ "Use Axes instead."+ )self.x_min = x_minself.x_max = x_maxself.x_axis_width = x_axis_width@@ -185,7 +193,7 @@ class GraphScene(Scene):**self.x_axis_config,)- x_axis = NumberLine(**self.x_axis_config)+ x_axis = NumberLineOld(**self.x_axis_config)x_shift = x_axis.number_to_point(0 if self.x_min <= 0 <= self.x_max else self.x_min)@@ -228,7 +236,7 @@ class GraphScene(Scene):**self.y_axis_config,)- y_axis = NumberLine(**self.y_axis_config)+ y_axis = NumberLineOld(**self.y_axis_config)y_shift = y_axis.number_to_point(0 if self.y_min <= 0 <= self.y_max else self.y_min)diff --git a/tests/control_data/graphical_units_data/coordinate_systems/NumberPlaneTest.npz b/tests/control_data/graphical_units_data/coordinate_systems/NumberPlaneTest.npzindex 949ab720f..1bc845d98 100644Binary files a/tests/control_data/graphical_units_data/coordinate_systems/NumberPlaneTest.npz and b/tests/control_data/graphical_units_data/coordinate_systems/NumberPlaneTest.npz differdiff --git a/tests/control_data/graphical_units_data/plot/AxesTest.npz b/tests/control_data/graphical_units_data/plot/AxesTest.npzindex 5cbf26cde..ee35c1525 100644Binary files a/tests/control_data/graphical_units_data/plot/AxesTest.npz and b/tests/control_data/graphical_units_data/plot/AxesTest.npz differdiff --git a/tests/control_data/graphical_units_data/plot/PlotFunctions.npz b/tests/control_data/graphical_units_data/plot/PlotFunctions.npzindex 97814c348..39cca75a6 100644Binary files a/tests/control_data/graphical_units_data/plot/PlotFunctions.npz and b/tests/control_data/graphical_units_data/plot/PlotFunctions.npz differdiff --git a/tests/control_data/graphical_units_data/threed/AxesTest.npz b/tests/control_data/graphical_units_data/threed/AxesTest.npzindex 49df37b47..2476f9e69 100644Binary files a/tests/control_data/graphical_units_data/threed/AxesTest.npz and b/tests/control_data/graphical_units_data/threed/AxesTest.npz differdiff --git a/tests/control_data/graphical_units_data/threed/FixedInFrameMObjectTest.npz b/tests/control_data/graphical_units_data/threed/FixedInFrameMObjectTest.npzindex c14f3c610..52b11443d 100644Binary files a/tests/control_data/graphical_units_data/threed/FixedInFrameMObjectTest.npz and b/tests/control_data/graphical_units_data/threed/FixedInFrameMObjectTest.npz differdiff --git a/tests/test_coordinate_system.py b/tests/test_coordinate_system.pyindex 5205af33c..273d6865a 100644--- a/tests/test_coordinate_system.py+++ b/tests/test_coordinate_system.py@@ -9,21 +9,23 @@ from manim import NumberPlane, ThreeDAxes, config, tempconfigdef test_initial_config():"""Check that all attributes are defined properly from the config."""cs = CS()- assert cs.x_min == -config["frame_x_radius"]- assert cs.x_max == config["frame_x_radius"]- assert cs.y_min == -config["frame_y_radius"]- assert cs.y_max == config["frame_y_radius"]+ assert cs.x_range[0] == round(-config["frame_x_radius"])+ assert cs.x_range[1] == round(config["frame_x_radius"])+ assert cs.x_range[2] == 1.0+ assert cs.y_range[0] == round(-config["frame_y_radius"])+ assert cs.y_range[1] == round(config["frame_y_radius"])+ assert cs.y_range[2] == 1.0ax = Axes()- assert np.allclose(ax.center_point, ORIGIN)+ assert np.allclose(ax.get_center(), ORIGIN)assert np.allclose(ax.y_axis_config["label_direction"], LEFT)with tempconfig({"frame_x_radius": 100, "frame_y_radius": 200}):cs = CS()- assert cs.x_min == -100- assert cs.x_max == 100- assert cs.y_min == -200- assert cs.y_max == 200+ assert cs.x_range[0] == -100+ assert cs.x_range[1] == 100+ assert cs.y_range[0] == -200+ assert cs.y_range[1] == 200def test_dimension():diff --git a/tests/test_graphical_units/test_axes.py b/tests/test_graphical_units/test_axes.pyindex 02e0bf670..6a84cbf4b 100644--- a/tests/test_graphical_units/test_axes.py+++ b/tests/test_graphical_units/test_axes.py@@ -6,29 +6,17 @@ from ..utils.GraphicalUnitTester import GraphicalUnitTesterfrom ..utils.testing_utils import get_scenes_to_test-class AxesTest(GraphScene):+class AxesTest(Scene):def construct(self):- self.x_min = -5- self.x_max = 5- self.y_min = -3- self.y_max = 3- self.x_axis_config = {- "add_start": 0.5,- "add_end": 0.5,- "include_tip": True,- }- self.y_axis_config = {- "add_start": 0.25,- "add_end": 0.5,- "include_tip": True,- }- self.x_axis_visibility = True- self.y_axis_visibility = True- self.y_label_position = UP- self.x_label_position = RIGHT- self.graph_origin = ORIGIN- self.axes_color = WHITE- self.setup_axes(animate=True)+ graph = Axes(+ x_range=[-10, 10, 1],+ y_range=[-10, 10, 1],+ x_length=6,+ y_length=6,+ color=WHITE,+ )+ labels = graph.get_axis_labels()+ self.add(graph, labels)MODULE_NAME = "plot"diff --git a/tests/test_graphical_units/test_coordinate_systems.py b/tests/test_graphical_units/test_coordinate_systems.pyindex 43bedd652..abe0549b5 100644--- a/tests/test_graphical_units/test_coordinate_systems.py+++ b/tests/test_graphical_units/test_coordinate_systems.py@@ -9,14 +9,14 @@ from ..utils.testing_utils import get_scenes_to_testclass NumberPlaneTest(Scene):def construct(self):plane = NumberPlane(- axis_config={"include_numbers": True, "x_min": -8},- x_min=-4,- x_max=6,+ x_range=[-4, 6, 1],+ axis_config={"include_numbers": True},x_axis_config={"unit_size": 1.2},- y_min=-2,- y_axis_config={"x_max": 5, "width": 6, "label_direction": UL},- center_point=2 * DL,+ y_range=[-2, 5],+ y_length=6,+ y_axis_config={"label_direction": UL},)+self.add(plane)diff --git a/tests/test_graphical_units/test_functions.py b/tests/test_graphical_units/test_functions.pyindex 1231f3361..ae02bac3f 100644--- a/tests/test_graphical_units/test_functions.py+++ b/tests/test_graphical_units/test_functions.py@@ -10,7 +10,7 @@ from ..utils.testing_utils import get_scenes_to_testclass FunctionGraphTest(Scene):def construct(self):graph = FunctionGraph(- lambda x: 2 * np.cos(0.5 * x), x_min=-PI, x_max=PI, color=BLUE+ lambda x: 2 * np.cos(0.5 * x), x_range=[-PI, PI], color=BLUE)self.add(graph)