A community-maintained Python framework for creating mathematical animations.
up to ShowVaryingLinearCombinations in eola chapter 2
Grant Sanderson3ab6b8579e22
diff --git a/animation/simple_animations.py b/animation/simple_animations.pyindex 9cae9ffd1..16816b333 100644--- a/animation/simple_animations.py+++ b/animation/simple_animations.py@@ -5,7 +5,7 @@ from helpers import *from mobject import Mobjectfrom mobject.vectorized_mobject import VMobject-from mobject.tex_mobject import DecimalNumber+from mobject.tex_mobject import TextMobjectfrom animation import Animation@@ -64,6 +64,12 @@ class Write(ShowCreation):"rate_func" : None,"submobject_mode" : "lagged_start",}+ def __init__(self, mob_or_text, **kwargs):+ if isinstance(mob_or_text, str):+ mobject = TextMobject(mob_or_text)+ else:+ mobject = mob_or_text+ ShowCreation.__init__(self, mobject, **kwargs)class ShowPassingFlash(ShowPartial):CONFIG = {@@ -164,53 +170,37 @@ class MoveAlongPath(Animation):point = self.path.points[int(alpha*n)]self.mobject.shift(point-self.mobject.get_center())-class RangingValues(Animation):- CONFIG = {- "num_decimal_points" : 2,- "rate_func" : None,- "tracking_function" : None,- "tracked_mobject" : None,- "tracked_mobject_next_to_kwargs" : {},- }- def __init__(self, start_val, end_val, **kwargs):+class UpdateFromFunc(Animation):+ """+ update_function of the form func(mobject), presumably+ to be used when the state of one mobject is dependent+ on another simultaneously animated mobject+ """+ def __init__(self, mobject, update_function, **kwargs):digest_config(self, kwargs, locals())- Animation.__init__(self, self.get_mobject_at_alpha(0), **kwargs)+ Animation.__init__(self, mobject, **kwargs)def update_mobject(self, alpha):- pairs = zip(- self.mobject.family_members_with_points(),- self.get_mobject_at_alpha(alpha).family_members_with_points()- )- for old, new in pairs:- ##TODO, figure out a better way- old.__dict__.update(new.__dict__)-- def get_number(self, alpha):- return interpolate(self.start_val, self.end_val, alpha)-- def get_mobject_at_alpha(self, alpha):- mob = DecimalNumber(- self.get_number(alpha),- num_decimal_points=self.num_decimal_points- )- if self.tracking_function:- self.tracking_function(alpha, mob)- elif self.tracked_mobject:- mob.next_to(- self.tracked_mobject,- **self.tracked_mobject_next_to_kwargs- )- return mob+ self.update_function(self.mobject)- def set_tracking_function(self, func):- """- func shoudl be of the form func(alpha, mobject), and- should dictate where to place running number during an- animation- """- self.tracking_function = func+class MaintainPositionRelativeTo(Animation):+ CONFIG = {+ "tracked_critical_point" : ORIGIN+ }+ def __init__(self, mobject, tracked_mobject, **kwargs):+ digest_config(self, kwargs, locals())+ tcp = self.tracked_critical_point+ self.diff = mobject.get_critical_point(tcp) - \+ tracked_mobject.get_critical_point(tcp)+ Animation.__init__(self, mobject, **kwargs)+ def update_mobject(self, alpha):+ self.mobject.shift(+ self.tracked_mobject.get_critical_point(self.tracked_critical_point) - \+ self.mobject.get_critical_point(self.tracked_critical_point) + \+ self.diff+ )### Animation modifiers ###diff --git a/eola/chapter2.py b/eola/chapter2.pyindex 602179028..263083077 100644--- a/eola/chapter2.py+++ b/eola/chapter2.py@@ -6,12 +6,11 @@ from mobject.vectorized_mobject import VMobjectfrom animation.animation import Animationfrom animation.transform import *from animation.simple_animations import *-from animation.playground import *from topics.geometry import *from topics.characters import *from topics.functions import *from topics.number_line import *-from topics.combinatorics import *+from topics.numerals import *from scene import Scenefrom camera import Camerafrom mobject.svg_mobject import *@@ -214,6 +213,177 @@ class CoordinatesAsScalarsExample2(CoordinatesAsScalars):CoordinatesAsScalars.construct(self)+class WhatIfWeChoseADifferentBasis(Scene):+ def construct(self):+ self.play(Write(+ "What if we chose different basis vectors?",+ run_time = 2+ ))+ self.dither(2)++class ShowVaryingLinearCombinations(VectorScene):+ CONFIG = {+ "vector1" : [1, 2],+ "vector2" : [3, -1],+ "vector1_color" : MAROON_C,+ "vector2_color" : BLUE,+ "vector1_label" : "v",+ "vector2_label" : "w",+ "sum_color" : PINK,+ "scalar_pairs" : [+ (1.5, 0.6),+ (0.7, 1.3),+ (-1, -1.5),+ (1, -1.13),+ (1.25, 0.5),+ (-0.6, 1.3),+ ],+ "finish_with_standard_basis_comparison" : True+ }+ def construct(self):+ # self.add_axes()+ v1 = self.add_vector(self.vector1, color = self.vector1_color)+ v2 = self.add_vector(self.vector2, color = self.vector2_color)+ v1_label = self.label_vector(+ v1, self.vector1_label, color = self.vector1_color,+ buff_factor = 3+ )+ v2_label = self.label_vector(+ v2, self.vector2_label, color = self.vector2_color,+ buff_factor = 3+ )+ label_anims = [+ MaintainPositionRelativeTo(label, v)+ for v, label in (v1, v1_label), (v2, v2_label)+ ]+ scalar_anims = self.get_scalar_anims(v1, v2, v1_label, v2_label)++ self.initial_scaling(v1, v2, label_anims, scalar_anims)+ self.show_sum(v1, v2, label_anims, scalar_anims)+ self.scale_with_sum(v1, v2, label_anims, scalar_anims)+ if self.finish_with_standard_basis_comparison:+ self.standard_basis_comparison(scalar_anims)++ def get_scalar_anims(self, v1, v2, v1_label, v2_label):+ def get_val_func(vect):+ original_vect = np.array(vect.get_end()-vect.get_start())+ square_norm = np.linalg.norm(original_vect)**2+ return lambda a : np.dot(+ original_vect, vect.get_end()-vect.get_start()+ )/square_norm+ return [+ RangingValues(+ tracked_mobject = label,+ tracked_mobject_next_to_kwargs = {+ "direction" : LEFT,+ "buff" : 0.1+ },+ scale_val = 0.75,+ value_function = get_val_func(v)+ )+ for v, label in (v1, v1_label), (v2, v2_label)+ ]++ def get_rate_func_pair(self):+ return [+ squish_rate_func(smooth, a, b)+ for a, b in (0, 0.7), (0.3, 1)+ ]++ def initial_scaling(self, v1, v2, label_anims, scalar_anims):+ scalar_pair = self.scalar_pairs.pop(0)+ anims = [+ ApplyMethod(v.scale, s, rate_func = rf)+ for v, s, rf in zip(+ [v1, v2],+ scalar_pair,+ self.get_rate_func_pair()+ )+ ]+ anims += [+ ApplyMethod(v.copy().fade, 0.7)+ for v in v1, v2+ ]+ anims += label_anims + scalar_anims+ self.play(*anims, **{"run_time" : 2})+ self.dither()+ self.last_scalar_pair = scalar_pair++ def show_sum(self, v1, v2, label_anims, scalar_anims):+ self.play(+ ApplyMethod(v2.shift, v1.get_end()),+ *label_anims + scalar_anims+ )+ self.sum_vector = self.add_vector(+ v2.get_end(), color = self.sum_color+ )+ self.dither()++ def scale_with_sum(self, v1, v2, label_anims, scalar_anims):+ v2_anim = UpdateFromFunc(+ v2, lambda m : m.shift(v1.get_end()-m.get_start())+ )+ sum_anim = UpdateFromFunc(+ self.sum_vector,+ lambda v : v.put_start_and_end_on(v1.get_start(), v2.get_end())+ )+ while self.scalar_pairs:+ scalar_pair = self.scalar_pairs.pop(0)+ anims = [+ ApplyMethod(v.scale, s/s_old, rate_func = rf)+ for v, s, s_old, rf in zip(+ [v1, v2],+ scalar_pair,+ self.last_scalar_pair,+ self.get_rate_func_pair()+ )+ ]+ anims += [v2_anim, sum_anim] + label_anims + scalar_anims+ self.play(*anims, **{"run_time" : 2})+ self.dither()+ self.last_scalar_pair = scalar_pair++ def standard_basis_comparison(self, scalar_anims):+ everything = VMobject(*self.get_mobjects())+ alt_coords = [a.mobject for a in scalar_anims]+ array = Matrix([m.copy() for m in alt_coords])+ array.scale(VECTOR_LABEL_SCALE_VAL)+ array.to_edge(UP)+ array.shift(RIGHT)+ brackets = array.get_brackets()++ self.play(*[+ Transform(*pair)+ for pair in zip(alt_coords, array.get_mob_matrix().flatten())+ ] + [Write(brackets)])+ self.dither()+ self.remove(brackets, *alt_coords)+ self.add(array)+ self.play(FadeOut(everything), Animation(self.sum_vector))++ self.add_axes(animate = True)+ ij_array, x_line, y_line = self.vector_to_coords(+ self.sum_vector, integer_labels = False+ )+ neq = TexMobject("\\neq")+ neq.next_to(array)+ self.play(+ ApplyMethod(ij_array.next_to, neq),+ Write(neq)+ )+ self.dither()++++++++++++diff --git a/mobject/mobject.py b/mobject/mobject.pyindex 3fcdd6c7f..97875432b 100644--- a/mobject/mobject.py+++ b/mobject/mobject.py@@ -546,12 +546,13 @@ class Mobject(object):Inputs 0 <= a < b <= 1 determine what portionof mobject to become."""- self.pointwise_become_partial(mobject, a, b)- #TODO, color- # self.interpolate_color(self, mobject, b)+ #TODO, color?spcm = submobject_partial_creation_mode or self.submobject_partial_creation_mode- pairs = zip(self.submobjects, mobject.submobjects)+ pairs = zip(+ self.family_members_with_points(),+ mobject.family_members_with_points()+ )for i, (self_sub, mob_sub) in enumerate(pairs):if spcm == "lagged_start":prop = float(i)/len(pairs)@@ -566,7 +567,7 @@ class Mobject(object):sub_a, sub_b = a, belse:raise Exception("Invalid submobject partial creation mode")- self_sub.become_partial(mob_sub, sub_a, sub_b)+ self_sub.pointwise_become_partial(mob_sub, sub_a, sub_b)return selfdef pointwise_become_partial(self, mobject, a, b):diff --git a/mobject/tex_mobject.py b/mobject/tex_mobject.pyindex cd7b9b4ad..285dcf9b2 100644--- a/mobject/tex_mobject.py+++ b/mobject/tex_mobject.py@@ -107,26 +107,6 @@ class Brace(TexMobject):for mob in mobject, self:mob.rotate(angle)-class DecimalNumber(TexMobject):- CONFIG = {- "num_decimal_points" : 2,- "digit_to_digit_buff" : 0.05- }- def __init__(self, float_num, **kwargs):- digest_config(self, kwargs)- num_string = '%.*f' % (self.num_decimal_points, float_num)- TexMobject.__init__(self, list(num_string))- self.arrange_submobjects(- buff = self.digit_to_digit_buff,- aligned_edge = DOWN- )- if float_num < 0:- minus = self.submobjects[0]- minus.next_to(- self.submobjects[1], LEFT,- buff = self.digit_to_digit_buff- )-def tex_hash(expression, template_tex_file):return str(hash(expression + template_tex_file))diff --git a/scene/scene.py b/scene/scene.pyindex df53ed74b..25a4f6bc8 100644--- a/scene/scene.py+++ b/scene/scene.py@@ -101,7 +101,7 @@ class Scene(object):def remove(self, *mobjects):if not all_elements_are_instances(mobjects, Mobject):raise Exception("Removing something which is not a mobject")- # mobjects = filter(lambda m : m in self.mobjects, mobjects)+ mobjects = list(it.chain(*[m.submobject_family() for m in mobjects]))if len(mobjects) == 0:returnself.mobjects = filter(lambda m : m not in mobjects, self.mobjects)@@ -137,16 +137,11 @@ class Scene(object):def separate_moving_and_static_mobjects(self, *animations):"""- During an animation, the only mobjects directly influencing- display are those with points. This allows for the case- where you might have intersections between the families of- animated mobjects and static mobjects"""- moving_mobjects = self.extract_mobjects_with_points(- *[anim.mobject for anim in animations]- )+ moving_mobjects = [anim.mobject for anim in animations]+ moving_parts = self.extract_mobjects_with_points(*moving_mobjects)static_mobjects = filter(- lambda m : m not in moving_mobjects,+ lambda m : m not in moving_parts,self.extract_mobjects_with_points(*self.mobjects))return moving_mobjects, static_mobjectsdiff --git a/topics/numerals.py b/topics/numerals.pynew file mode 100644index 000000000..750eb4384--- /dev/null+++ b/topics/numerals.py@@ -0,0 +1,82 @@+++from mobject.tex_mobject import TexMobject+from animation import Animation+from helpers import *++++class DecimalNumber(TexMobject):+ CONFIG = {+ "num_decimal_points" : 2,+ "digit_to_digit_buff" : 0.05+ }+ def __init__(self, float_num, **kwargs):+ digest_config(self, kwargs)+ num_string = '%.*f' % (self.num_decimal_points, float_num)+ TexMobject.__init__(self, list(num_string))+ self.arrange_submobjects(+ buff = self.digit_to_digit_buff,+ aligned_edge = DOWN+ )+ if float_num < 0:+ minus = self.submobjects[0]+ minus.next_to(+ self.submobjects[1], LEFT,+ buff = self.digit_to_digit_buff+ )++++class RangingValues(Animation):+ CONFIG = {+ "num_decimal_points" : 2,+ "rate_func" : None,+ "tracking_function" : None,+ "value_function" : None,+ "tracked_mobject" : None,+ "tracked_mobject_next_to_kwargs" : {},+ "scale_val" : None+ }+ def __init__(self, start_val = 0, end_val = 1, **kwargs):+ digest_config(self, kwargs, locals())+ Animation.__init__(self, self.get_mobject_at_alpha(0), **kwargs)++ def update_mobject(self, alpha):+ target = self.get_mobject_at_alpha(alpha)+ self.mobject.submobjects = target.submobjects++ def get_number(self, alpha):+ if self.value_function:+ return self.value_function(alpha)+ return interpolate(self.start_val, self.end_val, alpha)++ def get_mobject_at_alpha(self, alpha):+ mob = DecimalNumber(+ self.get_number(alpha),+ num_decimal_points=self.num_decimal_points+ )+ if self.scale_val:+ mob.scale(self.scale_val)+ if self.tracking_function:+ self.tracking_function(alpha, mob)+ elif self.tracked_mobject:+ mob.next_to(+ self.tracked_mobject,+ **self.tracked_mobject_next_to_kwargs+ )+ return mob++ def set_tracking_function(self, func):+ """+ func shoudl be of the form func(alpha, mobject), and+ should dictate where to place running number during an+ animation+ """+ self.tracking_function = func++ def set_value_function(self, func):+ """+ func must be of the form alpha->number+ """+ self.value_function = func