From cb3fff7da57b948a0494e028fedca8a47371414c Mon Sep 17 00:00:00 2001 From: Grant Sanderson Date: Tue, 19 Apr 2016 00:20:19 -0700 Subject: [PATCH] More vectorizations conversions --- animation/simple_animations.py | 21 +- helpers.py | 1 - mobject/svg_mobject.py | 1 + mobject/vectorized_mobject.py | 2 +- topics/functions.py | 59 +++--- topics/geometry.py | 10 +- topics/number_line.py | 360 +++++++++++---------------------- 7 files changed, 171 insertions(+), 283 deletions(-) diff --git a/animation/simple_animations.py b/animation/simple_animations.py index d1b8ed67..331c4e0f 100644 --- a/animation/simple_animations.py +++ b/animation/simple_animations.py @@ -32,13 +32,24 @@ class Rotating(Animation): class ShowPartial(Animation): + CONFIG = { + "one_submobject_at_a_time" : False + } def update_mobject(self, alpha): pairs = zip( self.starting_mobject.submobject_family(), self.mobject.submobject_family() ) - for start, mob in pairs: - mob.become_partial(start, *self.get_bounds(alpha)) + for i, (start, mob) in enumerate(pairs): + if self.one_submobject_at_a_time: + lower = float(i)/len(pairs) + upper = float(i+1)/len(pairs) + sub_alpha = (alpha-lower)/(upper-lower) + sub_alpha = max(0, sub_alpha) + sub_alpha = min(1, sub_alpha) + else: + sub_alpha = alpha + mob.become_partial(start, *self.get_bounds(sub_alpha)) def get_bounds(self, alpha): raise Exception("Not Implemented") @@ -48,6 +59,12 @@ class ShowCreation(ShowPartial): def get_bounds(self, alpha): return (0, alpha) +class ShowCreationPerSubmobject(ShowCreation): + CONFIG = { + "one_submobject_at_a_time" : True, + "run_time" : 3 + } + class ShowPassingFlash(ShowPartial): CONFIG = { "time_width" : 0.1 diff --git a/helpers.py b/helpers.py index 242033bc..b6f11074 100644 --- a/helpers.py +++ b/helpers.py @@ -11,7 +11,6 @@ from scipy import linalg from constants import * - def get_smooth_handle_points(points): num_handles = len(points) - 1 dim = points.shape[1] diff --git a/mobject/svg_mobject.py b/mobject/svg_mobject.py index 33878830..fb8e535f 100644 --- a/mobject/svg_mobject.py +++ b/mobject/svg_mobject.py @@ -184,6 +184,7 @@ class VMobjectFromSVGPathstring(VMobject): if not is_closed(points): #Both handles and new anchor are the start new_points = points[[0, 0, 0]] + self.mark_paths_closed = True self.growing_path.add_control_points(new_points) def string_to_points(self, coord_string): diff --git a/mobject/vectorized_mobject.py b/mobject/vectorized_mobject.py index eeb72083..3d4b1625 100644 --- a/mobject/vectorized_mobject.py +++ b/mobject/vectorized_mobject.py @@ -11,7 +11,7 @@ class VMobject(Mobject): #Indicates that it will not be displayed, but #that it should count in parent mobject's path "is_subpath" : False, - "close_new_points" : True, + "close_new_points" : False, "mark_paths_closed" : False, } def __init__(self, *args, **kwargs): diff --git a/topics/functions.py b/topics/functions.py index 72add70e..6fa20138 100644 --- a/topics/functions.py +++ b/topics/functions.py @@ -1,56 +1,51 @@ from scipy import integrate -from mobject import Mobject, Mobject1D, Mobject +from mobject.vectorized_mobject import VMobject from helpers import * -class FunctionGraph(Mobject1D): +class FunctionGraph(VMobject): CONFIG = { - "color" : BLUE, - "x_min" : -10, - "x_max" : 10, - "spatial_radius" : SPACE_WIDTH, + "color" : BLUE_D, + "x_min" : -SPACE_WIDTH, + "x_max" : SPACE_WIDTH, + "space_unit_to_num" : 1, + "epsilon" : 0.5, } def __init__(self, function, **kwargs): self.function = function - Mobject1D.__init__(self, **kwargs) + VMobject.__init__(self, **kwargs) def generate_points(self): - numerical_radius = (self.x_max - self.x_min)/2 - numerical_center = (self.x_max + self.x_min)/2 - ratio = numerical_radius / self.spatial_radius - epsilon = self.epsilon * ratio - self.add_points([ - np.array([(x-numerical_center)/ratio, self.function(x), 0]) - for x in np.arange(self.x_min, self.x_max, self.epsilon) - ]) + self.set_anchor_points([ + x*RIGHT + self.function(x)*UP + for pre_x in np.arange(self.x_min, self.x_max, self.epsilon) + for x in [self.space_unit_to_num*pre_x] + ], mode = "smooth") -class ParametricFunction(Mobject1D): +class ParametricFunction(VMobject): CONFIG = { - "start" : 0, - "end" : 1, + "t_min" : 0, + "t_max" : 1, + "epsilon" : 0.1, } def __init__(self, function, **kwargs): self.function = function - Mobject1D.__init__(self, **kwargs) + VMobject.__init__(self, **kwargs) def generate_points(self): - integral = integrate.quad( - lambda t : np.linalg.norm(self.function(t)), - self.start, self.end - ) - length = np.linalg.norm(integral) - epsilon = self.epsilon / length - t_range = np.arange(self.start, self.end, epsilon) - self.add_points([self.function(t) for t in t_range]) + self.set_anchor_points([ + self.function(t) + for t in np.arange(self.t_min, self.t_max, self.epsilon) + ], mode = "smooth") -class Axes(Mobject): - def __init__(self, **kwargs): - x_axis = NumberLine(**kwargs) - y_axis = NumberLine(**kwargs).rotate(np.pi/2, OUT) - Mobject.__init__(self, x_axis, y_axis) +class Axes(VMobject): + def generate_points(self): + self.x_axis = NumberLine(**kwargs) + self.y_axis = NumberLine(**kwargs).rotate(np.pi/2) + self.add(self.x_axis, self.y_axis) \ No newline at end of file diff --git a/topics/geometry.py b/topics/geometry.py index 314de5ee..5e807aeb 100644 --- a/topics/geometry.py +++ b/topics/geometry.py @@ -1,13 +1,12 @@ from helpers import * -from mobject import Mobject, Mobject1D, Point +from mobject import Mobject from mobject.vectorized_mobject import VMobject class Arc(VMobject): CONFIG = { "radius" : 1.0, "start_angle" : 0, - "close_new_points" : False, "num_anchors" : 8, "anchors_span_full_range" : True } @@ -59,7 +58,6 @@ class Dot(Circle): #Use 1D density, even though 2D class Line(VMobject): CONFIG = { "buff" : 0, - "close_new_points" : False, } def __init__(self, start, end, **kwargs): digest_config(self, kwargs) @@ -171,7 +169,8 @@ class CubicBezier(VMobject): class Polygon(VMobject): CONFIG = { "color" : GREEN_D, - "mark_paths_closed" : True + "mark_paths_closed" : True, + "close_new_points" : True, } def __init__(self, *vertices, **kwargs): assert len(vertices) > 1 @@ -190,7 +189,8 @@ class Rectangle(VMobject): "color" : YELLOW, "height" : 2.0, "width" : 4.0, - "mark_paths_closed" : True + "mark_paths_closed" : True, + "close_new_points" : True, } def generate_points(self): y, x = self.height/2, self.width/2 diff --git a/topics/number_line.py b/topics/number_line.py index b6e02cc3..326f74be 100644 --- a/topics/number_line.py +++ b/topics/number_line.py @@ -1,74 +1,61 @@ from helpers import * from mobject import Mobject1D +from mobject.vectorized_mobject import VMobject from mobject.tex_mobject import TexMobject +from topics.geometry import Line, Arrow from scene import Scene -class NumberLine(Mobject1D): +class NumberLine(VMobject): CONFIG = { - "color" : BLUE, - "numerical_radius" : SPACE_WIDTH, - "number_at_center" : 0, - "unit_length_to_spatial_width" : 1, - "tick_size" : 0.1, - "tick_frequency" : 0.5, - "leftmost_tick" : None, + "color" : BLUE, + "x_min" : -SPACE_WIDTH, + "x_max" : SPACE_WIDTH, + "space_unit_to_num" : 1, + "tick_size" : 0.1, + "tick_frequency" : 0.5, + "leftmost_tick" : None, #Defaults to ceil(x_min) "numbers_with_elongated_ticks" : [0], - "longer_tick_multiple" : 2, + "longer_tick_multiple" : 2, + "number_at_center" : 0, } def __init__(self, **kwargs): digest_config(self, kwargs) if self.leftmost_tick is None: - self.leftmost_tick = -int(self.numerical_radius-self.number_at_center) - self.left_num = self.number_at_center - self.numerical_radius - self.right_num = self.number_at_center + self.numerical_radius - Mobject1D.__init__(self, **kwargs) + self.leftmost_tick = np.ceil(self.x_min) + VMobject.__init__(self, **kwargs) def generate_points(self): - spatial_radius = self.numerical_radius*self.unit_length_to_spatial_width - self.add_points([ - (b*x, 0, 0) - for x in np.arange(0, spatial_radius, self.epsilon) - for b in [-1, 1] - ]) - self.index_of_left = np.argmin(self.points[:,0]) - self.index_of_right = np.argmax(self.points[:,0]) - spatial_tick_frequency = self.tick_frequency*self.unit_length_to_spatial_width - self.add_points([ - (x, y, 0) - for num in self.get_tick_numbers() - for y in np.arange(-self.tick_size, self.tick_size, self.epsilon) - for x in [self.number_to_point(num)[0]] - ]) - for number in self.numbers_with_elongated_ticks: - self.elongate_tick_at(number, self.longer_tick_multiple) - self.number_of_points_without_numbers = self.get_num_points() + self.main_line = Line(self.x_min*RIGHT, self.x_max*RIGHT) + self.add(self.main_line) + for x in self.get_tick_numbers(): + self.add_tick(x, self.tick_size) + for x in self.numbers_with_elongated_ticks: + self.add_tick(x, self.longer_tick_multiple*self.tick_size) + self.stretch(self.space_unit_to_num, 0) + self.shift(-self.number_to_point(self.number_at_center)) + + def add_tick(self, x, size): + self.add(Line( + x*RIGHT+size*DOWN, + x*RIGHT+size*UP, + )) + return self def get_tick_numbers(self): - return np.arange(self.leftmost_tick, self.right_num, self.tick_frequency) - - def elongate_tick_at(self, number, multiple = 2): - x = self.number_to_point(number)[0] - self.add_points([ - [x, y, 0] - for y in np.arange( - -multiple*self.tick_size, - multiple*self.tick_size, - self.epsilon - ) - ]) - return self + return np.arange(self.leftmost_tick, self.x_max, self.tick_frequency) def number_to_point(self, number): return interpolate( - self.get_left(), - self.get_right(), - float(number-self.left_num)/(self.right_num - self.left_num) + self.main_line.get_left(), + self.main_line.get_right(), + float(number-self.x_min)/(self.x_max - self.x_min) ) def point_to_number(self, point): - new_point = point-self.get_center() - return self.number_at_center + new_point[0]/self.unit_length_to_spatial_width + dist_from_left = (point[0]-self.main_line.get_left()[0]) + num_dist_from_left = num_dist_from_left/self.space_unit_to_num + return self.x_min + dist_from_left def default_numbers_to_display(self): return self.get_tick_numbers()[::2] @@ -83,11 +70,11 @@ class NumberLine(Mobject1D): result = [] for number in numbers: mob = TexMobject(str(int(number))) - vert_scale = 2*self.tick_size/mob.get_height() - hori_scale = self.tick_frequency*self.unit_length_to_spatial_width/mob.get_width() - mob.scale(min(vert_scale, hori_scale)) - mob.shift(self.number_to_point(number)) - mob.shift(self.get_vertical_number_offset(**kwargs)) + mob.scale_to_fit_height(2*self.tick_size) + mob.shift( + self.number_to_point(number), + self.get_vertical_number_offset(**kwargs) + ) result.append(mob) return result @@ -100,102 +87,110 @@ class NumberLine(Mobject1D): class UnitInterval(NumberLine): CONFIG = { - "numerical_radius" : 0.5, - "unit_length_to_spatial_width" : 2*(SPACE_WIDTH-1), - "tick_frequency" : 0.1, - "leftmost_tick" : 0, - "number_at_center" : 0.5, + "x_min" : 0, + "x_max" : 1, + "space_unit_to_num" : 6, + "tick_frequency" : 0.1, "numbers_with_elongated_ticks" : [0, 1], + "number_at_center" : 0.5, } -class NumberPlane(Mobject1D): +class NumberPlane(VMobject): CONFIG = { - "color" : BLUE, - "x_radius" : SPACE_WIDTH, - "y_radius" : SPACE_HEIGHT, - "x_unit_to_spatial_width" : 1, - "y_unit_to_spatial_height" : 1, - "x_line_frequency" : 1, - "x_faded_line_frequency" : 0.5, - "y_line_frequency" : 1, - "y_faded_line_frequency" : 0.5, - "fade_factor" : 0.3, - "number_scale_factor" : 0.25, - "num_pair_at_center" : np.array((0, 0)), + "color" : BLUE_D, + "secondary_color" : BLUE_E, + "axes_color" : WHITE, + "x_radius": SPACE_WIDTH, + "y_radius": SPACE_HEIGHT, + "space_unit_to_x_unit" : 1, + "space_unit_to_y_unit" : 1, + "x_line_frequency" : 1, + "y_line_frequency" : 1, + "secondary_line_ratio" : 1, + "written_coordinate_height" : 0.5, + "written_coordinate_nudge" : 0.1*(DOWN+RIGHT), + "num_pair_at_center" : (0, 0), } def generate_points(self): - #TODO, clean this - color = self.color - faded = Color(rgb = self.fade_factor*np.array(color.get_rgb())) - - freq_color_tuples = [ - (self.x_line_frequency, self.y_line_frequency, color), - (self.x_faded_line_frequency, self.y_faded_line_frequency, faded), + self.axes = VMobject() + self.main_lines = VMobject() + self.secondary_lines = VMobject() + tuples = [ + ( + self.x_radius, + self.x_line_frequency, + self.y_radius*DOWN, + self.y_radius*UP, + RIGHT + ), + ( + self.y_radius, + self.y_line_frequency, + self.x_radius*LEFT, + self.x_radius*RIGHT, + UP, + ), ] - x_vals = [] - y_vals = [] - for x_freq, y_freq, color in freq_color_tuples: - if not x_freq or not y_freq: - continue - x_vals = np.array(filter(lambda x : x not in x_vals, np.arange( - 0, self.x_radius, - self.x_unit_to_spatial_width*x_freq - ))) - y_vals = np.array(filter(lambda y : y not in y_vals, np.arange( - 0, self.y_radius, - self.y_unit_to_spatial_height*y_freq - ))) - x_cont_vals = np.arange( - 0, self.x_radius, - self.epsilon/self.x_unit_to_spatial_width - ) - y_cont_vals = np.arange( - 0, self.y_radius, - self.epsilon/self.y_unit_to_spatial_height - ) - for x_sgn, y_sgn in it.product([-1, 1], [-1, 1]): - self.add_points( - list(it.product(x_sgn*x_vals, y_sgn*y_cont_vals, [0])) + \ - list(it.product(x_sgn*x_cont_vals, y_sgn*y_vals, [0])), - color = color - ) - self.shift(self.get_center_point()) - + for radius, freq, start, end, unit in tuples: + main_range = np.arange(0, radius, freq) + step = freq/float(freq + self.secondary_line_ratio) + for v in np.arange(0, radius, step): + line1 = Line(start+v*unit, end+v*unit) + line2 = Line(start-v*unit, end-v*unit) + if v == 0: + self.axes.add(line1) + elif v in main_range: + self.main_lines.add(line1, line2) + else: + self.secondary_lines.add(line1, line2) + self.add(self.axes, self.main_lines, self.secondary_lines) + self.stretch(self.space_unit_to_x_unit, 0) + self.stretch(self.space_unit_to_y_unit, 1) + def init_colors(self): + VMobject.init_colors(self) + self.axes.set_stroke(self.axes_color) + # self.main_lines.set_stroke(self.color) + self.secondary_lines.set_stroke(self.secondary_color, 1) + return self def get_center_point(self): return self.num_pair_to_point(self.num_pair_at_center) def num_pair_to_point(self, pair): - pair = pair + self.num_pair_at_center + pair = np.array(pair) + self.num_pair_at_center result = self.get_center() - result[0] += pair[0]*self.x_unit_to_spatial_width - result[1] += pair[1]*self.y_unit_to_spatial_height + result[0] += pair[0]*self.space_unit_to_x_unit + result[1] += pair[1]*self.space_unit_to_y_unit return result def point_to_num_pair(self, point): new_point = point-self.get_center() center_x, center_y = self.num_pair_at_center - x = center_x + point[0]/self.x_unit_to_spatial_width - y = center_y + point[1]/self.y_unit_to_spatial_height + x = center_x + point[0]/self.space_unit_to_x_unit + y = center_y + point[1]/self.space_unit_to_y_unit return x, y def get_coordinate_labels(self, x_vals = None, y_vals = None): result = [] - nudge = 0.1*(DOWN+RIGHT) if x_vals == None and y_vals == None: x_vals = range(-int(self.x_radius), int(self.x_radius)) y_vals = range(-int(self.y_radius), int(self.y_radius)) - for index, vals in zip([0, 1], [x_vals, y_vals]): + for index, vals in enumerate([x_vals, y_vals]): num_pair = [0, 0] for val in vals: num_pair[index] = val point = self.num_pair_to_point(num_pair) num = TexMobject(str(val)) - num.scale(self.number_scale_factor) - num.shift(point-num.get_corner(UP+LEFT)+nudge) + num.scale_to_fit_height( + self.written_coordinate_height + ) + num.shift( + point-num.get_corner(UP+LEFT), + self.written_coordinate_nudge + ) result.append(num) return result @@ -204,134 +199,15 @@ class NumberPlane(Mobject1D): return self def get_vector(self, coords, **kwargs): - if len(coords) == 2: - coords = tuple(list(coords) + [0]) + point = coords[0]*RIGHT + coords[1]*UP arrow = Arrow(ORIGIN, coords, **kwargs) - arrow.remove_tip() - arrow.align_data(Line(ORIGIN, SPACE_WIDTH*LEFT)) - arrow.add_tip() return arrow - -class XYZAxes(Mobject1D): - CONFIG = { - "color" : TEAL, - "radius" : SPACE_HEIGHT, - "tick_frequency" : 1, - } - def generate_points(self): - self.x_axis = NumberLine( - numerical_radius = self.radius, - tick_frequency = self.tick_frequency - ) - self.y_axis = self.x_axis.copy().rotate(np.pi/2, OUT) - self.z_axis = self.x_axis.copy().rotate(np.pi/2, DOWN) - self.digest_mobject_attrs() - - - -class SpaceGrid(Mobject1D): - CONFIG = { - "color" : GREEN, - "radius" : SPACE_HEIGHT, - "unit_to_spatial_length" : 1, - "line_frequency" : 2, - } - def generate_points(self): - line_range = range(-int(self.radius), int(self.radius)+1, self.line_frequency) - for i in range(3): - perm = np.arange(i, i+3) % 3 - for a, b in it.product(line_range, line_range): - start = np.array([a, b, -self.radius])[perm] - end = np.array([a, b, self.radius])[perm] - self.add_line(start, end) - self.pose_at_angle() - - - -class NumberLineScene(Scene): - def construct(self, **number_line_config): - self.number_line = NumberLine(**number_line_config) - self.displayed_numbers = self.number_line.default_numbers_to_display() - self.number_mobs = self.number_line.get_number_mobjects(*self.displayed_numbers) - self.add(self.number_line, *self.number_mobs) - - def zoom_in_on(self, number, zoom_factor, run_time = 2.0): - unit_length_to_spatial_width = self.number_line.unit_length_to_spatial_width*zoom_factor - radius = SPACE_WIDTH/unit_length_to_spatial_width - tick_frequency = 10**(np.floor(np.log10(radius))) - left_tick = tick_frequency*(np.ceil((number-radius)/tick_frequency)) - new_number_line = NumberLine( - numerical_radius = radius, - unit_length_to_spatial_width = unit_length_to_spatial_width, - tick_frequency = tick_frequency, - leftmost_tick = left_tick, - number_at_center = number - ) - new_displayed_numbers = new_number_line.default_numbers_to_display() - new_number_mobs = new_number_line.get_number_mobjects(*new_displayed_numbers) - - transforms = [] - additional_mobjects = [] - squished_new_line = new_number_line.copy() - squished_new_line.scale(1.0/zoom_factor) - squished_new_line.shift(self.number_line.number_to_point(number)) - squished_new_line.points[:,1] = self.number_line.number_to_point(0)[1] - transforms.append(Transform(squished_new_line, new_number_line)) - for mob, num in zip(new_number_mobs, new_displayed_numbers): - point = Point(self.number_line.number_to_point(num)) - point.shift(new_number_line.get_vertical_number_offset()) - transforms.append(Transform(point, mob)) - for mob in self.mobjects: - if mob == self.number_line: - new_mob = mob.copy() - new_mob.shift(-self.number_line.number_to_point(number)) - new_mob.stretch(zoom_factor, 0) - transforms.append(Transform(mob, new_mob)) - continue - mob_center = mob.get_center() - number_under_center = self.number_line.point_to_number(mob_center) - new_point = new_number_line.number_to_point(number_under_center) - new_point += mob_center[1]*UP - if mob in self.number_mobs: - transforms.append(Transform(mob, Point(new_point))) - else: - transforms.append(ApplyMethod(mob.shift, new_point - mob_center)) - additional_mobjects.append(mob) - line_to_hide_pixelation = Line( - self.number_line.get_left(), - self.number_line.get_right(), - color = self.number_line.get_color() - ) - self.add(line_to_hide_pixelation) - self.play(*transforms, run_time = run_time) - self.clear() - self.number_line = new_number_line - self.displayed_numbers = new_displayed_numbers - self.number_mobs = new_number_mobs - self.add(self.number_line, *self.number_mobs) - self.add(*additional_mobjects) - - def show_multiplication(self, num, **kwargs): - if "path_func" not in kwargs: - if num > 0: - kwargs["path_func"] = straight_path - else: - kwargs["path_func"] = counterclockwise_path() - self.play(*[ - ApplyMethod(self.number_line.stretch, num, 0, **kwargs) - ]+[ - ApplyMethod(mob.shift, (num-1)*mob.get_center()[0]*RIGHT, **kwargs) - for mob in self.number_mobs - ]) - - - - - - - - + def prepare_for_nonlinear_transform(self): + for mob in self.submobject_family(): + if mob.get_num_points() > 0: + mob.insert_n_anchor_points(20) + mob.change_anchor_mode("smooth")