file_path
stringlengths
21
66
content
stringlengths
0
219k
videos_3b1b/README.md
This project contains the code used to generate the explanatory math videos found on [3Blue1Brown](https://www.3blue1brown.com/). This almost entirely consists of scenes generated using the library [Manim](https://github.com/3b1b/manim). See also the community maintained version at [ManimCommunity](https://github.com/ManimCommunity/manim/). Note, while the library Manim itself is open source and under the MIT license, the contents of this project are intended only to be used for 3Blue1Brown videos themselves. Copyright © 2022 3Blue1Brown
videos_3b1b/stage_scenes.py
#!/usr/bin/env python import inspect import os import sys import importlib from manimlib.config import get_module from manimlib.extract_scene import is_child_scene def get_sorted_scene_classes(module_name): module = get_module(module_name) if hasattr(module, "SCENES_IN_ORDER"): return module.SCENES_IN_ORDER # Otherwise, deduce from the order in which # they're defined in a file importlib.import_module(module.__name__) line_to_scene = {} name_scene_list = inspect.getmembers( module, lambda obj: is_child_scene(obj, module) ) for name, scene_class in name_scene_list: if inspect.getmodule(scene_class).__name__ != module.__name__: continue lines, line_no = inspect.getsourcelines(scene_class) line_to_scene[line_no] = scene_class return [ line_to_scene[index] for index in sorted(line_to_scene.keys()) ] def stage_scenes(module_name): scene_classes = get_sorted_scene_classes(module_name) if len(scene_classes) == 0: print("There are no rendered animations from this module") return # TODO, fix this animation_dir = os.path.join( os.path.expanduser('~'), "Dropbox/3Blue1Brown/videos/2021/holomorphic_dynamics/videos" ) # files = os.listdir(animation_dir) sorted_files = [] for scene_class in scene_classes: scene_name = scene_class.__name__ clips = [f for f in files if f.startswith(scene_name + ".")] for clip in clips: sorted_files.append(os.path.join(animation_dir, clip)) # Partial movie file directory # movie_dir = get_movie_output_directory( # scene_class, **output_directory_kwargs # ) # if os.path.exists(movie_dir): # for extension in [".mov", ".mp4"]: # int_files = get_sorted_integer_files( # pmf_dir, extension=extension # ) # for file in int_files: # sorted_files.append(os.path.join(pmf_dir, file)) # else: # animation_subdir = os.path.dirname(animation_dir) count = 0 while True: staged_scenes_dir = os.path.join( animation_dir, os.pardir, "staged_scenes_{}".format(count) ) if not os.path.exists(staged_scenes_dir): os.makedirs(staged_scenes_dir) break # Otherwise, keep trying new names until # there is a free one count += 1 for count, f in reversed(list(enumerate(sorted_files))): # Going in reversed order means that when finder # sorts by date modified, it shows up in the # correct order symlink_name = os.path.join( staged_scenes_dir, "Scene_{:03}_{}".format( count, f.split(os.sep)[-1] ) ) os.symlink(f, symlink_name) if __name__ == "__main__": if len(sys.argv) < 2: raise Exception("No module given.") module_name = sys.argv[1] stage_scenes(module_name)
videos_3b1b/manim_imports_ext.py
from manimlib import * from manimlib.mobject.svg.old_tex_mobject import * from custom.backdrops import * from custom.banner import * from custom.characters.pi_creature import * from custom.characters.pi_creature_animations import * from custom.characters.pi_creature_scene import * from custom.deprecated import * from custom.drawings import * from custom.end_screen import * from custom.filler import * from custom.logo import * from custom.opening_quote import *
videos_3b1b/custom_config.yml
directories: mirror_module_path: True removed_mirror_prefix: "/Users/grant/cs/videos/" output: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos" raster_images: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/images/raster" vector_images: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/images/vector" pi_creature_images: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/images/pi_creature/svg" sounds: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/sounds" data: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/data" temporary_storage: "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/manim_cache" universal_import_line: "from manim_imports_ext import *" # tex: # executable: "xelatex -no-pdf" # template_file: "ctex_template.tex" # intermediate_filetype: "xdv" style: font: "CMU Serif" text_alignment: "CENTER" background_color: "#000000" camera_resolutions: default_resolution: "4k" fps: 30 window_position: UR window_monitor: 0 full_screen: False embed_exception_mode: "Plain"
videos_3b1b/_2017/borsuk.py
from manim_imports_ext import * from functools import reduce class Jewel(VMobject): CONFIG = { "color" : WHITE, "fill_opacity" : 0.75, "stroke_width" : 0, "height" : 0.5, "num_equator_points" : 5, "sun_vect" : OUT+LEFT+UP, } def init_points(self): for vect in OUT, IN: compass_vects = list(compass_directions(self.num_equator_points)) if vect is IN: compass_vects.reverse() for vect_pair in adjacent_pairs(compass_vects): self.add(Polygon(vect, *vect_pair)) self.set_height(self.height) self.rotate(-np.pi/2-np.pi/24, RIGHT) self.rotate(-np.pi/12, UP) self.submobjects.sort( key=lambda m: -m1.get_center()[2] ) return self class Necklace(VMobject): CONFIG = { "width" : FRAME_WIDTH - 1, "jewel_buff" : MED_SMALL_BUFF, "chain_color" : GREY, "default_colors" : [(4, BLUE), (6, WHITE), (4, GREEN)] } def __init__(self, *colors, **kwargs): digest_config(self, kwargs, locals()) if len(colors) == 0: self.colors = self.get_default_colors() VMobject.__init__(self, **kwargs) def get_default_colors(self): result = list(it.chain(*[ num*[color] for num, color in self.default_colors ])) random.shuffle(result) return result def init_points(self): jewels = VGroup(*[ Jewel(color = color) for color in self.colors ]) jewels.arrange(buff = self.jewel_buff) jewels.set_width(self.width) jewels.center() j_to_j_dist = (jewels[1].get_center()-jewels[0].get_center())[0] chain = Line( jewels[0].get_center() + j_to_j_dist*LEFT/2, jewels[-1].get_center() + j_to_j_dist*RIGHT/2, color = self.chain_color, ) self.add(chain, *jewels) self.chain = chain self.jewels = jewels ################ class FromPreviousTopologyVideo(Scene): def construct(self): rect = Rectangle(height = 9, width = 16) rect.set_height(FRAME_HEIGHT-2) title = OldTexText("From original ``Who cares about topology'' video") title.to_edge(UP) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class CheckOutMathologer(PiCreatureScene): CONFIG = { "logo_height" : 1.5, "screen_height" : 5, "channel_name" : "Mathologer", "logo_file" : "mathologer_logo", "logo_color" : None, } def construct(self): logo = self.get_logo() name = OldTexText(self.channel_name) name.next_to(logo, RIGHT) rect = Rectangle(height = 9, width = 16) rect.set_height(self.screen_height) rect.next_to(logo, DOWN) rect.to_edge(LEFT) self.play( self.get_logo_intro_animation(logo), self.pi_creature.change_mode, "hooray", ) self.play( ShowCreation(rect), Write(name) ) self.wait(2) self.change_mode("happy") self.wait(2) def get_logo(self): logo = ImageMobject(self.logo_file) logo.set_height(self.logo_height) logo.to_corner(UP+LEFT) if self.logo_color is not None: logo.set_color(self.logo_color) logo.stroke_width = 1 return logo def get_logo_intro_animation(self, logo): logo.save_state() logo.shift(DOWN) logo.set_color(BLACK) return ApplyMethod(logo.restore) class IntroduceStolenNecklaceProblem(ThreeDScene): CONFIG = { "jewel_colors" : [BLUE, GREEN, WHITE, RED], "num_per_jewel" : [8, 10, 4, 6], "num_shuffles" : 1, "necklace_center" : UP, "random_seed" : 2, "forced_binary_choices" : (0, 1, 0, 1, 0), } def construct(self): random.seed(self.random_seed) self.add_thieves() self.write_title() self.introduce_necklace() self.divvy_by_cutting_all() self.divvy_with_n_cuts() self.shuffle_jewels(self.necklace.jewels) self.divvy_with_n_cuts() def add_thieves(self): thieves = VGroup( Randolph(), Mortimer() ) thieves.arrange(RIGHT, buff = 4*LARGE_BUFF) thieves.to_edge(DOWN) thieves[0].make_eye_contact(thieves[1]) self.add(thieves) self.thieves = thieves def write_title(self): title = OldTexText("Stolen necklace problem") title.to_edge(UP) self.play( Write(title), *[ ApplyMethod(pi.look_at, title) for pi in self.thieves ] ) self.title = title def introduce_necklace(self): necklace = self.get_necklace() jewels = necklace.jewels jewel_types = self.get_jewels_organized_by_type(jewels) enumeration_labels = VGroup() for jewel_type in jewel_types: num_mob = OldTex(str(len(jewel_type))) jewel_copy = jewel_type[0].copy().scale(2) jewel_copy.next_to(num_mob) label = VGroup(num_mob, jewel_copy) enumeration_labels.add(label) enumeration_labels.arrange(RIGHT, buff = LARGE_BUFF) enumeration_labels.to_edge(UP) self.play( FadeIn( necklace, lag_ratio = 0.5, run_time = 3 ), *it.chain(*[ [pi.change_mode, "conniving", pi.look_at, necklace] for pi in self.thieves ]) ) self.play(*[ ApplyMethod( jewel.rotate, np.pi/6, UP, rate_func = there_and_back ) for jewel in jewels ]) self.play(Blink(self.thieves[0])) for jewel_type in jewel_types: self.play( jewel_type.shift, 0.2*UP, rate_func = wiggle ) self.wait() for x in range(self.num_shuffles): self.shuffle_jewels(jewels) self.play(FadeOut(self.title)) for jewel_type, label in zip(jewel_types, enumeration_labels): jewel_type.submobjects.sort( key=lambda m: m1.get ) jewel_type.save_state() jewel_type.generate_target() jewel_type.target.arrange() jewel_type.target.scale(2) jewel_type.target.move_to(2*UP) self.play( MoveToTarget(jewel_type), Write(label) ) self.play(jewel_type.restore) self.play(Blink(self.thieves[1])) self.enumeration_labels = enumeration_labels self.jewel_types = jewel_types def divvy_by_cutting_all(self): enumeration_labels = self.enumeration_labels necklace = self.necklace jewel_types = self.jewel_types thieves = self.thieves both_half_labels = VGroup() for thief, vect in zip(self.thieves, [LEFT, RIGHT]): half_labels = VGroup() for label in enumeration_labels: tex, jewel = label num = int(tex.get_tex()) half_label = VGroup( OldTex(str(num/2)), jewel.copy() ) half_label.arrange() half_labels.add(half_label) half_labels.arrange(DOWN) half_labels.set_height(thief.get_height()) half_labels.next_to( thief, vect, buff = MED_LARGE_BUFF, aligned_edge = DOWN ) both_half_labels.add(half_labels) for half_labels in both_half_labels: self.play(ReplacementTransform( enumeration_labels.copy(), half_labels )) self.play(*[ApplyMethod(pi.change_mode, "pondering") for pi in thieves]) self.wait() for type_index, jewel_type in enumerate(jewel_types): jewel_type.save_state() jewel_type_copy = jewel_type.copy() n_jewels = len(jewel_type) halves = [ VGroup(*jewel_type_copy[:n_jewels/2]), VGroup(*jewel_type_copy[n_jewels/2:]), ] for half, thief, vect in zip(halves, thieves, [RIGHT, LEFT]): half.arrange(DOWN) half.next_to( thief, vect, buff = SMALL_BUFF + type_index*half.get_width(), aligned_edge = DOWN ) self.play( Transform(jewel_type, jewel_type_copy), *[ ApplyMethod(thief.look_at, jewel_type_copy) for thief in thieves ] ) self.play(*it.chain(*[ [thief.change_mode, "happy", thief.look_at, necklace] for thief in thieves ])) self.wait() self.play(*[ jewel_type.restore for jewel_type in jewel_types ]) self.play(*it.chain(*[ [thief.change_mode, "confused", thief.look_at, necklace] for thief in thieves ])) def divvy_with_n_cuts( self, with_thieves = True, highlight_groups = True, show_matching_after_divvying = True, ): necklace = self.necklace jewel_types = self.jewel_types jewels = sorted( necklace.jewels, lambda m1, m2 : cmp(m1.get_center()[0], m2.get_center()[0]) ) slice_indices, binary_choices = self.find_slice_indices(jewels, jewel_types) subgroups = [ VGroup(*jewels[i1:i2]) for i1, i2 in zip(slice_indices, slice_indices[1:]) ] buff = (jewels[1].get_left()[0]-jewels[0].get_right()[0])/2 v_lines = VGroup(*[ DashedLine(UP, DOWN).next_to(group, RIGHT, buff = buff) for group in subgroups[:-1] ]) strand_groups = [VGroup(), VGroup()] for group, choice in zip(subgroups, binary_choices): strand = Line( group[0].get_center(), group[-1].get_center(), color = necklace.chain.get_color() ) strand.add(*group) strand_groups[choice].add(strand) self.add(strand) self.play(ShowCreation(v_lines)) self.play( FadeOut(necklace.chain), *it.chain(*[ list(map(Animation, group)) for group in strand_groups ]) ) for group in strand_groups: group.save_state() self.play( strand_groups[0].shift, UP/2., strand_groups[1].shift, DOWN/2., ) if with_thieves: self.play(*it.chain(*[ [thief.change_mode, "happy", thief.look_at, self.necklace] for thief in self.thieves ])) self.play(Blink(self.thieves[1])) else: self.wait() if highlight_groups: for group in strand_groups: box = Rectangle( width = group.get_width()+2*SMALL_BUFF, height = group.get_height()+2*SMALL_BUFF, stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.3, ) box.move_to(group) self.play(FadeIn(box)) self.wait() self.play(FadeOut(box)) self.wait() if show_matching_after_divvying: for jewel_type in jewel_types: self.play( *[ ApplyMethod(jewel.scale, 1.5) for jewel in jewel_type ], rate_func = there_and_back, run_time = 2 ) self.wait() self.play( FadeOut(v_lines), FadeIn(necklace.chain), *[ group.restore for group in strand_groups ] ) self.remove(*strand_groups) self.add(necklace) ######## def get_necklace(self, **kwargs): colors = reduce(op.add, [ num*[color] for num, color in zip(self.num_per_jewel, self.jewel_colors) ]) self.necklace = Necklace(*colors, **kwargs) self.necklace.shift(self.necklace_center) return self.necklace def get_jewels_organized_by_type(self, jewels): return [ VGroup(*[m for m in jewels if m.get_color() == color]) for color in map(Color, self.jewel_colors) ] def shuffle_jewels(self, jewels, run_time = 2, path_arc = np.pi/2, **kwargs): shuffled_indices = list(range(len(jewels))) random.shuffle(shuffled_indices) target_group = VGroup(*[ jewel.copy().move_to(jewels[shuffled_indices[i]]) for i, jewel in enumerate(jewels) ]) self.play(Transform( jewels, target_group, run_time = run_time, path_arc = path_arc, **kwargs )) def find_slice_indices(self, jewels, jewel_types): def jewel_to_type_number(jewel): for i, jewel_type in enumerate(jewel_types): if jewel in jewel_type: return i raise Exception("Not in any jewel_types") type_numbers = list(map(jewel_to_type_number, jewels)) n_types = len(jewel_types) for slice_indices in it.combinations(list(range(1, len(jewels))), n_types): slice_indices = [0] + list(slice_indices) + [len(jewels)] if self.forced_binary_choices is not None: all_binary_choices = [self.forced_binary_choices] else: all_binary_choices = it.product(*[list(range(2))]*(n_types+1)) for binary_choices in all_binary_choices: subsets = [ type_numbers[i1:i2] for i1, i2 in zip(slice_indices, slice_indices[1:]) ] left_sets, right_sets = [ [ subset for subset, index in zip(subsets, binary_choices) if index == target_index ] for target_index in range(2) ] flat_left_set = np.array(list(it.chain(*left_sets))) flat_right_set = np.array(list(it.chain(*right_sets))) match_array = [ sum(flat_left_set == n) == sum(flat_right_set == n) for n in range(n_types) ] if np.all(match_array): return slice_indices, binary_choices raise Exception("No fair division found") class ThingToProve(PiCreatureScene): def construct(self): arrow = Arrow(UP, DOWN) top_words = OldTexText("$n$ jewel types") top_words.next_to(arrow, UP) bottom_words = OldTexText(""" Fair division possible with $n$ cuts """) bottom_words.next_to(arrow, DOWN) self.play( Write(top_words, run_time = 2), self.pi_creature.change_mode, "raise_right_hand" ) self.play(ShowCreation(arrow)) self.play( Write(bottom_words, run_time = 2), self.pi_creature.change_mode, "pondering" ) self.wait(3) class FiveJewelCase(IntroduceStolenNecklaceProblem): CONFIG = { "jewel_colors" : [BLUE, GREEN, WHITE, RED, YELLOW], "num_per_jewel" : [6, 4, 4, 2, 8], "forced_binary_choices" : (0, 1, 0, 1, 0, 1), } def construct(self): random.seed(self.random_seed) self.add(self.get_necklace()) jewels = self.necklace.jewels self.shuffle_jewels(jewels, run_time = 0) self.jewel_types = self.get_jewels_organized_by_type(jewels) self.add_title() self.add_thieves() for thief in self.thieves: ApplyMethod(thief.change_mode, "pondering").update(1) thief.look_at(self.necklace) self.divvy_with_n_cuts() def add_title(self): n_cuts = len(self.jewel_colors) title = OldTexText( "%d jewel types, %d cuts"%(n_cuts, n_cuts) ) title.to_edge(UP) self.add(title) class SixJewelCase(FiveJewelCase): CONFIG = { "jewel_colors" : [BLUE, GREEN, WHITE, RED, YELLOW, MAROON_B], "num_per_jewel" : [6, 4, 4, 2, 2, 6], "forced_binary_choices" : (0, 1, 0, 1, 0, 1, 0), } class DiscussApplicability(TeacherStudentsScene): def construct(self): self.teacher_says(""" Minimize sharding, allocate resources evenly """) self.play_student_changes(*["pondering"]*3) self.wait(2) class ThreeJewelCase(FiveJewelCase): CONFIG = { "jewel_colors" : [BLUE, GREEN, WHITE], "num_per_jewel" : [6, 4, 8], "forced_binary_choices" : (0, 1, 0, 1), } class RepeatedShuffling(IntroduceStolenNecklaceProblem): CONFIG = { "num_shuffles" : 5, "random_seed" : 3, "show_matching_after_divvying" : False, } def construct(self): random.seed(self.random_seed) self.add(self.get_necklace()) jewels = self.necklace.jewels self.jewel_types = self.get_jewels_organized_by_type(jewels) self.add_thieves() for thief in self.thieves: ApplyMethod(thief.change_mode, "pondering").update(1) thief.look_at(self.necklace) for x in range(self.num_shuffles): self.shuffle_jewels(jewels) self.divvy_with_n_cuts( show_matching_after_divvying = False ) class NowForTheTopology(TeacherStudentsScene): def construct(self): self.teacher_says("Now for the \\\\ topology") self.play_student_changes(*["hooray"]*3) self.wait(3) class ExternallyAnimatedScene(Scene): def construct(self): raise Exception("Don't actually run this class.") class SphereOntoPlaneIn3D(ExternallyAnimatedScene): pass class DiscontinuousSphereOntoPlaneIn3D(ExternallyAnimatedScene): pass class WriteWords(Scene): CONFIG = { "words" : "", "color" : WHITE, } def construct(self): words = OldTexText(self.words) words.set_color(self.color) words.set_width(FRAME_WIDTH-1) words.to_edge(DOWN) self.play(Write(words)) self.wait(2) class WriteNotAllowed(WriteWords): CONFIG = { "words" : "Not allowed", "color" : RED, } class NonAntipodalCollisionIn3D(ExternallyAnimatedScene): pass class AntipodalCollisionIn3D(ExternallyAnimatedScene): pass class WriteBorsukUlam(WriteWords): CONFIG = { "words" : "Borsuk-Ulam Theorem", } class WriteAntipodal(WriteWords): CONFIG = { "words" : "``Antipodal''", "color" : MAROON_B, } class ProjectOntoEquatorIn3D(ExternallyAnimatedScene): pass class ProjectOntoEquatorWithPolesIn3D(ExternallyAnimatedScene): pass class ProjectAntipodalNonCollisionIn3D(ExternallyAnimatedScene): pass class ShearThenProjectnOntoEquatorPolesMissIn3D(ExternallyAnimatedScene): pass class ShearThenProjectnOntoEquatorAntipodalCollisionIn3D(ExternallyAnimatedScene): pass class ClassicExample(TeacherStudentsScene): def construct(self): self.teacher_says("The classic example...") self.play_student_changes(*["happy"]*3) self.wait(2) class AntipodalEarthPoints(ExternallyAnimatedScene): pass class RotatingEarth(ExternallyAnimatedScene): pass class TemperaturePressurePlane(GraphScene): CONFIG = { "x_labeled_nums" : [], "y_labeled_nums" : [], "x_axis_label" : "Temperature", "y_axis_label" : "Pressure", "graph_origin" : 2.5*DOWN + 2*LEFT, "corner_square_width" : 4, "example_point_coords" : (2, 5), } def construct(self): self.setup_axes() self.draw_arrow() self.add_example_coordinates() self.wander_continuously() def draw_arrow(self): square = Square( side_length = self.corner_square_width, stroke_color = WHITE, stroke_width = 0, ) square.to_corner(UP+LEFT, buff = 0) arrow = Arrow( square.get_right(), self.coords_to_point(*self.example_point_coords) ) self.play(ShowCreation(arrow)) def add_example_coordinates(self): dot = Dot(self.coords_to_point(*self.example_point_coords)) dot.set_color(YELLOW) tex = OldTex("(25^\\circ\\text{C}, 101 \\text{ kPa})") tex.next_to(dot, UP+RIGHT, buff = SMALL_BUFF) self.play(ShowCreation(dot)) self.play(Write(tex)) self.wait() self.play(FadeOut(tex)) def wander_continuously(self): path = VMobject().set_points_smoothly([ ORIGIN, 2*UP+RIGHT, 2*DOWN+RIGHT, 5*RIGHT, 4*RIGHT+UP, 3*RIGHT+2*DOWN, DOWN+LEFT, 2*RIGHT ]) point = self.coords_to_point(*self.example_point_coords) path.shift(point) path.set_color(GREEN) self.play(ShowCreation(path, run_time = 10, rate_func=linear)) self.wait() class AlternateSphereSquishing(ExternallyAnimatedScene): pass class AlternateAntipodalCollision(ExternallyAnimatedScene): pass class AskWhy(TeacherStudentsScene): def construct(self): self.student_says("But...why?") self.play_student_changes("pondering", None, "thinking") self.play(self.get_teacher().change_mode, "happy") self.wait(3) class PointOutVSauce(CheckOutMathologer): CONFIG = { "channel_name" : "", "logo_file" : "Vsauce_logo", "logo_height" : 1, "logo_color" : GREY, } def get_logo(self): logo = SVGMobject(file_name = self.logo_file) logo.set_height(self.logo_height) logo.to_corner(UP+LEFT) logo.set_stroke(width = 0) logo.set_fill(GREEN) logo.sort() return logo def get_logo_intro_animation(self, logo): return DrawBorderThenFill( logo, run_time = 2, ) class WalkEquatorPostTransform(GraphScene): CONFIG = { "x_labeled_nums" : [], "y_labeled_nums" : [], "graph_origin" : 2.5*DOWN + 2*LEFT, "curved_arrow_color" : WHITE, "curved_arrow_radius" : 3, "num_great_arcs" : 10, } def construct(self): self.setup_axes() self.add_curved_arrow() self.great_arc_images = self.get_great_arc_images() self.walk_equator() self.walk_tilted_equator() self.draw_transverse_curve() self.walk_transverse_curve() def add_curved_arrow(self): arc = Arc( start_angle = 2*np.pi/3, angle = -np.pi/2, radius = self.curved_arrow_radius, color = self.curved_arrow_color ) arc.add_tip() arc.move_to(self.coords_to_point(0, 7)) self.add(arc) def walk_equator(self): equator = self.great_arc_images[0] dots = VGroup(Dot(), Dot()) dots.set_color(MAROON_B) dot_movement = self.get_arc_walk_dot_movement(equator, dots) dot_movement.update(0) self.play(ShowCreation(equator, run_time = 3)) self.play(FadeIn(dots[0])) dots[1].set_fill(opacity = 0) self.play(dot_movement) self.play(dots[1].set_fill, None, 1) self.play(dot_movement) self.play(dot_movement) proportion = equator.collision_point_proportion self.play(self.get_arc_walk_dot_movement( equator, dots, rate_func = lambda t : 2*proportion*smooth(t) )) v_line = DashedLine(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) v_line.shift(dots.get_center()[0]*RIGHT) self.play(ShowCreation(v_line)) self.wait() self.play(FadeOut(v_line)) dots.save_state() equator.save_state() self.play( equator.fade, dots.fade ) self.first_dots = dots def walk_tilted_equator(self): equator = self.great_arc_images[0] tilted_eq = self.great_arc_images[1] dots = VGroup(Dot(), Dot()) dots.set_color(MAROON_B) dot_movement = self.get_arc_walk_dot_movement(tilted_eq, dots) dot_movement.update(0) self.play(ReplacementTransform(equator.copy(), tilted_eq)) self.wait() self.play(FadeIn(dots)) self.play(dot_movement) proportion = tilted_eq.collision_point_proportion self.play(self.get_arc_walk_dot_movement( tilted_eq, dots, rate_func = lambda t : 2*proportion*smooth(t) )) v_line = DashedLine(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) v_line.shift(dots.get_center()[0]*RIGHT) self.play(ShowCreation(v_line)) self.wait() self.play(FadeOut(v_line)) self.play(*list(map(FadeOut, [tilted_eq, dots]))) def draw_transverse_curve(self): transverse_curve = self.get_transverse_curve(self.great_arc_images) dots = self.first_dots equator = self.great_arc_images[0] self.play(dots.restore) equator.restore() self.great_arc_images.fade() target_arcs = list(self.great_arc_images[1:]) target_dots = [] for arc in target_arcs: new_dots = dots.copy() for dot, point in zip(new_dots, arc.x_collision_points): dot.move_to(point) target_dots.append(new_dots) alt_eq = equator.copy() alt_eq.set_points(list(reversed(alt_eq.get_points()))) alt_dots = dots.copy() alt_dots.submobjects.reverse() target_arcs += [alt_eq, alt_eq.copy()] target_dots += [alt_dots, alt_dots.copy()] equator_transform = Succession(*[ Transform(equator, arc, rate_func=linear) for arc in target_arcs ]) dots_transform = Succession(*[ Transform(dots, target, rate_func=linear) for target in target_dots ]) self.play( ShowCreation(transverse_curve, lag_ratio = 0), equator_transform, dots_transform, run_time = 10, rate_func=linear, ) self.wait(2) def walk_transverse_curve(self): transverse_curve = self.get_transverse_curve(self.great_arc_images) dots = self.first_dots def dot_update(dots, alpha): for dot, curve in zip(dots, transverse_curve): dot.move_to(curve.point_from_proportion(alpha)) return dots for x in range(2): self.play( UpdateFromAlphaFunc(dots, dot_update), run_time = 4 ) self.play( UpdateFromAlphaFunc(dots, dot_update), run_time = 4, rate_func = lambda t : 0.455*smooth(t) ) self.play( dots.set_color, YELLOW, dots.scale, 1.2, rate_func = there_and_back ) self.wait() ####### def get_arc_walk_dot_movement(self, arc, dots, **kwargs): def dot_update(dots, alpha): dots[0].move_to(arc.point_from_proportion(0.5*alpha)) dots[1].move_to(arc.point_from_proportion(0.5+0.5*alpha)) return dots if "run_time" not in kwargs: kwargs["run_time"] = 5 return UpdateFromAlphaFunc(dots, dot_update, **kwargs) def sphere_to_plane(self, point): x, y, z = point return np.array([ x - 2*x*z + y + 1, y+0.5*y*np.cos(z*np.pi), 0 ]) def sphere_point(self, portion_around_equator, equator_tilt = 0): theta = portion_around_equator*2*np.pi point = np.cos(theta)*RIGHT + np.sin(theta)*UP phi = equator_tilt*np.pi return rotate_vector(point, phi, RIGHT) def get_great_arc_images(self): curves = VGroup(*[ ParametricCurve( lambda t : self.sphere_point(t, s) ).apply_function(self.sphere_to_plane) for s in np.arange(0, 1, 1./self.num_great_arcs) # for s in [0] ]) curves.set_color(YELLOW) curves[0].set_color(RED) for curve in curves: antipodal_x_diff = lambda x : \ curve.point_from_proportion(x+0.5)[0]-\ curve.point_from_proportion(x)[0] last_x = 0 last_sign = np.sign(antipodal_x_diff(last_x)) for x in np.linspace(0, 0.5, 100): sign = np.sign(antipodal_x_diff(x)) if sign != last_sign: mean = np.mean([last_x, x]) curve.x_collision_points = [ curve.point_from_proportion(mean), curve.point_from_proportion(mean+0.5), ] curve.collision_point_proportion = mean break last_x = x last_sign = sign return curves def get_transverse_curve(self, gerat_arc_images): points = list(it.chain(*[ [ curve.x_collision_points[i] for curve in gerat_arc_images ] for i in (0, 1) ])) full_curve = VMobject(close_new_points = True) full_curve.set_points_smoothly(points + [points[0]]) full_curve.set_color(MAROON_B) first_half = full_curve.copy().pointwise_become_partial( full_curve, 0, 0.5 ) second_half = first_half.copy().rotate(np.pi, RIGHT) broken_curve = VGroup(first_half, second_half) return broken_curve class WalkAroundEquatorPreimage(ExternallyAnimatedScene): pass class WalkTiltedEquatorPreimage(ExternallyAnimatedScene): pass class FormLoopTransverseToEquator(ExternallyAnimatedScene): pass class AntipodalWalkAroundTransverseLoop(ExternallyAnimatedScene): pass class MentionGenerality(TeacherStudentsScene, ThreeDScene): def construct(self): necklace = Necklace(width = FRAME_X_RADIUS) necklace.shift(2*UP) necklace.to_edge(RIGHT) arrow = OldTex("\\Leftrightarrow") arrow.scale(2) arrow.next_to(necklace, LEFT) q_marks = OldTex("???") q_marks.next_to(arrow, UP) arrow.add(q_marks) formula = OldTex("f(\\textbf{x}) = f(-\\textbf{x})") formula.next_to(self.get_students(), UP, buff = LARGE_BUFF) formula.to_edge(LEFT, buff = LARGE_BUFF) self.play( self.teacher.change_mode, "raise_right_hand", self.teacher.look_at, arrow ) self.play( FadeIn(necklace, run_time = 2, lag_ratio = 0.5), Write(arrow), *[ ApplyMethod(pi.look_at, arrow) for pi in self.get_pi_creatures() ] ) self.play_student_changes("pondering", "erm", "confused") self.wait() self.play(*[ ApplyMethod(pi.look_at, arrow) for pi in self.get_pi_creatures() ]) self.play(Write(formula)) self.wait(3) class SimpleSphere(ExternallyAnimatedScene): pass class PointsIn3D(Scene): CONFIG = { # "colors" : [RED, GREEN, BLUE], "colors" : color_gradient([GREEN, BLUE], 3), } def construct(self): sphere_def = OldTexText( "\\doublespacing Sphere in 3D: All", "$(x_1, x_2, x_3)$\\\\", "such that", "$x_1^2 + x_2^2 + x_3^2 = 1$", alignment = "", ) sphere_def.next_to(ORIGIN, DOWN) for index, subindex_list in (1, [1, 2, 4, 5, 7, 8]), (3, [0, 2, 4, 6, 8, 10]): colors = np.repeat(self.colors, 2) for subindex, color in zip(subindex_list, colors): sphere_def[index][subindex].set_color(color) point_ex = OldTexText( "For example, ", "(", "0.41", ", ", "-0.58", ", ", "0.71", ")", arg_separator = "" ) for index, color in zip([2, 4, 6], self.colors): point_ex[index].set_color(color) point_ex.scale(0.8) point_ex.next_to( sphere_def[1], UP+RIGHT, buff = 1.5*LARGE_BUFF ) point_ex.shift_onto_screen() arrow = Arrow(sphere_def[1].get_top(), point_ex.get_bottom()) self.play(Write(sphere_def[1])) self.play(ShowCreation(arrow)) self.play(Write(point_ex)) self.wait() self.play( Animation(sphere_def[1].copy(), remover = True), Write(sphere_def), ) self.wait() class AntipodalPairToBeGivenCoordinates(ExternallyAnimatedScene): pass class WritePointCoordinates(Scene): CONFIG = { "colors" : color_gradient([GREEN, BLUE], 3), "corner" : DOWN+RIGHT, } def construct(self): coords = self.get_coords() arrow = Arrow( -self.corner, self.corner, stroke_width = 8, color = MAROON_B ) x_component = self.corner[0]*RIGHT y_component = self.corner[1]*UP arrow.next_to( coords.get_edge_center(y_component), y_component, aligned_edge = -x_component, buff = MED_SMALL_BUFF ) group = VGroup(coords, arrow) group.scale(2) group.to_corner(self.corner) self.play(FadeIn(coords)) self.play(ShowCreation(arrow)) self.wait() def get_coords(self): coords = OldTex( "(", "0.41", ", ", "-0.58", ", ", "0.71", ")", arg_separator = "" ) for index, color in zip([1, 3, 5], self.colors): coords[index].set_color(color) return coords class WriteAntipodalCoordinates(WritePointCoordinates): CONFIG = { "corner" : UP+LEFT, "sign_color" : RED, } def get_coords(self): coords = OldTex( "(", "-", "0.41", ", ", "+", "0.58", ", ", "-", "0.71", ")", arg_separator = "" ) for index, color in zip([2, 5, 8], self.colors): coords[index].set_color(color) coords[index-1].set_color(self.sign_color) return coords class GeneralizeBorsukUlam(Scene): CONFIG = { "n_dims" : 3, "boundary_colors" : [GREEN_B, BLUE], "output_boundary_color" : [MAROON_B, YELLOW], "negative_color" : RED, } def setup(self): self.colors = color_gradient(self.boundary_colors, self.n_dims) def construct(self): sphere_set = self.get_sphere_set() arrow = Arrow(LEFT, RIGHT) f = OldTex("f") output_space = self.get_output_space() equation = self.get_equation() sphere_set.to_corner(UP+LEFT) arrow.next_to(sphere_set, RIGHT) f.next_to(arrow, UP) output_space.next_to(arrow, RIGHT) equation.next_to(sphere_set, DOWN, buff = LARGE_BUFF) equation.to_edge(RIGHT) lhs = VGroup(*equation[:2]) eq = equation[2] rhs = VGroup(*equation[3:]) self.play(FadeIn(sphere_set)) self.wait() self.play( ShowCreation(arrow), Write(f) ) self.play(Write(output_space)) self.wait() self.play(FadeIn(lhs)) self.play( ReplacementTransform(lhs.copy(), rhs), Write(eq) ) self.wait() def get_condition(self): squares = list(map(Tex, [ "x_%d^2"%d for d in range(1, 1+self.n_dims) ])) for square, color in zip(squares, self.colors): square[0].set_color(color) square[-1].set_color(color) plusses = [Tex("+") for x in range(self.n_dims-1)] plusses += [Tex("=1")] condition = VGroup(*it.chain(*list(zip(squares, plusses)))) condition.arrange(RIGHT) return condition def get_tuple(self): mid_parts = list(it.chain(*[ ["x_%d"%d, ","] for d in range(1, self.n_dims) ])) tup = OldTex(*["("] + mid_parts + ["x_%d"%self.n_dims, ")"]) for index, color in zip(it.count(1, 2), self.colors): tup[index].set_color(color) return tup def get_negative_tuple(self): mid_parts = list(it.chain(*[ ["-", "x_%d"%d, ","] for d in range(1, self.n_dims) ])) tup = OldTex(*["("] + mid_parts + ["-", "x_%d"%self.n_dims, ")"]) for index, color in zip(it.count(1, 3), self.colors): tup[index].set_color(self.negative_color) tup[index+1].set_color(color) return tup def get_output_space(self): return OldTexText("%dD space"%(self.n_dims-1)) # n_dims = self.n_dims-1 # colors = color_gradient(self.output_boundary_color, n_dims) # mid_parts = list(it.chain(*[ # ["y_%d"%d, ","] # for d in range(1, n_dims) # ])) # tup = OldTex(*["("] + mid_parts + ["y_%d"%n_dims, ")"]) # for index, color in zip(it.count(1, 2), colors): # tup[index].set_color(color) # return tup def get_equation(self): tup = self.get_tuple() neg_tup = self.get_negative_tuple() f1, f2 = [Tex("f") for x in range(2)] equals = OldTex("=") equation = VGroup(f1, tup, equals, f2, neg_tup) equation.arrange(RIGHT, buff = SMALL_BUFF) return equation def get_sphere_set(self): tup = self.get_tuple() such_that = OldTexText("such that") such_that.next_to(tup, RIGHT) condition = self.get_condition() condition.next_to( tup, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) group = VGroup(tup, such_that, condition) l_brace = Brace(group, LEFT) r_brace = Brace(group, RIGHT) group.add(l_brace, r_brace) return group # class FiveDBorsukUlam(GeneralizeBorsukUlam): # CONFIG = { # "n_dims" : 5, # } class MentionMakingNecklaceProblemContinuous(TeacherStudentsScene): def construct(self): self.teacher_says(""" Translate this into a continuous problem. """) self.play_student_changes("confused", "pondering", "erm") self.wait(3) class MakeTwoJewelCaseContinuous(IntroduceStolenNecklaceProblem): CONFIG = { "jewel_colors" : [BLUE, GREEN], "num_per_jewel" : [8, 10], "random_seed" : 2, "forced_binary_choices" : (0, 1, 0), "show_matching_after_divvying" : True, "necklace_center" : ORIGIN, "necklace_width" : FRAME_WIDTH - 3, "random_seed" : 0, "num_continuous_division_searches" : 4, } def construct(self): random.seed(self.random_seed) self.introduce_necklace() self.divvy_with_n_cuts() self.identify_necklace_with_unit_interval() self.color_necklace() self.find_continuous_fair_division() self.show_continuous_fair_division() self.set_color_continuous_groups() self.mention_equivalence_to_discrete_case() self.shift_divide_off_tick_marks() def introduce_necklace(self): self.get_necklace( width = self.necklace_width, ) self.play(FadeIn( self.necklace, lag_ratio = 0.5 )) self.shuffle_jewels(self.necklace.jewels) jewel_types = self.get_jewels_organized_by_type( self.necklace.jewels ) self.wait() self.count_jewel_types(jewel_types) self.wait() self.jewel_types = jewel_types def count_jewel_types(self, jewel_types): enumeration_labels = VGroup() for jewel_type in jewel_types: num_mob = OldTex(str(len(jewel_type))) jewel_copy = jewel_type[0].copy() # jewel_copy.set_height(num_mob.get_height()) jewel_copy.next_to(num_mob) label = VGroup(num_mob, jewel_copy) enumeration_labels.add(label) enumeration_labels.arrange(RIGHT, buff = LARGE_BUFF) enumeration_labels.to_edge(UP) for jewel_type, label in zip(jewel_types, enumeration_labels): jewel_type.sort() jewel_type.save_state() jewel_type.generate_target() jewel_type.target.arrange() jewel_type.target.move_to(2*UP) self.play( MoveToTarget(jewel_type), Write(label) ) self.play(jewel_type.restore) def divvy_with_n_cuts(self): IntroduceStolenNecklaceProblem.divvy_with_n_cuts( self, with_thieves = False, highlight_groups = False, show_matching_after_divvying = True, ) def identify_necklace_with_unit_interval(self): interval = UnitInterval( tick_frequency = 1./sum(self.num_per_jewel), tick_size = 0.2, numbers_with_elongated_ticks = [], ) interval.stretch_to_fit_width(self.necklace.get_width()) interval.move_to(self.necklace) tick_marks = interval.tick_marks tick_marks.set_stroke(WHITE, width = 2) brace = Brace(interval) brace_text = brace.get_text("Length = 1") self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play( ShowCreation(interval.tick_marks), ) self.wait() self.tick_marks = interval.tick_marks self.length_brace = VGroup(brace, brace_text) def color_necklace(self): example_index = len(self.necklace.jewels)/2 jewels = self.necklace.jewels chain = self.necklace.chain self.remove(self.necklace) self.add(chain, jewels) jewels.submobjects.sort( key=lambda m: m.get_center()[0] ) remaining_indices = list(range(len(jewels))) remaining_indices.remove(example_index) example_segment = self.color_necklace_by_indices(example_index) remaining_segments = self.color_necklace_by_indices(*remaining_indices) self.remove(chain) segments = VGroup(example_segment[0], *remaining_segments) segments.submobjects.sort( key=lambda m: m.get_center()[0] ) segment_types = VGroup(*[ VGroup(*[m for m in segments if m.get_color() == Color(color)]) for color in self.jewel_colors ]) for group in segment_types: length_tex = OldTex("\\frac{%d}{%d}"%( len(group), len(jewels) )) length_tex.next_to(group, UP) length_tex.shift(UP) self.play( group.shift, UP, Write(length_tex, run_time = 1), ) self.wait() self.play( group.shift, DOWN, FadeOut(length_tex) ) self.play(FadeOut(self.length_brace)) self.segments = segments def color_necklace_by_indices(self, *indices): chain = self.necklace.chain jewels = VGroup(*[ self.necklace.jewels[i] for i in indices ]) n_jewels = len(self.necklace.jewels) segments = VGroup(*[ Line( chain.point_from_proportion(index/float(n_jewels)), chain.point_from_proportion((index+1)/float(n_jewels)), color = jewel.get_color() ) for index, jewel in zip(indices, jewels) ]) for jewel in jewels: jewel.save_state() self.play(jewels.shift, jewels.get_height()*UP) self.play(ReplacementTransform( jewels, segments, lag_ratio = 0.5, run_time = 2 )) self.wait() return segments def find_continuous_fair_division(self): chain = self.necklace.chain n_jewels = len(self.necklace.jewels) slice_indices, ignore = self.find_slice_indices( self.necklace.jewels, self.jewel_types ) cut_proportions = [ sorted([random.random(), random.random()]) for x in range(self.num_continuous_division_searches) ] cut_proportions.append([ float(i)/n_jewels for i in slice_indices[1:-1] ]) cut_points = [ list(map(chain.point_from_proportion, pair)) for pair in cut_proportions ] v_lines = VGroup(*[DashedLine(UP, DOWN) for x in range(2)]) for line, point in zip(v_lines, cut_points[0]): line.move_to(point) self.play(ShowCreation(v_lines)) self.wait() for target_points in cut_points[1:]: self.play(*[ ApplyMethod(line.move_to, point) for line, point in zip(v_lines, target_points) ]) self.wait() self.slice_indices = slice_indices self.v_lines = v_lines def show_continuous_fair_division(self): slice_indices = self.slice_indices groups = [ VGroup( VGroup(*self.segments[i1:i2]), VGroup(*self.tick_marks[i1:i2]), ) for i1, i2 in zip(slice_indices, slice_indices[1:]) ] groups[-1].add(self.tick_marks[-1]) vects = [[UP, DOWN][i] for i in self.forced_binary_choices] self.play(*[ ApplyMethod(group.shift, 0.5*vect) for group, vect in zip(groups, vects) ]) self.wait() self.groups = groups def set_color_continuous_groups(self): top_group = VGroup(self.groups[0], self.groups[2]) bottom_group = self.groups[1] boxes = VGroup() for group in top_group, bottom_group: box = Rectangle( width = FRAME_WIDTH-2, height = group.get_height()+SMALL_BUFF, stroke_width = 0, fill_color = WHITE, fill_opacity = 0.25, ) box.shift(group.get_center()[1]*UP) boxes.add(box) weight_description = VGroup(*[ VGroup( OldTex("\\frac{%d}{%d}"%( len(jewel_type)/2, len(self.segments) )), Jewel(color = jewel_type[0].get_color()) ).arrange() for jewel_type in self.jewel_types ]) weight_description.arrange(buff = LARGE_BUFF) weight_description.next_to(boxes, UP, aligned_edge = LEFT) self.play(FadeIn(boxes)) self.play(Write(weight_description)) self.wait() self.set_color_box = boxes self.weight_description = weight_description def mention_equivalence_to_discrete_case(self): morty = Mortimer() morty.flip() morty.to_edge(DOWN) morty.shift(LEFT) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, """This is equivalent to the discrete case. """, bubble_config = { "height" : 3, "direction" : LEFT, } )) self.play(Blink(morty)) self.wait() self.play(*list(map(FadeOut, [ morty, morty.bubble, morty.bubble.content ]))) def shift_divide_off_tick_marks(self): groups = self.groups slice_indices = self.slice_indices v_lines = self.v_lines left_segment = groups[1][0][0] left_tick = groups[1][1][0] right_segment = groups[-1][0][0] right_tick = groups[-1][1][0] segment_width = left_segment.get_width() for mob in left_segment, right_segment: mob.parts = VGroup( mob.copy().pointwise_become_partial(mob, 0, 0.5), mob.copy().pointwise_become_partial(mob, 0.5, 1), ) self.remove(mob) self.add(mob.parts) restorers = [left_segment.parts, left_tick, right_segment.parts, right_tick] for mob in restorers: mob.save_state() emerald_segments = VGroup(*[ segment for segment in list(groups[0][0])+list(groups[2][0]) if segment.get_color() == Color(self.jewel_colors[1]) if segment is not right_segment ]) emerald_segments.add( left_segment.parts[0], right_segment.parts[1], ) emerald_segments.sort() self.play(v_lines.shift, segment_width*RIGHT/2) self.play(*[ ApplyMethod(mob.shift, vect) for mob, vect in [ (left_segment.parts[0], UP), (left_tick, UP), (right_segment.parts[0], DOWN), (right_tick, DOWN), ] ]) self.wait() words = OldTexText("Cut part way through segment") words.to_edge(RIGHT) words.shift(2*UP) arrow1 = Arrow(words.get_bottom(), left_segment.parts[0].get_right()) arrow2 = Arrow(words.get_bottom(), right_segment.parts[1].get_left()) VGroup(words, arrow1, arrow2).set_color(RED) self.play(Write(words), ShowCreation(arrow1)) self.wait() emerald_segments.save_state() emerald_segments.generate_target() emerald_segments.target.arrange() emerald_segments.target.move_to(2*DOWN) brace = Brace(emerald_segments.target, DOWN) label = VGroup( OldTex("5\\left( 1/18 \\right)"), Jewel(color = self.jewel_colors[1]) ).arrange() label.next_to(brace, DOWN) self.play(MoveToTarget(emerald_segments)) self.play(GrowFromCenter(brace)) self.play(Write(label)) self.wait() broken_pair = VGroup(*emerald_segments[2:4]) broken_pair.save_state() self.play(broken_pair.shift, 0.5*UP) vect = broken_pair[1].get_left()-broken_pair[1].get_right() self.play( broken_pair[0].shift, -vect/2, broken_pair[1].shift, vect/2, ) self.wait() self.play(broken_pair.space_out_submobjects) self.play(broken_pair.restore) self.wait() self.play( emerald_segments.restore, *list(map(FadeOut, [brace, label])) ) self.wait() self.play(ShowCreation(arrow2)) self.wait() self.play(*list(map(FadeOut, [words, arrow1, arrow2]))) for line in v_lines: self.play(line.shift, segment_width*LEFT/2) self.play(*[mob.restore for mob in restorers]) self.remove(left_segment.parts, right_segment.parts) self.add(left_segment, right_segment) class ThinkAboutTheChoices(TeacherStudentsScene): def construct(self): self.teacher_says(""" Think about the choices behind a division... """) self.play_student_changes( *["pondering"]*3, look_at = FRAME_X_RADIUS*RIGHT+FRAME_Y_RADIUS*DOWN ) self.wait(3) class ChoicesInNecklaceCutting(ReconfigurableScene): CONFIG = { "num_continuous_division_searches" : 4, "denoms" : [6, 3, 2], "necklace_center" : DOWN, "thief_box_offset" : 1.2, } def construct(self): self.add_necklace() self.choose_places_to_cut() self.show_three_numbers_adding_to_one() self.make_binary_choice() def add_necklace(self): width, colors, num_per_color = [ MakeTwoJewelCaseContinuous.CONFIG[key] for key in [ "necklace_width", "jewel_colors", "num_per_jewel" ] ] color_list = list(it.chain(*[ num*[color] for num, color in zip(num_per_color, colors) ])) random.shuffle(color_list) interval = UnitInterval( tick_frequency = 1./sum(num_per_color), tick_size = 0.2, numbers_with_elongated_ticks = [], ) interval.stretch_to_fit_width(width) interval.shift(self.necklace_center) tick_marks = interval.tick_marks tick_marks.set_stroke(WHITE, width = 2) segments = VGroup() for l_tick, r_tick, color in zip(tick_marks, tick_marks[1:], color_list): segment = Line( l_tick.get_center(), r_tick.get_center(), color = color ) segments.add(segment) self.necklace = VGroup(segments, tick_marks) self.add(self.necklace) self.interval = interval def choose_places_to_cut(self): v_lines = VGroup(*[DashedLine(UP, DOWN) for x in range(2)]) final_num_pair = np.cumsum([1./d for d in self.denoms[:2]]) num_pairs = [ sorted([random.random(), random.random()]) for x in range(self.num_continuous_division_searches) ] + [final_num_pair] point_pairs = [ list(map(self.interval.number_to_point, num_pair)) for num_pair in num_pairs ] for line, point in zip(v_lines, point_pairs[0]): line.move_to(point) self.play(ShowCreation(v_lines)) for point_pair in point_pairs[1:]: self.wait() self.play(*[ ApplyMethod(line.move_to, point) for line, point in zip(v_lines, point_pair) ]) self.wait() self.division_points = list(it.chain( [self.interval.get_left()], point_pairs[-1], [self.interval.get_right()] )) self.v_lines = v_lines def show_three_numbers_adding_to_one(self): points = self.division_points braces = [ Brace(Line(p1+SMALL_BUFF*RIGHT/2, p2+SMALL_BUFF*LEFT/2)) for p1, p2 in zip(points, points[1:]) ] for char, denom, brace in zip("abc", self.denoms, braces): brace.label = brace.get_text("$%s$"%char) brace.concrete_label = brace.get_text("$\\frac{1}{%d}$"%denom) VGroup( brace.label, brace.concrete_label ).set_color(YELLOW) words = OldTexText( "1) Choose", "$a$, $b$, $c$", "so that", "$a+b+c = 1$" ) words[1].set_color(YELLOW) words[3].set_color(YELLOW) words.to_corner(UP+LEFT) self.play(*it.chain(*[ [GrowFromCenter(brace), Write(brace.label)] for brace in braces ])) self.play(Write(words)) self.wait(2) self.play(*[ ReplacementTransform(brace.label, brace.concrete_label) for brace in braces ]) self.wait() self.wiggle_v_lines() self.wait() self.transition_to_alt_config(denoms = [3, 3, 3]) self.wait() self.play(*list(map(FadeOut, list(braces) + [ brace.concrete_label for brace in braces ]))) self.choice_one_words = words def make_binary_choice(self): groups = self.get_groups() boxes, labels = self.get_boxes_and_labels() arrow_pairs, curr_arrows = self.get_choice_arrow_pairs(groups) words = OldTexText("2) Make a binary choice for each segment") words.next_to( self.choice_one_words, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) self.play(Write(words)) self.play(*list(map(FadeIn, [boxes, labels]))) for binary_choices in it.product(*[[0, 1]]*3): self.play(*[ ApplyMethod(group.move_to, group.target_points[choice]) for group, choice in zip(groups, binary_choices) ] + [ Transform( curr_arrow, arrow_pair[choice], path_arc = np.pi ) for curr_arrow, arrow_pair, choice in zip( curr_arrows, arrow_pairs, binary_choices ) ]) self.wait() ###### def get_groups(self, indices = None): segments, tick_marks = self.necklace if indices is None: n_segments = len(segments) indices = [0, n_segments/6, n_segments/2, n_segments] groups = [ VGroup( VGroup(*segments[i1:i2]), VGroup(*tick_marks[i1:i2]), ) for i1, i2 in zip(indices, indices[1:]) ] for group, index in zip(groups, indices[1:]): group[1].add(tick_marks[index].copy()) groups[-1][1].add(tick_marks[-1]) for group in groups: group.target_points = [ group.get_center() + self.thief_box_offset*vect for vect in (UP, DOWN) ] return groups def get_boxes_and_labels(self): box = Rectangle( height = self.necklace.get_height()+SMALL_BUFF, width = self.necklace.get_width()+2*SMALL_BUFF, stroke_width = 0, fill_color = WHITE, fill_opacity = 0.25 ) box.move_to(self.necklace) boxes = VGroup(*[ box.copy().shift(self.thief_box_offset*vect) for vect in (UP, DOWN) ]) labels = VGroup(*[ OldTexText( "Thief %d"%(i+1) ).next_to(box, UP, aligned_edge = RIGHT) for i, box in enumerate(boxes) ]) return boxes, labels def get_choice_arrow_pairs(self, groups): arrow = OldTex("\\uparrow") arrow_pairs = [ [arrow.copy(), arrow.copy().rotate(np.pi)] for group in groups ] pre_arrow_points = [ VectorizedPoint(group.get_center()) for group in groups ] for point, arrow_pair in zip(pre_arrow_points, arrow_pairs): for arrow, color in zip(arrow_pair, [GREEN, RED]): arrow.set_color(color) arrow.move_to(point.get_center()) return arrow_pairs, pre_arrow_points def wiggle_v_lines(self): self.play( *it.chain(*[ [ line.rotate, np.pi/12, vect, line.set_color, RED ] for line, vect in zip(self.v_lines, [OUT, IN]) ]), rate_func = wiggle ) class CompareThisToSphereChoice(TeacherStudentsScene): def construct(self): self.teacher_says(""" Compare this to choosing a point on the sphere. """) self.play_student_changes( *["pondering"]*3, look_at = FRAME_X_RADIUS*RIGHT+FRAME_Y_RADIUS*DOWN ) self.wait(3) class SimpleRotatingSphereWithPoint(ExternallyAnimatedScene): pass class ChoicesForSpherePoint(GeneralizeBorsukUlam): def construct(self): self.add_sphere_set() self.initialize_words() self.play(Write(self.choice_one_words)) self.wait() self.show_example_choices() self.show_binary_choices() def get_tuple(self): tup = OldTex("(x, y, z)") for i, color in zip([1, 3, 5], self.colors): tup[i].set_color(color) return tup def get_condition(self): condition = OldTex("x^2+y^2+z^2 = 1") for i, color in zip([0, 3, 6], self.colors): VGroup(*condition[i:i+2]).set_color(color) return condition def add_sphere_set(self): sphere_set = self.get_sphere_set() sphere_set.scale(0.7) sphere_set.to_edge(RIGHT) sphere_set.shift(UP) self.add(sphere_set) self.sphere_set = sphere_set def initialize_words(self): choice_one_words = OldTexText( "1) Choose", "$x^2$, $y^2$, $z^2$", "so that", "$x^2+y^2+z^2 = 1$" ) for i in 1, 3: for j, color in zip([0, 3, 6], self.colors): VGroup(*choice_one_words[i][j:j+2]).set_color(color) choice_one_words.to_corner(UP+LEFT) choice_two_words = OldTexText( "2) Make a binary choice for each one" ) choice_two_words.next_to( choice_one_words, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) self.choice_one_words = choice_one_words self.choice_two_words = choice_two_words def show_example_choices(self): choices = VGroup(*[ OldTex(*tex).set_color(color) for color, tex in zip(self.colors, [ ("x", "^2 = ", "1/6"), ("y", "^2 = ", "1/3"), ("z", "^2 = ", "1/2"), ]) ]) choices.arrange( DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) choices.set_height(FRAME_Y_RADIUS) choices.to_edge(LEFT) choices.shift(DOWN) self.play(FadeIn( choices, run_time = 2, lag_ratio = 0.5 )) self.wait() self.choices = choices def show_binary_choices(self): for choice in self.choices: var_tex = choice.expression_parts[0] frac_tex = choice.expression_parts[2] sqrts = VGroup(*[ OldTex( var_tex + "=" + sign + \ "\\sqrt{%s}"%frac_tex) for sign in ["+", "-"] ]) for sqrt in sqrts: sqrt.scale(0.6) sqrts.arrange(DOWN) sqrts.next_to(choice, RIGHT, buff = LARGE_BUFF) sqrts.set_color(choice.get_color()) arrows = VGroup(*[ Arrow( choice.get_right(), sqrt.get_left(), color = WHITE, tip_length = 0.1, buff = SMALL_BUFF ) for sqrt in sqrts ]) self.play(ShowCreation(arrows)) self.play(FadeIn(sqrts, lag_ratio = 0.5)) self.play(Write(self.choice_two_words)) self.wait() class NecklaceDivisionSphereAssociation(ChoicesInNecklaceCutting): CONFIG = { "xyz_colors" : color_gradient([GREEN_B, BLUE], 3), "necklace_center" : DOWN, "thief_box_offset" : 1.6, "denoms" : [6, 3, 2], } def construct(self): self.add_necklace() self.add_sphere_point_label() self.choose_places_to_cut() self.add_braces() self.add_boxes_and_labels() self.show_binary_choice_association() self.ask_about_antipodal_pairs() def add_sphere_point_label(self): label = OldTexText( "$(x, y, z)$", "such that", "$x^2 + y^2 + z^2 = 1$" ) for i, j_list in (0, [1, 3, 5]), (2, [0, 3, 6]): for j, color in zip(j_list, self.xyz_colors): label[i][j].set_color(color) label.to_corner(UP+RIGHT) ghost_sphere_point = VectorizedPoint() ghost_sphere_point.to_corner(UP+LEFT, buff = LARGE_BUFF) ghost_sphere_point.shift(2*RIGHT) arrow = Arrow( label.get_left(), ghost_sphere_point, color = WHITE ) self.add(label, arrow) self.sphere_point_label = label def add_braces(self): points = self.division_points braces = [ Brace( Line(p1+SMALL_BUFF*RIGHT/2, p2+SMALL_BUFF*LEFT/2), UP ) for p1, p2 in zip(points, points[1:]) ] for char, brace, color, denom in zip("xyz", braces, self.xyz_colors, self.denoms): brace.label = brace.get_text( "$%s^2$"%char, "$= 1/%d$"%denom, buff = SMALL_BUFF ) brace.label.set_color(color) if brace.label.get_right()[0] > brace.get_right()[0]: brace.label.next_to( brace, UP, buff = SMALL_BUFF, aligned_edge = RIGHT ) self.play(*it.chain( list(map(GrowFromCenter, braces)), [Write(brace.label) for brace in braces] )) self.wait() self.braces = braces def add_boxes_and_labels(self): boxes, labels = self.get_boxes_and_labels() self.play(*list(map(FadeIn, [boxes, labels]))) self.wait() def show_binary_choice_association(self): groups = self.get_groups() self.swapping_anims = [] final_choices = [1, 0, 1] quads = list(zip(self.braces, self.denoms, groups, final_choices)) for brace, denom, group, final_choice in quads: char = brace.label.args[0][1] choices = [ OldTex( char, "=", sign, "\\sqrt{\\frac{1}{%d}}"%denom ) for sign in ("+", "-") ] for choice, color in zip(choices, [GREEN, RED]): # choice[0].set_color(brace.label.get_color()) choice[2].set_color(color) choice.scale(0.8) choice.move_to(group) if choice.get_width() > 0.8*group.get_width(): choice.next_to(group.get_right(), LEFT, buff = MED_SMALL_BUFF) original_choices = [m.copy() for m in choices] self.play( ReplacementTransform( VGroup(brace.label[0], brace, brace.label[1]), choices[0] ), group.move_to, group.target_points[0] ) self.wait() self.play( Transform(*choices), group.move_to, group.target_points[1] ) self.wait() if final_choice == 0: self.play( Transform(choices[0], original_choices[0]), group.move_to, group.target_points[0] ) self.swapping_anims += [ Transform(choices[0], original_choices[1-final_choice]), group.move_to, group.target_points[1-final_choice] ] def ask_about_antipodal_pairs(self): question = OldTexText("What do antipodal points signify?") question.move_to(self.sphere_point_label, LEFT) question.set_color(MAROON_B) antipodal_tex = OldTex( "(x, y, z) \\rightarrow (-x, -y, -z)" ) antipodal_tex.next_to(question, DOWN, aligned_edge = LEFT) self.play(FadeOut(self.sphere_point_label)) self.play(FadeIn(question)) self.wait() self.play(Write(antipodal_tex)) self.wait() self.wiggle_v_lines() self.wait() self.play(*self.swapping_anims) self.wait() class SimpleRotatingSphereWithAntipodes(ExternallyAnimatedScene): pass class TotalLengthOfEachJewelEquals(NecklaceDivisionSphereAssociation, ThreeDScene): CONFIG = { "random_seed" : 1, "thief_box_offset" : 1.2, } def construct(self): random.seed(self.random_seed) self.add_necklace() self.add_boxes_and_labels() self.find_fair_division() self.demonstrate_fair_division() self.perform_antipodal_swap() def find_fair_division(self): segments, tick_marks = self.necklace segments.sort() segment_colors = [ segment.get_color() for segment in segments ] indices = self.get_fair_division_indices(segment_colors) groups = self.get_groups( [0] + list(np.array(indices)+1) + [len(segments)] ) self.add(*groups) binary_choice = [0, 1, 0] v_lines = VGroup(*[DashedLine(UP, DOWN) for x in range(2)]) v_lines.move_to(self.necklace) self.play(ShowCreation(v_lines)) self.play(*[ ApplyMethod(line.move_to, segments[index].get_right()) for line, index in zip(v_lines, indices) ]) self.wait() self.play(*[ ApplyMethod(group.move_to, group.target_points[choice]) for group, choice in zip(groups, binary_choice) ]) self.wait() self.groups = groups self.v_lines = v_lines def get_fair_division_indices(self, colors): colors = np.array(list(colors)) color_types = list(map(Color, set([c.get_hex_l() for c in colors]))) type_to_count = dict([ (color, sum(colors == color)) for color in color_types ]) for i1, i2 in it.combinations(list(range(1, len(colors)-1)), 2): bools = [ sum(colors[i1:i2] == color) == type_to_count[color]/2 for color in color_types ] if np.all(bools): return i1, i2 raise Exception("No fair division found") def demonstrate_fair_division(self): segments, tick_marks = self.necklace color_types = list(map(Color, set([ segment.get_color().get_hex_l() for segment in segments ]))) top_segments = VGroup(*it.chain( self.groups[0][0], self.groups[2][0], )) bottom_segments = self.groups[1][0] for color in color_types: monochrome_groups = [ VGroup(*[segment for segment in segment_group if segment.get_color() == color]) for segment_group in (top_segments, bottom_segments) ] labels = VGroup() for i, group in enumerate(monochrome_groups): group.save_state() group.generate_target() group.target.arrange(buff = SMALL_BUFF) brace = Brace(group.target, UP) label = VGroup( OldTexText("Thief %d"%(i+1)), Jewel(color = group[0].get_color()) ) label.arrange() label.next_to(brace, UP) full_group = VGroup(group.target, brace, label) vect = LEFT if i == 0 else RIGHT full_group.next_to(ORIGIN, vect, buff = MED_LARGE_BUFF) full_group.to_edge(UP) labels.add(VGroup(brace, label)) equals = OldTex("=") equals.next_to(monochrome_groups[0].target, RIGHT) labels[-1].add(equals) for group, label in zip(monochrome_groups, labels): self.play( MoveToTarget(group), FadeIn(label), ) self.wait() self.play( FadeOut(labels), *[group.restore for group in monochrome_groups] ) self.wait() def perform_antipodal_swap(self): binary_choices_list = [(1, 0, 1), (0, 1, 0)] for binary_choices in binary_choices_list: self.play(*[ ApplyMethod( group.move_to, group.target_points[choice] ) for group, choice in zip(self.groups, binary_choices) ]) self.wait() class ExclaimBorsukUlam(TeacherStudentsScene): def construct(self): self.student_says( "Borsuk-Ulam!", target_mode = "hooray" ) self.play(*[ ApplyMethod(pi.change_mode, "hooray") for pi in self.get_pi_creatures() ]) self.wait(3) class ShowFunctionDiagram(TotalLengthOfEachJewelEquals, ReconfigurableScene): CONFIG = { "necklace_center" : ORIGIN, "camera_class" : ThreeDCamera, "thief_box_offset" : 0.3, "make_up_fair_division_indices" : False, } def construct(self): self.add_necklace() self.add_number_pair() self.swap_necklace_allocation() self.add_sphere_arrow() def add_necklace(self): random.seed(self.random_seed) ChoicesInNecklaceCutting.add_necklace(self) self.necklace.set_width(FRAME_X_RADIUS-1) self.necklace.to_edge(UP, buff = LARGE_BUFF) self.necklace.to_edge(LEFT, buff = SMALL_BUFF) self.add(self.necklace) self.find_fair_division() def add_number_pair(self): plane_classes = [ JewelPairPlane( skip_animations = True, thief_number = x ) for x in (1, 2) ] t1_plane, t2_plane = planes = VGroup(*[ VGroup(*plane_class.get_top_level_mobjects()) for plane_class in plane_classes ]) planes.set_width(FRAME_X_RADIUS) planes.to_edge(RIGHT) self.example_coords = plane_classes[0].example_coords[0] arrow = Arrow( self.necklace.get_corner(DOWN+RIGHT), self.example_coords, color = YELLOW ) self.play(ShowCreation(arrow)) self.play(Write(t1_plane), Animation(arrow)) self.wait() clean_state = VGroup(*self.mobjects).family_members_with_points() self.clear() self.add(*clean_state) self.transition_to_alt_config( make_up_fair_division_indices = True ) self.wait() t1_plane.save_state() self.play( Transform(*planes, path_arc = np.pi), Animation(arrow) ) self.wait(2) self.play( ApplyMethod(t1_plane.restore, path_arc = np.pi), Animation(arrow) ) self.wait() def swap_necklace_allocation(self): for choices in [(1, 0, 1), (0, 1, 0)]: self.play(*[ ApplyMethod(group.move_to, group.target_points[i]) for group, i in zip(self.groups, choices) ]) self.wait() def add_sphere_arrow(self): up_down_arrow = OldTex("\\updownarrow") up_down_arrow.scale(1.5) up_down_arrow.set_color(YELLOW) up_down_arrow.next_to(self.necklace, DOWN, buff = LARGE_BUFF) to_plane_arrow = Arrow( up_down_arrow.get_bottom() + DOWN+RIGHT, self.example_coords, color = YELLOW ) self.play(Write(up_down_arrow)) self.wait() self.play(ShowCreation(to_plane_arrow)) self.wait() def get_fair_division_indices(self, *args): if self.make_up_fair_division_indices: return [9, 14] else: return TotalLengthOfEachJewelEquals.get_fair_division_indices(self, *args) class JewelPairPlane(GraphScene): CONFIG = { "camera_class" : ThreeDCamera, "x_labeled_nums" : [], "y_labeled_nums" : [], "thief_number" : 1, "colors" : [BLUE, GREEN], } def construct(self): self.setup_axes() point = self.coords_to_point(4, 5) dot = Dot(point, color = WHITE) coord_pair = OldTex( "\\big(", "\\text{Thief %d }"%self.thief_number, "X", ",", "\\text{Thief %d }"%self.thief_number, "X", "\\big)" ) # coord_pair.scale(1.5) to_replace = [coord_pair[i] for i in [2, 5]] for mob, color in zip(to_replace, self.colors): jewel = Jewel(color = color) jewel.replace(mob) coord_pair.remove(mob) coord_pair.add(jewel) coord_pair.next_to(dot, UP+RIGHT, buff = 0) self.example_coords = VGroup(dot, coord_pair) self.add(self.example_coords) class WhatThisMappingActuallyLooksLikeWords(Scene): def construct(self): words = OldTexText("What this mapping actually looks like") words.set_width(FRAME_WIDTH-1) words.to_edge(DOWN) self.play(Write(words)) self.wait() class WhatAboutGeneralCase(TeacherStudentsScene): def construct(self): self.student_says(""" What about when there's more than 2 jewels? """) self.play_student_changes("confused", None, "sassy") self.wait() self.play(self.get_teacher().change_mode, "thinking") self.wait() self.teacher_says( """Use Borsuk-Ulam for higher-dimensional spheres """, target_mode = "hooray" ) self.play_student_changes(*["confused"]*3) self.wait(2) class Simple3DSpace(ExternallyAnimatedScene): pass class FourDBorsukUlam(GeneralizeBorsukUlam, PiCreatureScene): CONFIG = { "n_dims" : 4, "use_morty" : False, } def setup(self): GeneralizeBorsukUlam.setup(self) PiCreatureScene.setup(self) self.pi_creature.to_corner(DOWN+LEFT, buff = MED_SMALL_BUFF) def construct(self): sphere_set = self.get_sphere_set() arrow = Arrow(LEFT, RIGHT) f = OldTex("f") output_space = self.get_output_space() equation = self.get_equation() sphere_set.to_corner(UP+LEFT) arrow.next_to(sphere_set, RIGHT) f.next_to(arrow, UP) output_space.next_to(arrow, RIGHT) equation.next_to(sphere_set, DOWN, buff = LARGE_BUFF) equation.to_edge(RIGHT) lhs = VGroup(*equation[:2]) eq = equation[2] rhs = VGroup(*equation[3:]) brace = Brace(Line(ORIGIN, 5*RIGHT)) brace.to_edge(RIGHT) brace_text = brace.get_text("Triplets of numbers") brace_text.shift_onto_screen() self.play(FadeIn(sphere_set)) self.change_mode("confused") self.wait() self.play( ShowCreation(arrow), Write(f) ) self.play(Write(output_space)) self.wait() self.change_mode("maybe") self.wait(2) self.change_mode("pondering") self.wait() self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play(*list(map(FadeOut, [brace, brace_text]))) self.wait() self.play( FadeIn(lhs), self.pi_creature.change_mode, "raise_right_hand" ) self.play( ReplacementTransform(lhs.copy(), rhs), Write(eq) ) self.wait(2) def get_sphere_set(self): sphere_set = GeneralizeBorsukUlam.get_sphere_set(self) brace = Brace(sphere_set) text = brace.get_text("Hypersphere in 4D") sphere_set.add(brace, text) return sphere_set class CircleToSphereToQMarks(Scene): def construct(self): pi_groups = VGroup() modes = ["happy", "pondering", "pleading"] shapes = [ Circle(color = BLUE, radius = 0.5), VectorizedPoint(), OldTex("???") ] for d, mode, shape in zip(it.count(2), modes, shapes): randy = Randolph(mode = mode) randy.scale(0.7) bubble = randy.get_bubble( height = 3, width = 4, direction = LEFT ) bubble.pin_to(randy) bubble.position_mobject_inside(shape) title = OldTexText("%dD"%d) title.next_to(randy, UP) arrow = Arrow(LEFT, RIGHT) arrow.next_to(randy.get_corner(UP+RIGHT)) pi_groups.add(VGroup( randy, bubble, shape, title, arrow )) pi_groups[-1].remove(pi_groups[-1][-1]) pi_groups.arrange(buff = -1) for mob in pi_groups: self.play(FadeIn(mob)) self.wait(2) self.play(pi_groups[-1][0].change_mode, "thinking") self.wait(2) class BorsukPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Meshal Alshammari", "CrypticSwarm ", "Ankit Agarwal", "Yu Jun", "Shelby Doolittle", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Justin Helps", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Guido Gambardella", "Jerry Ling", "Mark Govea", "Vecht", "Jonathan Eppele", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } class MortyLookingAtRectangle(Scene): def construct(self): morty = Mortimer() morty.to_corner(DOWN+RIGHT) url = OldTexText("www.thegreatcoursesplus.com/3blue1brown") url.scale(0.75) url.to_corner(UP+LEFT) rect = Rectangle(height = 9, width = 16) rect.set_height(5) rect.next_to(url, DOWN) rect.shift_onto_screen() url.save_state() url.next_to(morty.get_corner(UP+LEFT), UP) url.shift_onto_screen() self.add(morty) self.play( morty.change_mode, "raise_right_hand", morty.look_at, url, ) self.play(Write(url)) self.play(Blink(morty)) self.wait() self.play( url.restore, morty.change_mode, "happy" ) self.play(ShowCreation(rect)) self.wait() self.play(Blink(morty)) for mode in ["pondering", "hooray", "happy", "pondering", "happy"]: self.play(morty.change_mode, mode) self.wait(2) self.play(Blink(morty)) self.wait(2) class RotatingThreeDSphereProjection(Scene): CONFIG = { "camera_class" : ThreeDCamera, } def construct(self): sphere = VGroup(*[ Circle(radius = np.sin(t)).shift(np.cos(t)*OUT) for t in np.linspace(0, np.pi, 20) ]) sphere.set_stroke(BLUE, width = 2) # sphere.set_fill(BLUE, opacity = 0.1) self.play(Rotating( sphere, axis = RIGHT+OUT, run_time = 10 )) self.repeat_frames(4) class FourDSphereProjectTo4D(ExternallyAnimatedScene): pass class Test(Scene): CONFIG = { "camera_class" : ThreeDCamera, } def construct(self): randy = Randolph() necklace = Necklace() necklace.insert_n_curves(20) # necklace.apply_function( # lambda (x, y, z) : x*RIGHT + (y + 0.1*x**2)*UP # ) necklace.set_width(randy.get_width() + 1) necklace.move_to(randy) self.add(randy, necklace)
videos_3b1b/_2017/triples.py
import fractions from manim_imports_ext import * A_COLOR = BLUE B_COLOR = GREEN C_COLOR = YELLOW SIDE_COLORS = [A_COLOR, B_COLOR, C_COLOR] U_COLOR = GREEN V_COLOR = RED #revert_to_original_skipping_status def complex_string_with_i(z): if z.real == 0: return str(int(z.imag)) + "i" elif z.imag == 0: return str(int(z.real)) return complex_string(z).replace("j", "i") class IntroduceTriples(TeacherStudentsScene): def construct(self): title = OldTex("a", "^2", "+", "b", "^2", "=", "c", "^2") for color, char in zip(SIDE_COLORS, "abc"): title.set_color_by_tex(char, color) title.to_corner(UP + RIGHT) triples = [ (3, 4, 5), (5, 12, 13), (8, 15, 17), (7, 24, 25), ] self.add(title) for a, b, c in triples: triangle = Polygon( ORIGIN, a*RIGHT, a*RIGHT+b*UP, stroke_width = 0, fill_color = WHITE, fill_opacity = 0.5 ) hyp_line = Line(ORIGIN, a*RIGHT+b*UP) elbow = VMobject() elbow.set_points_as_corners([LEFT, LEFT+UP, UP]) elbow.set_width(0.2*triangle.get_width()) elbow.move_to(triangle, DOWN+RIGHT) triangle.add(elbow) square = Square(side_length = 1) square_groups = VGroup() for n, color in zip([a, b, c], SIDE_COLORS): square_group = VGroup(*[ square.copy().shift(x*RIGHT + y*UP) for x in range(n) for y in range(n) ]) square_group.set_stroke(color, width = 3) square_group.set_fill(color, opacity = 0.5) square_groups.add(square_group) a_square, b_square, c_square = square_groups a_square.move_to(triangle.get_bottom(), UP) b_square.move_to(triangle.get_right(), LEFT) c_square.move_to(hyp_line.get_center(), DOWN) c_square.rotate( hyp_line.get_angle(), about_point = hyp_line.get_center() ) if c in [5, 13, 25]: if c == 5: keys = list(range(0, 5, 2)) elif c == 13: keys = list(range(0, 13, 3)) elif c == 25: keys = list(range(0, 25, 4)) i_list = [i for i in range(c**2) if (i%c) in keys and (i//c) in keys] else: i_list = list(range(a**2)) not_i_list = list(filter( lambda i : i not in i_list, list(range(c**2)), )) c_square_parts = [ VGroup(*[c_square[i] for i in i_list]), VGroup(*[c_square[i] for i in not_i_list]), ] full_group = VGroup(triangle, square_groups) full_group.set_height(4) full_group.center() full_group.to_edge(UP) equation = OldTex( str(a), "^2", "+", str(b), "^2", "=", str(c), "^2" ) for num, color in zip([a, b, c], SIDE_COLORS): equation.set_color_by_tex(str(num), color) equation.next_to(title, DOWN, MED_LARGE_BUFF) equation.shift_onto_screen() self.play( FadeIn(triangle), self.teacher.change_mode, "raise_right_hand" ) self.play(LaggedStartMap(FadeIn, a_square)) self.play_student_changes( *["pondering"]*3, look_at = triangle, added_anims = [LaggedStartMap(FadeIn, b_square)] ) self.play(self.teacher.change_mode, "happy") for start, target in zip([a_square, b_square], c_square_parts): mover = start.copy().set_fill(opacity = 0) target.set_color(start.get_color()) self.play(ReplacementTransform( mover, target, run_time = 2, path_arc = np.pi/2 )) self.play(Write(equation)) self.play(c_square.set_color, C_COLOR) self.wait() self.play(*list(map(FadeOut, [full_group, equation]))) class CompareToFermatsLastTheorem(TeacherStudentsScene): def construct(self): expressions = [ OldTex( "a", "^%d"%d, "+", "b", "^%d"%d, "=", "c", "^%d"%d ) for d in range(2, 9) ] for expression in expressions: for char, color in zip("abc", SIDE_COLORS): expression.set_color_by_tex(char, color) expression.next_to(self.get_pi_creatures(), UP, buff = 1.3) square_expression = expressions[0] low_expression = expressions[1] square_expression.to_edge(UP, buff = 1.3) top_brace = Brace(square_expression, UP, buff = SMALL_BUFF) top_text = top_brace.get_text( "Abundant integer solutions", buff = SMALL_BUFF ) low_brace = Brace(low_expression, DOWN, buff = SMALL_BUFF) low_text = low_brace.get_text( "No integer solutions", buff = SMALL_BUFF ) low_text.set_color(RED) self.add(square_expression, top_brace, top_text) self.play_student_changes(*["pondering"]*3) self.play(self.teacher.change, "happy", run_time = 0) self.play( ReplacementTransform( square_expression.copy(), low_expression ), self.teacher.change_mode, "raise_right_hand", *[ ApplyMethod(pi.change, "confused", expressions[1]) for pi in self.get_students() ] ) self.wait() self.play(Transform(low_expression, expressions[2])) self.play( GrowFromCenter(low_brace), FadeIn(low_text), ) self.play_student_changes( "sassy", "angry", "erm", look_at = low_expression, added_anims = [Transform(low_expression, expressions[3])] ) for expression in expressions[4:]: self.play(Transform(low_expression, expression)) self.wait() class WritePythagoreanTriple(Scene): def construct(self): words = OldTexText("``Pythagorean triple''") words.set_width(FRAME_WIDTH - LARGE_BUFF) words.to_corner(DOWN+LEFT) self.play(Write(words)) self.wait(2) class ShowManyTriples(Scene): def construct(self): triples = [ (u**2 - v**2, 2*u*v, u**2 + v**2) for u in range(1, 15) for v in range(1, u) if fractions.gcd(u, v) == 1 and not (u%2 == v%2) ][:40] triangles = VGroup() titles = VGroup() for i, (a, b, c) in enumerate(triples): triangle = Polygon(ORIGIN, a*RIGHT, a*RIGHT+b*UP) triangle.set_color(WHITE) max_width = max_height = 4 triangle.set_height(max_height) if triangle.get_width() > max_width: triangle.set_width(max_width) triangle.move_to(2*RIGHT) num_strings = list(map(str, (a, b, c))) labels = list(map(Tex, num_strings)) for label, color in zip(labels, SIDE_COLORS): label.set_color(color) labels[0].next_to(triangle, DOWN) labels[1].next_to(triangle, RIGHT) labels[2].next_to(triangle.get_center(), UP+LEFT) triangle.add(*labels) title = OldTex( str(a), "^2", "+", str(b), "^2", "=", str(c), "^2" ) for num, color in zip([a, b, c], SIDE_COLORS): title.set_color_by_tex(str(num), color) title.next_to(triangle, UP, LARGE_BUFF) title.generate_target() title.target.scale(0.5) title.target.move_to( (-FRAME_X_RADIUS + MED_LARGE_BUFF + 2.7*(i//8))*RIGHT + \ (FRAME_Y_RADIUS - MED_LARGE_BUFF - (i%8))*UP, UP+LEFT ) triangles.add(triangle) titles.add(title) triangle = triangles[0] title = titles[0] self.play( Write(triangle), Write(title), run_time = 2, ) self.wait() self.play(MoveToTarget(title)) for i in range(1, 17): new_triangle = triangles[i] new_title = titles[i] if i < 4: self.play( Transform(triangle, new_triangle), FadeIn(new_title) ) self.wait() self.play(MoveToTarget(new_title)) else: self.play( Transform(triangle, new_triangle), FadeIn(new_title.target) ) self.wait() self.play(FadeOut(triangle)) self.play(LaggedStartMap( FadeIn, VGroup(*[ title.target for title in titles[17:] ]), run_time = 5 )) self.wait(2) class BabylonianTablets(Scene): def construct(self): title = OldTexText("Plimpton 322 Tablets \\\\ (1800 BC)") title.to_corner(UP+LEFT) ac_pairs = [ (119, 169), (3367, 4825), (4601, 6649), (12709, 18541), (65, 97), (319, 481), (2291, 3541), (799, 1249), (481, 769), (4961, 8161), (45, 75), (1679, 2929), (161, 289), (1771, 3229), (56, 106), ] triples = VGroup() for a, c in ac_pairs: b = int(np.sqrt(c**2 - a**2)) tex = "%s^2 + %s^2 = %s^2"%tuple( map("{:,}".format, [a, b, c]) ) tex = tex.replace(",", "{,}") triple = OldTex(tex) triples.add(triple) triples.arrange(DOWN, aligned_edge = LEFT) triples.set_height(FRAME_HEIGHT - LARGE_BUFF) triples.to_edge(RIGHT) self.add(title) self.wait() self.play(LaggedStartMap(FadeIn, triples, run_time = 5)) self.wait() class AskAboutFavoriteProof(TeacherStudentsScene): def construct(self): self.student_says( "What's you're \\\\ favorite proof?", target_mode = "raise_right_hand" ) self.play_student_changes("happy", "raise_right_hand", "happy") self.teacher_thinks("", target_mode = "thinking") self.wait() self.zoom_in_on_thought_bubble() class PythagoreanProof(Scene): def construct(self): self.add_title() self.show_proof() def add_title(self): title = OldTex("a^2", "+", "b^2", "=", "c^2") for color, char in zip(SIDE_COLORS, "abc"): title.set_color_by_tex(char, color) title.to_edge(UP) self.add(title) self.title = title def show_proof(self): triangle = Polygon( ORIGIN, 5*RIGHT, 5*RIGHT+12*UP, stroke_color = WHITE, stroke_width = 2, fill_color = WHITE, fill_opacity = 0.5 ) triangle.set_height(3) triangle.center() side_labels = self.get_triangle_side_labels(triangle) triangle_copy = triangle.copy() squares = self.get_abc_squares(triangle) a_square, b_square, c_square = squares self.add(triangle, triangle_copy) self.play(Write(side_labels)) self.wait() self.play(*list(map(DrawBorderThenFill, squares))) self.add_labels_to_squares(squares, side_labels) self.wait() self.play( VGroup(triangle_copy, a_square, b_square).move_to, 4*LEFT+2*DOWN, DOWN, VGroup(triangle, c_square).move_to, 4*RIGHT+2*DOWN, DOWN, run_time = 2, path_arc = np.pi/2, ) self.wait() self.add_new_triangles( triangle, self.get_added_triangles_to_c_square(triangle, c_square) ) self.wait() self.add_new_triangles( triangle_copy, self.get_added_triangles_to_ab_squares(triangle_copy, a_square) ) self.wait() big_squares = VGroup(*list(map( self.get_big_square, [triangle, triangle_copy] ))) negative_space_words = OldTexText( "Same negative \\\\ space" ) negative_space_words.scale(0.75) negative_space_words.shift(UP) double_arrow = DoubleArrow(LEFT, RIGHT) double_arrow.next_to(negative_space_words, DOWN) self.play( FadeIn(big_squares), Write(negative_space_words), ShowCreation(double_arrow), *list(map(FadeOut, squares)) ) self.wait(2) self.play(*it.chain( list(map(FadeIn, squares)), list(map(Animation, big_squares)), )) self.wait(2) def add_labels_to_squares(self, squares, side_labels): for label, square in zip(side_labels, squares): label.target = OldTex(label.get_tex() + "^2") label.target.set_color(label.get_color()) # label.target.scale(0.7) label.target.move_to(square) square.add(label) self.play(LaggedStartMap(MoveToTarget, side_labels)) def add_new_triangles(self, triangle, added_triangles): brace = Brace(added_triangles, DOWN) label = OldTex("a", "+", "b") label.set_color_by_tex("a", A_COLOR) label.set_color_by_tex("b", B_COLOR) label.next_to(brace, DOWN) self.play(ReplacementTransform( VGroup(triangle.copy().set_fill(opacity = 0)), added_triangles, run_time = 2, )) self.play(GrowFromCenter(brace)) self.play(Write(label)) triangle.added_triangles = added_triangles def get_big_square(self, triangle): square = Square(stroke_color = RED) square.replace( VGroup(triangle, triangle.added_triangles), stretch = True ) square.scale(1.01) return square ##### def get_triangle_side_labels(self, triangle): a, b, c = list(map(Tex, "abc")) for mob, color in zip([a, b, c], SIDE_COLORS): mob.set_color(color) a.next_to(triangle, DOWN) b.next_to(triangle, RIGHT) c.next_to(triangle.get_center(), LEFT) return VGroup(a, b, c) def get_abc_squares(self, triangle): a_square, b_square, c_square = squares = [ Square( stroke_color = color, fill_color = color, fill_opacity = 0.5, ) for color in SIDE_COLORS ] a_square.set_width(triangle.get_width()) a_square.move_to(triangle.get_bottom(), UP) b_square.set_height(triangle.get_height()) b_square.move_to(triangle.get_right(), LEFT) hyp_line = Line( triangle.get_corner(UP+RIGHT), triangle.get_corner(DOWN+LEFT), ) c_square.set_width(hyp_line.get_length()) c_square.move_to(hyp_line.get_center(), UP) c_square.rotate( hyp_line.get_angle(), about_point = hyp_line.get_center() ) return a_square, b_square, c_square def get_added_triangles_to_c_square(self, triangle, c_square): return VGroup(*[ triangle.copy().rotate(i*np.pi/2, about_point = c_square.get_center()) for i in range(1, 4) ]) def get_added_triangles_to_ab_squares(self, triangle, a_square): t1 = triangle.copy() t1.rotate(np.pi) group = VGroup(triangle, t1).copy() group.rotate(-np.pi/2) group.move_to(a_square.get_right(), LEFT) t2, t3 = group return VGroup(t1, t2, t3) class ReframeOnLattice(PiCreatureScene): CONFIG = { "initial_plane_center" : 3*LEFT + DOWN, "new_plane_center" : ORIGIN, "initial_unit_size" : 0.5, "new_unit_size" : 0.8, "dot_radius" : 0.075, "dot_color" : YELLOW, } def construct(self): self.remove(self.pi_creature) self.add_plane() self.wander_over_lattice_points() self.show_whole_distance_examples() self.resize_plane() self.show_root_example() self.view_as_complex_number() self.mention_squaring_it() self.work_out_square_algebraically() self.walk_through_square_geometrically() def add_plane(self): plane = ComplexPlane( center_point = self.initial_plane_center, unit_size = self.initial_unit_size, stroke_width = 2, secondary_line_ratio = 0, ) plane.axes.set_stroke(width = 4) plane.coordinate_labels = VGroup() for x in range(-8, 20, 2): if x == 0: continue label = OldTex(str(x)) label.scale(0.5) label.add_background_rectangle(opacity = 1) label.next_to(plane.coords_to_point(x, 0), DOWN, SMALL_BUFF) plane.coordinate_labels.add(label) self.add(plane, plane.coordinate_labels) self.plane = plane def wander_over_lattice_points(self): initial_examples = [(5, 3), (6, 8), (2, 7)] integer_distance_examples = [(3, 4), (12, 5), (15, 8)] dot_tuple_groups = VGroup() for x, y in initial_examples + integer_distance_examples: dot = Dot( self.plane.coords_to_point(x, y), color = self.dot_color, radius = self.dot_radius, ) tuple_mob = OldTex("(", str(x), ",", str(y), ")") tuple_mob.add_background_rectangle() tuple_mob.next_to(dot, UP+RIGHT, buff = 0) dot_tuple_groups.add(VGroup(dot, tuple_mob)) dot_tuple_group = dot_tuple_groups[0] final_group = dot_tuple_groups[-len(integer_distance_examples)] all_dots = self.get_all_plane_dots() self.play(Write(dot_tuple_group, run_time = 2)) self.wait() for new_group in dot_tuple_groups[1:len(initial_examples)]: self.play(Transform(dot_tuple_group, new_group)) self.wait() self.play(LaggedStartMap( FadeIn, all_dots, rate_func = there_and_back, run_time = 3, lag_ratio = 0.2, )) self.wait() self.play(ReplacementTransform( dot_tuple_group, final_group )) self.integer_distance_dot_tuple_groups = VGroup( *dot_tuple_groups[len(initial_examples):] ) def show_whole_distance_examples(self): dot_tuple_groups = self.integer_distance_dot_tuple_groups for dot_tuple_group in dot_tuple_groups: dot, tuple_mob = dot_tuple_group p0 = self.plane.get_center_point() p1 = dot.get_center() triangle = Polygon( p0, p1[0]*RIGHT + p0[1]*UP, p1, stroke_width = 0, fill_color = BLUE, fill_opacity = 0.75, ) line = Line(p0, p1, color = dot.get_color()) a, b = self.plane.point_to_coords(p1) c = int(np.sqrt(a**2 + b**2)) hyp_label = OldTex(str(c)) hyp_label.add_background_rectangle() hyp_label.next_to( triangle.get_center(), UP+LEFT, buff = SMALL_BUFF ) line.add(hyp_label) dot_tuple_group.triangle = triangle dot_tuple_group.line = line group = dot_tuple_groups[0] self.play(Write(group.line)) self.play(FadeIn(group.triangle), Animation(group.line)) self.wait(2) for new_group in dot_tuple_groups[1:]: self.play( Transform(group, new_group), Transform(group.triangle, new_group.triangle), Transform(group.line, new_group.line), ) self.wait(2) self.play(*list(map(FadeOut, [group, group.triangle, group.line]))) def resize_plane(self): new_plane = ComplexPlane( plane_center = self.new_plane_center, unit_size = self.new_unit_size, y_radius = 8, x_radius = 11, stroke_width = 2, secondary_line_ratio = 0, ) new_plane.axes.set_stroke(width = 4) self.plane.generate_target() self.plane.target.unit_size = self.new_unit_size self.plane.target.plane_center = self.new_plane_center self.plane.target.shift( new_plane.coords_to_point(0, 0) - \ self.plane.target.coords_to_point(0, 0) ) self.plane.target.scale( self.new_unit_size / self.initial_unit_size ) coordinate_labels = self.plane.coordinate_labels for coord in coordinate_labels: x = int(coord.get_tex()) coord.generate_target() coord.target.scale(1.5) coord.target.next_to( new_plane.coords_to_point(x, 0), DOWN, buff = SMALL_BUFF ) self.play( MoveToTarget(self.plane), *list(map(MoveToTarget, self.plane.coordinate_labels)), run_time = 2 ) self.remove(self.plane) self.plane = new_plane self.plane.coordinate_labels = coordinate_labels self.add(self.plane, coordinate_labels) self.wait() def show_root_example(self): x, y = (2, 1) point = self.plane.coords_to_point(x, y) dot = Dot( point, color = self.dot_color, radius = self.dot_radius ) tuple_label = OldTex(str((x, y))) tuple_label.add_background_rectangle() tuple_label.next_to(dot, RIGHT, SMALL_BUFF) line = Line(self.plane.get_center_point(), point) line.set_color(dot.get_color()) distance_labels = VGroup() for tex in "2^2 + 1^2", "5": pre_label = OldTex("\\sqrt{%s}"%tex) rect = BackgroundRectangle(pre_label) label = VGroup( rect, VGroup(*pre_label[:2]), VGroup(*pre_label[2:]), ) label.scale(0.8) label.next_to(line.get_center(), UP, SMALL_BUFF) label.rotate( line.get_angle(), about_point = line.get_center() ) distance_labels.add(label) self.play( ShowCreation(line), DrawBorderThenFill( dot, stroke_width = 3, stroke_color = PINK ) ) self.play(Write(tuple_label)) self.wait() self.play(FadeIn(distance_labels[0])) self.wait(2) self.play(Transform(*distance_labels)) self.wait(2) self.distance_label = distance_labels[0] self.example_dot = dot self.example_line = line self.example_tuple_label = tuple_label def view_as_complex_number(self): imag_coords = VGroup() for y in range(-4, 5, 2): if y == 0: continue label = OldTex("%di"%y) label.add_background_rectangle() label.scale(0.75) label.next_to( self.plane.coords_to_point(0, y), LEFT, SMALL_BUFF ) imag_coords.add(label) tuple_label = self.example_tuple_label new_label = OldTex("2+i") new_label.add_background_rectangle() new_label.next_to( self.example_dot, DOWN+RIGHT, buff = 0, ) self.play(Write(imag_coords)) self.wait() self.play(FadeOut(tuple_label)) self.play(FadeIn(new_label)) self.wait(2) self.example_label = new_label self.plane.coordinate_labels.add(*imag_coords) def mention_squaring_it(self): morty = self.pi_creature arrow = Arrow( self.plane.coords_to_point(2, 1), self.plane.coords_to_point(3, 4), path_arc = np.pi/3, color = MAROON_B ) square_label = OldTex("z \\to z^2") square_label.set_color(arrow.get_color()) square_label.add_background_rectangle() square_label.next_to( arrow.point_from_proportion(0.5), RIGHT, buff = SMALL_BUFF ) self.play(FadeIn(morty)) self.play( PiCreatureSays( morty, "Try squaring \\\\ it!", target_mode = "hooray", bubble_config = {"width" : 4, "height" : 3}, ) ) self.play( ShowCreation(arrow), Write(square_label) ) self.wait() self.play(RemovePiCreatureBubble( morty, target_mode = "pondering", look_at = self.example_label )) def work_out_square_algebraically(self): rect = Rectangle( height = 3.5, width = 6.5, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.8 ) rect.to_corner(UP+LEFT, buff = 0) top_line = OldTex("(2+i)", "(2+i)") top_line.next_to(rect.get_top(), DOWN) second_line = OldTex( "2^2 + 2i + 2i + i^2" ) second_line.next_to(top_line, DOWN, MED_LARGE_BUFF) final_line = OldTex("3 + 4i") final_line.next_to(second_line, DOWN, MED_LARGE_BUFF) result_dot = Dot( self.plane.coords_to_point(3, 4), color = MAROON_B, radius = self.dot_radius ) self.play( FadeIn(rect), ReplacementTransform( VGroup(self.example_label[1].copy()), top_line ), run_time = 2 ) self.wait() #From top line to second line index_alignment_lists = [ [(0, 1, 0), (1, 1, 1)], [(0, 2, 2), (0, 1, 3), (1, 3, 4)], [(0, 2, 5), (1, 1, 6), (0, 3, 7)], [(0, 2, 8), (0, 3, 9), (1, 3, 10)], ] for index_alignment in index_alignment_lists: self.play(*[ ReplacementTransform( top_line[i][j].copy(), second_line[k], ) for i, j, k in index_alignment ]) self.wait(2) #From second line to final line index_alignment_lists = [ [(0, 0), (1, 0), (9, 0), (10, 0)], [(2, 1), (3, 2), (4, 3), (6, 2), (7, 3)], ] for index_alignment in index_alignment_lists: self.play(*[ ReplacementTransform( second_line[i].copy(), final_line[j], run_time = 1.5 ) for i, j in index_alignment ]) self.wait() #Move result to appropriate place result_label = final_line.copy() result_label.add_background_rectangle() self.play( result_label.next_to, result_dot, UP+RIGHT, SMALL_BUFF, Animation(final_line), run_time = 2, ) self.play(DrawBorderThenFill( result_dot, stroke_width = 4, stroke_color = PINK )) self.wait(2) def walk_through_square_geometrically(self): line = self.example_line dot = self.example_dot example_label = self.example_label distance_label = self.distance_label alt_line = line.copy().set_color(RED) arc = Arc( angle = line.get_angle(), radius = 0.7, color = WHITE ) double_arc = Arc( angle = 2*line.get_angle(), radius = 0.8, color = RED, ) theta = OldTex("\\theta") two_theta = OldTex("2\\theta") for tex_mob, arc_mob in (theta, arc), (two_theta, double_arc): tex_mob.scale(0.75) tex_mob.add_background_rectangle() point = arc_mob.point_from_proportion(0.5) tex_mob.move_to(point) tex_mob.shift(tex_mob.get_width()*point/get_norm(point)) self.play(self.pi_creature.change, "happy", arc) self.play(ShowCreation(alt_line)) self.play(ShowCreation(line)) self.remove(alt_line) self.wait() self.play( ShowCreation(arc), Write(theta) ) self.wait() self.play(Indicate(distance_label)) self.wait() #Multiply full plane under everything everything = VGroup(*self.get_top_level_mobjects()) everything.remove(self.plane) self.plane.save_state() ghost_plane = self.plane.copy().fade() method_args_list = [ (self.plane.rotate, (line.get_angle(),)), (self.plane.scale, (np.sqrt(5),)), (self.plane.restore, ()), ] for method, args in method_args_list: self.play( Animation(ghost_plane), ApplyMethod(method, *args), Animation(everything), run_time = 1.5 ) self.wait() #Multiply number by itself ghost_arc = arc.copy().fade() ghost_line = line.copy().fade() ghots_dot = dot.copy().fade() self.add(ghost_arc, ghost_line, ghots_dot) self.play( VGroup( line, dot, distance_label, ).rotate, line.get_angle(), Transform(arc, double_arc), Transform(theta, two_theta), ) self.wait() five = distance_label[2] distance_label.remove(five) for mob in five, line, dot: mob.generate_target() line.target.scale(np.sqrt(5)) five.target.shift(line.target.get_center()-line.get_center()) dot.target.move_to(line.target.get_end()) self.play( FadeOut(distance_label), *list(map(MoveToTarget, [five, line, dot])), run_time = 2 ) self.wait(2) #### def get_all_plane_dots(self): x_min, y_min = list(map(int, self.plane.point_to_coords( FRAME_X_RADIUS*LEFT + FRAME_Y_RADIUS*DOWN ))) x_max, y_max = list(map(int, self.plane.point_to_coords( FRAME_X_RADIUS*RIGHT + FRAME_Y_RADIUS*UP ))) result = VGroup(*[ Dot( self.plane.coords_to_point(x, y), radius = self.dot_radius, color = self.dot_color, ) for x in range(int(x_min), int(x_max)+1) for y in range(int(y_min), int(y_max)+1) ]) result.sort(lambda p : np.dot(p, UP+RIGHT)) return result def create_pi_creature(self): morty = Mortimer().flip() morty.to_corner(DOWN+LEFT, buff = MED_SMALL_BUFF) return morty class TimeToGetComplex(TeacherStudentsScene): def construct(self): self.teacher_says("Time to \\\\ get complex") self.play_student_changes("angry", "sassy", "pleading") self.wait(2) class OneMoreExample(Scene): CONFIG = { "unit_size" : 0.5, "plane_center" : 3*LEFT + 3*DOWN, "dot_color" : YELLOW, "x_label_range" : list(range(-6, 25, 3)), "y_label_range" : list(range(3, 13, 3)), } def construct(self): self.add_plane() self.add_point() self.square_algebraically() self.plot_result() self.show_triangle() def add_plane(self): plane = ComplexPlane( unit_size = self.unit_size, center_point = self.plane_center, stroke_width = 2, ) plane.axes.set_stroke(width = 4) coordinate_labels = VGroup() for x in self.x_label_range: if x == 0: continue coord = OldTex(str(x)) coord.scale(0.75) coord.next_to(plane.coords_to_point(x, 0), DOWN, SMALL_BUFF) coord.add_background_rectangle() coordinate_labels.add(coord) for y in self.y_label_range: if y == 0: continue coord = OldTex("%di"%y) coord.scale(0.75) coord.next_to(plane.coords_to_point(0, y), LEFT, SMALL_BUFF) coord.add_background_rectangle() coordinate_labels.add(coord) self.add(plane, coordinate_labels) self.plane = plane self.plane.coordinate_labels = coordinate_labels def add_point(self): point = self.plane.coords_to_point(3, 2) dot = Dot(point, color = self.dot_color) line = Line(self.plane.get_center_point(), point) line.set_color(dot.get_color()) number_label = OldTex("3+2i") number_label.add_background_rectangle() number_label.next_to(dot, RIGHT, SMALL_BUFF) distance_labels = VGroup() for tex in "3^2 + 2^2", "13": pre_label = OldTex("\\sqrt{%s}"%tex) label = VGroup( BackgroundRectangle(pre_label), VGroup(*pre_label[:2]), VGroup(*pre_label[2:]), ) label.scale(0.75) label.next_to(line.get_center(), UP, SMALL_BUFF) label.rotate( line.get_angle(), about_point = line.get_center() ) distance_labels.add(label) self.play( FadeIn(number_label), ShowCreation(line), DrawBorderThenFill(dot) ) self.play(Write(distance_labels[0])) self.wait() self.play(ReplacementTransform(*distance_labels)) self.wait() self.distance_label = distance_labels[1] self.line = line self.dot = dot self.number_label = number_label def square_algebraically(self): #Crazy hacky. To anyone looking at this, for God's #sake, don't mimic this. rect = Rectangle( height = 3.5, width = 7, stroke_color = WHITE, stroke_width = 2, fill_color = BLACK, fill_opacity = 0.8 ) rect.to_corner(UP+RIGHT, buff = 0) number = self.number_label[1].copy() top_line = OldTex("(3+2i)", "(3+2i)") for part in top_line: for i, color in zip([1, 3], [BLUE, YELLOW]): part[i].set_color(color) second_line = OldTex( "\\big( 3^2 + (2i)^2 \\big) + " + \ "\\big(3 \\cdot 2 + 2 \\cdot 3 \\big)i" ) for i in 1, 12, 18: second_line[i].set_color(BLUE) for i in 5, 14, 16: second_line[i].set_color(YELLOW) second_line.scale(0.9) final_line = OldTex("5 + 12i") for i in 0, 2, 3: final_line[i].set_color(GREEN) lines = VGroup(top_line, second_line, final_line) lines.arrange(DOWN, buff = MED_LARGE_BUFF) lines.next_to(rect.get_top(), DOWN) minus = OldTex("-").scale(0.9) minus.move_to(second_line[3]) self.play( FadeIn(rect), Transform(VGroup(number), top_line), run_time = 2 ) self.wait() index_alignment_lists = [ [(0, 0, 0), (0, 1, 1), (1, 1, 2), (1, 5, 9)], [ (0, 2, 3), (1, 3, 4), (0, 3, 5), (0, 4, 6), (1, 4, 7), (1, 3, 8) ], [ (0, 2, 10), (0, 0, 11), (0, 1, 12), (1, 3, 13), (1, 3, 14), (1, 5, 19), (0, 4, 20), (1, 4, 20), ], [ (0, 2, 15), (0, 3, 16), (1, 1, 17), (1, 1, 18), ], ] for index_alignment in index_alignment_lists[:2]: self.play(*[ ReplacementTransform( top_line[i][j].copy(), second_line[k], run_time = 1.5 ) for i, j, k in index_alignment ]) self.wait() self.play( Transform(second_line[3], minus), FadeOut(VGroup(*[ second_line[i] for i in (4, 6, 7) ])), second_line[5].shift, 0.35*RIGHT, ) self.play(VGroup(*second_line[:4]).shift, 0.55*RIGHT) self.wait() for index_alignment in index_alignment_lists[2:]: self.play(*[ ReplacementTransform( top_line[i][j].copy(), second_line[k], run_time = 1.5 ) for i, j, k in index_alignment ]) self.wait() self.play(FadeIn(final_line)) self.wait() self.final_line = final_line def plot_result(self): result_label = self.final_line.copy() result_label.add_background_rectangle() point = self.plane.coords_to_point(5, 12) dot = Dot(point, color = GREEN) line = Line(self.plane.get_center_point(), point) line.set_color(dot.get_color()) distance_label = OldTex("13") distance_label.add_background_rectangle() distance_label.next_to(line.get_center(), UP+LEFT, SMALL_BUFF) self.play( result_label.next_to, dot, UP+LEFT, SMALL_BUFF, Animation(self.final_line), DrawBorderThenFill(dot) ) self.wait() self.play(*[ ReplacementTransform(m1.copy(), m2) for m1, m2 in [ (self.line, line), (self.distance_label, distance_label) ] ]) self.wait() def show_triangle(self): triangle = Polygon(*[ self.plane.coords_to_point(x, y) for x, y in [(0, 0), (5, 0), (5, 12)] ]) triangle.set_stroke(WHITE, 1) triangle.set_fill(BLUE, opacity = 0.75) self.play( FadeIn(triangle), Animation(VGroup( self.line, self.dot, self.number_label[1], *self.distance_label[1:] )), run_time = 2 ) self.wait(2) class ThisIsMagic(TeacherStudentsScene): def construct(self): self.student_says( "This is magic", target_mode = "hooray" ) self.play(self.teacher.change, "happy") self.wait(2) class GeneralExample(OneMoreExample): CONFIG = { "number" : complex(4, 1), "square_color" : MAROON_B, "result_label_vect" : UP+LEFT, } def construct(self): self.add_plane() self.square_point() def square_point(self): z = self.number z_point = self.plane.number_to_point(z) zero_point = self.plane.number_to_point(0) dot = Dot(z_point, color = self.dot_color) line = Line(zero_point, z_point) line.set_color(dot.get_color()) label = OldTex(complex_string_with_i(z)) label.add_background_rectangle() label.next_to(dot, RIGHT, SMALL_BUFF) square_point = self.plane.number_to_point(z**2) square_dot = Dot(square_point, color = self.square_color) square_line = Line(zero_point, square_point) square_line.set_color(square_dot.get_color()) square_label = OldTex(complex_string_with_i(z**2)) square_label.add_background_rectangle() square_label.next_to(square_dot, UP+RIGHT, SMALL_BUFF) result_length_label = OldTex(str(int(abs(z**2)))) result_length_label.next_to( square_line.get_center(), self.result_label_vect ) result_length_label.add_background_rectangle() arrow = Arrow( z_point, square_point, # buff = SMALL_BUFF, path_arc = np.pi/2 ) arrow.set_color(WHITE) z_to_z_squared = OldTex("z", "\\to", "z^2") z_to_z_squared.set_color_by_tex("z", dot.get_color()) z_to_z_squared.set_color_by_tex("z^2", square_dot.get_color()) z_to_z_squared.next_to( arrow.point_from_proportion(0.5), RIGHT, MED_SMALL_BUFF ) z_to_z_squared.add_to_back( BackgroundRectangle(VGroup( z_to_z_squared[2][0], *z_to_z_squared[:-1] )), BackgroundRectangle(z_to_z_squared[2][1]) ) self.play( Write(label), ShowCreation(line), DrawBorderThenFill(dot) ) self.wait() self.play( ShowCreation(arrow), FadeIn(z_to_z_squared), Animation(label), ) self.play(*[ ReplacementTransform( start.copy(), target, path_arc = np.pi/2, run_time = 1.5 ) for start, target in [ (dot, square_dot), (line, square_line), (label, square_label), ] ]) self.wait() self.play(Write(result_length_label)) self.wait() self.example_dot = dot self.example_label = label self.example_line = line self.square_dot = square_dot self.square_label = square_label self.square_line = square_line self.z_to_z_squared = z_to_z_squared self.z_to_z_squared_arrow = arrow self.result_length_label = result_length_label class BoringExample(GeneralExample): CONFIG = { "number" : complex(2, 2), "result_label_vect" : RIGHT, } def construct(self): self.add_plane() self.square_point() self.show_associated_triplet() def show_associated_triplet(self): arrow = Arrow(LEFT, RIGHT, color = GREEN) arrow.next_to(self.square_label, RIGHT) triple = OldTex("0^2 + 8^2 = 8^2") for part, color in zip(triple[::3], SIDE_COLORS): part.set_color(color) triple.add_background_rectangle() triple.next_to(arrow, RIGHT) morty = Mortimer() morty.next_to(self.plane.coords_to_point(12, 0), UP) self.play( ShowCreation(arrow), FadeIn(morty) ) self.play( Write(triple), morty.change, "raise_right_hand", triple ) self.play(Blink(morty)) self.play(morty.change, "tired") self.wait(2) self.play(Blink(morty)) self.wait() class FiveTwoExample(GeneralExample): CONFIG = { "number" : complex(5, 2), "unit_size" : 0.25, "x_label_range" : list(range(-10, 40, 5)), "y_label_range" : list(range(0, 30, 5)), } class WriteGeneralFormula(GeneralExample): CONFIG = { "plane_center" : 2*RIGHT, "x_label_range" : [], "y_label_range" : [], "unit_size" : 0.7, "number" : complex(2, 1), } def construct(self): self.add_plane() self.show_squaring() self.expand_square() self.draw_triangle() self.show_uv_to_triples() def show_squaring(self): self.force_skipping() self.square_point() dot = self.example_dot old_label = self.example_label line = self.example_line square_dot = self.square_dot old_square_label = self.square_label square_line = self.square_line z_to_z_squared = self.z_to_z_squared arrow = self.z_to_z_squared_arrow result_length_label = self.result_length_label self.clear() self.add(self.plane, self.plane.coordinate_labels) self.revert_to_original_skipping_status() label = OldTex("u+vi") label.move_to(old_label, LEFT) label.add_background_rectangle() square_label = OldTex("(u+vi)^2") square_label.move_to(old_square_label, LEFT) square_label.add_background_rectangle() self.add(label, dot, line) self.play( ShowCreation(arrow), FadeIn(z_to_z_squared) ) self.play(*[ ReplacementTransform( start.copy(), target, run_time = 1.5, path_arc = np.pi/2 ) for start, target in [ (dot, square_dot), (line, square_line), (label, square_label), ] ]) self.example_label = label self.square_label = square_label def expand_square(self): rect = Rectangle( height = 2.5, width = 7, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.8, ) rect.to_corner(UP+LEFT, buff = 0) top_line = OldTex("(u+vi)(u+vi)") for i in 1, 7: top_line[i].set_color(U_COLOR) top_line[i+2].set_color(V_COLOR) top_line.next_to(rect.get_top(), DOWN) second_line = OldTex( "\\big(", "u^2 - v^2", "\\big)", "+", "\\big(", "2uv", "\\big)", "i" ) for i, j in (1, 0), (5, 1): second_line[i][j].set_color(U_COLOR) for i, j in (1, 3), (5, 2): second_line[i][j].set_color(V_COLOR) second_line.next_to(top_line, DOWN, MED_LARGE_BUFF) real_part = second_line[1] imag_part = second_line[5] for part in real_part, imag_part: part.add_to_back(BackgroundRectangle(part)) z = self.number**2 square_point = self.plane.number_to_point(z) zero_point = self.plane.number_to_point(0) real_part_point = self.plane.number_to_point(z.real) real_part_line = Line(zero_point, real_part_point) imag_part_line = Line(real_part_point, square_point) for line in real_part_line, imag_part_line: line.set_color(self.square_color) self.play(*list(map(FadeIn, [rect, top_line, second_line]))) self.wait() self.play( real_part.copy().next_to, real_part_line.copy(), DOWN, SMALL_BUFF, ShowCreation(real_part_line) ) self.wait() self.play( FadeOut(VGroup( self.example_label, self.example_dot, self.example_line, self.z_to_z_squared, self.z_to_z_squared_arrow )), imag_part.copy().next_to, imag_part_line.copy(), RIGHT, SMALL_BUFF, ShowCreation(imag_part_line) ) self.wait() self.corner_rect = rect def draw_triangle(self): hyp_length = OldTex("u", "^2", "+", "v", "^2") hyp_length.set_color_by_tex("u", U_COLOR) hyp_length.set_color_by_tex("v", V_COLOR) hyp_length.add_background_rectangle() line = self.square_line hyp_length.next_to(line.get_center(), UP, SMALL_BUFF) hyp_length.rotate( line.get_angle(), about_point = line.get_center() ) triangle = Polygon( ORIGIN, RIGHT, RIGHT+UP, stroke_width = 0, fill_color = MAROON_B, fill_opacity = 0.5, ) triangle.replace(line, stretch = True) self.play(Write(hyp_length)) self.wait() self.play(FadeIn(triangle)) self.wait() def show_uv_to_triples(self): rect = self.corner_rect.copy() rect.stretch_to_fit_height(FRAME_HEIGHT) rect.move_to(self.corner_rect.get_bottom(), UP) h_line = Line(rect.get_left(), rect.get_right()) h_line.next_to(rect.get_top(), DOWN, LARGE_BUFF) v_line = Line(rect.get_top(), rect.get_bottom()) v_line.shift(1.3*LEFT) uv_title = OldTex("(u, v)") triple_title = OldTex("(u^2 - v^2, 2uv, u^2 + v^2)") uv_title.scale(0.75) triple_title.scale(0.75) uv_title.next_to( h_line.point_from_proportion(1./6), UP, SMALL_BUFF ) triple_title.next_to( h_line.point_from_proportion(2./3), UP, SMALL_BUFF ) pairs = [(2, 1), (3, 2), (4, 1), (4, 3), (5, 2), (5, 4)] pair_mobs = VGroup() triple_mobs = VGroup() for u, v in pairs: a, b, c = u**2 - v**2, 2*u*v, u**2 + v**2 pair_mob = OldTex("(", str(u), ",", str(v), ")") pair_mob.set_color_by_tex(str(u), U_COLOR) pair_mob.set_color_by_tex(str(v), V_COLOR) triple_mob = OldTex("(%d, %d, %d)"%(a, b, c)) pair_mobs.add(pair_mob) triple_mobs.add(triple_mob) pair_mob.scale(0.75) triple_mob.scale(0.75) pair_mobs.arrange(DOWN) pair_mobs.next_to(uv_title, DOWN, MED_LARGE_BUFF) triple_mobs.arrange(DOWN) triple_mobs.next_to(triple_title, DOWN, MED_LARGE_BUFF) self.play(*list(map(FadeIn, [ rect, h_line, v_line, uv_title, triple_title ]))) self.play(*[ LaggedStartMap( FadeIn, mob, run_time = 5, lag_ratio = 0.2 ) for mob in (pair_mobs, triple_mobs) ]) class VisualizeZSquared(Scene): CONFIG = { "initial_unit_size" : 0.4, "final_unit_size" : 0.1, "plane_center" : 3*LEFT + 2*DOWN, "x_label_range" : list(range(-12, 24, 4)), "y_label_range" : list(range(-4, 24, 4)), "dot_color" : YELLOW, "square_color" : MAROON_B, "big_dot_radius" : 0.075, "dot_radius" : 0.05, } def construct(self): self.force_skipping() self.add_plane() self.write_z_to_z_squared() self.draw_arrows() self.draw_dots() self.add_colored_grid() self.apply_transformation() self.show_triangles() self.zoom_out() self.show_more_triangles() def add_plane(self): width = (FRAME_X_RADIUS+abs(self.plane_center[0]))/self.final_unit_size height = (FRAME_Y_RADIUS+abs(self.plane_center[1]))/self.final_unit_size background_plane = ComplexPlane( x_radius = width, y_radius = height, stroke_width = 2, stroke_color = BLUE_E, secondary_line_ratio = 0, ) background_plane.axes.set_stroke(width = 4) background_plane.scale(self.initial_unit_size) background_plane.shift(self.plane_center) coordinate_labels = VGroup() z_list = np.append( self.x_label_range, complex(0, 1)*np.array(self.y_label_range) ) for z in z_list: if z == 0: continue if z.imag == 0: tex = str(int(z.real)) else: tex = str(int(z.imag)) + "i" label = OldTex(tex) label.scale(0.75) label.add_background_rectangle() point = background_plane.number_to_point(z) if z.imag == 0: label.next_to(point, DOWN, SMALL_BUFF) else: label.next_to(point, LEFT, SMALL_BUFF) coordinate_labels.add(label) self.add(background_plane, coordinate_labels) self.background_plane = background_plane self.coordinate_labels = coordinate_labels def write_z_to_z_squared(self): z_to_z_squared = OldTex("z", "\\to", "z^2") z_to_z_squared.set_color_by_tex("z", YELLOW) z_to_z_squared.set_color_by_tex("z^2", MAROON_B) z_to_z_squared.add_background_rectangle() z_to_z_squared.to_edge(UP) z_to_z_squared.shift(2*RIGHT) self.play(Write(z_to_z_squared)) self.wait() self.z_to_z_squared = z_to_z_squared def draw_arrows(self): z_list = [ complex(2, 1), complex(3, 2), complex(0, 1), complex(-1, 0), ] arrows = VGroup() dots = VGroup() for z in z_list: z_point, square_point, mid_point = [ self.background_plane.number_to_point(z**p) for p in (1, 2, 1.5) ] angle = Line(mid_point, square_point).get_angle() angle -= Line(z_point, mid_point).get_angle() angle *= 2 arrow = Arrow( z_point, square_point, path_arc = angle, color = WHITE, tip_length = 0.15, buff = SMALL_BUFF, ) z_dot, square_dot = [ Dot( point, color = color, radius = self.big_dot_radius, ) for point, color in [ (z_point, self.dot_color), (square_point, self.square_color), ] ] z_label = OldTex(complex_string_with_i(z)) square_label = OldTex(complex_string_with_i(z**2)) for label, point in (z_label, z_point), (square_label, square_point): if abs(z) > 2: vect = RIGHT else: vect = point - self.plane_center vect /= get_norm(vect) if abs(vect[1]) < 0.1: vect[1] = -1 label.next_to(point, vect) label.add_background_rectangle() self.play(*list(map(FadeIn, [z_label, z_dot]))) self.wait() self.play(ShowCreation(arrow)) self.play(ReplacementTransform( z_dot.copy(), square_dot, path_arc = angle )) self.play(FadeIn(square_label)) self.wait() self.play( FadeOut(z_label), FadeOut(square_label), Animation(arrow) ) arrows.add(arrow) dots.add(z_dot, square_dot) self.wait() self.play(*list(map(FadeOut, [ dots, arrows, self.z_to_z_squared ]))) def draw_dots(self): min_corner, max_corner = [ self.background_plane.point_to_coords( u*FRAME_X_RADIUS*RIGHT + u*FRAME_Y_RADIUS*UP ) for u in (-1, 1) ] x_min, y_min = list(map(int, min_corner[:2])) x_max, y_max = list(map(int, max_corner[:2])) dots = VGroup(*[ Dot( self.background_plane.coords_to_point(x, y), color = self.dot_color, radius = self.dot_radius, ) for x in range(x_min, x_max+1) for y in range(y_min, y_max+1) ]) dots.sort(lambda p : np.dot(p, UP+RIGHT)) self.add_foreground_mobject(self.coordinate_labels) self.play(LaggedStartMap( DrawBorderThenFill, dots, stroke_width = 3, stroke_color = PINK, run_time = 3, lag_ratio = 0.2 )) self.wait() self.dots = dots def add_colored_grid(self): color_grid = self.get_color_grid() self.play( self.background_planes.set_stroke, None, 1, LaggedStartMap( FadeIn, color_grid, run_time = 2 ), Animation(self.dots), ) self.wait() self.color_grid = color_grid def apply_transformation(self): for dot in self.dots: dot.start_point = dot.get_center() def update_dot(dot, alpha): event = list(dot.start_point) + [alpha] dot.move_to(self.homotopy(*event)) return dot self.play( Homotopy(self.homotopy, self.color_grid), *[ UpdateFromAlphaFunc(dot, update_dot) for dot in self.dots ], run_time = 3 ) self.wait(2) self.play(self.color_grid.set_stroke, None, 3) self.wait() scale_factor = self.big_dot_radius/self.dot_radius self.play(LaggedStartMap( ApplyMethod, self.dots, lambda d : (d.scale, scale_factor), rate_func = there_and_back, run_time = 3 )) self.wait() def show_triangles(self): z_list = [ complex(u, v)**2 for u, v in [(2, 1), (3, 2), (4, 1)] ] triangles = self.get_triangles(z_list) triangle = triangles[0] triangle.save_state() triangle.scale(0.01, about_point = triangle.tip) self.play(triangle.restore, run_time = 2) self.wait(2) for new_triangle in triangles[1:]: self.play(Transform(triangle, new_triangle)) self.wait(2) self.play(FadeOut(triangle)) def zoom_out(self): self.remove_foreground_mobject(self.coordinate_labels) movers = [ self.background_plane, self.color_grid, self.dots, self.coordinate_labels, ] scale_factor = self.final_unit_size/self.initial_unit_size for mover in movers: mover.generate_target() mover.target.scale( scale_factor, about_point = self.plane_center ) for dot in self.dots.target: dot.scale(1./scale_factor) self.background_plane.target.fade() self.revert_to_original_skipping_status() self.play( *list(map(MoveToTarget, movers)), run_time = 3 ) self.wait(2) def show_more_triangles(self): z_list = [ complex(u, v)**2 for u in range(4, 7) for v in range(1, u) ] triangles = self.get_triangles(z_list) triangle = triangles[0] self.play(FadeOut(triangle)) self.wait(2) for new_triangle in triangles[1:]: self.play(Transform(triangle, new_triangle)) self.wait(2) ### def get_color_grid(self): width = (FRAME_X_RADIUS+abs(self.plane_center[0]))/self.initial_unit_size height = (FRAME_Y_RADIUS+abs(self.plane_center[1]))/self.initial_unit_size color_grid = ComplexPlane( x_radius = width, y_radius = int(height), secondary_line_ratio = 0, stroke_width = 2, ) color_grids.set_color_by_gradient( *[GREEN, RED, MAROON_B, TEAL]*2 ) color_grid.remove(color_grid.axes[0]) for line in color_grid.family_members_with_points(): center = line.get_center() if center[0] <= 0 and abs(center[1]) < 0.01: line_copy = line.copy() line.scale(0.499, about_point = line.get_start()) line_copy.scale(0.499, about_point = line_copy.get_end()) color_grid.add(line_copy) color_grid.scale(self.initial_unit_size) color_grid.shift(self.plane_center) color_grid.prepare_for_nonlinear_transform() return color_grid def get_triangles(self, z_list): triangles = VGroup() for z in z_list: point = self.background_plane.number_to_point(z) line = Line(self.plane_center, point) triangle = Polygon( ORIGIN, RIGHT, RIGHT+UP, stroke_color = BLUE, stroke_width = 2, fill_color = BLUE, fill_opacity = 0.5, ) triangle.replace(line, stretch = True) a = int(z.real) b = int(z.imag) c = int(abs(z)) a_label, b_label, c_label = labels = [ OldTex(str(num)) for num in (a, b, c) ] for label in b_label, c_label: label.add_background_rectangle() a_label.next_to(triangle.get_bottom(), UP, SMALL_BUFF) b_label.next_to(triangle, RIGHT, SMALL_BUFF) c_label.next_to(line.get_center(), UP+LEFT, SMALL_BUFF) triangle.add(*labels) triangle.tip = point triangles.add(triangle) return triangles def homotopy(self, x, y, z, t): z_complex = self.background_plane.point_to_number(np.array([x, y, z])) result = z_complex**(1+t) return self.background_plane.number_to_point(result) class AskAboutHittingAllPoints(TeacherStudentsScene): def construct(self): self.student_says( "Does this hit \\\\ all pythagorean triples?", target_mode = "raise_left_hand" ) self.wait() self.teacher_says("No", target_mode = "sad") self.play_student_changes(*["hesitant"]*3) self.wait() class PointsWeMiss(VisualizeZSquared): CONFIG = { "final_unit_size" : 0.4, "plane_center" : 2*LEFT + 2*DOWN, "dot_x_range" : list(range(-5, 6)), "dot_y_range" : list(range(-4, 4)), } def construct(self): self.add_plane() self.add_transformed_color_grid() self.add_dots() self.show_missing_point() self.show_second_missing_point() self.mention_one_half_rule() def add_transformed_color_grid(self): color_grid = self.get_color_grid() func = lambda p : self.homotopy(p[0], p[1], p[1], 1) color_grid.apply_function(func) color_grid.set_stroke(width = 4) self.add(color_grid, self.coordinate_labels) self.color_grid = color_grid def add_dots(self): z_list = [ complex(x, y)**2 for x in self.dot_x_range for y in self.dot_y_range ] dots = VGroup(*[ Dot( self.background_plane.number_to_point(z), color = self.dot_color, radius = self.big_dot_radius, ) for z in z_list ]) dots.sort(get_norm) self.add(dots) self.dots = dots def show_missing_point(self): z_list = [complex(6, 8), complex(9, 12), complex(3, 4)] points = list(map( self.background_plane.number_to_point, z_list )) dots = VGroup(*list(map(Dot, points))) for dot in dots[:2]: dot.set_stroke(RED, 4) dot.set_fill(opacity = 0) labels = VGroup(*[ OldTex(complex_string_with_i(z)) for z in z_list ]) labels.set_color(RED) labels[2].set_color(GREEN) rhss = VGroup() for label, dot in zip(labels, dots): label.add_background_rectangle() label.next_to(dot, UP+RIGHT, SMALL_BUFF) if label is labels[-1]: rhs = OldTex("= (2+i)^2") else: rhs = OldTex("\\ne (u+vi)^2") rhs.add_background_rectangle() rhs.next_to(label, RIGHT) rhss.add(rhs) triangles = self.get_triangles(z_list) self.play(FocusOn(dots[0])) self.play(ShowCreation(dots[0])) self.play(Write(labels[0])) self.wait() self.play(FadeIn(triangles[0])) self.wait(2) self.play(Write(rhss[0])) self.wait(2) groups = triangles, dots, labels, rhss for i in 1, 2: self.play(*[ Transform(group[0], group[i]) for group in groups ]) self.wait(3) self.play(*[ FadeOut(group[0]) for group in groups ]) def show_second_missing_point(self): z_list = [complex(4, 3), complex(8, 6)] points = list(map( self.background_plane.number_to_point, z_list )) dots = VGroup(*list(map(Dot, points))) dots[0].set_stroke(RED, 4) dots[0].set_fill(opacity = 0) labels = VGroup(*[ OldTex(complex_string_with_i(z)) for z in z_list ]) labels[0].set_color(RED) labels[1].set_color(GREEN) rhss = VGroup() for label, dot in zip(labels, dots): label.add_background_rectangle() label.next_to(dot, UP+RIGHT, SMALL_BUFF) if label is labels[-1]: rhs = OldTex("= (3+i)^2") else: rhs = OldTex("\\ne (u+vi)^2") rhs.add_background_rectangle() rhs.next_to(label, RIGHT) rhss.add(rhs) triangles = self.get_triangles(z_list) groups = [dots, labels, rhss, triangles] for group in groups: group[0].save_state() self.play(ShowCreation(dots[0])) self.play(Write(VGroup(labels[0], rhss[0]))) self.play(FadeIn(triangles[0])) self.wait(3) self.play(*[Transform(*group) for group in groups]) self.wait(3) self.play(*[group[0].restore for group in groups]) self.wait(2) def mention_one_half_rule(self): morty = Mortimer() morty.flip() morty.to_corner(DOWN+LEFT) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, "Never need to scale \\\\ by less than $\\frac{1}{2}$" )) self.play(Blink(morty)) self.wait(2) class PointsWeMissAreMultiplesOfOnesWeHit(TeacherStudentsScene): def construct(self): words = OldTexText( "Every point we", "miss", "is \\\\ a multiple of one we", "hit" ) words.set_color_by_tex("miss", RED) words.set_color_by_tex("hit", GREEN) self.teacher_says(words) self.play_student_changes(*["pondering"]*3) self.wait(2) class DrawSingleRadialLine(PointsWeMiss): def construct(self): self.add_plane() self.background_plane.set_stroke(width = 1) self.add_transformed_color_grid() self.color_grid.set_stroke(width = 1) self.add_dots() self.draw_line() def draw_line(self): point = self.background_plane.coords_to_point(3, 4) dot = Dot(point, color = RED) line = Line( self.plane_center, self.background_plane.coords_to_point(15, 20), color = WHITE, ) added_dots = VGroup(*[ Dot(self.background_plane.coords_to_point(3*k, 4*k)) for k in (2, 3, 5) ]) added_dots.set_color(GREEN) self.play(GrowFromCenter(dot)) self.play(Indicate(dot)) self.play(ShowCreation(line), Animation(dot)) self.wait() self.play(LaggedStartMap( DrawBorderThenFill, added_dots, stroke_color = PINK, stroke_width = 4, run_time = 3 )) self.wait() class DrawRadialLines(PointsWeMiss): CONFIG = { "final_unit_size" : 0.2, "dot_x_range" : list(range(-4, 10)), "dot_y_range" : list(range(-4, 10)), "x_label_range" : list(range(-12, 40, 4)), "y_label_range" : list(range(-4, 32, 4)), "big_dot_radius" : 0.05, } def construct(self): self.add_plane() self.add_transformed_color_grid() self.resize_plane() self.add_dots() self.create_lines() self.show_single_line() self.show_all_lines() self.show_triangles() def resize_plane(self): everything = VGroup(*self.get_top_level_mobjects()) everything.scale( self.final_unit_size/self.initial_unit_size, about_point = self.plane_center ) self.background_plane.set_stroke(width = 1) def create_lines(self): coord_strings = set([]) reduced_coords_yet_to_be_reached = set([]) for dot in self.dots: point = dot.get_center() float_coords = self.background_plane.point_to_coords(point) coords = np.round(float_coords).astype('int') gcd = fractions.gcd(*coords) reduced_coords = coords/abs(gcd) if np.all(coords == [3, 4]): first_dot = dot dot.coords = coords dot.reduced_coords = reduced_coords coord_strings.add(str(coords)) reduced_coords_yet_to_be_reached.add(str(reduced_coords)) lines = VGroup() for dot in [first_dot] + list(self.dots): rc_str = str(dot.reduced_coords) if rc_str not in reduced_coords_yet_to_be_reached: continue reduced_coords_yet_to_be_reached.remove(rc_str) new_dots = VGroup() for k in range(50): new_coords = k*dot.reduced_coords if str(new_coords) in coord_strings: continue coord_strings.add(str(new_coords)) point = self.background_plane.coords_to_point(*new_coords) if abs(point[0]) > FRAME_X_RADIUS or abs(point[1]) > FRAME_Y_RADIUS: continue new_dot = Dot( point, color = GREEN, radius = self.big_dot_radius ) new_dots.add(new_dot) line = Line(self.plane_center, dot.get_center()) line.scale( FRAME_WIDTH/line.get_length(), about_point = self.plane_center ) line.set_stroke(width = 1) line.seed_dot = dot.copy() line.new_dots = new_dots lines.add(line) self.lines = lines def show_single_line(self): line = self.lines[0] dot = line.seed_dot self.play( dot.scale, 2, dot.set_color, RED ) self.play(ReplacementTransform(dot, line)) self.wait() self.play(LaggedStartMap( DrawBorderThenFill, line.new_dots, stroke_width = 4, stroke_color = PINK, run_time = 3, )) self.wait() def show_all_lines(self): seed_dots = VGroup(*[line.seed_dot for line in self.lines]) new_dots = VGroup(*[line.new_dots for line in self.lines]) for dot in seed_dots: dot.generate_target() dot.target.scale(1.5) dot.target.set_color(RED) self.play(LaggedStartMap( MoveToTarget, seed_dots, run_time = 2 )) self.play(ReplacementTransform( seed_dots, self.lines, run_time = 3, lag_ratio = 0.5 )) self.play(LaggedStartMap( DrawBorderThenFill, new_dots, stroke_width = 4, stroke_color = PINK, run_time = 3, )) self.wait() self.new_dots = new_dots def show_triangles(self): z_list = [ complex(9, 12), complex(7, 24), complex(8, 15), complex(21, 20), complex(36, 15), ] triangles = self.get_triangles(z_list) triangle = triangles[0] self.play(FadeIn(triangle)) self.wait(2) for new_triangle in triangles[1:]: self.play(Transform(triangle, new_triangle)) self.wait(2) class RationalPointsOnUnitCircle(DrawRadialLines): CONFIG = { "initial_unit_size" : 1.2, "final_unit_size" : 0.4, "plane_center" : 1.5*DOWN } def construct(self): self.add_plane() self.show_rational_points_on_unit_circle() self.divide_by_c_squared() self.from_rational_point_to_triple() def add_plane(self): added_x_coords = list(range(-4, 6, 2)) added_y_coords = list(range(-2, 4, 2)) self.x_label_range += added_x_coords self.y_label_range += added_y_coords DrawRadialLines.add_plane(self) def show_rational_points_on_unit_circle(self): circle = self.get_unit_circle() coord_list = [ (12, 5), (8, 15), (7, 24), (3, 4), ] groups = VGroup() for x, y in coord_list: norm = np.sqrt(x**2 + y**2) point = self.background_plane.coords_to_point( x/norm, y/norm ) dot = Dot(point, color = YELLOW) line = Line(self.plane_center, point) line.set_color(dot.get_color()) label = OldTex( "{"+str(x), "\\over", str(int(norm))+"}", "+", "{"+str(y), "\\over", str(int(norm))+"}", "i" ) label.next_to(dot, UP+RIGHT, buff = 0) label.add_background_rectangle() group = VGroup(line, dot, label) group.coords = (x, y) groups.add(group) group = groups[0].copy() self.add(circle, self.coordinate_labels) self.play(FadeIn(group)) self.wait() for new_group in groups[1:]: self.play(Transform(group, new_group)) self.wait() self.curr_example_point_group = group self.next_rational_point_example = groups[0] self.unit_circle = circle def divide_by_c_squared(self): top_line = OldTex( "a", "^2", "+", "b", "^2", "=", "c", "^2 \\phantom{1}" ) top_line.shift(FRAME_X_RADIUS*RIGHT/2) top_line.to_corner(UP + LEFT) top_line.shift(RIGHT) top_rect = BackgroundRectangle(top_line) second_line = OldTex( "\\left(", "{a", "\\over", "c}", "\\right)", "^2", "+", "\\left(", "{b", "\\over", "c}", "\\right)", "^2", "=", "1" ) second_line.move_to(top_line, UP) second_line.shift_onto_screen() second_rect = BackgroundRectangle(second_line) circle_label = OldTexText( "All $x+yi$ where \\\\", "$x^2 + y^2 = 1$" ) circle_label.next_to(second_line, DOWN, MED_LARGE_BUFF) circle_label.shift_onto_screen() circle_label.set_color_by_tex("x^2", GREEN) circle_label.add_background_rectangle() circle_arrow = Arrow( circle_label.get_bottom(), self.unit_circle.point_from_proportion(0.45), color = GREEN ) self.play(FadeIn(top_rect), FadeIn(top_line)) self.wait() self.play(*[ ReplacementTransform(top_rect, second_rect) ] + [ ReplacementTransform( top_line.get_parts_by_tex(tex, substring = False), second_line.get_parts_by_tex(tex), run_time = 2, path_arc = -np.pi/3 ) for tex in ("a", "b", "c", "^2", "+", "=") ] + [ ReplacementTransform( top_line.get_parts_by_tex("1"), second_line.get_parts_by_tex("1"), run_time = 2 ) ] + [ Write( second_line.get_parts_by_tex(tex), run_time = 2, rate_func = squish_rate_func(smooth, 0, 0.5) ) for tex in ("(", ")", "over",) ]) self.wait(2) self.play(Write(circle_label)) self.play(ShowCreation(circle_arrow)) self.wait(2) self.play(FadeOut(circle_arrow)) self.algebra = VGroup( second_rect, second_line, circle_label, ) def from_rational_point_to_triple(self): rational_point_group = self.next_rational_point_example scale_factor = self.final_unit_size/self.initial_unit_size self.play(ReplacementTransform( self.curr_example_point_group, rational_point_group )) self.wait(2) self.play(*[ ApplyMethod( mob.scale_about_point, scale_factor, self.plane_center ) for mob in [ self.background_plane, self.coordinate_labels, self.unit_circle, rational_point_group, ] ] + [ Animation(self.algebra), ]) #mimic_group point = self.background_plane.coords_to_point( *rational_point_group.coords ) dot = Dot(point, color = YELLOW) line = Line(self.plane_center, point) line.set_color(dot.get_color()) x, y = rational_point_group.coords label = OldTex(str(x), "+", str(y), "i") label.next_to(dot, UP+RIGHT, buff = 0) label.add_background_rectangle() integer_point_group = VGroup(line, dot, label) distance_label = OldTex( str(int(np.sqrt(x**2 + y**2))) ) distance_label.add_background_rectangle() distance_label.next_to(line.get_center(), UP+LEFT, SMALL_BUFF) self.play(ReplacementTransform( rational_point_group, integer_point_group )) self.play(Write(distance_label)) self.wait(2) ### def get_unit_circle(self): template_line = Line(*[ self.background_plane.number_to_point(z) for z in (-1, 1) ]) circle = Circle(color = GREEN) circle.replace(template_line, dim_to_match = 0) return circle class ProjectPointsOntoUnitCircle(DrawRadialLines): def construct(self): ### self.force_skipping() self.add_plane() self.add_transformed_color_grid() self.resize_plane() self.add_dots() self.create_lines() self.show_all_lines() self.revert_to_original_skipping_status() ### self.add_unit_circle() self.project_all_dots() self.zoom_in() self.draw_infinitely_many_lines() def add_unit_circle(self): template_line = Line(*[ self.background_plane.number_to_point(n) for n in (-1, 1) ]) circle = Circle(color = BLUE) circle.replace(template_line, dim_to_match = 0) self.play(ShowCreation(circle)) self.unit_circle = circle def project_all_dots(self): dots = self.dots dots.add(*self.new_dots) dots.sort( lambda p : get_norm(p - self.plane_center) ) unit_length = self.unit_circle.get_width()/2.0 for dot in dots: dot.generate_target() point = dot.get_center() vect = point-self.plane_center if np.round(vect[0], 3) == 0 and abs(vect[1]) > 2*unit_length: dot.target.set_fill(opacity = 0) continue distance = get_norm(vect) dot.target.scale( unit_length/distance, about_point = self.plane_center ) dot.target.set_width(0.01) self.play(LaggedStartMap( MoveToTarget, dots, run_time = 3, lag_ratio = 0.2 )) def zoom_in(self): target_height = 5.0 scale_factor = target_height / self.unit_circle.get_height() group = VGroup( self.background_plane, self.coordinate_labels, self.color_grid, self.lines, self.unit_circle, self.dots, ) self.play( group.shift, -self.plane_center, group.scale, scale_factor, run_time = 2 ) self.wait(2) def draw_infinitely_many_lines(self): lines = VGroup(*[ Line(ORIGIN, FRAME_WIDTH*vect) for vect in compass_directions(1000) ]) self.play(LaggedStartMap( ShowCreation, lines, run_time = 3 )) self.play(FadeOut(lines)) self.wait() class ICanOnlyDrawFinitely(TeacherStudentsScene): def construct(self): self.teacher_says( "I can only \\\\ draw finitely", run_time = 2 ) self.wait(2) class SupposeMissingPoint(PointsWeMiss): def construct(self): self.add_plane() self.background_plane.set_stroke(width = 1) self.draw_missing_triple() self.project_onto_unit_circle() def draw_missing_triple(self): point = self.background_plane.coords_to_point(12, 5) origin = self.plane_center line = Line(origin, point, color = WHITE) dot = Dot(point, color = YELLOW) triangle = Polygon(ORIGIN, RIGHT, RIGHT+UP) triangle.set_stroke(BLUE, 2) triangle.set_fill(BLUE, 0.5) triangle.replace(line, stretch = True) a = OldTex("a") a.next_to(triangle.get_bottom(), UP, SMALL_BUFF) b = OldTex("b") b.add_background_rectangle() b.next_to(triangle, RIGHT, SMALL_BUFF) c = OldTex("c") c.add_background_rectangle() c.next_to(line.get_center(), UP+LEFT, SMALL_BUFF) triangle.add(a, b, c) words = OldTexText( "If we missed \\\\ a triple \\dots" ) words.add_background_rectangle() words.next_to(dot, UP+RIGHT) words.shift_onto_screen() self.add(triangle, line, dot) self.play(Write(words)) self.wait() self.words = words self.triangle = triangle self.line = line self.dot = dot def project_onto_unit_circle(self): dot, line = self.dot, self.line template_line = Line(*[ self.background_plane.number_to_point(n) for n in (-1, 1) ]) circle = Circle(color = GREEN) circle.replace(template_line, dim_to_match = 0) z = self.background_plane.point_to_number(dot.get_center()) z_norm = abs(z) unit_z = z/z_norm new_point = self.background_plane.number_to_point(unit_z) dot.generate_target() dot.target.move_to(new_point) line.generate_target() line.target.scale(1./z_norm, about_point = self.plane_center) rational_point_word = OldTex("(a/c) + (b/c)i") rational_point_word.next_to( self.background_plane.coords_to_point(0, 6), RIGHT ) rational_point_word.add_background_rectangle() arrow = Arrow( rational_point_word.get_bottom(), dot.target, buff = SMALL_BUFF ) self.play(ShowCreation(circle)) self.add(dot.copy().fade()) self.add(line.copy().set_stroke(GREY, 1)) self.play(*list(map(MoveToTarget, [dot, line]))) self.wait() self.play( Write(rational_point_word), ShowCreation(arrow) ) self.wait(2) class ProofTime(TeacherStudentsScene): def construct(self): self.teacher_says("Proof time!", target_mode = "hooray") self.play_student_changes(*["hooray"]*3) self.wait(2) class FinalProof(RationalPointsOnUnitCircle): def construct(self): self.add_plane() self.draw_rational_point() self.draw_line_from_example_point() self.show_slope_is_rational() self.show_all_rational_slopes() self.square_example_point() self.project_onto_circle() self.show_same_slope() self.write_v_over_u_slope() def draw_rational_point(self): circle = self.get_unit_circle() coords = (3./5., 4./5.) point = self.background_plane.coords_to_point(*coords) dot = Dot(point, color = YELLOW) label = OldTex( "(a/c) + (b/c)i" ) label.add_background_rectangle() label.next_to(dot, UP+RIGHT, buff = 0) self.add(circle) self.play( Write(label, run_time = 2), DrawBorderThenFill(dot) ) self.wait() self.example_dot = dot self.example_label = label self.unit_circle = circle def draw_line_from_example_point(self): neg_one_point = self.background_plane.number_to_point(-1) neg_one_dot = Dot(neg_one_point, color = RED) line = Line( neg_one_point, self.example_dot.get_center(), color = RED ) self.play( ShowCreation(line, run_time = 2), Animation(self.example_label) ) self.play(DrawBorderThenFill(neg_one_dot)) self.wait() self.neg_one_dot = neg_one_dot self.secant_line = line def show_slope_is_rational(self): p0 = self.neg_one_dot.get_center() p1 = self.example_dot.get_center() p_mid = p1[0]*RIGHT + p0[1]*UP h_line = Line(p0, p_mid, color = MAROON_B) v_line = Line(p_mid, p1, color = MAROON_B) run_brace = Brace(h_line, DOWN) run_text = run_brace.get_text( "Run = $1 + \\frac{a}{c}$" ) run_text.add_background_rectangle() rise_brace = Brace(v_line, RIGHT) rise_text = rise_brace.get_text("Rise = $\\frac{b}{c}$") rise_text.add_background_rectangle() self.play(*list(map(ShowCreation, [h_line, v_line]))) self.wait() self.play( GrowFromCenter(rise_brace), FadeIn(rise_text) ) self.wait() self.play( GrowFromCenter(run_brace), FadeIn(run_text) ) self.wait(3) self.play(*list(map(FadeOut, [ self.example_dot, self.example_label, self.secant_line, h_line, v_line, run_brace, rise_brace, run_text, rise_text, ]))) def show_all_rational_slopes(self): lines = VGroup() labels = VGroup() for u in range(2, 7): for v in range(1, u): if fractions.gcd(u, v) != 1: continue z_squared = complex(u, v)**2 unit_z_squared = z_squared/abs(z_squared) point = self.background_plane.number_to_point(unit_z_squared) dot = Dot(point, color = YELLOW) line = Line( self.background_plane.number_to_point(-1), point, color = self.neg_one_dot.get_color() ) line.add(dot) label = OldTex( "\\text{Slope = }", str(v), "/", str(u) ) label.add_background_rectangle() label.next_to( self.background_plane.coords_to_point(1, 1.5), RIGHT ) lines.add(line) labels.add(label) line = lines[0] label = labels[0] self.play( ShowCreation(line), FadeIn(label) ) self.wait() for new_line, new_label in zip(lines, labels)[1:]: self.play( Transform(line, new_line), Transform(label, new_label), ) self.wait() self.play(*list(map(FadeOut, [line, label]))) def square_example_point(self): z = complex(2, 1) point = self.background_plane.number_to_point(z) uv_dot = Dot(point, color = YELLOW) uv_label = OldTex("u", "+", "v", "i") uv_label.add_background_rectangle() uv_label.next_to(uv_dot, DOWN+RIGHT, buff = 0) uv_line = Line( self.plane_center, point, color = YELLOW ) uv_arc = Arc( angle = uv_line.get_angle(), radius = 0.75 ) uv_arc.shift(self.plane_center) theta = OldTex("\\theta") theta.next_to(uv_arc, RIGHT, SMALL_BUFF, DOWN) theta.scale(0.8) square_point = self.background_plane.number_to_point(z**2) square_dot = Dot(square_point, color = MAROON_B) square_label = OldTex("(u+vi)^2") square_label.add_background_rectangle() square_label.next_to(square_dot, RIGHT) square_line = Line( self.plane_center, square_point, color = MAROON_B ) square_arc = Arc( angle = square_line.get_angle(), radius = 0.65 ) square_arc.shift(self.plane_center) two_theta = OldTex("2\\theta") two_theta.next_to( self.background_plane.coords_to_point(0, 1), UP+RIGHT, SMALL_BUFF, ) two_theta_arrow = Arrow( two_theta.get_right(), square_arc.point_from_proportion(0.75), tip_length = 0.15, path_arc = -np.pi/2, color = WHITE, buff = SMALL_BUFF ) self.two_theta_group = VGroup(two_theta, two_theta_arrow) z_to_z_squared_arrow = Arrow( point, square_point, path_arc = np.pi/3, color = WHITE ) z_to_z_squared = OldTex("z", "\\to", "z^2") z_to_z_squared.set_color_by_tex("z", YELLOW) z_to_z_squared.set_color_by_tex("z^2", MAROON_B) z_to_z_squared.add_background_rectangle() z_to_z_squared.next_to( z_to_z_squared_arrow.point_from_proportion(0.5), RIGHT, SMALL_BUFF ) self.play( Write(uv_label), DrawBorderThenFill(uv_dot) ) self.play(ShowCreation(uv_line)) self.play(ShowCreation(uv_arc)) self.play(Write(theta)) self.wait() self.play( ShowCreation(z_to_z_squared_arrow), FadeIn(z_to_z_squared) ) self.play(*[ ReplacementTransform( m1.copy(), m2, path_arc = np.pi/3 ) for m1, m2 in [ (uv_dot, square_dot), (uv_line, square_line), (uv_label, square_label), (uv_arc, square_arc), ] ]) self.wait() self.play( Write(two_theta), ShowCreation(two_theta_arrow) ) self.wait(2) self.play(FadeOut(self.two_theta_group)) self.theta_group = VGroup(uv_arc, theta) self.uv_line = uv_line self.uv_dot = uv_dot self.uv_label = uv_label self.square_line = square_line self.square_dot = square_dot def project_onto_circle(self): line = self.square_line.copy() dot = self.square_dot.copy() self.square_line.fade() self.square_dot.fade() radius = self.unit_circle.get_width()/2 line.generate_target() line.target.scale( radius / line.get_length(), about_point = line.get_start() ) dot.generate_target() dot.target.move_to(line.target.get_end()) self.play( MoveToTarget(line), MoveToTarget(dot), ) self.wait() self.play(FadeIn(self.two_theta_group)) self.wait() self.play(FadeOut(self.two_theta_group)) self.wait(6) ##circle geometry self.rational_point_dot = dot def show_same_slope(self): line = Line( self.neg_one_dot.get_center(), self.rational_point_dot.get_center(), color = self.neg_one_dot.get_color() ) theta_group_copy = self.theta_group.copy() same_slope_words = OldTexText("Same slope") same_slope_words.add_background_rectangle() same_slope_words.shift(4*LEFT + 0.33*UP) line_copies = VGroup( line.copy(), self.uv_line.copy() ) line_copies.generate_target() line_copies.target.next_to(same_slope_words, DOWN) self.play(ShowCreation(line)) self.wait() self.play( theta_group_copy.shift, line.get_start() - self.uv_line.get_start() ) self.wait() self.play( Write(same_slope_words), MoveToTarget(line_copies) ) self.wait() self.same_slope_words = same_slope_words def write_v_over_u_slope(self): p0 = self.plane_center p1 = self.uv_dot.get_center() p_mid = p1[0]*RIGHT + p0[1]*UP h_line = Line(p0, p_mid, color = YELLOW) v_line = Line(p_mid, p1, color = YELLOW) rhs = OldTex("=", "{v", "\\over", "u}") rhs.next_to(self.same_slope_words, RIGHT) rect = SurroundingRectangle(VGroup(*rhs[1:])) morty = Mortimer().flip() morty.scale(0.5) morty.next_to(self.same_slope_words, UP, buff = 0) self.play(ShowCreation(h_line)) self.play(ShowCreation(v_line)) self.wait() self.play(*[ ReplacementTransform( self.uv_label.get_part_by_tex(tex).copy(), rhs.get_part_by_tex(tex), run_time = 2 ) for tex in ("u", "v") ] + [ Write(rhs.get_part_by_tex(tex)) for tex in ("=", "over") ]) self.wait(2) self.play( ShowCreation(rect), FadeIn(morty) ) self.play(PiCreatureSays( morty, "Free to choose!", bubble_config = {"height" : 1.5, "width" : 3}, target_mode = "hooray", look_at = rect )) self.play(Blink(morty)) self.wait(2) class BitOfCircleGeometry(Scene): def construct(self): circle = Circle(color = BLUE, radius = 3) p0, p1, p2 = [ circle.point_from_proportion(alpha) for alpha in (0, 0.15, 0.55) ] O = circle.get_center() O_dot = Dot(O, color = WHITE) self.add(circle, O_dot) groups = VGroup() for point, tex, color in (O, "2", MAROON_B), (p2, "", RED): line1 = Line(point, p0) line2 = Line(point, p1) dot1 = Dot(p0) dot2 = Dot(p1) angle = line1.get_angle() arc = Arc( angle = line2.get_angle()-line1.get_angle(), start_angle = line1.get_angle(), radius = 0.75, color = WHITE ) arc.set_stroke(YELLOW, 3) arc.shift(point) label = OldTex(tex + "\\theta") label.next_to( arc.point_from_proportion(0.9), RIGHT ) group = VGroup(line1, line2, dot1, dot2) group.set_color(color) group.add(arc, label) if len(groups) == 0: self.play(*list(map(ShowCreation, [dot1, dot2]))) self.play(*list(map(ShowCreation, [line1, line2]))) self.play(ShowCreation(arc)) self.play(FadeIn(label)) groups.add(group) self.wait(2) self.play(ReplacementTransform( groups[0].copy(), groups[1] )) self.wait(2) class PatreonThanksTriples(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Burt Humburg", "CrypticSwarm", "David Beyer", "Erik Sundell", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Yoni Nazarathy", "Joseph John Cox", "Dan Buchoff", "Luc Ritchie", "Ankalagon", "Eric Lavault", "Tomohiro Furusawa", "Boris Veselinovich", "Julian Pulgarin", "John Haley", "Jeff Linse", "Suraj Pratap", "Cooper Jones", "Ryan Dahl", "Ahmad Bamieh", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], } class Thumbnail(DrawRadialLines): def construct(self): self.force_skipping() self.add_plane() self.add_transformed_color_grid() self.color_grid.set_stroke(width = 5) self.resize_plane() self.add_dots() self.create_lines() self.show_single_line() self.show_all_lines() rect = Rectangle( height = 4.3, width = 4.2, stroke_width = 3, stroke_color = WHITE, fill_color = BLACK, fill_opacity = 1, ) rect.to_corner(UP+RIGHT, buff = 0.01) triples = VGroup(*list(map(Tex, [ "3^2 + 4^2 = 5^2", "5^2 + 12^2 = 13^2", "8^2 + 15^2 = 17^2", "\\vdots" ]))) triples.arrange(DOWN, buff = MED_LARGE_BUFF) triples.next_to(rect.get_top(), DOWN) self.add(rect, triples) class Poster(DrawRadialLines): CONFIG = { "final_unit_size" : 0.1, "plane_center" : ORIGIN, } def construct(self): self.force_skipping() self.add_plane() self.add_transformed_color_grid() self.color_grid.set_stroke(width = 5) self.resize_plane() self.add_dots() self.create_lines() self.show_single_line() self.show_all_lines() for dot_group in self.dots, self.new_dots: for dot in dot_group.family_members_with_points(): dot.scale(0.5) self.remove(self.coordinate_labels) # rect = Rectangle( # height = 4.3, width = 4.2, # stroke_width = 3, # stroke_color = WHITE, # fill_color = BLACK, # fill_opacity = 1, # ) # rect.to_corner(UP+RIGHT, buff = 0.01) # triples = VGroup(*map(Tex, [ # "3^2 + 4^2 = 5^2", # "5^2 + 12^2 = 13^2", # "8^2 + 15^2 = 17^2", # "\\vdots" # ])) # triples.arrange(DOWN, buff = MED_LARGE_BUFF) # triples.next_to(rect.get_top(), DOWN) # self.add(rect, triples)
videos_3b1b/_2017/gradient.py
from manim_imports_ext import * # Warning, this file uses ContinualChangingDecimal, # which has since been been deprecated. Use a mobject # updater instead class GradientDescentWrapper(Scene): def construct(self): title = OldTexText("Gradient descent") title.to_edge(UP) rect = ScreenRectangle(height=6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class ShowSimpleMultivariableFunction(Scene): def construct(self): scale_val = 1.5 func_tex = OldTex( "C(", "x_1,", "x_2,", "\\dots,", "x_n", ")", "=", ) func_tex.scale(scale_val) func_tex.shift(2 * LEFT) alt_func_tex = OldTex( "C(", "x,", "y", ")", "=" ) alt_func_tex.scale(scale_val) for tex in func_tex, alt_func_tex: tex.set_color_by_tex_to_color_map({ "C(": RED, ")": RED, }) alt_func_tex.move_to(func_tex, RIGHT) inputs = func_tex[1:-2] self.add(func_tex) many_inputs = OldTex(*[ "x_{%d}, " % d for d in range(1, 25) ]) many_inputs.set_width(FRAME_WIDTH) many_inputs.to_edge(UL) inputs_brace = Brace(inputs, UP) inputs_brace_text = inputs_brace.get_text("Multiple inputs") decimal = DecimalNumber(0) decimal.scale(scale_val) decimal.next_to(tex, RIGHT) value_tracker = ValueTracker(0) always_shift(value_tracker, rate=0.5) self.add(value_tracker) decimal_change = ContinualChangingDecimal( decimal, lambda a: 1 + np.sin(value_tracker.get_value()) ) self.add(decimal_change) output_brace = Brace(decimal, DOWN) output_brace_text = output_brace.get_text("Single output") self.wait(2) self.play(GrowFromCenter(inputs_brace)) self.play(Write(inputs_brace_text)) self.play(GrowFromCenter(output_brace)) self.play(Write(output_brace_text)) self.wait(3) self.play( ReplacementTransform( inputs, many_inputs[:len(inputs)] ), LaggedStartMap( FadeIn, many_inputs[len(inputs):] ), FadeOut(inputs_brace), FadeOut(inputs_brace_text), ) self.wait() self.play( ReplacementTransform( func_tex[0], alt_func_tex[0] ), Write(alt_func_tex[1:3]), LaggedStartMap(FadeOutAndShiftDown, many_inputs) ) self.wait(3) class ShowGraphWithVectors(ExternallyAnimatedScene): pass class ShowFunction(Scene): def construct(self): func = OldTex( "f(x, y) = e^{-x^2 + \\cos(2y)}", tex_to_color_map={ "x": BLUE, "y": RED, } ) func.scale(1.5) self.play(FadeInFromDown(func)) self.wait() class ShowExampleFunctionGraph(ExternallyAnimatedScene): pass class ShowGradient(Scene): def construct(self): lhs = OldTex( "\\nabla f(x, y)=", tex_to_color_map={"x": BLUE, "y": RED} ) vector = Matrix([ ["\\partial f / \\partial x"], ["\\partial f / \\partial y"], ], v_buff=1) gradient = VGroup(lhs, vector) gradient.arrange(RIGHT, buff=SMALL_BUFF) gradient.scale(1.5) del_x, del_y = partials = vector.get_entries() background_rects = VGroup() for partial, color in zip(partials, [BLUE, RED]): partial[-1].set_color(color) partial.rect = SurroundingRectangle( partial, buff=MED_SMALL_BUFF ) partial.rect.set_stroke(width=0) partial.rect.set_fill(color=color, opacity=0.5) background_rects.add(partial.rect.copy()) background_rects.set_fill(opacity=0.1) partials.set_fill(opacity=0) self.play( LaggedStartMap(FadeIn, gradient), LaggedStartMap( FadeIn, background_rects, rate_func=squish_rate_func(smooth, 0.5, 1) ) ) self.wait() for partial in partials: self.play(DrawBorderThenFill(partial.rect)) self.wait() self.play(FadeOut(partial.rect)) self.wait() for partial in partials: self.play(Write(partial)) self.wait() class ExampleGraphHoldXConstant(ExternallyAnimatedScene): pass class ExampleGraphHoldYConstant(ExternallyAnimatedScene): pass class TakePartialDerivatives(Scene): def construct(self): tex_to_color_map = { "x": BLUE, "y": RED, } func_tex = OldTex( "f", "(", "x", ",", "y", ")", "=", "e^{", "-x^2", "+ \\cos(2y)}", tex_to_color_map=tex_to_color_map ) partial_x = OldTex( "{\\partial", "f", "\\over", "\\partial", "x}", "=", "\\left(", "e^", "{-x^2", "+ \\cos(2y)}", "\\right)", "(", "-2", "x", ")", tex_to_color_map=tex_to_color_map, ) partial_y = OldTex( "{\\partial", "f", "\\over", "\\partial", "y}", "=", "\\left(", "e^", "{-x^2", "+ \\cos(", "2", "y)}", "\\right)", "(", "-\\sin(", "2", "y)", "\\cdot 2", ")", tex_to_color_map=tex_to_color_map, ) partials = VGroup(partial_x, partial_y) for mob in func_tex, partials: mob.scale(1.5) func_tex.move_to(2 * UP + 3 * LEFT) for partial in partials: partial.next_to(func_tex, DOWN, buff=LARGE_BUFF) top_eq_x = func_tex.get_part_by_tex("=").get_center()[0] low_eq_x = partial.get_part_by_tex("=").get_center()[0] partial.shift((top_eq_x - low_eq_x) * RIGHT) index = func_tex.index_of_part_by_tex("e^") exp_rect = SurroundingRectangle(func_tex[index + 1:], buff=0) exp_rect.set_stroke(width=0) exp_rect.set_fill(GREEN, opacity=0.5) xs = func_tex.get_parts_by_tex("x", substring=False) ys = func_tex.get_parts_by_tex("y", substring=False) for terms in xs, ys: terms.rects = VGroup(*[ SurroundingRectangle(term, buff=0.5 * SMALL_BUFF) for term in terms ]) terms.arrows = VGroup(*[ Vector(0.5 * DOWN).next_to(rect, UP, SMALL_BUFF) for rect in terms.rects ]) treat_as_constant = OldTexText("Treat as a constant") treat_as_constant.next_to(ys.arrows[1], UP) # Start to show partial_x self.play(FadeInFromDown(func_tex)) self.wait() self.play( ReplacementTransform(func_tex[0].copy(), partial_x[1]), Write(partial_x[0]), Write(partial_x[2:4]), Write(partial_x[6]), ) self.play( ReplacementTransform(func_tex[2].copy(), partial_x[4]) ) self.wait() # Label y as constant self.play(LaggedStartMap(ShowCreation, ys.rects)) self.play( LaggedStartMap(GrowArrow, ys.arrows, lag_ratio=0.8), Write(treat_as_constant) ) self.wait(2) # Perform partial_x derivative self.play(FadeIn(exp_rect), Animation(func_tex)) self.wait() pxi1 = 8 pxi2 = 15 self.play( ReplacementTransform( func_tex[7:].copy(), partial_x[pxi1:pxi2], ), FadeIn(partial_x[pxi1 - 1:pxi1]), FadeIn(partial_x[pxi2]), ) self.wait(2) self.play( ReplacementTransform( partial_x[10:12].copy(), partial_x[pxi2 + 2:pxi2 + 4], path_arc=-(TAU / 4) ), FadeIn(partial_x[pxi2 + 1]), FadeIn(partial_x[-1]), ) self.wait(2) # Swap out partial_x for partial_y self.play( FadeOutAndShiftDown(partial_x), FadeOut(ys.rects), FadeOut(ys.arrows), FadeOut(treat_as_constant), FadeOut(exp_rect), Animation(func_tex) ) self.play(FadeInFromDown(partial_y[:7])) self.wait() treat_as_constant.next_to(xs.arrows[1], UP, SMALL_BUFF) self.play( LaggedStartMap(ShowCreation, xs.rects), LaggedStartMap(GrowArrow, xs.arrows), Write(treat_as_constant), lag_ratio=0.8 ) self.wait() # Show same outer derivative self.play( ReplacementTransform( func_tex[7:].copy(), partial_x[pxi1:pxi2], ), FadeIn(partial_x[pxi1 - 2:pxi1]), FadeIn(partial_x[pxi2]), ) self.wait() self.play( ReplacementTransform( partial_y[12:16].copy(), partial_y[pxi2 + 3:pxi2 + 7], path_arc=-(TAU / 4) ), FadeIn(partial_y[pxi2 + 2]), FadeIn(partial_y[-1]), ) self.wait() self.play(ReplacementTransform( partial_y[-5].copy(), partial_y[-2], path_arc=-PI )) self.wait() class ShowDerivativeAtExamplePoint(Scene): def construct(self): tex_to_color_map = { "x": BLUE, "y": RED, } func_tex = OldTex( "f", "(", "x", ",", "y", ")", "=", "e^{", "-x^2", "+ \\cos(2y)}", tex_to_color_map=tex_to_color_map ) gradient_tex = OldTex( "\\nabla", "f", "(", "x", ",", "y", ")", "=", tex_to_color_map=tex_to_color_map ) partial_vect = Matrix([ ["{\\partial f / \\partial x}"], ["{\\partial f / \\partial y}"], ]) partial_vect.get_mob_matrix()[0, 0][-1].set_color(BLUE) partial_vect.get_mob_matrix()[1, 0][-1].set_color(RED) result_vector = self.get_result_vector("x", "y") gradient = VGroup( gradient_tex, partial_vect, OldTex("="), result_vector ) gradient.arrange(RIGHT, buff=SMALL_BUFF) func_tex.to_edge(UP) gradient.next_to(func_tex, DOWN, buff=LARGE_BUFF) example_lhs = OldTex( "\\nabla", "f", "(", "1", ",", "3", ")", "=", tex_to_color_map={"1": BLUE, "3": RED}, ) example_result_vector = self.get_result_vector("1", "3") example_rhs = DecimalMatrix([[-1.92], [0.54]]) example = VGroup( example_lhs, example_result_vector, OldTex("="), example_rhs, ) example.arrange(RIGHT, buff=SMALL_BUFF) example.next_to(gradient, DOWN, LARGE_BUFF) self.add(func_tex, gradient) self.wait() self.play( ReplacementTransform(gradient_tex.copy(), example_lhs), ReplacementTransform(result_vector.copy(), example_result_vector), ) self.wait() self.play(Write(example[2:])) self.wait() def get_result_vector(self, x, y): result_vector = Matrix([ ["e^{-%s^2 + \\cos(2\\cdot %s)} (-2\\cdot %s)" % (x, y, x)], ["e^{-%s^2 + \\cos(2\\cdot %s)} \\big(-\\sin(2\\cdot %s) \\cdot 2\\big)" % (x, y, y)], ], v_buff=1.2, element_alignment_corner=ORIGIN) x_terms = VGroup( result_vector.get_mob_matrix()[0, 0][2], result_vector.get_mob_matrix()[1, 0][2], result_vector.get_mob_matrix()[0, 0][-2], ) y_terms = VGroup( result_vector.get_mob_matrix()[0, 0][11], result_vector.get_mob_matrix()[1, 0][11], result_vector.get_mob_matrix()[1, 0][-5], ) x_terms.set_color(BLUE) y_terms.set_color(RED) return result_vector
videos_3b1b/_2017/highD.py
from manim_imports_ext import * ########## #force_skipping #revert_to_original_skipping_status ########## class Slider(NumberLine): CONFIG = { "color" : WHITE, "x_min" : -1, "x_max" : 1, "unit_size" : 2, "center_value" : 0, "number_scale_val" : 0.75, "label_scale_val" : 1, "numbers_with_elongated_ticks" : [], "line_to_number_vect" : LEFT, "line_to_number_buff" : MED_LARGE_BUFF, "dial_radius" : 0.1, "dial_color" : YELLOW, "include_real_estate_ticks" : True, } def __init__(self, **kwargs): NumberLine.__init__(self, **kwargs) self.rotate(np.pi/2) self.init_dial() if self.include_real_estate_ticks: self.add_real_estate_ticks() def init_dial(self): dial = Dot( radius = self.dial_radius, color = self.dial_color, ) dial.move_to(self.number_to_point(self.center_value)) re_dial = dial.copy() re_dial.set_fill(opacity = 0) self.add(dial, re_dial) self.dial = dial self.re_dial = re_dial self.last_sign = -1 def add_label(self, tex): label = OldTex(tex) label.scale(self.label_scale_val) label.move_to(self.get_top()) label.shift(MED_LARGE_BUFF*UP) self.add(label) self.label = label def add_real_estate_ticks( self, re_per_tick = 0.05, colors = [BLUE, RED], max_real_estate = 1, ): self.real_estate_ticks = VGroup(*[ self.get_tick(self.center_value + u*np.sqrt(x + re_per_tick)) for x in np.arange(0, max_real_estate, re_per_tick) for u in [-1, 1] ]) self.real_estate_ticks.set_stroke(width = 3) self.real_estate_ticks.set_color_by_gradient(*colors) self.add(self.real_estate_ticks) self.add(self.dial) return self.real_estate_ticks def set_value(self, x): re = (x - self.center_value)**2 for dial, val in (self.dial, x), (self.re_dial, re): dial.move_to(self.number_to_point(val)) return self def set_center_value(self, x): self.center_value = x return self def change_real_estate(self, d_re): left_over = 0 curr_re = self.get_real_estate() if d_re < -curr_re: left_over = d_re + curr_re d_re = -curr_re self.set_real_estate(curr_re + d_re) return left_over def set_real_estate(self, target_re): if target_re < 0: raise Exception("Cannot set real estate below 0") self.re_dial.move_to(self.number_to_point(target_re)) self.update_dial_by_re_dial() return self def get_dial_supplement_animation(self): return UpdateFromFunc(self.dial, self.update_dial_by_re_dial) def update_dial_by_re_dial(self, dial = None): dial = dial or self.dial re = self.get_real_estate() sign = np.sign(self.get_value() - self.center_value) if sign == 0: sign = -self.last_sign self.last_sign *= -1 dial.move_to(self.number_to_point( self.center_value + sign*np.sqrt(abs(re)) )) return dial def get_value(self): return self.point_to_number(self.dial.get_center()) def get_real_estate(self): return self.point_to_number(self.re_dial.get_center()) def copy(self): return self.deepcopy() class SliderScene(Scene): CONFIG = { "n_sliders" : 4, "slider_spacing" : MED_LARGE_BUFF, "slider_config" : {}, "center_point" : None, "total_real_estate" : 1, "ambiently_change_sliders" : False, "ambient_velocity_magnitude" : 1.0, "ambient_acceleration_magnitude" : 1.0, "ambient_jerk_magnitude" : 1.0/2, } def setup(self): if self.center_point is None: self.center_point = np.zeros(self.n_sliders) sliders = VGroup(*[ Slider(center_value = cv, **self.slider_config) for cv in self.center_point ]) sliders.arrange(RIGHT, buff = self.slider_spacing) sliders[0].add_numbers() sliders[0].set_value( self.center_point[0] + np.sqrt(self.total_real_estate) ) self.sliders = sliders self.add_labels_to_sliders() self.add(sliders) def add_labels_to_sliders(self): if len(self.sliders) <= 4: for slider, char in zip(self.sliders, "xyzw"): slider.add_label(char) for slider in self.sliders[1:]: slider.label.align_to(self.sliders[0].label, UP) else: for i, slider in enumerate(self.sliders): slider.add_label("x_{%d}"%(i+1)) return self def reset_dials(self, values, run_time = 1, **kwargs): target_vector = self.get_target_vect_from_subset_of_values(values, **kwargs) radius = np.sqrt(self.total_real_estate) def update_sliders(sliders): curr_vect = self.get_vector() curr_vect -= self.center_point curr_vect *= radius/get_norm(curr_vect) curr_vect += self.center_point self.set_to_vector(curr_vect) return sliders self.play(*[ ApplyMethod(slider.set_value, value) for value, slider in zip(target_vector, self.sliders) ] + [ UpdateFromFunc(self.sliders, update_sliders) ], run_time = run_time) def get_target_vect_from_subset_of_values(self, values, fixed_indices = None): if fixed_indices is None: fixed_indices = [] curr_vector = self.get_vector() target_vector = np.array(self.center_point, dtype = 'float') unspecified_vector = np.array(self.center_point, dtype = 'float') unspecified_indices = [] for i in range(len(curr_vector)): if i < len(values) and values[i] is not None: target_vector[i] = values[i] else: unspecified_indices.append(i) unspecified_vector[i] = curr_vector[i] used_re = get_norm(target_vector - self.center_point)**2 left_over_re = self.total_real_estate - used_re if left_over_re < -0.001: raise Exception("Overspecified reset") uv_norm = get_norm(unspecified_vector - self.center_point) if uv_norm == 0 and left_over_re > 0: unspecified_vector[unspecified_indices] = 1 uv_norm = get_norm(unspecified_vector - self.center_point) if uv_norm > 0: unspecified_vector -= self.center_point unspecified_vector *= np.sqrt(left_over_re)/uv_norm unspecified_vector += self.center_point return target_vector + unspecified_vector - self.center_point def set_to_vector(self, vect): assert len(vect) == len(self.sliders) for slider, value in zip(self.sliders, vect): slider.set_value(value) def get_vector(self): return np.array([slider.get_value() for slider in self.sliders]) def get_center_point(self): return np.array([slider.center_value for slider in self.sliders]) def set_center_point(self, new_center_point): self.center_point = np.array(new_center_point) for x, slider in zip(new_center_point, self.sliders): slider.set_center_value(x) return self def get_current_total_real_estate(self): return sum([ slider.get_real_estate() for slider in self.sliders ]) def get_all_dial_supplement_animations(self): return [ slider.get_dial_supplement_animation() for slider in self.sliders ] def initialize_ambiant_slider_movement(self): self.ambiently_change_sliders = True self.ambient_change_end_time = np.inf self.ambient_change_time = 0 self.ambient_velocity, self.ambient_acceleration, self.ambient_jerk = [ self.get_random_vector(magnitude) for magnitude in [ self.ambient_velocity_magnitude, self.ambient_acceleration_magnitude, self.ambient_jerk_magnitude, ] ] ##Ensure counterclockwise rotations in 2D if len(self.ambient_velocity) == 2: cross = np.cross(self.get_vector(), self.ambient_velocity) if cross < 0: self.ambient_velocity *= -1 self.add_foreground_mobjects(self.sliders) def wind_down_ambient_movement(self, time = 1, wait = True): self.ambient_change_end_time = self.ambient_change_time + time if wait: self.wait(time) if self.skip_animations: self.ambient_change_time += time def ambient_slider_movement_update(self): #Set velocity_magnitude based on start up or wind down velocity_magnitude = float(self.ambient_velocity_magnitude) if self.ambient_change_time <= 1: velocity_magnitude *= smooth(self.ambient_change_time) time_until_end = self.ambient_change_end_time - self.ambient_change_time if time_until_end <= 1: velocity_magnitude *= smooth(time_until_end) if time_until_end < 0: self.ambiently_change_sliders = False return center_point = self.get_center_point() target_vector = self.get_vector() - center_point if get_norm(target_vector) == 0: return vectors_and_magnitudes = [ (self.ambient_acceleration, self.ambient_acceleration_magnitude), (self.ambient_velocity, velocity_magnitude), (target_vector, np.sqrt(self.total_real_estate)), ] jerk = self.get_random_vector(self.ambient_jerk_magnitude) deriv = jerk for vect, mag in vectors_and_magnitudes: vect += self.frame_duration*deriv if vect is self.ambient_velocity: unit_r_vect = target_vector / get_norm(target_vector) vect -= np.dot(vect, unit_r_vect)*unit_r_vect vect *= mag/get_norm(vect) deriv = vect self.set_to_vector(target_vector + center_point) self.ambient_change_time += self.frame_duration def get_random_vector(self, magnitude): result = 2*np.random.random(len(self.sliders)) - 1 result *= magnitude / get_norm(result) return result def update_frame(self, *args, **kwargs): if self.ambiently_change_sliders: self.ambient_slider_movement_update() Scene.update_frame(self, *args, **kwargs) def wait(self, time = 1): if self.ambiently_change_sliders: self.play(Animation(self.sliders, run_time = time)) else: Scene.wait(self,time) ########## class MathIsATease(Scene): def construct(self): randy = Randolph() lashes = VGroup() for eye in randy.eyes: for angle in np.linspace(-np.pi/3, np.pi/3, 12): lash = Line(ORIGIN, RIGHT) lash.set_stroke(GREY_D, 2) lash.set_width(0.27) lash.next_to(ORIGIN, RIGHT, buff = 0) lash.rotate(angle + np.pi/2) lash.shift(eye.get_center()) lashes.add(lash) lashes.do_in_place(lashes.stretch, 0.8, 1) lashes.shift(0.04*DOWN) fan = SVGMobject( file_name = "fan", fill_opacity = 1, fill_color = YELLOW, stroke_width = 2, stroke_color = YELLOW, height = 0.7, ) VGroup(*fan[-12:]).set_fill(YELLOW_E) fan.rotate(-np.pi/4) fan.move_to(randy) fan.shift(0.85*UP+0.25*LEFT) self.add(randy) self.play( ShowCreation(lashes, lag_ratio = 0), randy.change, "tease", randy.look, OUT, ) self.add_foreground_mobjects(fan) eye_bottom_y = randy.eyes.get_bottom()[1] self.play( ApplyMethod( lashes.apply_function, lambda p : [p[0], eye_bottom_y, p[2]], rate_func = Blink.CONFIG["rate_func"], ), Blink(randy), DrawBorderThenFill(fan), ) self.play( ApplyMethod( lashes.apply_function, lambda p : [p[0], eye_bottom_y, p[2]], rate_func = Blink.CONFIG["rate_func"], ), Blink(randy), ) self.wait() class TODODeterminants(TODOStub): CONFIG = { "message" : "Determinants clip" } class CircleToPairsOfPoints(Scene): def construct(self): plane = NumberPlane(written_coordinate_height = 0.3) plane.scale(2) plane.add_coordinates(y_vals = [-1, 1]) background_plane = plane.copy() background_plane.set_color(GREY) background_plane.fade() circle = Circle(radius = 2, color = YELLOW) x, y = [np.sqrt(2)/2]*2 dot = Dot(2*x*RIGHT + 2*y*UP, color = GREY_B) equation = OldTex("x", "^2", "+", "y", "^2", "=", "1") equation.set_color_by_tex("x", GREEN) equation.set_color_by_tex("y", RED) equation.to_corner(UP+LEFT) equation.add_background_rectangle() coord_pair = OldTex("(", "-%.02f"%x, ",", "-%.02f"%y, ")") fixed_numbers = coord_pair.get_parts_by_tex("-") fixed_numbers.set_fill(opacity = 0) coord_pair.add_background_rectangle() coord_pair.next_to(dot, UP+RIGHT, SMALL_BUFF) numbers = VGroup(*[ DecimalNumber(val).replace(num, dim_to_match = 1) for val, num in zip([x, y], fixed_numbers) ]) numbers[0].set_color(GREEN) numbers[1].set_color(RED) def get_update_func(i): return lambda t : dot.get_center()[i]/2.0 self.add(background_plane, plane) self.play(ShowCreation(circle)) self.play( FadeIn(coord_pair), Write(numbers, run_time = 1), ShowCreation(dot), ) self.play( Write(equation), *[ Transform( number.copy(), equation.get_parts_by_tex(tex), remover = True ) for tex, number in zip("xy", numbers) ] ) self.play(FocusOn(dot, run_time = 1)) self.play( Rotating( dot, run_time = 7, in_place = False, rate_func = smooth, ), MaintainPositionRelativeTo(coord_pair, dot), *[ ChangingDecimal( num, get_update_func(i), tracked_mobject = fixed_num ) for num, i, fixed_num in zip( numbers, (0, 1), fixed_numbers ) ] ) self.wait() ######### Rotation equations ########## rot_equation = OldTex( "\\Rightarrow" "\\big(\\cos(\\theta)x - \\sin(\\theta)y\\big)^2 + ", "\\big(\\sin(\\theta)x + \\cos(\\theta)y\\big)^2 = 1", ) rot_equation.scale(0.9) rot_equation.next_to(equation, RIGHT) rot_equation.add_background_rectangle() words = OldTexText("Rotational \\\\ symmetry") words.next_to(ORIGIN, UP) words.to_edge(RIGHT) words.add_background_rectangle() arrow = Arrow( words.get_left(), rot_equation.get_bottom(), path_arc = -np.pi/6 ) randy = Randolph(color = GREY_BROWN) randy.to_corner(DOWN+LEFT) self.play( Write(rot_equation, run_time = 2), FadeOut(coord_pair), FadeOut(numbers), FadeOut(dot), FadeIn(randy) ) self.play(randy.change, "confused", rot_equation) self.play(Blink(randy)) self.play( Write(words, run_time = 1), ShowCreation(arrow), randy.look_at, words ) plane.remove(*plane.coordinate_labels) self.play( Rotate( plane, np.pi/3, run_time = 4, rate_func = there_and_back ), Animation(equation), Animation(rot_equation), Animation(words), Animation(arrow), Animation(circle), randy.change, "hooray" ) self.wait() class GreatSourceOfMaterial(TeacherStudentsScene): def construct(self): self.teacher_says( "It's a great source \\\\ of material.", target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.wait(3) class CirclesSpheresSumsSquares(ExternallyAnimatedScene): pass class BackAndForth(Scene): def construct(self): analytic = OldTexText("Analytic") analytic.shift(FRAME_X_RADIUS*LEFT/2) analytic.to_edge(UP, buff = MED_SMALL_BUFF) geometric = OldTexText("Geometric") geometric.shift(FRAME_X_RADIUS*RIGHT/2) geometric.to_edge(UP, buff = MED_SMALL_BUFF) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.to_edge(UP, LARGE_BUFF) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) self.add(analytic, geometric, h_line, v_line) pair = OldTex("(", "x", ",", "y", ")") pair.shift(FRAME_X_RADIUS*LEFT/2 + FRAME_Y_RADIUS*UP/3) triplet = OldTex("(", "x", ",", "y", ",", "z", ")") triplet.shift(FRAME_X_RADIUS*LEFT/2 + FRAME_Y_RADIUS*DOWN/2) for mob in pair, triplet: arrow = DoubleArrow(LEFT, RIGHT) arrow.move_to(mob) arrow.shift(2*RIGHT) mob.arrow = arrow circle_eq = OldTex("x", "^2", "+", "y", "^2", "=", "1") circle_eq.move_to(pair) sphere_eq = OldTex("x", "^2", "+", "y", "^2", "+", "z", "^2", "=", "1") sphere_eq.move_to(triplet) plane = NumberPlane(x_unit_size = 2, y_unit_size = 2) circle = Circle(radius = 2, color = YELLOW) plane_group = VGroup(plane, circle) plane_group.scale(0.4) plane_group.next_to(h_line, DOWN, SMALL_BUFF) plane_group.shift(FRAME_X_RADIUS*RIGHT/2) self.play(Write(pair)) # self.play(ShowCreation(pair.arrow)) self.play(ShowCreation(plane, run_time = 3)) self.play(Write(triplet)) # self.play(ShowCreation(triplet.arrow)) self.wait(3) for tup, eq, to_draw in (pair, circle_eq, circle), (triplet, sphere_eq, VMobject()): for mob in tup, eq: mob.xyz = VGroup(*[sm for sm in map(mob.get_part_by_tex, "xyz") if sm is not None]) self.play( ReplacementTransform(tup.xyz, eq.xyz), FadeOut(VGroup(*[sm for sm in tup if sm not in tup.xyz])), ) self.play( Write(VGroup(*[sm for sm in eq if sm not in eq.xyz])), ShowCreation(to_draw) ) self.wait(3) class SphereForming(ExternallyAnimatedScene): pass class PreviousVideos(Scene): def construct(self): titles = VGroup(*list(map(TexText, [ "Pi hiding in prime regularities", "Visualizing all possible pythagorean triples", "Borsuk-Ulam theorem", ]))) titles.to_edge(UP, buff = MED_SMALL_BUFF) screen = ScreenRectangle(height = 6) screen.next_to(titles, DOWN) title = titles[0] self.add(title, screen) self.wait(2) for new_title in titles[1:]: self.play(Transform(title, new_title)) self.wait(2) class TODOTease(TODOStub): CONFIG = { "message" : "Tease" } class AskAboutLongerLists(TeacherStudentsScene): def construct(self): question = OldTexText( "What about \\\\", "$(x_1, x_2, x_3, x_4)?$" ) tup = question[1] alt_tups = list(map(TexText, [ "$(x_1, x_2, x_3, x_4, x_5)?$", "$(x_1, x_2, \\dots, x_{99}, x_{100})?$" ])) self.student_says(question, run_time = 1) self.wait() for alt_tup in alt_tups: alt_tup.move_to(tup) self.play(Transform(tup, alt_tup)) self.wait() self.wait() self.play( RemovePiCreatureBubble(self.students[1]), self.teacher.change, "raise_right_hand" ) self.play_student_changes( *["confused"]*3, look_at = self.teacher.get_top() + 2*UP ) self.play(self.teacher.look, UP) self.wait(5) self.student_says( "I...don't see it.", target_mode = "maybe", index = 0 ) self.wait(3) class FourDCubeRotation(ExternallyAnimatedScene): pass class HypersphereRotation(ExternallyAnimatedScene): pass class FourDSurfaceRotating(ExternallyAnimatedScene): pass class Professionals(PiCreatureScene): def construct(self): self.introduce_characters() self.add_equation() self.analogies() def introduce_characters(self): titles = VGroup(*list(map(TexText, [ "Mathematician", "Computer scientist", "Physicist", ]))) self.remove(*self.pi_creatures) for title, pi in zip(titles, self.pi_creatures): title.next_to(pi, DOWN) self.play( Animation(VectorizedPoint(pi.eyes.get_center())), FadeIn(pi), Write(title, run_time = 1), ) self.wait() def add_equation(self): quaternion = OldTex( "\\frac{1}{2}", "+", "0", "\\textbf{i}", "+", "\\frac{\\sqrt{6}}{4}", "\\textbf{j}", "+", "\\frac{\\sqrt{6}}{4}", "\\textbf{k}", ) quaternion.scale(0.7) quaternion.next_to(self.mathy, UP) quaternion.set_color_by_tex_to_color_map({ "i" : RED, "j" : GREEN, "k" : BLUE, }) array = OldTex("[a_1, a_2, \\dots, a_{100}]") array.next_to(self.compy, UP) kets = OldTex( "\\alpha", "|\\!\\uparrow\\rangle + ", "\\beta", "|\\!\\downarrow\\rangle" ) kets.set_color_by_tex_to_color_map({ "\\alpha" : GREEN, "\\beta" : RED, }) kets.next_to(self.physy, UP) terms = VGroup(quaternion, array, kets) for term, pi in zip(terms, self.pi_creatures): self.play( Write(term, run_time = 1), pi.change, "pondering", term ) self.wait(2) self.terms = terms def analogies(self): examples = VGroup() plane = ComplexPlane( x_radius = 2.5, y_radius = 1.5, ) plane.add_coordinates() plane.add(Circle(color = YELLOW)) plane.scale(0.75) examples.add(plane) examples.add(Circle()) examples.arrange(RIGHT, buff = 2) examples.to_edge(UP, buff = LARGE_BUFF) labels = VGroup(*list(map(TexText, ["2D", "3D"]))) title = OldTexText("Fly by instruments") title.scale(1.5) title.to_edge(UP) for label, example in zip(labels, examples): label.next_to(example, DOWN) self.play( ShowCreation(example), Write(label, run_time = 1) ) example.add(label) self.wait() self.wait() self.play( FadeOut(examples), self.terms.shift, UP, Write(title, run_time = 2) ) self.play(*[ ApplyMethod( pi.change, mode, self.terms.get_left(), run_time = 2, rate_func = squish_rate_func(smooth, a, a+0.5) ) for pi, mode, a in zip( self.pi_creatures, ["confused", "sassy", "erm"], np.linspace(0, 0.5, len(self.pi_creatures)) ) ]) self.wait() self.play(Animation(self.terms[-1])) self.wait(2) ###### def create_pi_creatures(self): self.mathy = Mathematician() self.physy = PiCreature(color = PINK) self.compy = PiCreature(color = PURPLE) pi_creatures = VGroup(self.mathy, self.compy, self.physy) for pi in pi_creatures: pi.scale(0.7) pi_creatures.arrange(RIGHT, buff = 3) pi_creatures.to_edge(DOWN, buff = LARGE_BUFF) return pi_creatures class OfferAHybrid(SliderScene): CONFIG = { "n_sliders" : 3, } def construct(self): self.remove(self.sliders) titles = self.get_titles() h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(titles, DOWN) v_lines = VGroup(*[ Line(UP, DOWN).scale(FRAME_Y_RADIUS) for x in range(2) ]) v_lines.generate_target() for line, vect in zip(v_lines.target, [LEFT, RIGHT]): line.shift(vect*FRAME_X_RADIUS/3) equation = OldTex("x^2 + y^2 + z^2 = 1") equation.generate_target() equation.shift(FRAME_X_RADIUS*LEFT/2) equation.target.shift(FRAME_WIDTH*LEFT/3) self.add(titles, h_line, v_lines, equation) self.wait() self.play(*list(map(MoveToTarget, [titles, v_lines, equation]))) self.play(Write(self.sliders, run_time = 1)) self.initialize_ambiant_slider_movement() self.wait(10) self.wind_down_ambient_movement() self.wait() def get_titles(self): titles = VGroup(*list(map(TexText, [ "Analytic", "Hybrid", "Geometric" ]))) titles.to_edge(UP) titles[1].set_color(BLUE) titles.generate_target() titles[1].scale(0.001) titles[0].shift(FRAME_X_RADIUS*LEFT/2) titles.target[0].shift(FRAME_WIDTH*LEFT/3) titles[2].shift(FRAME_X_RADIUS*RIGHT/2) titles.target[2].shift(FRAME_WIDTH*RIGHT/3) return titles class TODOBoxExample(TODOStub): CONFIG = { "message" : "Box Example" } class RotatingSphereWithWanderingPoint(ExternallyAnimatedScene): pass class DismissProjection(PiCreatureScene): CONFIG = { "screen_rect_color" : WHITE, "example_vect" : np.array([0.52, 0.26, 0.53, 0.60]), } def construct(self): self.remove(self.pi_creature) self.show_all_spheres() self.discuss_4d_sphere_definition() self.talk_through_animation() self.transition_to_next_scene() def show_all_spheres(self): equations = VGroup(*list(map(Tex, [ "x^2 + y^2 = 1", "x^2 + y^2 + z^2 = 1", "x^2 + y^2 + z^2 + w^2 = 1", ]))) colors = [YELLOW, GREEN, BLUE] for equation, edge, color in zip(equations, [LEFT, ORIGIN, RIGHT], colors): equation.set_color(color) equation.shift(3*UP) equation.to_edge(edge) equations[1].shift(LEFT) spheres = VGroup( self.get_circle(equations[0]), self.get_sphere_screen(equations[1], DOWN), self.get_sphere_screen(equations[2], DOWN), ) for equation, sphere in zip(equations, spheres): self.play( Write(equation), LaggedStartMap(ShowCreation, sphere), ) self.wait() self.equations = equations self.spheres = spheres def get_circle(self, equation): result = VGroup( NumberPlane( x_radius = 2.5, y_radius = 2, ).fade(0.4), Circle(color = YELLOW, radius = 1), ) result.scale(0.7) result.next_to(equation, DOWN) return result def get_sphere_screen(self, equation, vect): square = Rectangle() square.set_width(equation.get_width()) square.stretch_to_fit_height(3) square.next_to(equation, vect) square.set_color(self.screen_rect_color) return square def discuss_4d_sphere_definition(self): sphere = self.spheres[-1] equation = self.equations[-1] sphere_words = OldTexText("``4-dimensional sphere''") sphere_words.next_to(sphere, DOWN+LEFT, buff = LARGE_BUFF) arrow = Arrow( sphere_words.get_right(), sphere.get_bottom(), path_arc = np.pi/3, color = BLUE ) descriptor = OldTex( "\\text{Just lists of numbers like }", "(%.02f \\,, %.02f \\,, %.02f \\,, %.02f \\,)"%tuple(self.example_vect) ) descriptor[1].set_color(BLUE) descriptor.next_to(sphere_words, DOWN) dot = Dot(descriptor[1].get_top()) dot.set_fill(WHITE, opacity = 0.75) self.play( Write(sphere_words), ShowCreation( arrow, rate_func = squish_rate_func(smooth, 0.5, 1) ), run_time = 3, ) self.wait() self.play(Write(descriptor, run_time = 2)) self.wait() self.play( dot.move_to, equation.get_left(), dot.set_fill, None, 0, path_arc = -np.pi/12 ) self.wait(2) self.sphere_words = sphere_words self.sphere_arrow = arrow self.descriptor = descriptor def talk_through_animation(self): sphere = self.spheres[-1] morty = self.pi_creature alt_dims = VGroup(*list(map(TexText, ["5D", "6D", "7D"]))) alt_dims.next_to(morty.eyes, UP, SMALL_BUFF) alt_dim = alt_dims[0] self.play(FadeIn(morty)) self.play(morty.change, "raise_right_hand", sphere) self.wait(3) self.play(morty.change, "confused", sphere) self.wait(3) self.play( morty.change, "erm", alt_dims, FadeIn(alt_dim) ) for new_alt_dim in alt_dims[1:]: self.wait() self.play(Transform(alt_dim, new_alt_dim)) self.wait() self.play(morty.change, "concerned_musician") self.play(FadeOut(alt_dim)) self.wait() self.play(morty.change, "angry", sphere) self.wait(2) def transition_to_next_scene(self): equation = self.equations[-1] self.equations.remove(equation) tup = self.descriptor[1] self.descriptor.remove(tup) equation.generate_target() equation.target.center().to_edge(UP) tup.generate_target() tup.target.next_to(equation.target, DOWN) tup.target.set_color(WHITE) self.play(LaggedStartMap(FadeOut, VGroup(*[ self.equations, self.spheres, self.sphere_words, self.sphere_arrow, self.descriptor, self.pi_creature ]))) self.play(*list(map(MoveToTarget, [equation, tup]))) self.wait() ### def create_pi_creature(self): return Mortimer().scale(0.8).to_corner(DOWN+RIGHT) class RotatingSphere(ExternallyAnimatedScene): pass class Introduce4DSliders(SliderScene): CONFIG = { "slider_config" : { "include_real_estate_ticks" : False, "numbers_with_elongated_ticks" : [-1, 0, 1], "tick_frequency" : 0.25, "tick_size" : 0.05, "dial_color" : YELLOW, }, "slider_spacing" : LARGE_BUFF, } def construct(self): self.match_last_scene() self.introduce_sliders() self.ask_about_constraint() def match_last_scene(self): self.start_vect = DismissProjection.CONFIG["example_vect"] self.remove(self.sliders) equation = OldTex("x^2 + y^2 + z^2 + w^2 = 1") x, y, z, w = self.start_vect tup = OldTex( "(", "%.02f \\,"%x, ",", "%.02f \\,"%y, ",", "%.02f \\,"%z, ",", "%.02f \\,"%w, ")" ) equation.center().to_edge(UP) equation.set_color(BLUE) tup.next_to(equation, DOWN) self.sliders.next_to(tup, DOWN) self.sliders.shift(0.8*LEFT) self.add(equation, tup) self.wait() self.equation = equation self.tup = tup def introduce_sliders(self): self.set_to_vector(self.start_vect) numbers = self.tup.get_parts_by_tex(".") self.tup.remove(*numbers) dials = VGroup(*[slider.dial for slider in self.sliders]) dial_copies = dials.copy() dials.set_fill(opacity = 0) self.play(LaggedStartMap(FadeIn, self.sliders)) self.play(*[ Transform( num, dial, run_time = 3, rate_func = squish_rate_func(smooth, a, a+0.5), remover = True ) for num, dial, a in zip( numbers, dial_copies, np.linspace(0, 0.5, len(numbers)) ) ]) dials.set_fill(opacity = 1) self.initialize_ambiant_slider_movement() self.play(FadeOut(self.tup)) self.wait(10) def ask_about_constraint(self): equation = self.equation rect = SurroundingRectangle(equation, color = GREEN) randy = Randolph().scale(0.5) randy.next_to(rect, DOWN+LEFT, LARGE_BUFF) self.play(ShowCreation(rect)) self.play(FadeIn(randy)) self.play(randy.change, "pondering", rect) self.wait() for mob in self.sliders, rect: self.play(randy.look_at, mob) self.play(Blink(randy)) self.wait() self.wait() class TwoDimensionalCase(Introduce4DSliders): CONFIG = { "n_sliders" : 2, } def setup(self): SliderScene.setup(self) self.sliders.shift(RIGHT) for number in self.sliders[0].numbers: value = int(number.get_tex()) number.move_to(center_of_mass([ slider.number_to_point(value) for slider in self.sliders ])) plane = NumberPlane( x_radius = 2.5, y_radius = 2.5, ) plane.fade(0.25) plane.axes.set_color(GREY) plane.add_coordinates() plane.to_edge(LEFT) origin = plane.coords_to_point(0, 0) circle = Circle(radius = 1, color = WHITE) circle.move_to(plane.coords_to_point(*self.center_point)) dot = Dot(color = YELLOW) dot.move_to(plane.coords_to_point(1, 0)) equation = OldTex("x^2 + y^2 = 1") equation.to_corner(UP + RIGHT) self.add(plane, circle, dot, equation) self.add_foreground_mobjects(dot) self.plane = plane self.circle = circle self.dot = dot self.equation = equation def construct(self): self.let_values_wander() self.introduce_real_estate() self.let_values_wander(6) self.comment_on_cheap_vs_expensive_real_estate() self.nudge_x_from_one_example() self.note_circle_steepness() self.add_tick_marks() self.write_distance_squared() def let_values_wander(self, total_time = 5): self.initialize_ambiant_slider_movement() self.wait(total_time - 1) self.wind_down_ambient_movement() def introduce_real_estate(self): x_squared_mob = VGroup(*self.equation[:2]) y_squared_mob = VGroup(*self.equation[3:5]) x_rect = SurroundingRectangle(x_squared_mob) y_rect = SurroundingRectangle(y_squared_mob) rects = VGroup(x_rect, y_rect) decimals = VGroup(*[ DecimalNumber(num**2) for num in self.get_vector() ]) decimals.arrange(RIGHT, buff = LARGE_BUFF) decimals.next_to(rects, DOWN, LARGE_BUFF) real_estate_word = OldTexText("``Real estate''") real_estate_word.next_to(decimals, DOWN, MED_LARGE_BUFF) self.play(FadeIn(real_estate_word)) colors = GREEN, RED arrows = VGroup() for rect, decimal, color in zip(rects, decimals, colors): rect.set_color(color) decimal.set_color(color) arrow = Arrow( rect.get_bottom()+SMALL_BUFF*UP, decimal.get_top(), tip_length = 0.2, ) arrow.set_color(color) arrows.add(arrow) self.play(ShowCreation(rect)) self.play( ShowCreation(arrow), Write(decimal) ) self.wait() sliders = self.sliders def create_update_func(i): return lambda alpha : sliders[i].get_real_estate() self.add_foreground_mobjects(decimals) self.decimals = decimals self.decimal_update_anims = [ ChangingDecimal(decimal, create_update_func(i)) for i, decimal in enumerate(decimals) ] self.real_estate_word = real_estate_word def comment_on_cheap_vs_expensive_real_estate(self): blue_rects = VGroup() red_rects = VGroup() for slider in self.sliders: for x1, x2 in (-0.5, 0.5), (0.75, 1.0), (-1.0, -0.75): p1, p2 = list(map(slider.number_to_point, [x1, x2])) rect = Rectangle( stroke_width = 0, fill_opacity = 0.5, width = 0.25, height = (p2-p1)[1] ) rect.move_to((p1+p2)/2) if np.mean([x1, x2]) == 0: rect.set_color(BLUE) blue_rects.add(rect) else: rect.set_color(RED) red_rects.add(rect) blue_rects.save_state() self.play(DrawBorderThenFill(blue_rects)) self.wait() self.play(ReplacementTransform(blue_rects, red_rects)) self.wait() self.play(FadeOut(red_rects)) blue_rects.restore() self.real_estate_rects = VGroup(blue_rects, red_rects) def nudge_x_from_one_example(self): x_re = self.decimals[0] rect = SurroundingRectangle(x_re) self.reset_dials([1, 0]) self.wait() self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play(FocusOn(self.dot)) self.wait() self.reset_dials([0.9, -np.sqrt(0.19)]) x_brace, y_brace = [ Brace( VGroup(slider.dial, Dot(slider.number_to_point(0))), vect ) for slider, vect in zip(self.sliders, [LEFT, RIGHT]) ] x_text = x_brace.get_tex("0.9") y_text = y_brace.get_tex("%.02f"%self.sliders[1].get_value()) self.play( GrowFromCenter(x_brace), Write(x_text) ) self.play(ReplacementTransform( VGroup(x_text.copy()), x_re )) self.wait(2) self.play( GrowFromCenter(y_brace), Write(y_text), ) self.wait(2) self.play(FadeIn(self.real_estate_rects)) self.reset_dials([1, 0], run_time = 1) self.reset_dials([0.9, -np.sqrt(0.19)], run_time = 2) self.play(FadeOut(self.real_estate_rects)) self.play(*list(map(FadeOut, [x_brace, y_brace, x_text, y_text]))) self.wait() def note_circle_steepness(self): line = Line( self.plane.coords_to_point(0.5, 1), self.plane.coords_to_point(1.5, -1), ) rect = Rectangle( stroke_width = 0, fill_color = BLUE, fill_opacity = 0.5, ) rect.replace(line, stretch = True) self.play(DrawBorderThenFill(rect, stroke_color = YELLOW)) for x, u in (1, 1), (0.8, 1), (1, 1), (0.8, -1), (1, 1): self.reset_dials([x, u*np.sqrt(1 - x**2)]) self.play(FadeOut(rect)) def add_tick_marks(self): self.remove_foreground_mobjects(self.sliders) self.add(self.sliders) old_ticks = VGroup() all_ticks = VGroup() for slider in self.sliders: slider.tick_size = 0.1 slider.add_real_estate_ticks() slider.remove(slider.get_tick_marks()) all_ticks.add(*slider.real_estate_ticks) old_ticks.add(*slider.get_tick_marks()[:-3]) self.play( FadeOut(old_ticks), ShowCreation(all_ticks, run_time = 3), Animation(VGroup(*[slider.dial for slider in self.sliders])), ) self.add_foreground_mobjects(self.sliders) self.wait() for x in np.arange(0.95, 0.05, -0.05): self.reset_dials( [np.sqrt(x), np.sqrt(1-x)], run_time = 0.5 ) self.wait(0.5) self.initialize_ambiant_slider_movement() self.wait(10) def write_distance_squared(self): d_squared = OldTex("(\\text{Distance})^2") d_squared.next_to(self.real_estate_word, DOWN) d_squared.set_color(YELLOW) self.play(Write(d_squared)) self.wait(3) ##### def update_frame(self, *args, **kwargs): if hasattr(self, "dot"): x, y = self.get_vector() self.dot.move_to(self.plane.coords_to_point(x, y)) if hasattr(self, "decimals"): for anim in self.decimal_update_anims: anim.update(0) SliderScene.update_frame(self, *args, **kwargs) class TwoDimensionalCaseIntro(TwoDimensionalCase): def construct(self): self.initialize_ambiant_slider_movement() self.wait(10) class ThreeDCase(TwoDimensionalCase): CONFIG = { "n_sliders" : 3, "slider_config" : { "include_real_estate_ticks" : True, "numbers_with_elongated_ticks" : [], "tick_frequency" : 1, "tick_size" : 0.1, }, } def setup(self): SliderScene.setup(self) self.equation = OldTex( "x^2", "+", "y^2", "+", "z^2", "=", "1" ) self.equation.to_corner(UP+RIGHT) self.add(self.equation) def construct(self): self.force_skipping() self.add_real_estate_decimals() self.initialize_ambiant_slider_movement() self.point_out_third_slider() self.wait(3) self.hold_x_at(0.5, 12) self.revert_to_original_skipping_status() self.hold_x_at(0.85, 12) return self.hold_x_at(1, 5) def add_real_estate_decimals(self): rects = VGroup(*[ SurroundingRectangle(self.equation.get_part_by_tex(char)) for char in "xyz" ]) decimals = VGroup(*[ DecimalNumber(num**2) for num in self.get_vector() ]) decimals.arrange(RIGHT, buff = LARGE_BUFF) decimals.next_to(rects, DOWN, LARGE_BUFF) colors = [GREEN, RED, BLUE] arrows = VGroup() for rect, decimal, color in zip(rects, decimals, colors): rect.set_color(color) decimal.set_color(color) arrow = Arrow( rect.get_bottom()+SMALL_BUFF*UP, decimal.get_top(), tip_length = 0.2, color = color ) arrows.add(arrow) real_estate_word = OldTexText("``Real estate''") real_estate_word.next_to(decimals, DOWN, MED_LARGE_BUFF) sliders = self.sliders def create_update_func(i): return lambda alpha : sliders[i].get_real_estate() self.add_foreground_mobjects(decimals) self.decimals = decimals self.decimal_update_anims = [ ChangingDecimal(decimal, create_update_func(i)) for i, decimal in enumerate(decimals) ] self.add(rects, arrows, real_estate_word) self.rects = rects self.arrows = arrows self.real_estate_word = real_estate_word def point_out_third_slider(self): rect = SurroundingRectangle(self.sliders[-1]) self.wait(4) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.wait(8) def hold_x_at(self, x_val, wait_time): #Save these all_sliders = self.sliders original_total_real_estate = self.total_real_estate self.reset_dials([x_val], run_time = 3) self.sliders = VGroup(*self.sliders[1:]) self.total_real_estate = self.total_real_estate-x_val**2 self.initialize_ambiant_slider_movement() self.wait(wait_time-2) self.wind_down_ambient_movement() self.sliders = all_sliders self.total_real_estate = original_total_real_estate self.initialize_ambiant_slider_movement() #### class ThreeDCaseInsert(ThreeDCase): def construct(self): self.add_real_estate_decimals() self.reset_dials([0.85, np.sqrt(1-0.85**2)], run_time = 0) self.reset_dials([1], run_time = 3) self.wait() class SphereAtRest(ExternallyAnimatedScene): pass class BugOnASurface(TeacherStudentsScene): def construct(self): self.teacher_says("You're a bug \\\\ on a surface") self.wait(3) class SphereWithWanderingDotAtX0point5(ExternallyAnimatedScene): pass class MoveSphereSliceFromPoint5ToPoint85(ExternallyAnimatedScene): pass class SphereWithWanderingDotAtX0point85(ExternallyAnimatedScene): pass class MoveSphereSliceFromPoint85To1(ExternallyAnimatedScene): pass class BugOnTheSurfaceSlidersPart(ThreeDCase): CONFIG = { "run_time" : 30 } def construct(self): self.add_real_estate_decimals() self.reset_dials([0.9], run_time = 0) time_range = np.arange(0, self.run_time, self.frame_duration) for time in ProgressDisplay(time_range): t = 0.3*np.sin(2*np.pi*time/7.0) + 1 u = 0.3*np.sin(4*np.pi*time/7.0) + 1.5 self.set_to_vector([ np.cos(u), np.sin(u)*np.cos(t), np.sin(u)*np.sin(t), ]) self.wait(self.frame_duration) class BugOnTheSurfaceSpherePart(ExternallyAnimatedScene): pass class FourDCase(SliderScene, TeacherStudentsScene): def setup(self): TeacherStudentsScene.setup(self) SliderScene.setup(self) self.sliders.scale(0.9) self.sliders.to_edge(UP) self.sliders.shift(2*RIGHT) self.initialize_ambiant_slider_movement() def construct(self): self.show_initial_exchange() self.fix_one_slider() self.ask_now_what() self.set_aside_sliders() def show_initial_exchange(self): dot = Dot(fill_opacity = 0) dot.to_corner(UP+LEFT, buff = 2) self.play(Animation(dot)) self.wait() self.play( Animation(self.sliders), self.teacher.change, "raise_right_hand", ) self.play_student_changes( *["pondering"]*3, look_at = self.sliders ) self.wait(4) def fix_one_slider(self): x_slider = self.sliders[0] dial = x_slider.dial self.wind_down_ambient_movement(wait = False) self.play(self.teacher.change, "speaking") self.sliders.remove(x_slider) self.total_real_estate = get_norm(self.get_vector())**2 self.initialize_ambiant_slider_movement() arrow = Arrow(LEFT, RIGHT, color = GREEN) arrow.next_to(dial, LEFT) self.play( ShowCreation(arrow), dial.set_color, arrow.get_color() ) self.play_student_changes( "erm", "confused", "hooray", look_at = self.sliders, added_anims = [self.teacher.change, "plain"] ) self.wait(5) self.x_slider = x_slider self.x_arrow = arrow def ask_now_what(self): self.student_says( "Okay...now what?", target_mode = "raise_left_hand", index = 0, added_anims = [self.teacher.change, "plain"] ) self.play_student_changes( None, "pondering", "pondering", look_at = self.students[0].bubble, ) self.wait(4) self.play(RemovePiCreatureBubble(self.students[0])) def set_aside_sliders(self): self.sliders.add(self.x_slider) self.total_real_estate = 1 self.initialize_ambiant_slider_movement() self.play( self.sliders.scale, 0.5, self.sliders.to_corner, UP+RIGHT, FadeOut(self.x_arrow) ) self.teacher_says( "Time for some \\\\ high-dimensional \\\\ strangeness!", target_mode = "hooray", ) self.wait(7) ##### def non_blink_wait(self, time = 1): SliderScene.wait(self, time) class TwoDBoxExample(Scene): def setup(self): scale_factor = 1.7 self.plane = NumberPlane() self.plane.scale(scale_factor) self.plane.add_coordinates() self.plane.axes.set_color(GREY) self.add(self.plane) def construct(self): self.add_box() self.label_corner_coordinates() self.add_corner_circles() self.add_center_circle() self.compute_radius() def add_box(self): box = Square(color = RED, stroke_width = 6) line = Line( self.plane.coords_to_point(-1, -1), self.plane.coords_to_point(1, 1), ) box.replace(line, stretch = True) self.play(ShowCreation(box)) self.wait() def label_corner_coordinates(self): corner_dots = VGroup() coords_group = VGroup() for x, y in it.product(*[[1, -1]]*2): point = self.plane.coords_to_point(x, y) dot = Dot(point, color = WHITE) coords = OldTex("(%d, %d)"%(x, y)) coords.add_background_rectangle() coords.next_to(point, point, SMALL_BUFF) corner_dots.add(dot) coords_group.add(coords) self.play( ShowCreation(dot), Write(coords, run_time = 1) ) self.add_foreground_mobjects(coords_group) self.corner_dots = corner_dots self.coords_group = coords_group def add_corner_circles(self): line = Line( self.plane.coords_to_point(-1, 0), self.plane.coords_to_point(1, 0), ) circle = Circle(color = YELLOW) circle.replace(line, dim_to_match = 0) circles = VGroup(*[ circle.copy().move_to(dot) for dot in self.corner_dots ]) radius = Line(ORIGIN, self.plane.coords_to_point(1, 0)) radius.set_stroke(GREY, 6) radius.rotate(-np.pi/4) c0_center = circles[0].get_center() radius.shift(c0_center) r_equals_1 = OldTex("r = 1") r_equals_1.add_background_rectangle() r_equals_1.next_to( radius.point_from_proportion(0.75), UP+RIGHT, SMALL_BUFF ) self.play(LaggedStartMap(ShowCreation, circles)) self.play( ShowCreation(radius), Write(r_equals_1) ) for angle in -np.pi/4, -np.pi/2, 3*np.pi/4: self.play(Rotating( radius, about_point = c0_center, radians = angle, run_time = 1, rate_func = smooth, )) self.wait(0.5) self.play(*list(map(FadeOut, [radius, r_equals_1]))) self.wait() self.corner_radius = radius self.corner_circles = circles def add_center_circle(self): r = np.sqrt(2) - 1 radius = Line(ORIGIN, self.plane.coords_to_point(r, 0)) radius.set_stroke(WHITE) circle = Circle(color = GREEN) circle.replace( VGroup(radius, radius.copy().rotate(np.pi)), dim_to_match = 0 ) radius.rotate(np.pi/4) r_equals_q = OldTex("r", "= ???") r_equals_q[1].add_background_rectangle() r_equals_q.next_to(radius, RIGHT, buff = -SMALL_BUFF) self.play(GrowFromCenter(circle, run_time = 2)) self.play(circle.scale, 1.2, rate_func = wiggle) self.play(ShowCreation(radius)) self.play(Write(r_equals_q)) self.wait(2) self.play(FadeOut(r_equals_q[1])) self.inner_radius = radius self.inner_circle = circle self.inner_r = r_equals_q[0] def compute_radius(self): triangle = Polygon( ORIGIN, self.plane.coords_to_point(1, 0), self.plane.coords_to_point(1, 1), fill_color = BLUE, fill_opacity = 0.5, stroke_width = 6, stroke_color = WHITE, ) bottom_one = OldTex("1") bottom_one.next_to(triangle.get_bottom(), UP, SMALL_BUFF) bottom_one.shift(MED_SMALL_BUFF*RIGHT) side_one = OldTex("1") side_one.next_to(triangle, RIGHT) sqrt_1_plus_1 = OldTex("\\sqrt", "{1^2 + 1^2}") sqrt_2 = OldTex("\\sqrt", "{2}") for sqrt in sqrt_1_plus_1, sqrt_2: sqrt.add_background_rectangle() sqrt.next_to(ORIGIN, UP, SMALL_BUFF) sqrt.rotate(np.pi/4) sqrt.shift(triangle.get_center()) root_2_value = OldTex("\\sqrt{2} \\approx 1.414") root_2_value.to_corner(UP+RIGHT) root_2_value.add_background_rectangle() root_2_minus_1_value = OldTex( "\\sqrt{2} - 1 \\approx 0.414" ) root_2_minus_1_value.next_to(root_2_value, DOWN) root_2_minus_1_value.to_edge(RIGHT) root_2_minus_1_value.add_background_rectangle() corner_radius = self.corner_radius c0_center = self.corner_circles[0].get_center() corner_radius.rotate(-np.pi/2, about_point = c0_center) rhs = OldTex("=", "\\sqrt", "{2}", "-1") rhs.next_to(self.inner_r, RIGHT, SMALL_BUFF, DOWN) rhs.shift(0.5*SMALL_BUFF*DOWN) sqrt_2_target = VGroup(*rhs[1:3]) rhs.add_background_rectangle() self.play( FadeIn(triangle), Write(VGroup(bottom_one, side_one, sqrt_1_plus_1)) ) self.wait(2) self.play(ReplacementTransform(sqrt_1_plus_1, sqrt_2)) self.play( Write(root_2_value, run_time = 1), *list(map(FadeOut, [bottom_one, side_one])) ) self.wait() self.play(ShowCreation(corner_radius)) self.play(Rotating( corner_radius, about_point = c0_center, run_time = 2, rate_func = smooth )) self.play(FadeOut(triangle), Animation(corner_radius)) self.wait() self.play( Write(rhs), Transform(sqrt_2, sqrt_2_target), ) self.play(Write(root_2_minus_1_value)) self.wait(2) class ThreeDBoxExample(ExternallyAnimatedScene): pass class ThreeDCubeCorners(Scene): def construct(self): coordinates = VGroup(*[ OldTex("(%d,\\, %d,\\, %d)"%(x, y, z)) for x, y, z in it.product(*3*[[1, -1]]) ]) coordinates.arrange(DOWN, aligned_edge = LEFT) name = OldTexText("Corners: ") name.next_to(coordinates[0], LEFT) group = VGroup(name, coordinates) group.set_height(FRAME_HEIGHT - 1) group.to_edge(LEFT) self.play(Write(name, run_time = 2)) self.play(LaggedStartMap(FadeIn, coordinates, run_time = 3)) self.wait() class ShowDistanceFormula(TeacherStudentsScene): def construct(self): rule = OldTex( "||(", "x_1", ", ", "x_2", "\\dots, ", "x_n", ")||", "=", "\\sqrt", "{x_1^2", " + ", "x_2^2", " +\\cdots", "x_n^2", "}" ) rule.set_color_by_tex_to_color_map({ "x_1" : GREEN, "x_2" : RED, "x_n" : BLUE, }) for part in rule.get_parts_by_tex("x_"): if len(part) > 2: part[1].set_color(WHITE) rule.next_to(self.teacher, UP, LARGE_BUFF) rule.to_edge(RIGHT) rule.shift(UP) rule.save_state() rule.shift(2*DOWN) rule.set_fill(opacity = 0) self.play( rule.restore, self.teacher.change, "raise_right_hand", ) self.wait(3) self.student_says("Why?", index = 0) self.play(self.teacher.change, "thinking") self.wait(3) class GeneralizePythagoreanTheoremBeyondTwoD(ThreeDScene): def construct(self): tex_to_color_map = { "x" : GREEN, "y" : RED, "z" : BLUE, } rect = Rectangle( height = 4, width = 5, fill_color = WHITE, fill_opacity = 0.2, ) diag = Line( rect.get_corner(DOWN+LEFT), rect.get_corner(UP+RIGHT), color = YELLOW ) bottom = Line(rect.get_left(), rect.get_right()) bottom.move_to(rect.get_bottom()) bottom.set_color(tex_to_color_map["x"]) side = Line(rect.get_bottom(), rect.get_top()) side.move_to(rect.get_right()) side.set_color(tex_to_color_map["y"]) x = OldTex("x") x.next_to(rect.get_bottom(), UP, SMALL_BUFF) y = OldTex("y") y.next_to(rect.get_right(), LEFT, SMALL_BUFF) hyp = OldTex("\\sqrt", "{x", "^2 + ", "y", "^2}") hyp.set_color_by_tex_to_color_map(tex_to_color_map) hyp.next_to(ORIGIN, UP) hyp.rotate(diag.get_angle()) hyp.shift(diag.get_center()) group = VGroup(rect, bottom, side, diag, x, y, hyp) self.add(rect) for line, tex in (bottom, x), (side, y), (diag, hyp): self.play( ShowCreation(line), Write(tex, run_time = 1) ) self.wait() self.play( group.rotate, 0.45*np.pi, LEFT, group.shift, 2*DOWN ) corner = diag.get_end() z_line = Line(corner, corner + 3*UP) z_line.set_color(tex_to_color_map["z"]) z = OldTex("z") z.set_color(tex_to_color_map["z"]) z.next_to(z_line, RIGHT) dot = Dot(z_line.get_end()) three_d_diag = Line(diag.get_start(), z_line.get_end()) three_d_diag.set_color(MAROON_B) self.play( ShowCreation(z_line), ShowCreation(dot), Write(z, run_time = 1) ) self.play(ShowCreation(three_d_diag)) self.wait() full_group = VGroup(group, z_line, z, three_d_diag, dot) self.play(Rotating( full_group, radians = -np.pi/6, axis = UP, run_time = 10, )) self.wait() class ThreeDBoxFormulas(Scene): def construct(self): question = OldTex( "||(1, 1, 1)||", "=", "???" ) answer = OldTex( "||(1, 1, 1)||", "&=", "\\sqrt{1^2 + 1^2 + 1^2}\\\\", "&= \\sqrt{3}\\\\", "&\\approx", "1.73", ) for mob in question, answer: mob.to_corner(UP+LEFT) inner_r = OldTex( "\\text{Inner radius}", "&=", "\\sqrt{3} - 1\\\\", "&\\approx", "0.73" ) inner_r.next_to(answer, DOWN, LARGE_BUFF, LEFT) inner_r.set_color(GREEN_C) VGroup(question, answer).shift(0.55*RIGHT) self.play(Write(question)) self.wait(2) self.play(ReplacementTransform(question, answer)) self.wait(2) self.play(Write(inner_r)) self.wait(2) class AskAboutHigherDimensions(TeacherStudentsScene): def construct(self): self.teacher_says( "What happens for \\\\ higher dimensions?" ) self.play_student_changes(*["pondering"]*3) self.wait(2) self.student_thinks( "$\\sqrt{N} - 1$", target_mode = "happy", index = 1 ) self.wait() pi = self.students[1] self.play(pi.change, "confused", pi.bubble) self.wait(3) class TenSliders(SliderScene): CONFIG = { "n_sliders" : 10, "run_time": 30, "slider_spacing" : 0.75, "ambient_acceleration_magnitude" : 2.0, } def construct(self): self.initialize_ambiant_slider_movement() self.wait(self.run_time) self.wind_down_ambient_movement() class TwoDBoxWithSliders(TwoDimensionalCase): CONFIG = { "slider_config" : { "include_real_estate_ticks" : True, "tick_frequency" : 1, "numbers_with_elongated_ticks" : [], "tick_size" : 0.1, "dial_color" : YELLOW, "x_min" : -2, "x_max" : 2, "unit_size" : 1.5, }, "center_point" : [1, -1], } def setup(self): TwoDimensionalCase.setup(self) ##Correct from previous setup self.remove(self.equation) self.sliders.shift(RIGHT) VGroup(*self.get_top_level_mobjects()).shift(RIGHT) x_slider = self.sliders[0] for number in x_slider.numbers: value = int(number.get_tex()) number.next_to( x_slider.number_to_point(value), LEFT, MED_SMALL_BUFF ) self.plane.axes.set_color(BLUE) ##Add box material corner_circles = VGroup(*[ self.circle.copy().move_to( self.plane.coords_to_point(*coords) ).set_color(GREY) for coords in ((1, 1), (-1, 1), (-1, -1)) ]) line = Line( self.plane.coords_to_point(-1, -1), self.plane.coords_to_point(1, 1), ) box = Square(color = RED) box.replace(line, stretch = True) self.add(box, corner_circles) self.box = box self.corner_circles = corner_circles def construct(self): self.ask_about_off_center_circle() self.recenter_circle() self.write_x_and_y_real_estate() self.swap_with_top_right_circle() self.show_center_circle() self.describe_tangent_point() self.perterb_point() self.wander_on_inner_circle() self.ask_about_inner_real_estate() def ask_about_off_center_circle(self): question = OldTexText("Off-center circles?") question.next_to(self.plane, UP) self.initialize_ambiant_slider_movement() self.play(Write(question)) self.wait(4) self.wind_down_ambient_movement() self.question = question def recenter_circle(self): original_center_point = self.center_point self.play( self.circle.move_to, self.plane.coords_to_point(0, 0), Animation(self.sliders), *[ ApplyMethod( mob.shift, slider.number_to_point(0)-slider.number_to_point(slider.center_value) ) for slider in self.sliders for mob in [slider.real_estate_ticks, slider.dial] ] ) self.center_point = [0, 0] for x, slider in zip(self.center_point, self.sliders): slider.center_value = x self.initialize_ambiant_slider_movement() self.wait(7) self.wind_down_ambient_movement() self.play( self.circle.move_to, self.plane.coords_to_point(*original_center_point), Animation(self.sliders), *[ ApplyMethod( mob.shift, slider.number_to_point(x)-slider.number_to_point(0) ) for x, slider in zip(original_center_point, self.sliders) for mob in [slider.real_estate_ticks, slider.dial] ] ) self.center_point = original_center_point for x, slider in zip(self.center_point, self.sliders): slider.center_value = x self.initialize_ambiant_slider_movement() self.wait(5) def write_x_and_y_real_estate(self): phrases = VGroup( OldTexText("$x$", "real estate:", "$(x-1)^2$"), OldTexText("$y$", "real estate:", "$(y+1)^2$"), ) phrases.next_to(self.plane, UP) phrases[0].set_color_by_tex("x", GREEN) phrases[1].set_color_by_tex("y", RED) x_brace, y_brace = [ Brace(slider.real_estate_ticks, RIGHT) for slider in self.sliders ] x_brace.set_color(GREEN) y_brace.set_color(RED) self.play(FadeOut(self.question)) self.play( Write(phrases[0]), GrowFromCenter(x_brace) ) self.wait(3) self.play( Transform(*phrases), Transform(x_brace, y_brace) ) self.wait(5) self.wind_down_ambient_movement(wait = False) self.play(*list(map(FadeOut, [x_brace, phrases[0]]))) def swap_with_top_right_circle(self): alt_circle = self.corner_circles[0] slider = self.sliders[1] self.play( self.circle.move_to, alt_circle, alt_circle.move_to, self.circle, Animation(slider), *[ ApplyMethod( mob.shift, slider.number_to_point(1) - slider.number_to_point(-1) ) for mob in (slider.real_estate_ticks, slider.dial) ] ) slider.center_value = 1 self.center_point[1] = 1 self.initialize_ambiant_slider_movement() self.wait(3) def show_center_circle(self): origin = self.plane.coords_to_point(0, 0) radius = get_norm( self.plane.coords_to_point(np.sqrt(2)-1, 0) - origin ) circle = Circle(radius = radius, color = GREEN) circle.move_to(origin) self.play(FocusOn(circle)) self.play(GrowFromCenter(circle, run_time = 2)) self.wait(3) def describe_tangent_point(self): target_vector = np.array([ 1-np.sqrt(2)/2, 1-np.sqrt(2)/2 ]) point = self.plane.coords_to_point(*target_vector) origin = self.plane.coords_to_point(0, 0) h_line = Line(point[1]*UP + origin[0]*RIGHT, point) v_line = Line(point[0]*RIGHT+origin[1]*UP, point) while get_norm(self.get_vector()-target_vector) > 0.5: self.wait() self.wind_down_ambient_movement(0) self.reset_dials(target_vector) self.play(*list(map(ShowCreation, [h_line, v_line]))) self.wait() re_line = DashedLine( self.sliders[0].dial.get_left() + MED_SMALL_BUFF*LEFT, self.sliders[1].dial.get_right() + MED_SMALL_BUFF*RIGHT, ) words = OldTexText("Evenly shared \\\\ real estate") words.scale(0.8) words.next_to(re_line, RIGHT) self.play(ShowCreation(re_line)) self.play(Write(words)) self.wait() self.evenly_shared_words = words self.re_line = re_line def perterb_point(self): #Perturb dials target_vector = np.array([ 1 - np.sqrt(0.7), 1 - np.sqrt(0.3), ]) ghost_dials = VGroup(*[ slider.dial.copy() for slider in self.sliders ]) ghost_dials.set_fill(WHITE, opacity = 0.75) self.add_foreground_mobjects(ghost_dials) self.reset_dials(target_vector) self.wait() #Comment on real estate exchange x_words = OldTexText("Gain expensive \\\\", "real estate") y_words = OldTexText("Give up cheap \\\\", "real estate") VGroup(x_words, y_words).scale(0.8) x_words.next_to(self.re_line, UP+LEFT) x_words.shift(SMALL_BUFF*(DOWN+LEFT)) y_words.next_to(self.re_line, UP+RIGHT) y_words.shift(MED_LARGE_BUFF*UP) x_arrow, y_arrow = [ Arrow( words[1].get_edge_center(vect), self.sliders[i].dial, tip_length = 0.15, ) for i, words, vect in zip( (0, 1), [x_words, y_words], [RIGHT, LEFT] ) ] self.play( Write(x_words, run_time = 2), ShowCreation(x_arrow) ) self.wait() self.play(FadeOut(self.evenly_shared_words)) self.play( Write(y_words, run_time = 2), ShowCreation(y_arrow) ) self.wait(2) #Swap perspective word_starts = VGroup(y_words[0], x_words[0]) crosses = VGroup() new_words = VGroup() for w1, w2 in zip(word_starts, reversed(word_starts)): crosses.add(Cross(w1)) w1_copy = w1.copy() w1_copy.generate_target() w1_copy.target.next_to(w2, UP, SMALL_BUFF) new_words.add(w1_copy) self.play(*[ ApplyMethod( slider.real_estate_ticks.shift, slider.number_to_point(0)-slider.number_to_point(1) ) for slider in self.sliders ]) self.wait() self.play(ShowCreation(crosses)) self.play( LaggedStartMap(MoveToTarget, new_words), Animation(crosses) ) self.wait(3) #Return to original position target_vector = np.array(2*[1-np.sqrt(0.5)]) self.play(LaggedStartMap(FadeOut, VGroup(*[ ghost_dials, x_words, y_words, x_arrow, y_arrow, crosses, new_words, ]))) self.remove_foreground_mobjects(ghost_dials) self.reset_dials(target_vector) self.center_point = np.zeros(2) for x, slider in zip(self.center_point, self.sliders): slider.center_value = x self.set_to_vector(target_vector) self.total_real_estate = self.get_current_total_real_estate() self.wait(2) def wander_on_inner_circle(self): self.initialize_ambiant_slider_movement() self.wait(9) def ask_about_inner_real_estate(self): question = OldTexText("What is \\\\ $x^2 + y^2$?") question.next_to(self.re_line, RIGHT) rhs = OldTex("<0.5^2 + 0.5^2") rhs.scale(0.8) rhs.next_to(question, DOWN) rhs.to_edge(RIGHT) half_line = Line(*[ slider.number_to_point(0.5) + MED_LARGE_BUFF*vect for slider, vect in zip(self.sliders, [LEFT, RIGHT]) ]) half = OldTex("0.5") half.scale(self.sliders[0].number_scale_val) half.next_to(half_line, LEFT, SMALL_BUFF) target_vector = np.array(2*[1-np.sqrt(0.5)]) while get_norm(target_vector - self.get_vector()) > 0.5: self.wait() self.wind_down_ambient_movement(0) self.reset_dials(target_vector) self.play(Write(question)) self.wait(3) self.play( ShowCreation(half_line), Write(half) ) self.wait() self.play(Write(rhs)) self.wait(3) class AskWhy(TeacherStudentsScene): def construct(self): self.student_says( "Wait, why?", target_mode = "confused" ) self.wait(3) class MentionComparisonToZeroPointFive(TeacherStudentsScene): def construct(self): self.teacher_says( "Comparing to $0.5$ will \\\\"+\ "be surprisingly useful!", target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.wait(3) class ThreeDBoxExampleWithSliders(SliderScene): CONFIG = { "n_sliders" : 3, "slider_config" : { "x_min" : -2, "x_max" : 2, "unit_size" : 1.5, }, "center_point" : np.ones(3), } def setup(self): SliderScene.setup(self) self.sliders.shift(2*RIGHT) def construct(self): self.initialize_ambiant_slider_movement() self.name_corner_sphere() self.point_out_closest_point() self.compare_to_halfway_point() self.reframe_as_inner_sphere_point() self.place_bound_on_inner_real_estate() self.comment_on_inner_sphere_smallness() def name_corner_sphere(self): sphere_name = OldTexText( """Sphere with radius 1\\\\ centered at (1, 1, 1)""" ) sphere_name.to_corner(UP+LEFT) arrow = Arrow( sphere_name, VGroup(*self.sliders[0].numbers[-2:]), color = BLUE ) self.play( LaggedStartMap(FadeIn, sphere_name,), ShowCreation(arrow, rate_func = squish_rate_func(smooth, 0.7, 1)), run_time = 3 ) self.wait(5) self.sphere_name = sphere_name self.arrow = arrow def point_out_closest_point(self): target_x = 1-np.sqrt(1./3) target_vector = np.array(3*[target_x]) re_words = OldTexText( "$x$, $y$ and $z$ each have \\\\", "$\\frac{1}{3}$", "units of real estate" ) re_words.to_corner(UP+LEFT) re_line = DashedLine(*[ self.sliders[i].number_to_point(target_x) + MED_SMALL_BUFF*vect for i, vect in [(0, LEFT), (2, RIGHT)] ]) new_arrow = Arrow( re_words.get_corner(DOWN+RIGHT), re_line.get_left(), color = BLUE ) self.wind_down_ambient_movement() self.play(*[ ApplyMethod(slider.set_value, x) for x, slider in zip(target_vector, self.sliders) ]) self.play(ShowCreation(re_line)) self.play( FadeOut(self.sphere_name), Transform(self.arrow, new_arrow), ) self.play(LaggedStartMap(FadeIn, re_words)) self.wait(2) self.re_words = re_words self.re_line = re_line def compare_to_halfway_point(self): half_line = Line(*[ self.sliders[i].number_to_point(0.5)+MED_SMALL_BUFF*vect for i, vect in [(0, LEFT), (2, RIGHT)] ]) half_line.set_stroke(MAROON_B, 6) half_label = OldTex("0.5") half_label.scale(self.sliders[0].number_scale_val) half_label.next_to(half_line, LEFT, MED_SMALL_BUFF) half_label.set_color(half_line.get_color()) curr_vector = self.get_vector() target_vector = 0.5*np.ones(3) ghost_dials = VGroup(*[ slider.dial.copy().set_fill(WHITE, 0.5) for slider in self.sliders ]) cross = Cross(self.re_words.get_parts_by_tex("frac")) new_re = OldTex("(0.5)^2 = 0.25") new_re.next_to(cross, DOWN, MED_SMALL_BUFF, LEFT) new_re.set_color(MAROON_B) self.play( FadeOut(self.arrow), Write(half_label, run_time = 1), ShowCreation(half_line) ) self.wait() self.add(ghost_dials) self.play(*[ ApplyMethod(slider.set_value, 0.5) for slider in self.sliders ]) self.play(ShowCreation(cross)) self.play(Write(new_re)) self.wait(3) self.play( FadeOut(new_re), FadeOut(cross), *[ ApplyMethod(slider.set_value, x) for x, slider in zip(curr_vector, self.sliders) ] ) def reframe_as_inner_sphere_point(self): s = self.sliders[0] shift_vect = s.number_to_point(0)-s.number_to_point(1) curr_vector = self.get_vector() self.set_center_point(np.zeros(3)) self.set_to_vector(curr_vector) self.total_real_estate = self.get_current_total_real_estate() all_re_ticks = VGroup(*[ slider.real_estate_ticks for slider in self.sliders ]) inner_sphere_words = OldTexText( "Also a point on \\\\", "the inner sphere" ) inner_sphere_words.next_to(self.re_line, RIGHT) question = OldTexText("How much \\\\", "real estate?") question.next_to(self.re_line, RIGHT, MED_LARGE_BUFF) self.play( Animation(self.sliders), FadeOut(self.re_words), LaggedStartMap( ApplyMethod, all_re_ticks, lambda m : (m.shift, shift_vect) ) ) self.initialize_ambiant_slider_movement() self.play(Write(inner_sphere_words)) self.wait(5) self.wind_down_ambient_movement(0) self.play(*[ ApplyMethod(slider.set_value, x) for slider, x in zip(self.sliders, curr_vector) ]) self.play(ReplacementTransform( inner_sphere_words, question )) self.wait(2) self.re_question = question def place_bound_on_inner_real_estate(self): bound = OldTex( "&< 3(0.5)^2 ", "= 0.75" ) bound.next_to(self.re_question, DOWN) bound.to_edge(RIGHT) self.play(Write(bound)) self.wait(2) def comment_on_inner_sphere_smallness(self): self.initialize_ambiant_slider_movement() self.wait(15) class Rotating3DCornerSphere(ExternallyAnimatedScene): pass class FourDBoxExampleWithSliders(ThreeDBoxExampleWithSliders): CONFIG = { "n_sliders" : 4, "center_point" : np.ones(4), } def construct(self): self.list_corner_coordinates() self.show_16_corner_spheres() self.show_closest_point() self.show_real_estate_at_closest_point() self.reframe_as_inner_sphere_point() self.compute_inner_radius_numerically() self.inner_sphere_touches_box() def list_corner_coordinates(self): title = OldTexText( "$2 \\!\\times\\! 2 \\!\\times\\! 2 \\!\\times\\! 2$ box vertices:" ) title.shift(FRAME_X_RADIUS*LEFT/2) title.to_edge(UP) coordinates = list(it.product(*4*[[1, -1]])) coordinate_mobs = VGroup(*[ OldTex("(%d, %d, %d, %d)"%tup) for tup in coordinates ]) coordinate_mobs.arrange(DOWN, aligned_edge = LEFT) coordinate_mobs.scale(0.8) left_column = VGroup(*coordinate_mobs[:8]) right_column = VGroup(*coordinate_mobs[8:]) right_column.next_to(left_column, RIGHT) coordinate_mobs.next_to(title, DOWN) self.play(Write(title)) self.play(LaggedStartMap(FadeIn, coordinate_mobs)) self.wait() self.coordinate_mobs = coordinate_mobs self.coordinates = coordinates self.box_vertices_title = title def show_16_corner_spheres(self): sphere_words = VGroup(OldTexText("Sphere centered at")) sphere_words.scale(0.8) sphere_words.next_to(self.sliders, RIGHT) sphere_words.shift(2*UP) self.add(sphere_words) pairs = list(zip(self.coordinate_mobs, self.coordinates)) for coord_mob, coords in pairs[1:] + [pairs[0]]: coord_mob.set_color(GREEN) coord_mob_copy = coord_mob.copy() coord_mob_copy.next_to(sphere_words, DOWN) for slider, x in zip(self.sliders, coords): point = slider.number_to_point(x) slider.real_estate_ticks.move_to(point) slider.dial.move_to(point) self.sliders[0].dial.move_to( self.sliders[0].number_to_point(coords[0]+1) ) self.add(coord_mob_copy) self.wait() self.remove(coord_mob_copy) coord_mob.set_color(WHITE) self.add(coord_mob_copy) sphere_words.add(coord_mob_copy) self.sphere_words = sphere_words self.play( self.sliders.center, sphere_words.shift, LEFT, *list(map(FadeOut, [ self.coordinate_mobs, self.box_vertices_title ])) ) self.initialize_ambiant_slider_movement() self.wait(4) def show_closest_point(self): target_vector = 0.5*np.ones(4) re_line = DashedLine(*[ self.sliders[i].number_to_point(0.5)+MED_SMALL_BUFF*vect for i, vect in [(0, LEFT), (-1, RIGHT)] ]) half_label = OldTex("0.5") half_label.scale(self.sliders[0].number_scale_val) half_label.next_to(re_line, LEFT, MED_SMALL_BUFF) half_label.set_color(MAROON_B) self.wind_down_ambient_movement() self.play(*[ ApplyMethod(slider.set_value, x) for x, slider in zip(target_vector, self.sliders) ]) self.play(ShowCreation(re_line)) self.play(Write(half_label)) self.wait(2) self.re_line = re_line self.half_label = half_label def show_real_estate_at_closest_point(self): words = OldTexText("Total real estate:") value = OldTex("4(0.5)^2 = 4(0.25) = 1") value.next_to(words, DOWN) re_words = VGroup(words, value) re_words.scale(0.8) re_words.next_to(self.sphere_words, DOWN, MED_LARGE_BUFF) re_rects = VGroup() for slider in self.sliders: rect = Rectangle( width = 2*slider.tick_size, height = 0.5*slider.unit_size, stroke_width = 0, fill_color = MAROON_B, fill_opacity = 0.75, ) rect.move_to(slider.number_to_point(0.75)) re_rects.add(rect) self.play(FadeIn(re_words)) self.play(LaggedStartMap(DrawBorderThenFill, re_rects, run_time = 3)) self.wait(2) self.re_words = re_words self.re_rects = re_rects def reframe_as_inner_sphere_point(self): sphere_words = self.sphere_words sphere_words.generate_target() sphere_words.target.shift(2*DOWN) old_coords = sphere_words.target[1] new_coords = OldTex("(0, 0, 0, 0)") new_coords.replace(old_coords, dim_to_match = 1) new_coords.set_color(old_coords.get_color()) Transform(old_coords, new_coords).update(1) self.play(Animation(self.sliders), *[ ApplyMethod( s.real_estate_ticks.move_to, s.number_to_point(0), run_time = 2, rate_func = squish_rate_func(smooth, a, a+0.5) ) for s, a in zip(self.sliders, np.linspace(0, 0.5, 4)) ]) self.play( MoveToTarget(sphere_words), self.re_words.next_to, sphere_words.target, UP, MED_LARGE_BUFF, path_arc = np.pi ) self.wait(2) re_shift_vect = 0.5*self.sliders[0].unit_size*DOWN self.play(LaggedStartMap( ApplyMethod, self.re_rects, lambda m : (m.shift, re_shift_vect), path_arc = np.pi )) self.wait() re_words_rect = SurroundingRectangle(self.re_words) self.play(ShowCreation(re_words_rect)) self.wait() self.play(FadeOut(re_words_rect)) self.wait() self.set_center_point(np.zeros(4)) self.initialize_ambiant_slider_movement() self.wait(4) def compute_inner_radius_numerically(self): computation = OldTex( "R_\\text{Inner}", "&= ||(1, 1, 1, 1)|| - 1 \\\\", # "&= \\sqrt{1^2 + 1^2 + 1^2 + 1^2} - 1 \\\\", "&= \\sqrt{4} - 1 \\\\", "&= 1" ) computation.scale(0.8) computation.to_corner(UP+LEFT) computation.shift(DOWN) brace = Brace(VGroup(*computation[1][1:-2]), UP) brace_text = brace.get_text("Distance to corner") brace_text.scale(0.8, about_point = brace_text.get_bottom()) VGroup(brace, brace_text).set_color(RED) self.play(LaggedStartMap(FadeIn, computation, run_time = 3)) self.play(GrowFromCenter(brace)) self.play(Write(brace_text, run_time = 2)) self.wait(16) computation.add(brace, brace_text) self.computation = computation def inner_sphere_touches_box(self): touching_words = OldTexText( "This point touches\\\\", "the $2 \\!\\times\\! 2 \\!\\times\\! 2 \\!\\times\\! 2$ box!" ) touching_words.to_corner(UP+LEFT) arrow = Arrow(MED_SMALL_BUFF*DOWN, 3*RIGHT+DOWN) arrow.set_color(BLUE) arrow.shift(touching_words.get_bottom()) self.wind_down_ambient_movement(wait = False) self.play(FadeOut(self.computation)) self.reset_dials([1]) self.play(Write(touching_words)) self.play(ShowCreation(arrow)) self.wait(2) class TwoDInnerSphereTouchingBox(TwoDBoxWithSliders, PiCreatureScene): def setup(self): TwoDBoxWithSliders.setup(self) PiCreatureScene.setup(self) self.remove(self.sliders) self.remove(self.dot) self.circle.set_color(GREY) self.randy.next_to(self.plane, RIGHT, LARGE_BUFF, DOWN) def construct(self): little_inner_circle, big_inner_circle = [ Circle( radius = radius*self.plane.x_unit_size, color = GREEN ).move_to(self.plane.coords_to_point(0, 0)) for radius in (np.sqrt(2)-1, 1) ] randy = self.randy tangency_points = VGroup(*[ Dot(self.plane.coords_to_point(x, y)) for x, y in [(1, 0), (0, 1), (-1, 0), (0, -1)] ]) tangency_points.set_fill(YELLOW, 0.5) self.play( ShowCreation(little_inner_circle), randy.change, "pondering", little_inner_circle ) self.wait() self.play( ReplacementTransform( little_inner_circle.copy(), big_inner_circle ), little_inner_circle.fade, randy.change, "confused" ) big_inner_circle.save_state() self.play(big_inner_circle.move_to, self.circle) self.play(big_inner_circle.restore) self.wait() self.play(LaggedStartMap( DrawBorderThenFill, tangency_points, rate_func = double_smooth )) self.play(randy.change, "maybe") self.play(randy.look_at, self.circle) self.wait() self.play(randy.look_at, little_inner_circle) self.wait() #### def create_pi_creature(self): self.randy = Randolph().flip() return self.randy class FiveDBoxExampleWithSliders(FourDBoxExampleWithSliders): CONFIG = { "n_sliders" : 5, "center_point" : np.ones(5), } def setup(self): FourDBoxExampleWithSliders.setup(self) self.sliders.center() def construct(self): self.show_32_corner_spheres() self.show_closest_point() self.show_halfway_point() self.reframe_as_inner_sphere_point() self.compute_radius() self.poke_out_of_box() def show_32_corner_spheres(self): sphere_words = VGroup(OldTexText("Sphere centered at")) sphere_words.next_to(self.sliders, RIGHT, MED_LARGE_BUFF) sphere_words.shift(2.5*UP) self.add(sphere_words) n_sphere_words = OldTexText("32 corner spheres") n_sphere_words.to_edge(LEFT) n_sphere_words.shift(2*UP) self.add(n_sphere_words) for coords in it.product(*5*[[-1, 1]]): s = str(tuple(coords)) s = s.replace("1", "+1") s = s.replace("-+1", "-1") coords_mob = OldTex(s) coords_mob.set_color(GREEN) coords_mob.next_to(sphere_words, DOWN) for slider, x in zip(self.sliders, coords): for mob in slider.real_estate_ticks, slider.dial: mob.move_to(slider.number_to_point(x)) self.sliders[0].dial.move_to( self.sliders[0].number_to_point(coords[0]+1) ) self.add(coords_mob) self.wait(0.25) self.remove(coords_mob) self.add(coords_mob) sphere_words.add(coords_mob) self.sphere_words = sphere_words self.initialize_ambiant_slider_movement() self.play(FadeOut(n_sphere_words)) self.wait(3) def show_closest_point(self): target_x = 1-np.sqrt(0.2) re_line = DashedLine(*[ self.sliders[i].number_to_point(target_x)+MED_SMALL_BUFF*vect for i, vect in [(0, LEFT), (-1, RIGHT)] ]) re_words = OldTexText( "$0.2$", "units of real \\\\ estate each" ) re_words.next_to(self.sphere_words, DOWN, MED_LARGE_BUFF) re_rects = VGroup() for slider in self.sliders: rect = Rectangle( width = 2*slider.tick_size, height = (1-target_x)*slider.unit_size, stroke_width = 0, fill_color = GREEN, fill_opacity = 0.75, ) rect.move_to(slider.number_to_point(1), UP) re_rects.add(rect) self.wind_down_ambient_movement() self.reset_dials(5*[target_x]) self.play( ShowCreation(re_line), Write(re_words, run_time = 2) ) self.play(LaggedStartMap( DrawBorderThenFill, re_rects, rate_func = double_smooth )) self.wait() self.re_rects = re_rects self.re_words = re_words self.re_line = re_line def show_halfway_point(self): half_line = Line(*[ self.sliders[i].number_to_point(0.5)+MED_SMALL_BUFF*vect for i, vect in [(0, LEFT), (-1, RIGHT)] ]) half_line.set_color(MAROON_B) half_label = OldTex("0.5") half_label.scale(self.sliders[0].number_scale_val) half_label.next_to(half_line, LEFT, MED_SMALL_BUFF) half_label.set_color(half_line.get_color()) curr_vector = self.get_vector() ghost_dials = VGroup(*[ slider.dial.copy().set_fill(WHITE, 0.75) for slider in self.sliders ]) point_25 = OldTex("0.25") point_25.set_color(half_label.get_color()) point_25.move_to(self.re_words[0], RIGHT) self.re_words.save_state() self.play( Write(half_label), ShowCreation(half_line) ) self.wait(2) self.add(ghost_dials) self.play(*[ ApplyMethod(slider.set_value, 0.5) for slider in self.sliders ]) self.play(Transform(self.re_words[0], point_25)) self.wait(2) self.play(*[ ApplyMethod(slider.set_value, x) for x, slider in zip(curr_vector, self.sliders) ]) self.play(self.re_words.restore) def reframe_as_inner_sphere_point(self): s = self.sliders[0] shift_vect = s.number_to_point(0)-s.number_to_point(1) re_ticks = VGroup(*[ slider.real_estate_ticks for slider in self.sliders ]) re_rects = self.re_rects re_rects.generate_target() for rect, slider in zip(re_rects.target, self.sliders): height = slider.unit_size*(1-np.sqrt(0.2)) rect.set_height(height) rect.move_to(slider.number_to_point(0), DOWN) self.sphere_words.generate_target() old_coords = self.sphere_words.target[1] new_coords = OldTex(str(tuple(5*[0]))) new_coords.replace(old_coords, dim_to_match = 1) new_coords.set_color(old_coords.get_color()) Transform(old_coords, new_coords).update(1) self.re_words.generate_target() new_re = OldTex("0.31") new_re.set_color(GREEN) old_re = self.re_words.target[0] new_re.move_to(old_re, RIGHT) Transform(old_re, new_re).update(1) self.play( Animation(self.sliders), LaggedStartMap( ApplyMethod, re_ticks, lambda m : (m.shift, shift_vect), path_arc = np.pi ), MoveToTarget(self.sphere_words), ) self.play( MoveToTarget( re_rects, run_time = 2, lag_ratio = 0.5, path_arc = np.pi ), MoveToTarget(self.re_words), ) self.wait(2) self.set_center_point(np.zeros(5)) self.total_real_estate = (np.sqrt(5)-1)**2 self.initialize_ambiant_slider_movement() self.wait(12) def compute_radius(self): computation = OldTex( "R_{\\text{inner}} &= \\sqrt{5}-1 \\\\", "&\\approx 1.24" ) computation.to_corner(UP+LEFT) self.play(Write(computation, run_time = 2)) self.wait(12) def poke_out_of_box(self): self.wind_down_ambient_movement(0) self.reset_dials([np.sqrt(5)-1]) words = OldTexText("Poking outside \\\\ the box!") words.to_edge(LEFT) words.set_color(RED) arrow = Arrow( words.get_top(), self.sliders[0].dial, path_arc = -np.pi/3, color = words.get_color() ) self.play( ShowCreation(arrow), Write(words) ) self.wait(2) class SkipAheadTo10(TeacherStudentsScene): def construct(self): self.teacher_says( "Let's skip ahead \\\\ to 10 dimensions", target_mode = "hooray" ) self.play_student_changes( "pleading", "confused", "horrified" ) self.wait(3) class TenDBoxExampleWithSliders(FiveDBoxExampleWithSliders): CONFIG = { "n_sliders" : 10, "center_point" : np.ones(10), "ambient_velocity_magnitude" : 2.0, "ambient_acceleration_magnitude" : 3.0, } def setup(self): FourDBoxExampleWithSliders.setup(self) self.sliders.to_edge(RIGHT) def construct(self): self.initial_wandering() self.show_closest_point() self.reframe_as_inner_sphere_point() self.compute_inner_radius_numerically() self.wander_on_inner_sphere() self.poke_outside_outer_box() def initial_wandering(self): self.initialize_ambiant_slider_movement() self.wait(9) def show_closest_point(self): target_x = 1-np.sqrt(1./self.n_sliders) re_line = DashedLine(*[ self.sliders[i].number_to_point(target_x)+MED_SMALL_BUFF*vect for i, vect in [(0, LEFT), (-1, RIGHT)] ]) re_rects = VGroup() for slider in self.sliders: rect = Rectangle( width = 2*slider.tick_size, height = (1-target_x)*slider.unit_size, stroke_width = 0, fill_color = GREEN, fill_opacity = 0.75, ) rect.move_to(slider.number_to_point(1), UP) re_rects.add(rect) self.wind_down_ambient_movement() self.reset_dials(self.n_sliders*[target_x]) self.play(ShowCreation(re_line)) self.play(LaggedStartMap( DrawBorderThenFill, re_rects, rate_func = double_smooth )) self.wait(2) self.re_line = re_line self.re_rects = re_rects def reframe_as_inner_sphere_point(self): s = self.sliders[0] shift_vect = s.number_to_point(0)-s.number_to_point(1) re_ticks = VGroup(*[ slider.real_estate_ticks for slider in self.sliders ]) re_rects = self.re_rects re_rects.generate_target() for rect, slider in zip(re_rects.target, self.sliders): height = slider.unit_size*(1-np.sqrt(1./self.n_sliders)) rect.stretch_to_fit_height(height) rect.move_to(slider.number_to_point(0), DOWN) self.play( Animation(self.sliders), LaggedStartMap( ApplyMethod, re_ticks, lambda m : (m.shift, shift_vect), path_arc = np.pi ), ) self.play( MoveToTarget( re_rects, run_time = 2, lag_ratio = 0.5, path_arc = np.pi ), ) self.wait(2) self.set_center_point(np.zeros(self.n_sliders)) self.total_real_estate = (np.sqrt(self.n_sliders)-1)**2 self.initialize_ambiant_slider_movement() self.wait(5) def compute_inner_radius_numerically(self): computation = OldTex( "R_{\\text{inner}} &= \\sqrt{10}-1 \\\\", "&\\approx 2.16" ) computation.to_corner(UP+LEFT) self.play(Write(computation, run_time = 2)) def wander_on_inner_sphere(self): self.wait(10) def poke_outside_outer_box(self): self.wind_down_ambient_movement() self.reset_dials([np.sqrt(10)-1]) words = OldTexText( "Outside the \\emph{outer} \\\\", "bounding box!" ) words.to_edge(LEFT) words.set_color(RED) arrow = Arrow( words.get_top(), self.sliders[0].dial, path_arc = -np.pi/3, color = words.get_color() ) self.play( Write(words, run_time = 2), ShowCreation(arrow) ) self.wait(3) class TwoDOuterBox(TwoDInnerSphereTouchingBox): def construct(self): words = OldTexText("$4 \\!\\times\\! 4$ outer bounding box") words.next_to(self.plane, UP) words.set_color(MAROON_B) line = Line( self.plane.coords_to_point(-2, -2), self.plane.coords_to_point(2, 2), ) box = Square(color = words.get_color()) box.replace(line, stretch = True) box.set_stroke(width = 8) self.play( Write(words), ShowCreation(box), self.randy.change, "pondering", ) self.wait(3) self.outer_box = box class ThreeDOuterBoundingBox(ExternallyAnimatedScene): pass class ThreeDOuterBoundingBoxWords(Scene): def construct(self): words = OldTexText( "$4 \\!\\times\\! 4\\!\\times\\! 4$ outer\\\\", "bounding box" ) words.set_width(FRAME_WIDTH-1) words.to_edge(DOWN) words.set_color(MAROON_B) self.play(Write(words)) self.wait(4) class FaceDistanceDoesntDependOnDimension(TwoDOuterBox): def construct(self): self.force_skipping() TwoDOuterBox.construct(self) self.randy.change("confused") self.revert_to_original_skipping_status() line = Line( self.plane.coords_to_point(0, 0), self.outer_box.get_right(), buff = 0, stroke_width = 6, color = YELLOW ) length_words = OldTexText("Always 2, in all dimensions") length_words.next_to(self.plane, RIGHT, MED_LARGE_BUFF, UP) arrow = Arrow(length_words[4].get_bottom(), line.get_center()) self.play(ShowCreation(line)) self.play( Write(length_words), ShowCreation(arrow) ) self.play(self.randy.change, "thinking") self.wait(3) class TenDCornerIsVeryFarAway(TenDBoxExampleWithSliders): CONFIG = { "center_point" : np.zeros(10) } def construct(self): self.show_re_rects() def show_re_rects(self): re_rects = VGroup() for slider in self.sliders: rect = Rectangle( width = 2*slider.tick_size, height = slider.unit_size, stroke_width = 0, fill_color = GREEN, fill_opacity = 0.75, ) rect.move_to(slider.number_to_point(0), DOWN) re_rects.add(rect) rect.save_state() rect.stretch_to_fit_height(0) rect.move_to(rect.saved_state, DOWN) self.set_to_vector(np.zeros(10)) self.play( LaggedStartMap( ApplyMethod, re_rects, lambda m : (m.restore,), lag_ratio = 0.3, ), LaggedStartMap( ApplyMethod, self.sliders, lambda m : (m.set_value, 1), lag_ratio = 0.3, ), run_time = 10, ) self.wait() class InnerRadiusIsUnbounded(TeacherStudentsScene): def construct(self): self.teacher_says("Inner radius \\\\ is unbounded") self.play_student_changes(*["erm"]*3) self.wait(3) class ProportionOfSphereInBox(GraphScene): CONFIG = { "x_axis_label" : "Dimension", "y_axis_label" : "", "y_max" : 1.5, "y_min" : 0, "y_tick_frequency" : 0.25, "y_labeled_nums" : np.linspace(0.25, 1, 4), "x_min" : 0, "x_max" : 50, "x_tick_frequency" : 5, "x_labeled_nums" : list(range(10, 50, 10)), "num_graph_anchor_points" : 100, } def construct(self): self.setup_axes() title = OldTexText( "Proportion of inner sphere \\\\ inside box" ) title.next_to(self.y_axis, RIGHT, MED_SMALL_BUFF, UP) self.add(title) graph = self.get_graph(lambda x : np.exp(0.1*(9-x))) max_y = self.coords_to_point(0, 1)[1] too_high = graph.get_points()[:,1] > max_y graph.get_points()[too_high, 1] = max_y footnote = OldTexText(""" \\begin{flushleft} *I may or may not have used an easy-to-compute \\\\ but not-totally-accurate curve here, due to \\\\ the surprising difficulty in computing the real \\\\ proportion :) \\end{flushleft} """,) footnote.scale(0.75) footnote.next_to( graph.point_from_proportion(0.3), UP+RIGHT, SMALL_BUFF ) footnote.set_color(YELLOW) self.play(ShowCreation(graph, run_time = 5, rate_func=linear)) self.wait() self.add(footnote) self.wait(0.25) class ShowingToFriend(PiCreatureScene, SliderScene): CONFIG = { "n_sliders" : 10, "ambient_acceleration_magnitude" : 3.0, "seconds_to_blink" : 4, } def setup(self): PiCreatureScene.setup(self) SliderScene.setup(self) self.sliders.scale(0.75) self.sliders.next_to( self.morty.get_corner(UP+LEFT), UP, MED_LARGE_BUFF ) self.initialize_ambiant_slider_movement() def construct(self): morty, randy = self.morty, self.randy self.play(morty.change, "raise_right_hand", self.sliders) self.play(randy.change, "happy", self.sliders) self.wait(7) self.play(randy.change, "skeptical", morty.eyes) self.wait(3) self.play(randy.change, "thinking", self.sliders) self.wait(6) ### def create_pi_creatures(self): self.morty = Mortimer() self.morty.to_edge(DOWN).shift(4*RIGHT) self.randy = Randolph() self.randy.to_edge(DOWN).shift(4*LEFT) return VGroup(self.morty, self.randy) def non_blink_wait(self, time = 1): SliderScene.wait(self, time) class QuestionsFromStudents(TeacherStudentsScene): def construct(self): self.student_says( "Is 10-dimensional \\\\ space real?", target_mode = "sassy", run_time = 2, ) self.wait() self.teacher_says( "No less real \\\\ than reals", target_mode = "shruggie", content_introduction_class = FadeIn, ) self.wait(2) self.student_says( "How do you think \\\\ about volume?", index = 0, content_introduction_class = FadeIn, ) self.wait() self.student_says( "How do cubes work?", index = 2, run_time = 2, ) self.wait(2) class FunHighDSpherePhenomena(Scene): def construct(self): title = OldTexText( "Fun high-D sphere phenomena" ) title.to_edge(UP) title.set_color(BLUE) h_line = Line(LEFT, RIGHT).scale(5) h_line.next_to(title, DOWN) self.add(title, h_line) items = VGroup(*list(map(TexText, [ "$\\cdot$ Most volume is near the equator", "$\\cdot$ Most volume is near the surface", "$\\cdot$ Sphere packing in 8 dimensions", "$\\cdot$ Sphere packing in 24 dimensions", ]))) items.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) items.next_to(h_line, DOWN) for item in items: self.play(LaggedStartMap(FadeIn, item, run_time = 2)) self.wait() class TODOBugOnSurface(TODOStub): CONFIG = { "message" : "Bug on surface" } class CoordinateFree(PiCreatureScene): def construct(self): plane = NumberPlane(x_radius = 2.5, y_radius = 2.5) plane.add_coordinates() plane.to_corner(UP+LEFT) self.add(plane) circles = VGroup(*[ Circle(color = YELLOW).move_to( plane.coords_to_point(*coords) ) for coords in it.product(*2*[[-1, 1]]) ]) inner_circle = Circle( radius = np.sqrt(2)-1, color = GREEN ).move_to(plane.coords_to_point(0, 0)) self.add_foreground_mobjects(circles, inner_circle) self.play(PiCreatureSays( self.pi_creature, "Lose the \\\\ coordinates!", target_mode = "hooray" )) self.play(FadeOut(plane, run_time = 2)) self.wait(3) class Skeptic(TeacherStudentsScene, SliderScene): def setup(self): SliderScene.setup(self) TeacherStudentsScene.setup(self) self.sliders.scale(0.7) self.sliders.next_to(self.teacher, UP, aligned_edge = LEFT) self.sliders.to_edge(UP) self.initialize_ambiant_slider_movement() def construct(self): analytic_thought = VGroup(OldTexText("No different from")) equation = OldTex( "x", "^2 + ", "y", "^2 + ", "z", "^2 + ", "w", "^2 = 1" ) variables = VGroup(*[ equation.get_part_by_tex(tex) for tex in "xyzw" ]) slider_labels = VGroup(*[ slider.label for slider in self.sliders ]) equation.next_to(analytic_thought, DOWN) analytic_thought.add(equation) all_real_estate_ticks = VGroup(*it.chain(*[ slider.real_estate_ticks for slider in self.sliders ])) box = Square(color = RED) box.next_to(self.sliders, LEFT) line = Line(box.get_center(), box.get_corner(UP+RIGHT)) line.set_color(YELLOW) self.student_says( analytic_thought, index = 0, target_mode = "sassy", added_anims = [self.teacher.change, "guilty"] ) self.wait(2) equation.remove(*variables) self.play(ReplacementTransform(variables, slider_labels)) self.play( self.teacher.change, "pondering", slider_labels, RemovePiCreatureBubble( self.students[0], target_mode = "hesitant" ), ) self.wait(4) bubble = self.teacher.get_bubble( "It's much \\\\ more playful!", bubble_type = SpeechBubble ) bubble.resize_to_content() VGroup(bubble, bubble.content).next_to(self.teacher, UP+LEFT) self.play( self.teacher.change, "hooray", ShowCreation(bubble), Write(bubble.content) ) self.wait(3) self.play( RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand", look_at = self.sliders ), *[ ApplyMethod(pi.change, "pondering") for pi in self.students ] ) self.play(Animation(self.sliders), LaggedStartMap( ApplyMethod, all_real_estate_ticks, lambda m : (m.shift, SMALL_BUFF*LEFT), rate_func = wiggle, lag_ratio = 0.3, run_time = 4, )) self.play( ShowCreation(box), self.teacher.change, "happy" ) self.play(ShowCreation(line)) self.wait(3) ##### def non_blink_wait(self, time = 1): SliderScene.wait(self, time) class ClipFrom4DBoxExampleTODO(TODOStub): CONFIG = { "message" : "Clip from 4d box example" } class JustBecauseYouCantVisualize(Scene): def construct(self): phrase = "\\raggedright " phrase += "Just because you can't visualize\\\\ " phrase += "something doesn't mean you can't\\\\ " phrase += "still think about it visually." phrase_mob = OldTexText(*phrase.split(" ")) phrase_mob.set_color_by_tex("visual", YELLOW) phrase_mob.next_to(ORIGIN, UP) for part in phrase_mob: self.play(LaggedStartMap( FadeIn, part, run_time = 0.05*len(part) )) self.wait(2) class Announcements(TeacherStudentsScene): def construct(self): title = OldTexText("Announcements") title.scale(1.5) title.to_edge(UP, buff = MED_SMALL_BUFF) h_line = Line(LEFT, RIGHT).scale(3) h_line.next_to(title, DOWN) self.add(title, h_line) items = VGroup(*list(map(TexText, [ "$\\cdot$ Where to learn more", "$\\cdot$ Q\\&A Followup (podcast!)", ]))) items.arrange(DOWN, aligned_edge = LEFT) items.next_to(h_line, DOWN) self.play( Write(items[0], run_time = 2), ) self.play(*[ ApplyMethod(pi.change, "hooray", items) for pi in self.pi_creatures ]) self.play(Write(items[1], run_time = 2)) self.wait(2) class Promotion(PiCreatureScene): CONFIG = { "seconds_to_blink" : 5, } def construct(self): url = OldTexText("https://brilliant.org/3b1b/") url.to_corner(UP+LEFT) rect = Rectangle(height = 9, width = 16) rect.set_height(5.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) self.play( Write(url), self.pi_creature.change, "raise_right_hand" ) self.play(ShowCreation(rect)) self.wait(2) self.change_mode("thinking") self.wait() self.look_at(url) self.wait(10) self.change_mode("happy") self.wait(10) self.change_mode("raise_right_hand") self.wait(10) self.remove(rect) self.play( url.next_to, self.pi_creature, UP+LEFT ) url_rect = SurroundingRectangle(url) self.play(ShowCreation(url_rect)) self.play(FadeOut(url_rect)) self.wait(3) class BrilliantGeometryQuiz(ExternallyAnimatedScene): pass class BrilliantScrollThroughCourses(ExternallyAnimatedScene): pass class Podcast(TeacherStudentsScene): def construct(self): title = OldTexText("Podcast!") title.scale(1.5) title.to_edge(UP) title.shift(FRAME_X_RADIUS*LEFT/2) self.add(title) q_and_a = OldTexText("Q\\&A Followup") q_and_a.next_to(self.teacher.get_corner(UP+LEFT), UP, LARGE_BUFF) self.play( LaggedStartMap( ApplyMethod, self.pi_creatures, lambda pi : (pi.change, "hooray", title) ), Write(title) ) self.wait(5) self.play( Write(q_and_a), self.teacher.change, "raise_right_hand", ) self.wait(4) class HighDPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Desmos", "Burt Humburg", "CrypticSwarm", "Juan Benet", "Ali Yahya", "William", "Mayank M. Mehrotra", "Lukas Biewald", "Samantha D. Suplee", "James Park", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "dave nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Corey Ogburn", "Ed Kellett", "Joseph John Cox", "Dan Buchoff", "Luc Ritchie", "Erik Sundell", "Xueqi Li", "David Stork", "Tianyu Ge", "Ted Suzman", "Amir Fayazi", "Linh Tran", "Andrew Busey", "Michael McGuffin", "John Haley", "Ankalagon", "Eric Lavault", "Tomohiro Furusawa", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class Thumbnail(SliderScene): CONFIG = { "n_sliders" : 10, } def construct(self): for slider in self.sliders: self.remove(slider.label) slider.remove(slider.label) vect = np.random.random(10) - 0.5 vect /= get_norm(vect) self.set_to_vector(vect) title = OldTexText("10D Sphere?") title.scale(2) title.to_edge(UP) self.add(title) class TenDThumbnail(Scene): def construct(self): square = Square() square.set_height(3.5) square.set_stroke(YELLOW, 5) r = square.get_width() / 2 circles = VGroup(*[ Circle(radius=r).move_to(corner) for corner in square.get_vertices() ]) circles.set_stroke(BLUE, 5) circles.set_fill(BLUE, 0.5) circles.set_sheen(0.5, UL) lil_circle = Circle( radius=(np.sqrt(2) - 1) * r ) lil_circle.set_stroke(YELLOW, 3) lil_circle.set_fill(YELLOW, 0.5) group = VGroup(circles, lil_circle, square) group.to_edge(LEFT) square.scale(2) words = OldTexText( "What\\\\" "about\\\\" "in 10D?\\\\" # "dimensions?" ) words.set_height(5) words.to_edge(RIGHT) arrow = Arrow( words[0][0].get_left(), lil_circle.get_center(), path_arc=90 * DEGREES, buff=0.5, ) arrow.set_color(RED) arrow.set_stroke(width=12) arrow_group = VGroup( arrow.copy().set_stroke(BLACK, 16), arrow, ) self.add(group) self.add(words) self.add(arrow_group)
videos_3b1b/_2017/qa_round_two.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from manim_imports_ext import * from _2017.efvgt import get_confetti_animations class Test(Scene): def construct(self): pass class Announcements(PiCreatureScene): def construct(self): title = OldTexText("Announcements!") title.scale(1.5) title.to_edge(UP) title.shift(LEFT) underline = Line(LEFT, RIGHT) underline.set_width(1.2*title.get_width()) underline.next_to(title, DOWN) announcements = VGroup(*[ OldTexText("$\\cdot$ %s"%s) for s in [ "Q\\&A Round 2", "The case against Net Neutrality?", ] ]) announcements.arrange( DOWN, buff = LARGE_BUFF, aligned_edge = LEFT, ) announcements.next_to(underline, DOWN, LARGE_BUFF, aligned_edge = LEFT) announcements.set_color_by_gradient(GREEN, YELLOW) self.play( Write(title), LaggedStartMap(FadeIn, announcements), ShowCreation(underline), self.pi_creature.change, "hooray", underline, ) self.play(self.pi_creature.change, "confused", announcements) self.wait(2) class PowersOfTwo(Scene): def construct(self): powers_of_2 = VGroup(*[ OldTex("2^{%d}"%n, "=", "{:,}".format(2**n)) for n in range(20) ]) powers_of_2.to_edge(UP) max_height = 6 center = MED_LARGE_BUFF*DOWN mob = Dot(color = BLUE) mob.move_to(center) vects = it.cycle(5*[UP] + 5*[RIGHT]) curr_po2 = powers_of_2[0] for i, vect, po2 in zip(it.count(), vects, powers_of_2[1:]): if i == 10: rect = SurroundingRectangle(mob, color = GREEN) group = VGroup(mob, rect) two_to_ten = group.copy() group.generate_target() group.target.set_height(0.2) group.target[1].set_fill(BLUE, 1) self.play(ShowCreation(rect)) self.play(MoveToTarget(group)) self.remove(group) mob = rect self.add(mob) m1, m2 = mob.copy(), mob.copy() group = VGroup(m1, m2) group.arrange( vect, buff = SMALL_BUFF ) if group.get_height() > max_height: group.set_height(max_height) group.move_to(center) pa = np.pi/3 self.play( Transform(curr_po2, po2), ReplacementTransform(mob, m1, path_arc = pa), ReplacementTransform(mob.copy(), m2, path_arc = pa), ) mob = VGroup(*it.chain(m1, m2)) #Show two_to_ten for comparrison self.play( mob.space_out_submobjects, 1.1, mob.to_edge, RIGHT ) two_to_ten.to_edge(LEFT) lines = VGroup(*[ Line( two_to_ten.get_corner(vect+RIGHT), mob[0].get_corner(vect+LEFT), ) for vect in (UP, DOWN) ]) two_to_ten.save_state() two_to_ten.replace(mob[0]) self.play( two_to_ten.restore, *list(map(ShowCreation, lines)) ) curr_po2_outline = curr_po2[-1].copy() curr_po2_outline.set_fill(opacity = 0) curr_po2_outline.set_stroke(width = 2) curr_po2_outline.set_color_by_gradient( YELLOW, RED, PINK, PURPLE, BLUE, GREEN ) self.play( LaggedStartMap( FadeIn, curr_po2_outline, rate_func = lambda t : wiggle(t, 8), run_time = 2, lag_ratio = 0.75, ), *get_confetti_animations(50) ) class PiHoldingScreen(PiCreatureScene): def construct(self): morty = self.pi_creature screen = ScreenRectangle() screen.set_height(5.5) screen.to_edge(UP, buff = LARGE_BUFF) screen.to_edge(LEFT) words = VGroup( OldTexText("Ben Eater"), OldTexText("The Case Against Net Neutrality?"), ) words.next_to(screen, UP, SMALL_BUFF) self.play( ShowCreation(screen), morty.change, "raise_right_hand", screen ) self.wait(10) self.play( morty.change, "hooray", words[0], Write(words[0]) ) self.wait(10) self.play( morty.change, "pondering", words[1], Transform(words[0], words[1]) ) self.wait(10) class QuestionsLink(Scene): def construct(self): link = OldTexText("https://3b1b.co/questions") link.set_width(FRAME_WIDTH) link.to_edge(DOWN) self.play(Write(link)) self.wait() class Thumbnail(Scene): def construct(self): equation = OldTex("2^{19} = " + "{:,}".format(2**19)) equation.set_width(FRAME_X_RADIUS) equation.to_edge(DOWN, buff = LARGE_BUFF) q_and_a = OldTexText("Q\\&A \\\\ Round 2") q_and_a.set_color_by_gradient(BLUE, YELLOW) q_and_a.set_width(FRAME_X_RADIUS) q_and_a.to_edge(UP, buff = LARGE_BUFF) eater = ImageMobject("eater", height = 3) eater.to_corner(UP+RIGHT, buff = 0) confetti_anims = get_confetti_animations(100) for anim in confetti_anims: anim.update(0.5) confetti = VGroup(*[a.mobject for a in confetti_anims]) self.add(equation, q_and_a, eater)
videos_3b1b/_2017/efvgt.py
from manim_imports_ext import * ADDER_COLOR = GREEN MULTIPLIER_COLOR = YELLOW def normalize(vect): norm = get_norm(vect) if norm == 0: return OUT else: return vect/norm def get_composite_rotation_angle_and_axis(angles, axes): angle1, axis1 = 0, OUT for angle2, axis2 in zip(angles, axes): ## Figure out what (angle3, axis3) is the same ## as first applying (angle1, axis1), then (angle2, axis2) axis2 = normalize(axis2) dot = np.dot(axis2, axis1) cross = np.cross(axis2, axis1) angle3 = 2*np.arccos( np.cos(angle2/2)*np.cos(angle1/2) - \ np.sin(angle2/2)*np.sin(angle1/2)*dot ) axis3 = ( np.sin(angle2/2)*np.cos(angle1/2)*axis2 + \ np.cos(angle2/2)*np.sin(angle1/2)*axis1 + \ np.sin(angle2/2)*np.sin(angle1/2)*cross ) axis3 = normalize(axis3) angle1, axis1 = angle3, axis3 if angle1 > np.pi: angle1 -= 2*np.pi return angle1, axis1 class ConfettiSpiril(Animation): CONFIG = { "x_start" : 0, "spiril_radius" : 0.5, "num_spirils" : 4, "run_time" : 10, "rate_func" : None, } def __init__(self, mobject, **kwargs): digest_config(self, kwargs) mobject.next_to(self.x_start*RIGHT + FRAME_Y_RADIUS*UP, UP) self.total_vert_shift = \ FRAME_HEIGHT + mobject.get_height() + 2*MED_SMALL_BUFF Animation.__init__(self, mobject, **kwargs) def interpolate_submobject(self, submobject, starting_submobject, alpha): submobject.set_points(starting_submobject.get_points()) def interpolate_mobject(self, alpha): Animation.interpolate_mobject(self, alpha) angle = alpha*self.num_spirils*2*np.pi vert_shift = alpha*self.total_vert_shift start_center = self.mobject.get_center() self.mobject.shift(self.spiril_radius*OUT) self.mobject.rotate(angle, axis = UP, about_point = start_center) self.mobject.shift(vert_shift*DOWN) def get_confetti_animations(num_confetti_squares): colors = [RED, YELLOW, GREEN, BLUE, PURPLE, RED] confetti_squares = [ Square( side_length = 0.2, stroke_width = 0, fill_opacity = 0.75, fill_color = random.choice(colors), ) for x in range(num_confetti_squares) ] confetti_spirils = [ ConfettiSpiril( square, x_start = 2*random.random()*FRAME_X_RADIUS - FRAME_X_RADIUS, rate_func = squish_rate_func(rush_from, a, a+0.5) ) for a, square in zip( np.linspace(0, 0.5, num_confetti_squares), confetti_squares ) ] return confetti_spirils class Anniversary(TeacherStudentsScene): CONFIG = { "num_confetti_squares" : 50, "message": "2 year Anniversary!", } def construct(self): self.celebrate() self.complain() def celebrate(self): title = OldTexText(self.message) title.scale(1.5) title.to_edge(UP) first_video = Rectangle( height = 2, width = 2*(16.0/9), stroke_color = WHITE, fill_color = "#111111", fill_opacity = 0.75, ) first_video.next_to(self.get_teacher(), UP+LEFT) first_video.shift(RIGHT) formula = OldTex("e^{\\pi i} = -1") formula.move_to(first_video) first_video.add(formula) first_video.fade(1) hats = self.get_party_hats() confetti_spirils = get_confetti_animations( self.num_confetti_squares ) self.play( Write(title, run_time = 2), *[ ApplyMethod(pi.change_mode, "hooray") for pi in self.get_pi_creatures() ] ) self.play( DrawBorderThenFill( hats, lag_ratio = 0.5, rate_func=linear, run_time = 2, ), *confetti_spirils + [ Succession( Animation(pi, run_time = 2), ApplyMethod(pi.look, UP+LEFT), ApplyMethod(pi.look, UP+RIGHT), Animation(pi), ApplyMethod(pi.look_at, first_video), rate_func=linear ) for pi in self.get_students() ] + [ Succession( Animation(self.get_teacher(), run_time = 2), Blink(self.get_teacher()), Animation(self.get_teacher(), run_time = 2), ApplyMethod(self.get_teacher().change_mode, "raise_right_hand"), rate_func=linear ), DrawBorderThenFill( first_video, run_time = 10, rate_func = squish_rate_func(smooth, 0.5, 0.7) ) ] ) self.play_student_changes(*["confused"]*3) def complain(self): self.student_says( "Why were you \\\\ talking so fast?", index = 0, target_mode = "sassy", ) self.play_student_changes(*["sassy"]*3) self.play(self.get_teacher().change_mode, "shruggie") self.wait(2) def get_party_hats(self): hats = VGroup(*[ PartyHat( pi_creature = pi, height = 0.5*pi.get_height() ) for pi in self.get_pi_creatures() ]) max_angle = np.pi/6 for hat in hats: hat.rotate( random.random()*2*max_angle - max_angle, about_point = hat.get_bottom() ) return hats class HomomophismPreview(Scene): def construct(self): raise Exception("Meant as a place holder, not to be excecuted") class WatchingScreen(PiCreatureScene): CONFIG = { "screen_height" : 5.5 } def create_pi_creatures(self): randy = Randolph().to_corner(DOWN+LEFT) return VGroup(randy) def construct(self): screen = Rectangle(height = 9, width = 16) screen.set_height(self.screen_height) screen.to_corner(UP+RIGHT) self.add(screen) for mode in "erm", "pondering", "confused": self.wait() self.change_mode(mode) self.play(Animation(screen)) self.wait() class LetsStudyTheBasics(TeacherStudentsScene): def construct(self): self.teacher_says("Let's learn some \\\\ group theory!") self.play_student_changes(*["hooray"]*3) self.wait(2) class JustGiveMeAQuickExplanation(TeacherStudentsScene): def construct(self): self.student_says( "I ain't got \\\\ time for this!", target_mode = "angry", ) self.play(*it.chain(*[ [ pi.change_mode, "hesitant", pi.look_at, self.get_students()[1].eyes ] for pi in self.get_students()[::2] ])) self.wait(2) class ComplexTransformationScene(Scene): pass class QuickExplanation(ComplexTransformationScene): CONFIG = { "plane_config" : { "x_line_frequency" : 1, "y_line_frequency" : 1, "secondary_line_ratio" : 1, "space_unit_to_x_unit" : 1.5, "space_unit_to_y_unit" : 1.5, }, "background_fade_factor" : 0.2, "background_label_scale_val" : 0.7, "velocity_color" : RED, "position_color" : YELLOW, } def construct(self): # self.add_transformable_plane() self.add_equation() self.add_explanation() self.add_vectors() def add_equation(self): equation = OldTex( "\\frac{d(e^{it})}{dt}", "=", "i", "e^{it}" ) equation[0].set_color(self.velocity_color) equation[-1].set_color(self.position_color) equation.add_background_rectangle() brace = Brace(equation, UP) equation.add(brace) brace_text = OldTexText( "Velocity vector", "is a", "$90^\\circ$ \\\\ rotation", "of", "position vector" ) brace_text[0].set_color(self.velocity_color) brace_text[-1].set_color(self.position_color) brace_text.add_background_rectangle() brace_text.scale(0.8) brace_text.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) equation.next_to(brace_text, DOWN) self.add_foreground_mobjects(brace_text, equation) self.brace_text = brace_text def add_explanation(self): words = OldTexText(""" Only a walk around the unit circle at rate 1 satisfies both this property and e^0 = 1. """) words.scale(0.8) words.add_background_rectangle() words.to_corner(UP+RIGHT, buff = MED_SMALL_BUFF) arrow = Arrow(RIGHT, 1.5*LEFT, color = WHITE) arrow.to_edge(UP) self.add(words, arrow) def add_vectors(self): right = self.z_to_point(1) s_vector = Arrow( ORIGIN, right, tip_length = 0.2, buff = 0, color = self.position_color, ) v_vector = s_vector.copy().rotate(np.pi/2) v_vector.set_color(self.velocity_color) circle = Circle( radius = self.z_to_point(1)[0], color = self.position_color ) self.wait(2) self.play(ShowCreation(s_vector)) self.play(ReplacementTransform( s_vector.copy(), v_vector, path_arc = np.pi/2 )) self.wait() self.play(v_vector.shift, right) self.wait() self.vectors = VGroup(s_vector, v_vector) kwargs = { "rate_func" : None, "run_time" : 5, } rotation = Rotating(self.vectors, about_point = ORIGIN, **kwargs) self.play( ShowCreation(circle, **kwargs), rotation ) self.play(rotation) self.play(rotation) class SymmetriesOfSquare(ThreeDScene): CONFIG = { "square_config" : { "side_length" : 2, "stroke_width" : 0, "fill_color" : BLUE, "fill_opacity" : 0.75, }, "dashed_line_config" : {}, } def construct(self): self.add_title() self.ask_about_square_symmetry() self.talk_through_90_degree_rotation() self.talk_through_vertical_flip() self.confused_by_lack_of_labels() self.add_labels() self.show_full_group() self.show_top_actions() self.show_bottom_actions() self.name_dihedral_group() def add_title(self): title = OldTexText("Groups", "$\\leftrightarrow$", "Symmetry") title.to_edge(UP) for index in 0, 2: self.play(Write(title[index], run_time = 1)) self.play(GrowFromCenter(title[1])) self.wait() self.title = title def ask_about_square_symmetry(self): brace = Brace(self.title[-1]) q_marks = brace.get_text("???") self.square = Square(**self.square_config) self.play(DrawBorderThenFill(self.square)) self.play(GrowFromCenter(brace), Write(q_marks)) self.rotate_square() self.wait() for axis in UP, UP+RIGHT: self.flip_square(axis) self.wait() self.rotate_square(-np.pi) self.wait() self.play(*list(map(FadeOut, [brace, q_marks]))) def talk_through_90_degree_rotation(self): arcs = self.get_rotation_arcs(self.square, np.pi/2) self.play(*list(map(ShowCreation, arcs))) self.wait() self.rotate_square(np.pi/2, run_time = 2) self.wait() self.play(FadeOut(arcs)) self.wait() def talk_through_vertical_flip(self): self.flip_square(UP, run_time = 2) self.wait() def confused_by_lack_of_labels(self): randy = Randolph(mode = "confused") randy.next_to(self.square, LEFT, buff = LARGE_BUFF) randy.to_edge(DOWN) self.play(FadeIn(randy)) for axis in OUT, RIGHT, UP: self.rotate_square( angle = np.pi, axis = axis, added_anims = [randy.look_at, self.square.get_points()[0]] ) self.play(Blink(randy)) self.wait() self.randy = randy def add_labels(self): self.add_randy_to_square(self.square) self.play( FadeIn(self.square.randy), self.randy.change_mode, "happy", self.randy.look_at, self.square.randy.eyes ) self.play(Blink(self.randy)) self.play(FadeOut(self.randy)) self.wait() def show_full_group(self): new_title = OldTexText("Group", "of", "symmetries") new_title.move_to(self.title) all_squares = VGroup(*[ self.square.copy().scale(0.5) for x in range(8) ]) all_squares.arrange(RIGHT, buff = LARGE_BUFF) top_squares = VGroup(*all_squares[:4]) bottom_squares = VGroup(*all_squares[4:]) bottom_squares.next_to(top_squares, DOWN, buff = LARGE_BUFF) all_squares.set_width(FRAME_WIDTH-2*LARGE_BUFF) all_squares.center() all_squares.to_edge(DOWN, buff = LARGE_BUFF) self.play(ReplacementTransform(self.square, all_squares[0])) self.play(ReplacementTransform(self.title, new_title)) self.title = new_title self.play(*[ ApplyMethod(mob.set_color, GREY) for mob in self.title[1:] ]) for square, angle in zip(all_squares[1:4], [np.pi/2, np.pi, -np.pi/2]): arcs = self.get_rotation_arcs(square, angle, MED_SMALL_BUFF) self.play(*list(map(FadeIn, [square, arcs]))) square.rotation_kwargs = {"angle" : angle} self.rotate_square(square = square, **square.rotation_kwargs) square.add(arcs) for square, axis in zip(bottom_squares, [RIGHT, RIGHT+UP, UP, UP+LEFT]): axis_line = self.get_axis_line(square, axis) self.play(FadeIn(square)) self.play(ShowCreation(axis_line)) square.rotation_kwargs = {"angle" : np.pi, "axis" : axis} self.rotate_square(square = square, **square.rotation_kwargs) square.add(axis_line) self.wait() self.all_squares = all_squares def show_top_actions(self): all_squares = self.all_squares self.play(Indicate(all_squares[0])) self.wait() self.play(*[ Rotate( square, rate_func = lambda t : -there_and_back(t), run_time = 3, about_point = square.get_center(), **square.rotation_kwargs ) for square in all_squares[1:4] ]) self.wait() def show_bottom_actions(self): for square in self.all_squares[4:]: self.rotate_square( square = square, rate_func = there_and_back, run_time = 2, **square.rotation_kwargs ) self.wait() def name_dihedral_group(self): new_title = OldTexText( "``Dihedral group'' of order 8" ) new_title.to_edge(UP) self.play(FadeOut(self.title)) self.play(FadeIn(new_title)) self.wait() ########## def rotate_square( self, angle = np.pi/2, axis = OUT, square = None, show_axis = False, added_anims = None, **kwargs ): if square is None: assert hasattr(self, "square") square = self.square added_anims = added_anims or [] rotation = Rotate( square, angle = angle, axis = axis, about_point = square.get_center(), **kwargs ) if hasattr(square, "labels"): for label in rotation.target_mobject.labels: label.rotate(-angle, axis) if show_axis: axis_line = self.get_axis_line(square, axis) self.play( ShowCreation(axis_line), Animation(square) ) self.play(rotation, *added_anims) if show_axis: self.play( FadeOut(axis_line), Animation(square) ) def flip_square(self, axis = UP, **kwargs): self.rotate_square( angle = np.pi, axis = axis, show_axis = True, **kwargs ) def get_rotation_arcs(self, square, angle, angle_buff = SMALL_BUFF): square_radius = get_norm( square.get_points()[0] - square.get_center() ) arc = Arc( radius = square_radius + SMALL_BUFF, start_angle = np.pi/4 + np.sign(angle)*angle_buff, angle = angle - np.sign(angle)*2*angle_buff, color = YELLOW ) arc.add_tip() if abs(angle) < 3*np.pi/4: angle_multiple_range = list(range(1, 4)) else: angle_multiple_range = [2] arcs = VGroup(arc, *[ arc.copy().rotate(i*np.pi/2) for i in angle_multiple_range ]) arcs.move_to(square[0]) return arcs def get_axis_line(self, square, axis): axis_line = DashedLine(2*axis, -2*axis, **self.dashed_line_config) axis_line.replace(square, dim_to_match = np.argmax(np.abs(axis))) axis_line.scale(1.2) return axis_line def add_labels_and_dots(self, square): labels = VGroup() dots = VGroup() for tex, vertex in zip("ABCD", square.get_anchors()): label = OldTex(tex) label.add_background_rectangle() label.next_to(vertex, vertex-square.get_center(), SMALL_BUFF) labels.add(label) dot = Dot(vertex, color = WHITE) dots.add(dot) square.add(labels, dots) square.labels = labels square.dots = dots def add_randy_to_square(self, square, mode = "pondering"): randy = Randolph(mode = mode) randy.set_height(0.75*square.get_height()) randy.move_to(square) square.add(randy) square.randy = randy class ManyGroupsAreInfinite(TeacherStudentsScene): def construct(self): self.teacher_says("Many groups are infinite") self.play_student_changes(*["pondering"]*3) self.wait(2) class CircleSymmetries(Scene): CONFIG = { "circle_radius" : 2, } def construct(self): self.add_circle_and_title() self.show_range_of_angles() self.associate_rotations_with_points() def add_circle_and_title(self): title = OldTexText("Group of rotations") title.to_edge(UP) circle = self.get_circle() self.play(Write(title), ShowCreation(circle, run_time = 2)) self.wait() angles = [ np.pi/2, -np.pi/3, 5*np.pi/6, 3*np.pi/2 + 0.1 ] angles.append(-sum(angles)) for angle in angles: self.play(Rotate(circle, angle = angle)) self.wait() self.circle = circle def show_range_of_angles(self): self.add_radial_line() arc_circle = self.get_arc_circle() theta = OldTex("\\theta = ") theta_value = DecimalNumber(0.00) theta_value.next_to(theta, RIGHT) theta_group = VGroup(theta, theta_value) theta_group.next_to(arc_circle, UP) def theta_value_update(theta_value, alpha): new_theta_value = DecimalNumber(alpha*2*np.pi) new_theta_value.set_height(theta.get_height()) new_theta_value.next_to(theta, RIGHT) Transform(theta_value, new_theta_value).update(1) return new_theta_value self.play(FadeIn(theta_group)) for rate_func in smooth, lambda t : smooth(1-t): self.play( Rotate(self.circle, 2*np.pi-0.001), ShowCreation(arc_circle), UpdateFromAlphaFunc(theta_value, theta_value_update), run_time = 7, rate_func = rate_func ) self.wait() self.play(FadeOut(theta_group)) self.wait() def associate_rotations_with_points(self): zero_dot = Dot(self.circle.point_from_proportion(0)) zero_dot.set_color(RED) zero_arrow = Arrow(UP+RIGHT, ORIGIN) zero_arrow.set_color(zero_dot.get_color()) zero_arrow.next_to(zero_dot, UP+RIGHT, buff = SMALL_BUFF) self.play( ShowCreation(zero_arrow), DrawBorderThenFill(zero_dot) ) self.circle.add(zero_dot) self.wait() for alpha in 0.2, 0.6, 0.4, 0.8: point = self.circle.point_from_proportion(alpha) dot = Dot(point, color = YELLOW) vect = np.sign(point) arrow = Arrow(vect, ORIGIN) arrow.next_to(dot, vect, buff = SMALL_BUFF) arrow.set_color(dot.get_color()) angle = alpha*2*np.pi self.play( ShowCreation(arrow), DrawBorderThenFill(dot) ) self.play( Rotate(self.circle, angle, run_time = 2), Animation(dot) ) self.wait() self.play( Rotate(self.circle, -angle, run_time = 2), FadeOut(dot), FadeOut(arrow), ) self.wait() #### def get_circle(self): circle = Circle(color = MAROON_B, radius = self.circle_radius) circle.ticks = VGroup() for alpha in np.arange(0, 1, 1./8): point = circle.point_from_proportion(alpha) tick = Line((1 - 0.05)*point, (1 + 0.05)*point) circle.ticks.add(tick) circle.add(circle.ticks) return circle def add_radial_line(self): radius = Line( self.circle.get_center(), self.circle.point_from_proportion(0) ) static_radius = radius.copy().set_color(GREY) self.play(ShowCreation(radius)) self.add(static_radius, radius) self.circle.radius = radius self.circle.static_radius = static_radius self.circle.add(radius) def get_arc_circle(self): arc_radius = self.circle_radius/5.0 arc_circle = Circle( radius = arc_radius, color = WHITE ) return arc_circle class GroupOfCubeSymmetries(ThreeDScene): CONFIG = { "cube_opacity" : 0.5, "cube_colors" : [BLUE], "put_randy_on_cube" : True, } def construct(self): title = OldTexText("Group of cube symmetries") title.to_edge(UP) self.add(title) cube = self.get_cube() face_centers = [face.get_center() for face in cube[0:7:2]] angle_axis_pairs = list(zip(3*[np.pi/2], face_centers)) for i in range(3): ones = np.ones(3) ones[i] = -1 axis = np.dot(ones, face_centers) angle_axis_pairs.append((2*np.pi/3, axis)) for angle, axis in angle_axis_pairs: self.play(Rotate( cube, angle = angle, axis = axis, run_time = 2 )) self.wait() def get_cube(self): cube = Cube(fill_opacity = self.cube_opacity) cube.set_color_by_gradient(*self.cube_colors) if self.put_randy_on_cube: randy = Randolph(mode = "pondering") # randy.pupils.shift(0.01*OUT) # randy.add(randy.pupils.copy().shift(0.02*IN)) # for submob in randy.get_family(): # submob.part_of_three_d_mobject = True randy.scale(0.5) face = cube[1] randy.move_to(face) face.add(randy) pose_matrix = self.get_pose_matrix() cube.apply_function( lambda p : np.dot(p, pose_matrix.T), maintain_smoothness = False ) return cube def get_pose_matrix(self): return np.dot( rotation_matrix(np.pi/8, UP), rotation_matrix(np.pi/24, RIGHT) ) class HowDoSymmetriesPlayWithEachOther(TeacherStudentsScene): def construct(self): self.teacher_says( "How do symmetries \\\\ play with each other?", target_mode = "hesitant", ) self.play_student_changes("pondering", "maybe", "confused") self.wait(2) class AddSquareSymmetries(SymmetriesOfSquare): def construct(self): square = Square(**self.square_config) square.flip(RIGHT) square.shift(DOWN) self.add_randy_to_square(square, mode = "shruggie") alt_square = square.copy() equals = OldTex("=") equals.move_to(square) equation_square = Square(**self.square_config) equation = VGroup( equation_square, OldTex("+"), equation_square.copy(), OldTex("="), equation_square.copy(), ) equation[0].add(self.get_rotation_arcs( equation[0], np.pi/2, )) equation[2].add(self.get_axis_line(equation[4], UP)) equation[4].add(self.get_axis_line(equation[4], UP+RIGHT)) for mob in equation[::2]: mob.scale(0.5) equation.arrange(RIGHT) equation.to_edge(UP) arcs = self.get_rotation_arcs(square, np.pi/2) self.add(square) self.play(FadeIn(arcs)) self.rotate_square( square = square, angle = np.pi/2, added_anims = list(map(FadeIn, equation[:2])) ) self.wait() self.play(FadeOut(arcs)) self.flip_square( square = square, axis = UP, added_anims = list(map(FadeIn, equation[2:4])) ) self.wait() alt_square.next_to(equals, RIGHT, buff = LARGE_BUFF) alt_square.save_state() alt_square.move_to(square) alt_square.set_fill(opacity = 0) self.play( square.next_to, equals, LEFT, LARGE_BUFF, alt_square.restore, Write(equals) ) self.flip_square( square = alt_square, axis = UP+RIGHT, added_anims = list(map(FadeIn, equation[4:])), ) self.wait(2) ## Reiterate composition self.rotate_square(square = square, angle = np.pi/2) self.flip_square(square = square, axis = UP) self.wait() self.flip_square(square = alt_square, axis = UP+RIGHT) self.wait() class AddCircleSymmetries(CircleSymmetries): def construct(self): circle = self.circle = self.get_circle() arc_circle = self.get_arc_circle() angles = [3*np.pi/2, 2*np.pi/3, np.pi/6] arcs = [ arc_circle.copy().scale(scalar) for scalar in [1, 1.2, 1.4] ] equation = OldTex( "270^\\circ", "+", "120^\\circ", "=", "30^\\circ", ) equation.to_edge(UP) colors = [BLUE, YELLOW, GREEN] for color, arc, term in zip(colors, arcs, equation[::2]): arc.set_color(color) term.set_color(color) self.play(FadeIn(circle)) self.add_radial_line() alt_radius = circle.radius.copy() alt_radius.set_color(GREY) alt_circle = circle.copy() equals = OldTex("=") equals.move_to(circle) def rotate(circle, angle, arc, terms): self.play( Rotate(circle, angle, in_place = True), ShowCreation( arc, rate_func = lambda t : (angle/(2*np.pi))*smooth(t) ), Write(VGroup(*terms)), run_time = 2, ) rotate(circle, angles[0], arcs[0], equation[:2]) self.wait() circle.add(alt_radius) rotate(circle, angles[1], arcs[1], equation[2:4]) self.play(FadeOut(alt_radius)) circle.remove(alt_radius) self.wait() circle.add(circle.static_radius) circle.add(*arcs[:2]) alt_static_radius = circle.static_radius.copy() alt_circle.add(alt_static_radius) alt_circle.next_to(equals, RIGHT, buff = LARGE_BUFF) alt_circle.save_state() alt_circle.move_to(circle) alt_circle.set_stroke(width = 0) self.play( circle.next_to, equals, LEFT, LARGE_BUFF, alt_circle.restore, Write(equals) ) arcs[2].shift(alt_circle.get_center()) alt_circle.remove(alt_static_radius) self.wait() rotate(alt_circle, angles[2], arcs[2], equation[4:]) self.wait() self.play( Rotate(arcs[1], angles[0], about_point = circle.get_center()) ) self.wait(2) for term, arc in zip(equation[::2], arcs): self.play(*[ ApplyMethod(mob.scale, 1.2, rate_func = there_and_back) for mob in (term, arc) ]) self.wait() class AddCubeSymmetries(GroupOfCubeSymmetries): CONFIG = { "angle_axis_pairs" : [ (np.pi/2, RIGHT), (np.pi/2, UP), ], "cube_opacity" : 0.5, "cube_colors" : [BLUE], } def construct(self): angle_axis_pairs = list(self.angle_axis_pairs) angle_axis_pairs.append( self.get_composition_angle_and_axis() ) self.pose_matrix = self.get_pose_matrix() cube = self.get_cube() equation = cube1, plus, cube2, equals, cube3 = VGroup( cube, OldTex("+"), cube.copy(), OldTex("="), cube.copy() ) equation.arrange(RIGHT, buff = MED_LARGE_BUFF) equation.center() self.add(cube1) self.rotate_cube(cube1, *angle_axis_pairs[0]) cube_copy = cube1.copy() cube_copy.set_fill(opacity = 0) self.play( cube_copy.move_to, cube2, cube_copy.set_fill, None, self.cube_opacity, Write(plus) ) self.rotate_cube(cube_copy, *angle_axis_pairs[1]) self.play(Write(equals)) self.play(DrawBorderThenFill(cube3, run_time = 1)) self.rotate_cube(cube3, *angle_axis_pairs[2]) self.wait(2) times = OldTex("\\times") times.scale(1.5) times.move_to(plus) times.set_color(RED) self.wait() self.play(ReplacementTransform(plus, times)) self.play(Indicate(times)) self.wait() for cube, (angle, axis) in zip([cube1, cube_copy, cube3], angle_axis_pairs): self.rotate_cube( cube, -angle, axis, add_arrows = False, rate_func = there_and_back, run_time = 1.5 ) self.wait() def rotate_cube(self, cube, angle, axis, add_arrows = True, **kwargs): axis = np.dot(axis, self.pose_matrix.T) anims = [] if add_arrows: arrows = VGroup(*[ Arc( start_angle = np.pi/12+a, angle = 5*np.pi/6, color = YELLOW ).add_tip() for a in (0, np.pi) ]) arrows.set_height(1.5*cube.get_height()) z_to_axis = z_to_vector(axis) arrows.apply_function( lambda p : np.dot(p, z_to_axis.T), maintain_smoothness = False ) arrows.move_to(cube) arrows.shift(-axis*cube.get_height()/2/get_norm(axis)) anims += list(map(ShowCreation, arrows)) anims.append( Rotate( cube, axis = axis, angle = angle, in_place = True, **kwargs ) ) self.play(*anims, run_time = 1.5) def get_composition_angle_and_axis(self): return get_composite_rotation_angle_and_axis( *list(zip(*self.angle_axis_pairs)) ) class DihedralGroupStructure(SymmetriesOfSquare): CONFIG = { "dashed_line_config" : { "dash_length" : 0.1 }, "filed_sum_scale_factor" : 0.4, "num_rows" : 5, } def construct(self): angle_axis_pairs = [ (np.pi/2, OUT), (np.pi, OUT), (-np.pi/2, OUT), # (np.pi, RIGHT), # (np.pi, UP+RIGHT), (np.pi, UP), (np.pi, UP+LEFT), ] pair_pairs = list(it.product(*[angle_axis_pairs]*2)) random.shuffle(pair_pairs) for pair_pair in pair_pairs[:4]: sum_expression = self.demonstrate_sum(pair_pair) self.file_away_sum(sum_expression) for pair_pair in pair_pairs[4:]: should_skip_animations = self.skip_animations self.skip_animations = True sum_expression = self.demonstrate_sum(pair_pair) self.file_away_sum(sum_expression) self.skip_animations = should_skip_animations self.play(FadeIn(sum_expression)) self.wait(3) def demonstrate_sum(self, angle_axis_pairs): angle_axis_pairs = list(angle_axis_pairs) + [ get_composite_rotation_angle_and_axis( *list(zip(*angle_axis_pairs)) ) ] prototype_square = Square(**self.square_config) prototype_square.flip(RIGHT) self.add_randy_to_square(prototype_square) # self.add_labels_and_dots(prototype_square) prototype_square.scale(0.7) expression = s1, plus, s2, equals, s3 = VGroup( prototype_square, OldTex("+").scale(2), prototype_square.copy(), OldTex("=").scale(2), prototype_square.copy() ) final_expression = VGroup() for square, (angle, axis) in zip([s1, s2, s3], angle_axis_pairs): if np.cos(angle) > 0.5: square.action_illustration = VectorizedPoint() elif np.argmax(np.abs(axis)) == 2: ##Axis is in z direction square.action_illustration = self.get_rotation_arcs( square, angle ) else: square.action_illustration = self.get_axis_line( square, axis ) square.add(square.action_illustration) final_expression.add(square.action_illustration) square.rotation_kwargs = { "square" : square, "angle" : angle, "axis" : axis, } expression.arrange() expression.set_width(FRAME_X_RADIUS+1) expression.to_edge(RIGHT, buff = SMALL_BUFF) for square in s1, s2, s3: square.remove(square.action_illustration) self.play(FadeIn(s1)) self.play(*list(map(ShowCreation, s1.action_illustration))) self.rotate_square(**s1.rotation_kwargs) s1_copy = s1.copy() self.play( # FadeIn(s2), s1_copy.move_to, s2, Write(plus) ) Transform(s2, s1_copy).update(1) self.remove(s1_copy) self.add(s2) self.play(*list(map(ShowCreation, s2.action_illustration))) self.rotate_square(**s2.rotation_kwargs) self.play( Write(equals), FadeIn(s3) ) self.play(*list(map(ShowCreation, s3.action_illustration))) self.rotate_square(**s3.rotation_kwargs) self.wait() final_expression.add(*expression) return final_expression def file_away_sum(self, sum_expression): if not hasattr(self, "num_sum_expressions"): self.num_sum_expressions = 0 target = sum_expression.copy() target.scale(self.filed_sum_scale_factor) y_index = self.num_sum_expressions%self.num_rows y_prop = float(y_index)/(self.num_rows-1) y = interpolate(FRAME_Y_RADIUS-LARGE_BUFF, -FRAME_Y_RADIUS+LARGE_BUFF, y_prop) x_index = self.num_sum_expressions//self.num_rows x_spacing = FRAME_WIDTH/3 x = (x_index-1)*x_spacing target.move_to(x*RIGHT + y*UP) self.play(Transform(sum_expression, target)) self.wait() self.num_sum_expressions += 1 self.last_sum_expression = sum_expression class ThisIsAVeryGeneralIdea(Scene): def construct(self): groups = OldTexText("Groups") groups.to_edge(UP) groups.set_color(BLUE) examples = VGroup(*list(map(TexText, [ "Square matrices \\\\ \\small (Where $\\det(M) \\ne 0$)", "Molecular \\\\ symmetry", "Cryptography", "Numbers", ]))) numbers = examples[-1] examples.arrange(buff = LARGE_BUFF) examples.set_width(FRAME_WIDTH-1) examples.move_to(UP) lines = VGroup(*[ Line(groups.get_bottom(), ex.get_top(), buff = MED_SMALL_BUFF) for ex in examples ]) lines.set_color(groups.get_color()) self.add(groups) for example, line in zip(examples, lines): self.play( ShowCreation(line), Write(example, run_time = 2) ) self.wait() self.play( VGroup(*examples[:-1]).fade, 0.7, VGroup(*lines[:-1]).fade, 0.7, ) self.play( numbers.scale, 1.2, numbers.get_corner(UP+RIGHT), ) self.wait(2) sub_categories = VGroup(*list(map(TexText, [ "Numbers \\\\ (Additive)", "Numbers \\\\ (Multiplicative)", ]))) sub_categories.arrange(RIGHT, buff = MED_LARGE_BUFF) sub_categories.next_to(numbers, DOWN, 1.5*LARGE_BUFF) sub_categories.to_edge(RIGHT) sub_categories[0].set_color(ADDER_COLOR) sub_categories[1].set_color(MULTIPLIER_COLOR) sub_lines = VGroup(*[ Line(numbers.get_bottom(), sc.get_top(), buff = MED_SMALL_BUFF) for sc in sub_categories ]) sub_lines.set_color(numbers.get_color()) self.play(*it.chain( list(map(ShowCreation, sub_lines)), list(map(Write, sub_categories)) )) self.wait() class NumbersAsActionsQ(TeacherStudentsScene): def construct(self): self.student_says( "Numbers are actions?", target_mode = "confused", ) self.play_student_changes("pondering", "confused", "erm") self.play(self.get_teacher().change_mode, "happy") self.wait(3) class AdditiveGroupOfReals(Scene): CONFIG = { "number_line_center" : UP, "shadow_line_center" : DOWN, "zero_color" : GREEN_B, "x_min" : -FRAME_WIDTH, "x_max" : FRAME_WIDTH, } def construct(self): self.add_number_line() self.show_example_slides(3, -7) self.write_group_of_slides() self.show_example_slides(2, 6, -1, -3) self.mark_zero() self.show_example_slides_labeled(3, -2) self.comment_on_zero_as_identity() self.show_example_slides_labeled( 5.5, added_anims = [self.get_write_name_of_group_anim()] ) self.show_example_additions((3, 2), (2, -5), (-4, 4)) def add_number_line(self): number_line = NumberLine( x_min = self.x_min, x_max = self.x_max, ) number_line.shift(self.number_line_center) shadow_line = NumberLine(color = GREY, stroke_width = 2) shadow_line.shift(self.shadow_line_center) for line in number_line, shadow_line: line.add_numbers() shadow_line.numbers.fade(0.25) shadow_line.save_state() shadow_line.set_color(BLACK) shadow_line.move_to(number_line) self.play(*list(map(Write, number_line)), run_time = 1) self.play(shadow_line.restore, Animation(number_line)) self.wait() self.number_line = number_line self.shadow_line = shadow_line def show_example_slides(self, *nums): for num in nums: zero_point = self.number_line.number_to_point(0) num_point = self.number_line.number_to_point(num) arrow = Arrow(zero_point, num_point, buff = 0) arrow.set_color(ADDER_COLOR) arrow.shift(MED_LARGE_BUFF*UP) self.play(ShowCreation(arrow)) self.play( self.number_line.shift, num_point - zero_point, run_time = 2 ) self.play(FadeOut(arrow)) def write_group_of_slides(self): title = OldTexText("Group of line symmetries") title.to_edge(UP) self.play(Write(title)) self.title = title def mark_zero(self): dot = Dot( self.number_line.number_to_point(0), color = self.zero_color ) arrow = Arrow(dot, color = self.zero_color) words = OldTexText("Follow zero") words.next_to(arrow.get_start(), UP) words.set_color(self.zero_color) self.play( ShowCreation(arrow), DrawBorderThenFill(dot), Write(words), ) self.wait() self.play(*list(map(FadeOut, [arrow, words]))) self.number_line.add(dot) def show_example_slides_labeled(self, *nums, **kwargs): for num in nums: line = DashedLine( self.number_line.number_to_point(num)+MED_LARGE_BUFF*UP, self.shadow_line.number_to_point(num)+MED_LARGE_BUFF*DOWN, ) vect = self.number_line.number_to_point(num) - \ self.number_line.number_to_point(0) self.play(ShowCreation(line)) self.wait() self.play(self.number_line.shift, vect, run_time = 2) self.wait() if "added_anims" in kwargs: self.play(*kwargs["added_anims"]) self.wait() self.play( self.number_line.shift, -vect, FadeOut(line) ) def comment_on_zero_as_identity(self): line = DashedLine( self.number_line.number_to_point(0)+MED_LARGE_BUFF*UP, self.shadow_line.number_to_point(0)+MED_LARGE_BUFF*DOWN, ) words = OldTex("0 \\leftrightarrow \\text{Do nothing}") words.shift(line.get_top()+MED_SMALL_BUFF*UP - words[0].get_bottom()) self.play( ShowCreation(line), Write(words) ) self.wait(2) self.play(*list(map(FadeOut, [line, words]))) def get_write_name_of_group_anim(self): new_title = OldTexText("Additive group of real numbers") VGroup(*new_title[-len("realnumbers"):]).set_color(BLUE) VGroup(*new_title[:len("Additive")]).set_color(ADDER_COLOR) new_title.to_edge(UP) return Transform(self.title, new_title) def show_example_additions(self, *num_pairs): for num_pair in num_pairs: num_mobs = VGroup() arrows = VGroup() self.number_line.save_state() for num in num_pair: zero_point, num_point, arrow, num_mob = \ self.get_adder_mobs(num) if len(num_mobs) > 0: last_num_mob = num_mobs[0] x = num_mob.get_center()[0] if x < last_num_mob.get_right()[0] and x > last_num_mob.get_left()[0]: num_mob.next_to(last_num_mob, RIGHT) num_mobs.add(num_mob) arrows.add(arrow) self.play( ShowCreation(arrow), Write(num_mob, run_time = 1) ) self.play( self.number_line.shift, num_point - zero_point ) self.wait() #Reset self.play( FadeOut(num_mobs), FadeOut(self.number_line) ) ApplyMethod(self.number_line.restore).update(1) self.play(FadeIn(self.number_line)) #Sum arrow num = sum(num_pair) zero_point, sum_point, arrow, sum_mob = \ self.get_adder_mobs(sum(num_pair)) VGroup(arrow, sum_mob).shift(MED_LARGE_BUFF*UP) arrows.add(arrow) self.play( ShowCreation(arrow), Write(sum_mob, run_time = 1) ) self.wait() self.play( self.number_line.shift, num_point - zero_point, run_time = 2 ) self.wait() self.play( self.number_line.restore, *list(map(FadeOut, [arrows, sum_mob])) ) def get_adder_mobs(self, num): zero_point = self.number_line.number_to_point(0) num_point = self.number_line.number_to_point(num) arrow = Arrow(zero_point, num_point, buff = 0) arrow.set_color(ADDER_COLOR) arrow.shift(MED_SMALL_BUFF*UP) if num == 0: arrow = DashedLine(UP, ORIGIN) arrow.move_to(zero_point) elif num < 0: arrow.set_color(RED) arrow.shift(SMALL_BUFF*UP) sign = "+" if num >= 0 else "" num_mob = OldTex(sign + str(num)) num_mob.next_to(arrow, UP) num_mob.set_color(arrow.get_color()) return zero_point, num_point, arrow, num_mob class AdditiveGroupOfComplexNumbers(ComplexTransformationScene): CONFIG = { "x_min" : -2*int(FRAME_X_RADIUS), "x_max" : 2*int(FRAME_X_RADIUS), "y_min" : -FRAME_HEIGHT, "y_max" : FRAME_HEIGHT, "example_points" : [ complex(3, 2), complex(1, -3), ] } def construct(self): self.add_plane() self.show_preview_example_slides() self.show_vertical_slide() self.show_example_point() self.show_example_addition() self.write_group_name() self.show_some_random_slides() def add_plane(self): self.add_transformable_plane(animate = True) zero_dot = Dot( self.z_to_point(0), color = ADDER_COLOR ) self.play(ShowCreation(zero_dot)) self.plane.add(zero_dot) self.plane.zero_dot = zero_dot self.wait() def show_preview_example_slides(self): example_vect = 2*UP+RIGHT for vect in example_vect, -example_vect: self.play(self.plane.shift, vect, run_time = 2) self.wait() def show_vertical_slide(self): dots = VGroup(*[ Dot(self.z_to_point(complex(0, i))) for i in range(1, 4) ]) dots.set_color(YELLOW) labels = VGroup(*self.imag_labels[-3:]) arrow = Arrow(ORIGIN, dots[-1].get_center(), buff = 0) arrow.set_color(ADDER_COLOR) self.plane.save_state() for dot, label in zip(dots, labels): self.play( Indicate(label), ShowCreation(dot) ) self.add_foreground_mobjects(dots) self.wait() Scene.play(self, ShowCreation(arrow)) self.add_foreground_mobjects(arrow) self.play( self.plane.shift, dots[-1].get_center(), run_time = 2 ) self.wait() self.play(FadeOut(arrow)) self.foreground_mobjects.remove(arrow) self.play( self.plane.shift, 6*DOWN, run_time = 3, ) self.wait() self.play(self.plane.restore, run_time = 2) self.foreground_mobjects.remove(dots) self.play(FadeOut(dots)) def show_example_point(self): z = self.example_points[0] point = self.z_to_point(z) dot = Dot(point, color = YELLOW) arrow = Vector(point, buff = dot.radius) arrow.set_color(dot.get_color()) label = OldTex("%d + %di"%(z.real, z.imag)) label.next_to(point, UP) label.set_color(dot.get_color()) label.add_background_rectangle() real_arrow = Vector(self.z_to_point(z.real)) imag_arrow = Vector(self.z_to_point(z - z.real)) VGroup(real_arrow, imag_arrow).set_color(ADDER_COLOR) self.play( Write(label), DrawBorderThenFill(dot) ) self.wait() self.play(ShowCreation(arrow)) self.add_foreground_mobjects(label, dot, arrow) self.wait() self.slide(z) self.wait() self.play(FadeOut(self.plane)) self.plane.restore() self.plane.set_stroke(width = 0) self.play(self.plane.restore) self.play(ShowCreation(real_arrow)) self.add_foreground_mobjects(real_arrow) self.slide(z.real) self.wait() self.play(ShowCreation(imag_arrow)) self.wait() self.play(imag_arrow.shift, self.z_to_point(z.real)) self.add_foreground_mobjects(imag_arrow) self.slide(z - z.real) self.wait() self.foreground_mobjects.remove(real_arrow) self.foreground_mobjects.remove(imag_arrow) self.play(*list(map(FadeOut, [real_arrow, imag_arrow, self.plane]))) self.plane.restore() self.plane.set_stroke(width = 0) self.play(self.plane.restore) self.z1 = z self.arrow1 = arrow self.dot1 = dot self.label1 = label def show_example_addition(self): z1 = self.z1 arrow1 = self.arrow1 dot1 = self.dot1 label1 = self.label1 z2 = self.example_points[1] point2 = self.z_to_point(z2) dot2 = Dot(point2, color = TEAL) arrow2 = Vector( point2, buff = dot2.radius, color = dot2.get_color() ) label2 = OldTex( "%d %di"%(z2.real, z2.imag) ) label2.next_to(point2, UP+RIGHT) label2.set_color(dot2.get_color()) label2.add_background_rectangle() self.play(ShowCreation(arrow2)) self.play( DrawBorderThenFill(dot2), Write(label2) ) self.add_foreground_mobjects(arrow2, dot2, label2) self.wait() self.slide(z1) arrow2_copy = arrow2.copy() self.play(arrow2_copy.shift, self.z_to_point(z1)) self.add_foreground_mobjects(arrow2_copy) self.slide(z2) self.play(FadeOut(arrow2_copy)) self.foreground_mobjects.remove(arrow2_copy) self.wait() ##Break into components real_arrow, imag_arrow = component_arrows = [ Vector( self.z_to_point(z), color = ADDER_COLOR ) for z in [ z1.real+z2.real, complex(0, z1.imag+z2.imag), ] ] imag_arrow.shift(real_arrow.get_end()) plus = OldTex("+").next_to( real_arrow.get_center(), UP+RIGHT ) plus.add_background_rectangle() rp1, rp2, ip1, ip2 = label_parts = [ VGroup(label1[1][0].copy()), VGroup(label2[1][0].copy()), VGroup(*label1[1][2:]).copy(), VGroup(*label2[1][1:]).copy(), ] for part in label_parts: part.generate_target() rp1.target.next_to(plus, LEFT) rp2.target.next_to(plus, RIGHT) ip1.target.next_to(imag_arrow.get_center(), RIGHT) ip1.target.shift(SMALL_BUFF*DOWN) ip2.target.next_to(ip1.target, RIGHT) real_background_rect = BackgroundRectangle( VGroup(rp1.target, rp2.target) ) imag_background_rect = BackgroundRectangle( VGroup(ip1.target, ip2.target) ) self.play( ShowCreation(real_arrow), ShowCreation( real_background_rect, rate_func = squish_rate_func(smooth, 0.75, 1), ), Write(plus), *list(map(MoveToTarget, [rp1, rp2])) ) self.wait() self.play( ShowCreation(imag_arrow), ShowCreation( imag_background_rect, rate_func = squish_rate_func(smooth, 0.75, 1), ), *list(map(MoveToTarget, [ip1, ip2])) ) self.wait(2) to_remove = [ arrow1, dot1, label1, arrow2, dot2, label2, real_background_rect, imag_background_rect, plus, ] + label_parts + component_arrows for mob in to_remove: if mob in self.foreground_mobjects: self.foreground_mobjects.remove(mob) self.play(*list(map(FadeOut, to_remove))) self.play(self.plane.restore, run_time = 2) self.wait() def write_group_name(self): title = OldTexText( "Additive", "group of", "complex numbers" ) title[0].set_color(ADDER_COLOR) title[2].set_color(BLUE) title.add_background_rectangle() title.to_edge(UP, buff = MED_SMALL_BUFF) self.play(Write(title)) self.add_foreground_mobjects(title) self.wait() def show_some_random_slides(self): example_slides = [ complex(3), complex(0, 2), complex(-4, -1), complex(-2, -1), complex(4, 2), ] for z in example_slides: self.slide(z) self.wait() ######### def slide(self, z, *added_anims, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 2) self.play( ApplyMethod( self.plane.shift, self.z_to_point(z), **kwargs ), *added_anims ) class SchizophrenicNumbers(Scene): def construct(self): v_line = DashedLine( FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN ) left_title = OldTexText("Additive group") left_title.shift(FRAME_X_RADIUS*LEFT/2) right_title = OldTexText("Multiplicative group") right_title.shift(FRAME_X_RADIUS*RIGHT/2) VGroup(left_title, right_title).to_edge(UP) self.add(v_line, left_title, right_title) numbers = VGroup( Randolph(mode = "happy").scale(0.2), OldTex("3").shift(UP+LEFT), OldTex("5.83").shift(UP+RIGHT), OldTex("\\sqrt{2}").shift(DOWN+LEFT), OldTex("2-i").shift(DOWN+RIGHT), ) for number in numbers: number.set_color(ADDER_COLOR) number.scale(1.5) if isinstance(number, PiCreature): continue number.eyes = Eyes(number[0], height = 0.1) number.add(number.eyes) numbers[3].eyes.next_to(numbers[3][1], UP, buff = 0) numbers.shift(FRAME_X_RADIUS*LEFT/2) self.play(FadeIn(numbers)) self.blink_numbers(numbers) self.wait() self.add(numbers.copy()) for number in numbers: number.generate_target() number.target.shift(FRAME_X_RADIUS*RIGHT) number.target.eyes.save_state() number.target.set_color(MULTIPLIER_COLOR) number.target.eyes.restore() self.play(*[ MoveToTarget( number, rate_func = squish_rate_func( smooth, alpha, alpha+0.5 ), run_time = 2, ) for number, alpha in zip(numbers, np.linspace(0, 0.5, len(numbers))) ]) self.wait() self.blink_numbers(numbers) self.wait() def blink_numbers(self, numbers): self.play(*[ num.eyes.blink_anim( rate_func = squish_rate_func( there_and_back, alpha, alpha+0.2 ) ) for num, alpha in zip( numbers[1:], 0.8*np.random.random(len(numbers)) ) ]) class MultiplicativeGroupOfReals(AdditiveGroupOfReals): CONFIG = { "number_line_center" : 0.5*UP, "shadow_line_center" : 1.5*DOWN, "x_min" : -3*FRAME_X_RADIUS, "x_max" : 3*FRAME_X_RADIUS, "positive_reals_color" : MAROON_B, } def setup(self): self.foreground_mobjects = VGroup() def construct(self): self.add_title() self.add_number_line() self.introduce_stretch_and_squish() self.show_zero_fixed_in_place() self.follow_one() self.every_positive_number_association() self.compose_actions(3, 2) self.compose_actions(4, 0.5) self.write_group_name() self.compose_actions(1.5, 1.5) def add_title(self): self.title = OldTexText("Group of stretching/squishing actions") self.title.to_edge(UP) self.add(self.title) def add_number_line(self): AdditiveGroupOfReals.add_number_line(self) self.zero_point = self.number_line.number_to_point(0) self.one = [m for m in self.number_line.numbers if m.get_tex() is "1"][0] self.one.add_background_rectangle() self.one.background_rectangle.scale(1.3) self.number_line.save_state() def introduce_stretch_and_squish(self): for num in [3, 0.25]: self.stretch(num) self.wait() self.play(self.number_line.restore) self.wait() def show_zero_fixed_in_place(self): arrow = Arrow(self.zero_point + UP, self.zero_point, buff = 0) arrow.set_color(ADDER_COLOR) words = OldTexText("Fix zero") words.set_color(ADDER_COLOR) words.next_to(arrow, UP) self.play( ShowCreation(arrow), Write(words) ) self.foreground_mobjects.add(arrow) self.stretch(4) self.stretch(0.1) self.wait() self.play(self.number_line.restore) self.play(FadeOut(words)) self.wait() self.zero_arrow = arrow def follow_one(self): dot = Dot(self.number_line.number_to_point(1)) arrow = Arrow(dot.get_center()+UP+RIGHT, dot) words = OldTexText("Follow one") words.next_to(arrow.get_start(), UP) for mob in dot, arrow, words: mob.set_color(MULTIPLIER_COLOR) three_line, half_line = [ DashedLine( self.number_line.number_to_point(num), self.shadow_line.number_to_point(num) ) for num in (3, 0.5) ] three_mob = [m for m in self.shadow_line.numbers if m.get_tex() == "3"][0] half_point = self.shadow_line.number_to_point(0.5) half_arrow = Arrow( half_point+UP+LEFT, half_point, buff = SMALL_BUFF, tip_length = 0.15, ) half_label = OldTex("1/2") half_label.scale(0.7) half_label.set_color(MULTIPLIER_COLOR) half_label.next_to(half_arrow.get_start(), LEFT, buff = SMALL_BUFF) self.play( ShowCreation(arrow), DrawBorderThenFill(dot), Write(words) ) self.number_line.add(dot) self.number_line.numbers.add(dot) self.number_line.save_state() self.wait() self.play(*list(map(FadeOut, [arrow, words]))) self.stretch(3) self.play( ShowCreation(three_line), Animation(self.one) ) dot_copy = dot.copy() self.play( dot_copy.move_to, three_line.get_bottom() ) self.play(Indicate(three_mob, run_time = 2)) self.wait() self.play( self.number_line.restore, *list(map(FadeOut, [three_line, dot_copy])) ) self.wait() self.stretch(0.5) self.play( ShowCreation(half_line), Animation(self.one) ) dot_copy = dot.copy() self.play( dot_copy.move_to, half_line.get_bottom() ) self.play( Write(half_label), ShowCreation(half_arrow) ) self.wait() self.play( self.number_line.restore, *list(map(FadeOut, [ half_label, half_arrow, half_line, dot_copy ])) ) self.wait() self.one_dot = dot def every_positive_number_association(self): positive_reals_line = Line( self.shadow_line.number_to_point(0), self.shadow_line.number_to_point(FRAME_X_RADIUS), color = self.positive_reals_color ) positive_reals_words = OldTexText("All positive reals") positive_reals_words.set_color(self.positive_reals_color) positive_reals_words.next_to(positive_reals_line, UP) positive_reals_words.add_background_rectangle() third_line, one_line = [ DashedLine( self.number_line.number_to_point(num), self.shadow_line.number_to_point(num) ) for num in (0.33, 1) ] self.play( self.zero_arrow.shift, 0.5*UP, rate_func = there_and_back ) self.wait() self.play( self.one_dot.shift, 0.25*UP, rate_func = wiggle ) self.stretch(3) self.stretch(0.33/3, run_time = 3) self.wait() self.play(ShowCreation(third_line), Animation(self.one)) self.play( ShowCreation(positive_reals_line), Write(positive_reals_words), ) self.wait() self.play( ReplacementTransform(third_line, one_line), self.number_line.restore, Animation(positive_reals_words), run_time = 2 ) self.number_line.add_to_back(one_line) self.number_line.save_state() self.stretch( 7, run_time = 10, rate_func = there_and_back, added_anims = [Animation(positive_reals_words)] ) self.wait() def compose_actions(self, num1, num2): words = VGroup(*[ OldTexText("(%s by %s)"%(word, str(num))) for num in (num1, num2, num1*num2) for word in ["Stretch" if num > 1 else "Squish"] ]) words.submobjects.insert(2, OldTex("=")) words.arrange(RIGHT) top_words = VGroup(*words[:2]) top_words.set_color(MULTIPLIER_COLOR) bottom_words = VGroup(*words[2:]) bottom_words.next_to(top_words, DOWN) words.scale(0.8) words.next_to(self.number_line, UP) words.to_edge(RIGHT) for num, word in zip([num1, num2], top_words): self.stretch( num, added_anims = [FadeIn(word)], run_time = 3 ) self.wait() self.play(Write(bottom_words, run_time = 2)) self.wait(2) self.play( ApplyMethod(self.number_line.restore, run_time = 2), FadeOut(words), ) self.wait() def write_group_name(self): new_title = OldTexText( "Multiplicative group of positive real numbers" ) new_title.to_edge(UP) VGroup( *new_title[:len("Multiplicative")] ).set_color(MULTIPLIER_COLOR) VGroup( *new_title[-len("positiverealnumbers"):] ).set_color(self.positive_reals_color) self.play(Transform(self.title, new_title)) self.wait() ### def stretch(self, factor, run_time = 2, **kwargs): kwargs["run_time"] = run_time target = self.number_line.copy() target.stretch_about_point(factor, 0, self.zero_point) total_factor = (target.number_to_point(1)-self.zero_point)[0] for number in target.numbers: number.stretch_in_place(1./factor, dim = 0) if total_factor < 0.7: number.stretch_in_place(total_factor, dim = 0) self.play( Transform(self.number_line, target, **kwargs), *kwargs.get("added_anims", []) ) def play(self, *anims, **kwargs): anims = list(anims) + [Animation(self.foreground_mobjects)] Scene.play(self, *anims, **kwargs) class MultiplicativeGroupOfComplexNumbers(AdditiveGroupOfComplexNumbers): CONFIG = { "dot_radius" : Dot.CONFIG["radius"], "y_min" : -3*FRAME_Y_RADIUS, "y_max" : 3*FRAME_Y_RADIUS, } def construct(self): self.add_plane() self.add_title() self.fix_zero_and_move_one() self.show_example_actions() self.show_action_at_i() self.show_action_at_i_again() self.show_i_squared_is_negative_one() self.talk_through_specific_example() self.show_break_down() self.example_actions_broken_down() def add_plane(self): AdditiveGroupOfComplexNumbers.add_plane(self) one_dot = Dot( self.z_to_point(1), color = MULTIPLIER_COLOR, radius = self.dot_radius, ) self.plane.add(one_dot) self.plane.one_dot = one_dot self.plane.save_state() self.add(self.plane) def add_title(self): title = OldTexText( "Multiplicative", "group of", "complex numbers" ) title.to_edge(UP) title[0].set_color(MULTIPLIER_COLOR) title[2].set_color(BLUE) title.add_background_rectangle() self.play(Write(title, run_time = 2)) self.wait() self.add_foreground_mobjects(title) def fix_zero_and_move_one(self): zero_arrow = Arrow( UP+1.25*LEFT, ORIGIN, buff = 2*self.dot_radius ) zero_arrow.set_color(ADDER_COLOR) zero_words = OldTexText("Fix zero") zero_words.set_color(ADDER_COLOR) zero_words.add_background_rectangle() zero_words.next_to(zero_arrow.get_start(), UP) one_point = self.z_to_point(1) one_arrow = Arrow( one_point+UP+1.25*RIGHT, one_point, buff = 2*self.dot_radius, color = MULTIPLIER_COLOR, ) one_words = OldTexText("Drag one") one_words.set_color(MULTIPLIER_COLOR) one_words.add_background_rectangle() one_words.next_to(one_arrow.get_start(), UP) self.play( Write(zero_words, run_time = 2), ShowCreation(zero_arrow), Indicate(self.plane.zero_dot, color = RED), ) self.play( Write(one_words, run_time = 2), ShowCreation(one_arrow), Indicate(self.plane.one_dot, color = RED), ) self.wait(2) self.play(*list(map(FadeOut, [ zero_words, zero_arrow, one_words, one_arrow, ]))) def show_example_actions(self): z_list = [ complex(2), complex(0.5), complex(2, 1), complex(-2, 2), ] for last_z, z in zip([1] + z_list, z_list): self.multiply_by_z(z/last_z) self.wait() self.reset_plane() self.wait() def show_action_at_i(self): i_point = self.z_to_point(complex(0, 1)) i_dot = Dot(i_point) i_dot.set_color(RED) i_arrow = Arrow(i_point+UP+LEFT, i_point) i_arrow.set_color(i_dot.get_color()) arc = Arc( start_angle = np.pi/24, angle = 10*np.pi/24, radius = self.z_to_point(1)[0], num_anchors = 20, ) arc.add_tip(tip_length = 0.15) arc.set_color(YELLOW) self.play( ShowCreation(i_arrow), DrawBorderThenFill(i_dot) ) self.wait() self.play( FadeOut(i_arrow), ShowCreation(arc) ) self.add_foreground_mobjects(arc) self.wait(2) self.multiply_by_z(complex(0, 1), run_time = 3) self.remove(i_dot) self.wait() self.turn_arrow = arc def show_action_at_i_again(self): neg_one_label = [m for m in self.real_labels if m.get_tex() == "-1"][0] half_turn_arc = Arc( start_angle = np.pi/12, angle = 10*np.pi/12, color = self.turn_arrow.get_color() ) half_turn_arc.add_tip(tip_length = 0.15) self.multiply_by_z(complex(0, 1), run_time = 3) self.wait() self.play(Transform( self.turn_arrow, half_turn_arc, path_arc = np.pi/2 )) self.wait() self.play(Indicate(neg_one_label, run_time = 2)) self.wait() self.foreground_mobjects.remove(self.turn_arrow) self.reset_plane(FadeOut(self.turn_arrow)) def show_i_squared_is_negative_one(self): equation = OldTex("i", "\\cdot", "i", "=", "-1") terms = equation[::2] equation.add_background_rectangle() equation.next_to(ORIGIN, RIGHT) equation.shift(1.5*UP) equation.set_color(MULTIPLIER_COLOR) self.play(Write(equation, run_time = 2)) self.wait() for term in terms[:2]: self.multiply_by_z( complex(0, 1), added_anims = [ Animation(equation), Indicate(term, color = RED, run_time = 2) ] ) self.wait() self.play(Indicate(terms[-1], color = RED, run_time = 2)) self.wait() self.reset_plane(FadeOut(equation)) def talk_through_specific_example(self): z = complex(2, 1) angle = np.angle(z) point = self.z_to_point(z) dot = Dot(point, color = WHITE) label = OldTex("%d + %di"%(z.real, z.imag)) label.add_background_rectangle() label.next_to(dot, UP+RIGHT, buff = 0) brace = Brace( Line(ORIGIN, self.z_to_point(np.sqrt(5))), UP ) brace_text = brace.get_text("$\\sqrt{5}$") brace_text.add_background_rectangle() brace_text.scale(0.7, about_point = brace.get_top()) brace.rotate(angle) brace_text.rotate(angle).rotate(-angle) VGroup(brace, brace_text).set_color(MAROON_B) arc = Arc(angle, color = WHITE, radius = 0.5) angle_label = OldTex("30^\\circ") angle_label.scale(0.7) angle_label.next_to( arc, RIGHT, buff = SMALL_BUFF, aligned_edge = DOWN ) angle_label.set_color(MULTIPLIER_COLOR) self.play( Write(label), DrawBorderThenFill(dot) ) self.add_foreground_mobjects(label, dot) self.wait() self.multiply_by_z(z, run_time = 3) self.wait() self.reset_plane() self.multiply_by_z( np.exp(complex(0, 1)*angle), added_anims = [ ShowCreation(arc, run_time = 2), Write(angle_label) ] ) self.add_foreground_mobjects(arc, angle_label) self.wait() self.play( GrowFromCenter(brace), Write(brace_text) ) self.add_foreground_mobjects(brace, brace_text) self.multiply_by_z(np.sqrt(5), run_time = 3) self.wait(2) to_remove = [ label, dot, brace, brace_text, arc, angle_label, ] for mob in to_remove: self.foreground_mobjects.remove(mob) self.reset_plane(*list(map(FadeOut, to_remove))) self.wait() def show_break_down(self): positive_reals = Line(ORIGIN, FRAME_X_RADIUS*RIGHT) positive_reals.set_color(MAROON_B) circle = Circle( radius = self.z_to_point(1)[0], color = MULTIPLIER_COLOR ) real_actions = [3, 0.5, 1] rotation_actions = [ np.exp(complex(0, angle)) for angle in np.linspace(0, 2*np.pi, 4)[1:] ] self.play(ShowCreation(positive_reals)) self.add_foreground_mobjects(positive_reals) for last_z, z in zip([1]+real_actions, real_actions): self.multiply_by_z(z/last_z) self.wait() self.play(ShowCreation(circle)) self.add_foreground_mobjects(circle) for last_z, z in zip([1]+rotation_actions, rotation_actions): self.multiply_by_z(z/last_z, run_time = 3) self.wait() def example_actions_broken_down(self): z_list = [ complex(2, -1), complex(-2, -3), complex(0.5, 0.5), ] for z in z_list: dot = Dot(self.z_to_point(z)) dot.set_color(WHITE) dot.save_state() dot.move_to(self.plane.one_dot) dot.set_fill(opacity = 1) norm = np.abs(z) angle = np.angle(z) rot_z = np.exp(complex(0, angle)) self.play(dot.restore) self.multiply_by_z(norm) self.wait() self.multiply_by_z(rot_z) self.wait() self.reset_plane(FadeOut(dot)) ## def multiply_by_z(self, z, run_time = 2, **kwargs): target = self.plane.copy() target.apply_complex_function(lambda w : z*w) for dot in target.zero_dot, target.one_dot: dot.set_width(2*self.dot_radius) angle = np.angle(z) kwargs["path_arc"] = kwargs.get("path_arc", angle) self.play( Transform(self.plane, target, run_time = run_time, **kwargs), *kwargs.get("added_anims", []) ) def reset_plane(self, *added_anims): self.play(FadeOut(self.plane), *added_anims) self.plane.restore() self.play(FadeIn(self.plane)) class ExponentsAsRepeatedMultiplication(TeacherStudentsScene): def construct(self): self.show_repeated_multiplication() self.show_non_counting_exponents() def show_repeated_multiplication(self): three_twos = OldTex("2 \\cdot 2 \\cdot 2") five_twos = OldTex("2 \\cdot "*4 + "2") exponents = [] teacher_corner = self.get_teacher().get_corner(UP+LEFT) for twos in three_twos, five_twos: twos.next_to(teacher_corner, UP) twos.generate_target() d = sum(np.array(list(twos.get_tex())) == "2") exponents.append(d) twos.brace = Brace(twos, UP) twos.exp = twos.brace.get_text("$2^%d$"%d) twos.generate_target() twos.brace_anim = MaintainPositionRelativeTo( VGroup(twos.brace, twos.exp), twos ) self.play( GrowFromCenter(three_twos.brace), Write(three_twos.exp), self.get_teacher().change_mode, "raise_right_hand", ) for mob in three_twos: self.play(Write(mob, run_time = 1)) self.play_student_changes(*["pondering"]*3) self.wait(2) self.play( FadeIn(five_twos.brace), FadeIn(five_twos.exp), three_twos.center, three_twos.to_edge, UP, 2*LARGE_BUFF, three_twos.brace_anim, ) self.play(FadeIn( five_twos, run_time = 3, lag_ratio = 0.5 )) self.wait(2) cdot = OldTex("\\cdot") lhs = OldTex("2^{%d + %d} = "%tuple(exponents)) rule = VGroup( lhs, three_twos.target, cdot, five_twos.target ) rule.arrange() lhs.next_to(three_twos.target, LEFT, aligned_edge = DOWN) rule.next_to(self.get_pi_creatures(), UP) self.play( MoveToTarget(three_twos), three_twos.brace_anim, MoveToTarget(five_twos), five_twos.brace_anim, Write(cdot), self.get_teacher().change_mode, "happy", ) self.wait() self.play(Write(lhs)) self.wait() self.play_student_changes(*["happy"]*3) self.wait() general_equation = OldTex("2^{x+y}=", "2^x", "2^y") general_equation.to_edge(UP, buff = MED_LARGE_BUFF) general_equation[0].set_color(GREEN_B) VGroup(*general_equation[1:]).set_color(MULTIPLIER_COLOR) self.play(*[ ReplacementTransform( mob.copy(), term, run_time = 2 ) for term, mob in zip(general_equation, [ lhs, three_twos.exp, five_twos.exp ]) ]) self.wait(2) self.exponential_rule = general_equation self.expanded_exponential_rule = VGroup( lhs, three_twos, three_twos.brace, three_twos.exp, cdot, five_twos, five_twos.brace, five_twos.exp, ) def show_non_counting_exponents(self): self.play( self.expanded_exponential_rule.scale, 0.5, self.expanded_exponential_rule.to_corner, UP+LEFT ) half_power, neg_power, imag_power = alt_powers = VGroup( OldTex("2^{1/2}"), OldTex("2^{-1}"), OldTex("2^{i}"), ) alt_powers.arrange(RIGHT, buff = LARGE_BUFF) alt_powers.next_to(self.get_students(), UP, buff = LARGE_BUFF) self.play( Write(half_power, run_time = 2), *[ ApplyMethod(pi.change_mode, "pondering") for pi in self.get_pi_creatures() ] ) for mob in alt_powers[1:]: self.play(Write(mob, run_time = 1)) self.wait() self.wait() self.play(*it.chain(*[ [pi.change_mode, "confused", pi.look_at, half_power] for pi in self.get_students() ])) for power in alt_powers[:2]: self.play(Indicate(power)) self.wait() self.wait() self.teacher_says("Extend the \\\\ definition") self.play_student_changes("pondering", "confused", "erm") self.wait() half_expression = OldTex( "\\big(", "2^{1/2}", "\\big)", "\\big(2^{1/2}\\big) = 2^{1}" ) neg_one_expression = OldTex( "\\big(", "2^{-1}", "\\big)", "\\big( 2^{1} \\big) = 2^{0}" ) expressions = VGroup(half_expression, neg_one_expression) expressions.arrange( DOWN, aligned_edge = LEFT, buff = MED_LARGE_BUFF ) expressions.next_to(self.get_students(), UP, buff = LARGE_BUFF) expressions.to_edge(LEFT) self.play( Transform(half_power, half_expression[1]), Write(half_expression), RemovePiCreatureBubble(self.get_teacher()), ) self.wait() self.play( Transform(neg_power, neg_one_expression[1]), Write(neg_one_expression) ) self.wait(2) self.play( self.exponential_rule.next_to, self.get_teacher().get_corner(UP+LEFT), UP, MED_LARGE_BUFF, self.get_teacher().change_mode, "raise_right_hand", ) self.wait(2) self.play( imag_power.move_to, UP, imag_power.scale, 1.5, imag_power.set_color, BLUE, self.exponential_rule.to_edge, RIGHT, self.get_teacher().change_mode, "speaking" ) self.play(*it.chain(*[ [pi.change_mode, "pondering", pi.look_at, imag_power] for pi in self.get_students() ])) self.wait() group_theory_words = OldTexText("Group theory?") group_theory_words.next_to( self.exponential_rule, UP, buff = LARGE_BUFF ) arrow = Arrow( group_theory_words, self.exponential_rule, color = WHITE, buff = SMALL_BUFF ) group_theory_words.shift_onto_screen() self.play( Write(group_theory_words), ShowCreation(arrow) ) self.wait(2) class ExponentsAsHomomorphism(Scene): CONFIG = { "top_line_center" : 2.5*UP, "top_line_config" : { "x_min" : -16, "x_max" : 16, }, "bottom_line_center" : 2.5*DOWN, "bottom_line_config" : { "x_min" : -FRAME_WIDTH, "x_max" : FRAME_WIDTH, } } def construct(self): self.comment_on_equation() self.show_adders() self.show_multipliers() self.confused_at_mapping() self.talk_through_composition() self.add_quote() def comment_on_equation(self): equation = OldTex( "2", "^{x", "+", "y}", "=", "2^x", "2^y" ) lhs = VGroup(*equation[:4]) rhs = VGroup(*equation[5:]) lhs_brace = Brace(lhs, UP) lhs_text = lhs_brace.get_text("Add inputs") lhs_text.set_color(GREEN_B) rhs_brace = Brace(rhs, DOWN) rhs_text = rhs_brace.get_text("Multiply outputs") rhs_text.set_color(MULTIPLIER_COLOR) self.add(equation) for brace, text in (lhs_brace, lhs_text), (rhs_brace, rhs_text): self.play( GrowFromCenter(brace), Write(text) ) self.wait() self.wait() self.equation = equation self.lhs_brace_group = VGroup(lhs_brace, lhs_text) self.rhs_brace_group = VGroup(rhs_brace, rhs_text) def show_adders(self): equation = self.equation adders = VGroup(equation[1], equation[3]).copy() top_line = NumberLine(**self.top_line_config) top_line.add_numbers() top_line.shift(self.top_line_center) self.play( adders.scale, 1.5, adders.center, adders.space_out_submobjects, 2, adders.to_edge, UP, adders.set_color, GREEN_B, FadeOut(self.lhs_brace_group), Write(top_line) ) self.wait() for x in 3, 5, -8: self.play(top_line.shift, x*RIGHT, run_time = 2) self.wait() self.top_line = top_line self.adders = adders def show_multipliers(self): equation = self.equation multipliers = VGroup(*self.equation[-2:]).copy() bottom_line = NumberLine(**self.bottom_line_config) bottom_line.add_numbers() bottom_line.shift(self.bottom_line_center) self.play( multipliers.space_out_submobjects, 4, multipliers.next_to, self.bottom_line_center, UP, MED_LARGE_BUFF, multipliers.set_color, YELLOW, FadeOut(self.rhs_brace_group), Write(bottom_line), ) stretch_kwargs = { } for x in 3, 1./5, 5./3: self.play( self.get_stretch_anim(bottom_line, x), run_time = 3 ) self.wait() self.bottom_line = bottom_line self.multipliers = multipliers def confused_at_mapping(self): arrow = Arrow( self.top_line.get_bottom()[1]*UP, self.bottom_line.get_top()[1]*UP, color = WHITE ) randy = Randolph(mode = "confused") randy.scale(0.75) randy.flip() randy.next_to(arrow, RIGHT, LARGE_BUFF) randy.look_at(arrow.get_top()) self.play(self.equation.to_edge, LEFT) self.play( ShowCreation(arrow), FadeIn(randy) ) self.play(randy.look_at, arrow.get_bottom()) self.play(Blink(randy)) self.wait() for x in 1, -2, 3, 1, -3: self.play( self.get_stretch_anim(self.bottom_line, 2**x), self.top_line.shift, x*RIGHT, randy.look_at, self.top_line, run_time = 2 ) if random.random() < 0.3: self.play(Blink(randy)) else: self.wait() self.randy = randy def talk_through_composition(self): randy = self.randy terms = list(self.adders) + list(self.multipliers) inputs = [-1, 2] target_texs = list(map(str, inputs)) target_texs += ["2^{%d}"%x for x in inputs] for mob, target_tex in zip(terms, target_texs): target = OldTex(target_tex) target.set_color(mob[0].get_color()) target.move_to(mob, DOWN) if mob in self.adders: target.to_edge(UP) mob.target = target self.play( self.equation.next_to, ORIGIN, LEFT, MED_LARGE_BUFF, randy.change_mode, "pondering", randy.look_at, self.equation ) self.wait() self.play(randy.look_at, self.top_line) self.show_composition( *inputs, parallel_anims = list(map(MoveToTarget, self.adders)) ) self.play( FocusOn(self.bottom_line_center), randy.look_at, self.bottom_line_center, ) self.show_composition( *inputs, parallel_anims = list(map(MoveToTarget, self.multipliers)) ) self.wait() def add_quote(self): brace = Brace(self.equation, UP) quote = OldTexText("``Preserves the group structure''") quote.add_background_rectangle() quote.next_to(brace, UP) self.play( GrowFromCenter(brace), Write(quote), self.randy.look_at, quote, ) self.play(self.randy.change_mode, "thinking") self.play(Blink(self.randy)) self.wait() self.show_composition(-1, 2) self.wait() #### def show_composition(self, *inputs, **kwargs): parallel_anims = kwargs.get("parallel_anims", []) for x in range(len(inputs) - len(parallel_anims)): parallel_anims.append(Animation(Mobject())) for line in self.top_line, self.bottom_line: line.save_state() for x, parallel_anim in zip(inputs, parallel_anims): anims = [ ApplyMethod(self.top_line.shift, x*RIGHT), self.get_stretch_anim(self.bottom_line, 2**x), ] for anim in anims: anim.set_run_time(2) self.play(parallel_anim) self.play(*anims) self.wait() self.play(*[ line.restore for line in (self.top_line, self.bottom_line) ]) def get_stretch_anim(self, bottom_line, x): target = bottom_line.copy() target.stretch_about_point( x, 0, self.bottom_line_center, ) for number in target.numbers: number.stretch_in_place(1./x, dim = 0) return Transform(bottom_line, target) class DihedralCubeHomomorphism(GroupOfCubeSymmetries, SymmetriesOfSquare): def construct(self): angle_axis_pairs = [ (np.pi/2, OUT), (np.pi, RIGHT), (np.pi, OUT), (np.pi, UP+RIGHT), (-np.pi/2, OUT), (np.pi, UP+LEFT), ] angle_axis_pairs *= 3 title = OldTexText( "``", "Homo", "morph", "ism", "''", arg_separator = "" ) homo_brace = Brace(title[1], UP, buff = SMALL_BUFF) homo_def = homo_brace.get_text("same") morph_brace = Brace(title[2], UP, buff = SMALL_BUFF) morph_def = morph_brace.get_text("shape", buff = SMALL_BUFF) def_group = VGroup( homo_brace, homo_def, morph_brace, morph_def ) VGroup(title, def_group).to_edge(UP) homo_group = VGroup(title[1], homo_brace, homo_def) morph_group = VGroup(title[2], morph_brace, morph_def) equation = OldTex("f(X \\circ Y) = f(X) \\circ f(Y)") equation.next_to(title, DOWN) self.add(title, equation) arrow = Arrow(LEFT, RIGHT) cube = self.get_cube() cube.next_to(arrow, RIGHT) pose_matrix = self.get_pose_matrix() square = self.square = Square(**self.square_config) self.add_randy_to_square(square) square.next_to(arrow, LEFT) VGroup(square, arrow, cube).next_to( equation, DOWN, buff = MED_LARGE_BUFF ) self.add(square, cube) self.play(ShowCreation(arrow)) for i, (angle, raw_axis) in enumerate(angle_axis_pairs): posed_axis = np.dot(raw_axis, pose_matrix.T) self.play(*[ Rotate( mob, angle = angle, axis = axis, in_place = True, run_time = abs(angle/(np.pi/2)) ) for mob, axis in [(square, raw_axis), (cube, posed_axis)] ]) self.wait() if i == 2: for group, color in (homo_group, YELLOW), (morph_group, BLUE): part, remainder = group[0], VGroup(*group[1:]) remainder.set_color(color) self.play( part.set_color, color, FadeIn(remainder) ) class ComplexExponentiationAbstract(): CONFIG = { "start_base" : 2, "new_base" : 5, "group_type" : None, "color" : None, "vect" : None, } def construct(self): self.base = self.start_base example_inputs = [2, -3, 1] self.add_vertical_line() self.add_plane_unanimated() self.add_title() self.add_arrow() self.show_example(complex(1, 1)) self.draw_real_line() self.show_real_actions(*example_inputs) self.show_pure_imaginary_actions(*example_inputs) self.set_color_vertical_line() self.set_color_unit_circle() self.show_pure_imaginary_actions(*example_inputs) self.walk_input_up_vertical() self.change_base(self.new_base, str(self.new_base)) self.walk_input_up_vertical() self.change_base(np.exp(1), "e") self.take_steps_for_e() self.write_eulers_formula() self.show_pure_imaginary_actions(-np.pi, np.pi) self.wait() def add_vertical_line(self): line = Line(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) line.set_stroke(color = self.color, width = 10) line.shift(-FRAME_X_RADIUS*self.vect/2) self.add(line) self.add_foreground_mobjects(line) def add_plane_unanimated(self): should_skip_animations = self.skip_animations self.skip_animations = True self.add_plane() self.skip_animations = should_skip_animations def add_title(self): title = OldTexText(self.group_type, "group") title.scale(0.8) title[0].set_color(self.color) title.add_background_rectangle() title.to_edge(UP, buff = MED_SMALL_BUFF) self.add_foreground_mobjects(title) def add_arrow(self): arrow = Arrow(LEFT, RIGHT, color = WHITE) arrow.move_to(-FRAME_X_RADIUS*self.vect/2 + 2*UP) arrow.set_stroke(width = 6), func_mob = OldTex("2^x") func_mob.next_to(arrow, UP, aligned_edge = LEFT) func_mob.add_background_rectangle() self.add_foreground_mobjects(arrow, func_mob) self.wait() self.func_mob = func_mob def show_example(self, z): self.apply_action( z, run_time = 5, rate_func = there_and_back ) def draw_real_line(self): line = VGroup(Line(ORIGIN, FRAME_X_RADIUS*RIGHT)) if self.vect[0] < 0: line.add(Line(ORIGIN, FRAME_X_RADIUS*LEFT)) line.set_color(RED) self.play(*list(map(ShowCreation, line)), run_time = 3) self.add_foreground_mobjects(line) self.real_line = line def show_real_actions(self, *example_inputs): for x in example_inputs: self.apply_action(x) self.wait() def show_pure_imaginary_actions(self, *example_input_imag_parts): for y in example_input_imag_parts: self.apply_action(complex(0, y), run_time = 3) self.wait() def change_base(self, new_base, new_base_tex): new_func_mob = OldTex(new_base_tex + "^x") new_func_mob.add_background_rectangle() new_func_mob.move_to(self.func_mob) self.play(FocusOn(self.func_mob)) self.play(Transform(self.func_mob, new_func_mob)) self.wait() self.base = new_base def write_eulers_formula(self): formula = OldTex("e^", "{\\pi", "i}", "=", "-1") VGroup(*formula[1:3]).set_color(ADDER_COLOR) formula[-1].set_color(MULTIPLIER_COLOR) formula.scale(1.5) formula.next_to(ORIGIN, UP) formula.shift(-FRAME_X_RADIUS*self.vect/2) for part in formula: part.add_to_back(BackgroundRectangle(part)) Scene.play(self, Write(formula)) self.add_foreground_mobjects(formula) self.wait(2) class ComplexExponentiationAdderHalf( ComplexExponentiationAbstract, AdditiveGroupOfComplexNumbers ): CONFIG = { "group_type" : "Additive", "color" : GREEN_B, "vect" : LEFT, } def construct(self): ComplexExponentiationAbstract.construct(self) def apply_action(self, z, run_time = 2, **kwargs): kwargs["run_time"] = run_time self.play( ApplyMethod( self.plane.shift, self.z_to_point(z), **kwargs ), *kwargs.get("added_anims", []) ) def set_color_vertical_line(self): line = VGroup( Line(ORIGIN, FRAME_Y_RADIUS*UP), Line(ORIGIN, FRAME_Y_RADIUS*DOWN), ) line.set_color(YELLOW) self.play( FadeOut(self.real_line), *list(map(ShowCreation, line)) ) self.foreground_mobjects.remove(self.real_line) self.play( line.rotate, np.pi/24, rate_func = wiggle, ) self.wait() self.foreground_mobjects = [line] + self.foreground_mobjects self.vertical_line = line def set_color_unit_circle(self): line = VGroup( Line(ORIGIN, FRAME_Y_RADIUS*UP), Line(ORIGIN, FRAME_Y_RADIUS*DOWN), ) line.set_color(YELLOW) for submob in line: submob.insert_n_curves(10) submob.make_smooth() circle = VGroup( Circle(), Circle().flip(RIGHT), ) circle.set_color(YELLOW) circle.shift(FRAME_X_RADIUS*RIGHT) self.play(ReplacementTransform( line, circle, run_time = 3 )) self.remove(circle) self.wait() def walk_input_up_vertical(self): arrow = Arrow(ORIGIN, UP, buff = 0, tip_length = 0.15) arrow.set_color(GREEN) brace = Brace(arrow, RIGHT, buff = SMALL_BUFF) brace_text = brace.get_text("1 unit") brace_text.add_background_rectangle() Scene.play(self, ShowCreation(arrow)) self.add_foreground_mobjects(arrow) self.play( GrowFromCenter(brace), Write(brace_text, run_time = 1) ) self.add_foreground_mobjects(brace, brace_text) self.wait() self.apply_action(complex(0, 1)) self.wait(7)##Line up with MultiplierHalf to_remove = arrow, brace, brace_text for mob in to_remove: self.foreground_mobjects.remove(mob) self.play(*list(map(FadeOut, to_remove))) self.apply_action(complex(0, -1)) def take_steps_for_e(self): slide_values = [1, 1, 1, np.pi-3] braces = [ Brace(Line(ORIGIN, x*UP), RIGHT, buff = SMALL_BUFF) for x in np.cumsum(slide_values) ] labels = list(map(TexText, [ "1 unit", "2 units", "3 units", "$\\pi$ units", ])) for label, brace in zip(labels, braces): label.add_background_rectangle() label.next_to(brace, RIGHT, buff = SMALL_BUFF) curr_brace = None curr_label = None for slide_value, label, brace in zip(slide_values, labels, braces): self.apply_action(complex(0, slide_value)) if curr_brace is None: curr_brace = brace curr_label = label self.play( GrowFromCenter(curr_brace), Write(curr_label) ) self.add_foreground_mobjects(brace, label) else: self.play( Transform(curr_brace, brace), Transform(curr_label, label), ) self.wait() self.wait(4) ##Line up with multiplier half class ComplexExponentiationMultiplierHalf( ComplexExponentiationAbstract, MultiplicativeGroupOfComplexNumbers ): CONFIG = { "group_type" : "Multiplicative", "color" : MULTIPLIER_COLOR, "vect" : RIGHT, } def construct(self): ComplexExponentiationAbstract.construct(self) def apply_action(self, z, run_time = 2, **kwargs): kwargs["run_time"] = run_time self.multiply_by_z(self.base**z, **kwargs) def set_color_vertical_line(self): self.play(FadeOut(self.real_line)) self.foreground_mobjects.remove(self.real_line) self.wait(2) def set_color_unit_circle(self): line = VGroup( Line(ORIGIN, FRAME_Y_RADIUS*UP), Line(ORIGIN, FRAME_Y_RADIUS*DOWN), ) line.set_color(YELLOW) line.shift(FRAME_X_RADIUS*LEFT) for submob in line: submob.insert_n_curves(10) submob.make_smooth() circle = VGroup( Circle(), Circle().flip(RIGHT), ) circle.set_color(YELLOW) self.play(ReplacementTransform( line, circle, run_time = 3 )) self.add_foreground_mobjects(circle) self.wait() def walk_input_up_vertical(self): output_z = self.base**complex(0, 1) angle = np.angle(output_z) arc, brace, curved_brace, radians_label = \ self.get_arc_braces_and_label(angle) self.wait(3) self.apply_action(complex(0, 1)) Scene.play(self, ShowCreation(arc)) self.add_foreground_mobjects(arc) self.play(GrowFromCenter(brace)) self.play(Transform(brace, curved_brace)) self.play(Write(radians_label, run_time = 2)) self.wait(2) self.foreground_mobjects.remove(arc) self.play(*list(map(FadeOut, [arc, brace, radians_label]))) self.apply_action(complex(0, -1)) def get_arc_braces_and_label(self, angle): arc = Arc(angle) arc.set_stroke(GREEN, width = 6) arc_line = Line(RIGHT, RIGHT+angle*UP) brace = Brace(arc_line, RIGHT, buff = 0) for submob in brace.family_members_with_points(): submob.insert_n_curves(10) curved_brace = brace.copy() curved_brace.shift(LEFT) curved_brace.apply_complex_function( np.exp, maintain_smoothness = False ) half_point = arc.point_from_proportion(0.5) radians_label = OldTex("%.3f"%angle) radians_label.add_background_rectangle() radians_label.next_to( 1.5*half_point, np.round(half_point), buff = 0 ) return arc, brace, curved_brace, radians_label def take_steps_for_e(self): angles = [1, 2, 3, np.pi] curr_brace = None curr_label = None curr_arc = None for last_angle, angle in zip([0]+angles, angles): arc, brace, curved_brace, label = self.get_arc_braces_and_label(angle) if angle == np.pi: label = OldTex("%.5f\\dots"%np.pi) label.add_background_rectangle(opacity = 1) label.next_to(curved_brace, UP, buff = SMALL_BUFF) self.apply_action(complex(0, angle-last_angle)) self.wait(2)#Line up with Adder half if curr_brace is None: curr_brace = curved_brace curr_label = label curr_arc = arc brace.set_fill(opacity = 0) Scene.play(self, ShowCreation(curr_arc)) self.add_foreground_mobjects(curr_arc) self.play( ReplacementTransform(brace, curr_brace), Write(curr_label) ) self.add_foreground_mobjects(curr_brace, curr_label) else: Scene.play(self, ShowCreation(arc)) self.add_foreground_mobjects(arc) self.foreground_mobjects.remove(curr_arc) self.remove(curr_arc) curr_arc = arc self.play( Transform(curr_brace, curved_brace), Transform(curr_label, label), ) self.wait() self.wait() class ExpComplexHomomorphismPreviewAbstract(ComplexExponentiationAbstract): def construct(self): self.base = self.start_base self.add_vertical_line() self.add_plane_unanimated() self.add_title() self.add_arrow() self.change_base(np.exp(1), "e") self.write_eulers_formula() self.show_pure_imaginary_actions(np.pi, 0, -np.pi) self.wait() class ExpComplexHomomorphismPreviewAdderHalf( ExpComplexHomomorphismPreviewAbstract, ComplexExponentiationAdderHalf ): def construct(self): ExpComplexHomomorphismPreviewAbstract.construct(self) class ExpComplexHomomorphismPreviewMultiplierHalf( ExpComplexHomomorphismPreviewAbstract, ComplexExponentiationMultiplierHalf ): def construct(self): ExpComplexHomomorphismPreviewAbstract.construct(self) class WhyE(TeacherStudentsScene): def construct(self): self.student_says("Why e?") self.play(self.get_teacher().change_mode, "pondering") self.wait(3) class ReadFormula(Scene): def construct(self): formula = OldTex("e^", "{\\pi i}", "=", "-1") formula[1].set_color(GREEN_B) formula[3].set_color(MULTIPLIER_COLOR) formula.scale(2) randy = Randolph() randy.shift(2*LEFT) formula.next_to(randy, RIGHT, aligned_edge = UP) randy.look_at(formula) self.add(randy, formula) self.wait() self.play(randy.change_mode, "thinking") self.wait() self.play(Blink(randy)) self.wait(3) class EfvgtPatreonThanks(PatreonEndScreen): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Meshal Alshammari", "CrypticSwarm ", "Justin Helps", "Ankit Agarwal", "Yu Jun", "Shelby Doolittle", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Nils Schneider", "Mathew Bramson", "Guido Gambardella", "Jerry Ling", "Mark Govea", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } class EmeraldLogo(SVGMobject): CONFIG = { "file_name" : "emerald_logo", "stroke_width" : 0, "fill_opacity" : 1, # "helix_color" : "#439271", "helix_color" : GREEN_E, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.set_height(1) for submob in self.split()[18:]: submob.set_color(self.helix_color) class ECLPromo(PiCreatureScene): CONFIG = { "seconds_to_blink" : 4, } def construct(self): logo = EmeraldLogo() logo.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) logo_part1 = VGroup(*logo[:15]) logo_part2 = VGroup(*logo[15:]) rect = Rectangle(height = 9, width = 16) rect.set_height(5) rect.next_to(logo, DOWN) rect.to_edge(LEFT) self.play( self.pi_creature.change_mode, "hooray", ShowCreation(rect) ) self.wait(3) self.play(FadeIn( logo_part1, run_time = 3, lag_ratio = 0.5 )) logo_part2.save_state() logo_part2.scale(2) logo_part2.next_to(self.pi_creature.get_corner(UP+LEFT), UP) logo_part2.shift(MED_SMALL_BUFF*RIGHT) self.play( self.pi_creature.change_mode, "raise_right_hand", ) self.play(DrawBorderThenFill(logo_part2)) self.play( logo_part2.scale, 0.5, logo_part2.to_edge, UP ) self.play( logo_part2.restore, self.pi_creature.change_mode, "happy" ) self.play(self.pi_creature.look_at, rect) self.wait(10) self.play( self.pi_creature.change_mode, "pondering", self.pi_creature.look, DOWN ) self.wait(10) class ExpTransformation(ComplexTransformationScene): CONFIG = { "camera_class": ThreeDCamera, } def construct(self): self.camera.camera_distance = 10, self.add_transformable_plane() self.prepare_for_transformation(self.plane) final_plane = self.plane.copy().apply_complex_function(np.exp) cylinder = self.plane.copy().apply_function( lambda x_y_z : np.array([x_y_z[0], np.sin(x_y_z[1]), -np.cos(x_y_z[1])]) ) title = OldTex("x \\to e^x") title.add_background_rectangle() title.scale(1.5) title.next_to(ORIGIN, RIGHT) title.to_edge(UP, buff = MED_SMALL_BUFF) self.add_foreground_mobjects(title) self.play(Transform( self.plane, cylinder, run_time = 3, path_arc_axis = RIGHT, path_arc = np.pi, )) self.play(Rotate( self.plane, -np.pi/3, UP, run_time = 5 )) self.play(Transform(self.plane, final_plane, run_time = 3)) self.wait(3) class Thumbnail(Scene): def construct(self): formula = OldTex("e^", "{\\pi i}", "=", "-1") formula[1].set_color(GREEN_B) formula[3].set_color(YELLOW) formula.scale(4) formula.to_edge(UP, buff = LARGE_BUFF) self.add(formula) via = OldTexText("via") via.scale(2) groups = OldTexText("Group theory") groups.scale(3) groups.to_edge(DOWN) via.move_to(VGroup(formula, groups)) self.add(via, groups)
videos_3b1b/_2017/tattoo.py
from manim_imports_ext import * class TrigRepresentationsScene(Scene): CONFIG = { "unit_length" : 1.5, "arc_radius" : 0.5, "axes_color" : WHITE, "circle_color" : RED, "theta_color" : YELLOW, "theta_height" : 0.3, "theta_value" : np.pi/5, "x_line_colors" : MAROON_B, "y_line_colors" : BLUE, } def setup(self): self.init_axes() self.init_circle() self.init_theta_group() def init_axes(self): self.axes = Axes( unit_size = self.unit_length, ) self.axes.set_color(self.axes_color) self.add(self.axes) def init_circle(self): self.circle = Circle( radius = self.unit_length, color = self.circle_color ) self.add(self.circle) def init_theta_group(self): self.theta_group = self.get_theta_group() self.add(self.theta_group) def add_trig_lines(self, *funcs, **kwargs): lines = VGroup(*[ self.get_trig_line(func, **kwargs) for func in funcs ]) self.add(*lines) def get_theta_group(self): arc = Arc( self.theta_value, radius = self.arc_radius, color = self.theta_color, ) theta = OldTex("\\theta") theta.shift(1.5*arc.point_from_proportion(0.5)) theta.set_color(self.theta_color) theta.set_height(self.theta_height) line = Line(ORIGIN, self.get_circle_point()) dot = Dot(line.get_end(), radius = 0.05) return VGroup(line, arc, theta, dot) def get_circle_point(self): return rotate_vector(self.unit_length*RIGHT, self.theta_value) def get_trig_line(self, func_name = "sin", color = None): assert(func_name in ["sin", "tan", "sec", "cos", "cot", "csc"]) is_co = func_name in ["cos", "cot", "csc"] if color is None: if is_co: color = self.y_line_colors else: color = self.x_line_colors #Establish start point if func_name in ["sin", "cos", "tan", "cot"]: start_point = self.get_circle_point() else: start_point = ORIGIN #Establish end point if func_name is "sin": end_point = start_point[0]*RIGHT elif func_name is "cos": end_point = start_point[1]*UP elif func_name in ["tan", "sec"]: end_point = (1./np.cos(self.theta_value))*self.unit_length*RIGHT elif func_name in ["cot", "csc"]: end_point = (1./np.sin(self.theta_value))*self.unit_length*UP return Line(start_point, end_point, color = color) class Introduce(TeacherStudentsScene): def construct(self): self.teacher_says( "Something different today!", target_mode = "hooray", run_time = 2 ) self.play_student_changes("thinking", "happy", "sassy") self.random_blink(2) class ReactionsToTattoo(PiCreatureScene): def construct(self): modes = [ "horrified", "hesitant", "pondering", "thinking", "sassy", ] tattoo_on_math = OldTexText("Tattoo on \\\\ math") tattoo_on_math.to_edge(UP) self.wait(2) for mode in modes: self.play( self.pi_creature.change_mode, mode, self.pi_creature.look, UP+RIGHT ) self.wait(2) self.play( Write(tattoo_on_math), self.pi_creature.change_mode, "hooray", self.pi_creature.look, UP ) self.wait() self.change_mode("happy") self.wait(2) def create_pi_creature(self): randy = Randolph() randy.next_to(ORIGIN, DOWN) return randy class IntroduceCSC(TrigRepresentationsScene): def construct(self): self.clear() Cam_S_C = OldTexText("Cam", "S.", "C.") CSC = OldTexText("C", "S", "C", arg_separator = "") csc_of_theta = OldTexText("c", "s", "c", "(\\theta)", arg_separator = "") csc, of_theta = VGroup(*csc_of_theta[:3]), csc_of_theta[-1] of_theta[1].set_color(YELLOW) CSC.move_to(csc, DOWN) csc_line = self.get_trig_line("csc") csc_line.set_stroke(width = 8) cot_line = self.get_trig_line("cot") cot_line.set_color(WHITE) brace = Brace(csc_line, LEFT) self.play(Write(Cam_S_C)) self.wait() self.play(Transform(Cam_S_C, CSC)) self.wait() self.play(Transform(Cam_S_C, csc)) self.remove(Cam_S_C) self.add(csc) self.play(Write(of_theta)) self.wait(2) csc_of_theta.add_to_back(BackgroundRectangle(csc)) self.play( ShowCreation(self.axes), ShowCreation(self.circle), GrowFromCenter(brace), csc_of_theta.rotate, np.pi/2, csc_of_theta.next_to, brace, LEFT, path_arc = np.pi/2, ) self.play(Write(self.theta_group, run_time = 1)) self.play(ShowCreation(cot_line)) self.play( ShowCreation(csc_line), csc.set_color, csc_line.get_color(), ) self.wait(3) class TeachObscureTrigFunctions(TeacherStudentsScene): def construct(self): self.teacher_says( "$\\sec(\\theta)$, ", "$\\csc(\\theta)$, ", "$\\cot(\\theta)$", ) content = self.teacher.bubble.content.copy() self.play_student_changes(*["confused"]*3) self.student_says( "But why?", target_mode = "pleading", added_anims = [content.to_corner, UP+RIGHT] ) self.wait() self.play(self.get_teacher().change_mode, "pondering") self.wait(3) class CanYouExplainTheTattoo(TeacherStudentsScene): def construct(self): self.student_says(""" Wait, can you explain the actual tattoo here? """) self.random_blink() self.play(self.get_teacher().change_mode, "hooray") self.wait() class ExplainTrigFunctionDistances(TrigRepresentationsScene, PiCreatureScene): CONFIG = { "use_morty" : False, "alt_theta_val" : 2*np.pi/5, } def setup(self): PiCreatureScene.setup(self) TrigRepresentationsScene.setup(self) def construct(self): self.introduce_angle() self.show_sine_and_cosine() self.show_tangent_and_cotangent() self.show_secant_and_cosecant() self.explain_cosecant() self.summarize_full_group() def introduce_angle(self): self.remove(self.circle) self.remove(self.theta_group) line, arc, theta, dot = self.theta_group line.rotate(-self.theta_value) brace = Brace(line, UP, buff = SMALL_BUFF) one = brace.get_text("1", buff = SMALL_BUFF) VGroup(line, brace, one).rotate(self.theta_value) one.rotate(-self.theta_value) self.circle.rotate(self.theta_value) words = OldTexText("Corresponding point") words.next_to(dot, UP+RIGHT, buff = 1.5*LARGE_BUFF) words.shift_onto_screen() arrow = Arrow(words.get_bottom(), dot, buff = SMALL_BUFF) self.play( ShowCreation(line), ShowCreation(arc), ) self.play(Write(theta)) self.play(self.pi_creature.change_mode, "pondering") self.play( ShowCreation(self.circle), Rotating(line, rate_func = smooth, in_place = False), run_time = 2 ) self.play( Write(words), ShowCreation(arrow), ShowCreation(dot) ) self.wait() self.play( GrowFromCenter(brace), Write(one) ) self.wait(2) self.play(*list(map(FadeOut, [ words, arrow, brace, one ]))) self.radial_line_label = VGroup(brace, one) def show_sine_and_cosine(self): sin_line, sin_brace, sin_text = sin_group = self.get_line_brace_text("sin") cos_line, cos_brace, cos_text = cos_group = self.get_line_brace_text("cos") self.play(ShowCreation(sin_line)) self.play( GrowFromCenter(sin_brace), Write(sin_text), ) self.play(self.pi_creature.change_mode, "happy") self.play(ShowCreation(cos_line)) self.play( GrowFromCenter(cos_brace), Write(cos_text), ) self.wait() self.change_mode("well") mover = VGroup( sin_group, cos_group, self.theta_group, ) thetas = np.linspace(self.theta_value, self.alt_theta_val, 100) targets = [] for theta in thetas: self.theta_value = theta targets.append(VGroup( self.get_line_brace_text("sin"), self.get_line_brace_text("cos"), self.get_theta_group() )) self.play(Succession( *[ Transform(mover, target, rate_func=linear) for target in targets ], run_time = 5, rate_func = there_and_back )) self.theta_value = thetas[0] self.change_mode("happy") self.wait() self.sin_group, self.cos_group = sin_group, cos_group def show_tangent_and_cotangent(self): tan_group = self.get_line_brace_text("tan") cot_group = self.get_line_brace_text("cot") tan_text = tan_group[-1] cot_text = cot_group[-1] line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) line.rotate(self.theta_value) line.move_to(self.theta_group[-1]) line.set_stroke(width = 2) sin_tex = "{\\sin(\\theta)}" cos_tex = "{\\cos(\\theta)}" tan_frac = OldTex("= \\frac" + sin_tex + cos_tex) cot_frac = OldTex("= \\frac" + cos_tex + sin_tex) tan_frac.to_corner(UP+LEFT) tan_frac.shift(2*RIGHT) cot_frac.next_to(tan_frac, DOWN) self.change_mode("pondering") for frac, text in (tan_frac, tan_text), (cot_frac, cot_text): VGroup(frac[5], frac[-2]).set_color(YELLOW) frac.scale(0.7) text.save_state() text.next_to(frac, LEFT) self.play(Write(VGroup(text, frac))) self.wait() self.change_mode("confused") self.wait() self.play(*list(map(FadeOut, [ tan_frac, cot_frac, self.sin_group, self.cos_group ]))) self.wait() self.play( self.theta_group[-1].set_color, YELLOW, ShowCreation(line), self.pi_creature.change_mode, 'pondering' ) small_lines = VGroup() for group in tan_group, cot_group: small_line, brace, text = group self.play( ShowCreation(small_line), GrowFromCenter(brace), text.restore, ) self.wait() small_lines.add(small_line) self.play(FadeOut(line), Animation(small_lines)) mover = VGroup( tan_group, cot_group, self.theta_group, ) thetas = np.linspace(self.theta_value, self.alt_theta_val, 100) targets = [] for theta in thetas: self.theta_value = theta targets.append(VGroup( self.get_line_brace_text("tan"), self.get_line_brace_text("cot"), self.get_theta_group() )) self.play(Succession( *[ Transform(mover, target, rate_func=linear) for target in targets ], run_time = 5, rate_func = there_and_back )) self.theta_value = thetas[0] self.change_mode("happy") self.wait(2) self.tangent_line = self.get_tangent_line() self.add(self.tangent_line) self.play(*it.chain(*[ list(map(FadeOut, [tan_group, cot_group])), [Animation(self.theta_group[-1])] ])) def show_secant_and_cosecant(self): sec_group = self.get_line_brace_text("sec") csc_group = self.get_line_brace_text("csc") sec_line, sec_brace, sec_text = sec_group csc_line, csc_brace, csc_text = csc_group sec_frac = OldTex("= \\frac{1}{\\cos(\\theta)}") sec_frac.to_corner(UP+LEFT).shift(2*RIGHT) csc_frac = OldTex("= \\frac{1}{\\sin(\\theta)}") csc_frac.next_to(sec_frac, DOWN) sec_dot, csc_dot = [ Dot(line.get_end(), color = line.get_color()) for line in (sec_line, csc_line) ] sec_group.add(sec_dot) csc_group.add(csc_dot) for text, frac in (sec_text, sec_frac), (csc_text, csc_frac): frac[-2].set_color(YELLOW) frac.scale(0.7) text.save_state() text.next_to(frac, LEFT) frac.add_to_back(text.copy()) self.play( Write(frac), self.pi_creature.change_mode, "erm" ) self.wait() self.wait() for group in sec_group, csc_group: line, brace, text, dot = group dot.save_state() dot.move_to(text) dot.set_fill(opacity = 0) self.play(dot.restore) self.wait() self.play( ShowCreation(line), GrowFromCenter(brace), text.restore, self.pi_creature.change_mode, "pondering" ) self.wait() mover = VGroup( sec_group, csc_group, self.theta_group, self.tangent_line, ) thetas = np.linspace(self.theta_value, self.alt_theta_val, 100) targets = [] for theta in thetas: self.theta_value = theta new_sec_group = self.get_line_brace_text("sec") new_csc_group = self.get_line_brace_text("csc") for group in new_sec_group, new_csc_group: line = group[0] group.add( Dot(line.get_end(), color = line.get_color()) ) targets.append(VGroup( new_sec_group, new_csc_group, self.get_theta_group(), self.get_tangent_line(), )) self.play(Succession( *[ Transform(mover, target, rate_func=linear) for target in targets ], run_time = 5, rate_func = there_and_back )) self.theta_value = thetas[0] self.change_mode("confused") self.wait(2) self.play(*list(map(FadeOut, [ sec_group, sec_frac ]))) self.csc_group = csc_group self.csc_frac =csc_frac def explain_cosecant(self): sin_group = self.get_line_brace_text("sin") sin_line, sin_brace, sin_text = sin_group csc_line, csc_brace, csc_text, csc_dot = self.csc_group csc_subgroup = VGroup(csc_brace, csc_text) arc_theta = VGroup(*self.theta_group[1:3]).copy() arc_theta.rotate(-np.pi/2) arc_theta.shift(csc_line.get_end()) arc_theta[1].rotate(np.pi/2) radial_line = self.theta_group[0] tri1 = Polygon( ORIGIN, radial_line.get_end(), sin_line.get_end(), color = GREEN, stroke_width = 8, ) tri2 = Polygon( csc_line.get_end(), ORIGIN, radial_line.get_end(), color = GREEN, stroke_width = 8, ) opp_over_hyp = OldTex( "\\frac{\\text{Opposite}}{\\text{Hypotenuse}} =" ) frac1 = OldTex("\\frac{\\sin(\\theta)}{1}") frac1.next_to(opp_over_hyp) frac1[-4].set_color(YELLOW) frac2 = OldTex("= \\frac{1}{\\csc(\\theta)}") frac2.next_to(frac1) frac2[-2].set_color(YELLOW) frac_group = VGroup(opp_over_hyp, frac1, frac2) frac_group.set_width(FRAME_X_RADIUS-1) frac_group.next_to(ORIGIN, RIGHT).to_edge(UP) question = OldTexText("Why is this $\\theta$?") question.set_color(YELLOW) question.to_corner(UP+RIGHT) arrow = Arrow(question.get_bottom(), arc_theta) one_brace, one = self.radial_line_label one.move_to(one_brace.get_center_of_mass()) self.play(ShowCreation(tri1)) self.play( ApplyMethod(tri1.rotate, np.pi/12, rate_func = wiggle), self.pi_creature.change_mode, "thinking" ) self.wait() tri1.save_state() self.play(Transform(tri1, tri2, path_arc = np.pi/2)) self.play(Write(arc_theta)) self.play(ApplyMethod( tri1.rotate, np.pi/12, rate_func = wiggle )) self.wait(2) self.play( Write(question), ShowCreation(arrow), self.pi_creature.change_mode, "confused" ) self.wait(2) self.play(*list(map(FadeOut, [question, arrow]))) self.play(Write(opp_over_hyp)) self.wait() csc_subgroup.save_state() self.play( tri1.restore, csc_subgroup.fade, 0.7 ) self.play( ShowCreation(sin_line), GrowFromCenter(sin_brace), Write(sin_text) ) self.wait() self.play(Write(one)) self.wait() self.play(Write(frac1)) self.wait() self.play( Transform(tri1, tri2), FadeOut(sin_group) ) self.play( radial_line.rotate, np.pi/12, rate_func = wiggle ) self.wait() self.play(csc_subgroup.restore) self.wait() self.play(Write(frac2)) self.change_mode("happy") self.play(FadeOut(opp_over_hyp)) self.reciprocate(frac1, frac2) self.play(*list(map(FadeOut, [ one, self.csc_group, tri1, frac1, frac2, self.csc_frac, arc_theta ]))) def reciprocate(self, frac1, frac2): # Not general, meant only for these definitions: # frac1 = OldTex("\\frac{\\sin(\\theta)}{1}") # frac2 = OldTex("= \\frac{1}{\\csc(\\theta)}") num1 = VGroup(*frac1[:6]) dem1 = frac1[-1] num2 = frac2[1] dem2 = VGroup(*frac2[-6:]) group = VGroup(frac1, frac2) self.play( group.scale, 1/0.7, group.to_corner, UP+RIGHT, ) self.play( num1.move_to, dem1, dem1.move_to, num1, num2.move_to, dem2, dem2.move_to, num2, path_arc = np.pi ) self.wait() self.play( dem2.move_to, frac2[2], VGroup(*frac2[1:3]).set_fill, BLACK, 0 ) self.wait() def summarize_full_group(self): scale_factor = 1.5 theta_subgroup = VGroup(self.theta_group[0], self.theta_group[-1]) self.play(*it.chain(*[ [mob.scale, scale_factor] for mob in [ self.circle, self.axes, theta_subgroup, self.tangent_line ] ])) self.unit_length *= scale_factor to_fade = VGroup() for func_name in ["sin", "tan", "sec", "cos", "cot", "csc"]: line, brace, text = self.get_line_brace_text(func_name) if func_name in ["sin", "cos"]: angle = line.get_angle() if np.cos(angle) < 0: angle += np.pi if func_name is "sin": target = line.get_center()+0.2*LEFT+0.1*DOWN else: target = VGroup(brace, line).get_center_of_mass() text.scale(0.75) text.rotate(angle) text.move_to(target) line.set_stroke(width = 6) self.play( ShowCreation(line), Write(text, run_time = 1) ) else: self.play( ShowCreation(line), GrowFromCenter(brace), Write(text, run_time = 1) ) if func_name in ["sec", "csc", "cot"]: to_fade.add(*self.get_mobjects_from_last_animation()) if func_name is "sec": self.wait() self.wait() self.change_mode("surprised") self.wait(2) self.remove(self.tangent_line) self.play( FadeOut(to_fade), self.pi_creature.change_mode, "sassy" ) self.wait(2) def get_line_brace_text(self, func_name = "sin"): line = self.get_trig_line(func_name) angle = line.get_angle() vect = rotate_vector(UP, angle) vect = np.round(vect, 1) if (vect[1] < 0) ^ (func_name is "sec"): vect = -vect angle += np.pi brace = Brace( Line( line.get_length()*LEFT/2, line.get_length()*RIGHT/2, ), UP ) brace.rotate(angle) brace.shift(line.get_center()) brace.set_color(line.get_color()) text = OldTex("\\%s(\\theta)"%func_name) text.scale(0.75) text[-2].set_color(self.theta_color) text.add_background_rectangle() text.next_to(brace.get_center_of_mass(), vect, buff = 1.2*MED_SMALL_BUFF) return VGroup(line, brace, text) def get_tangent_line(self): return Line( self.unit_length*(1./np.sin(self.theta_value))*UP, self.unit_length*(1./np.cos(self.theta_value))*RIGHT, color = GREY ) class RenameAllInTermsOfSine(Scene): def construct(self): texs = [ "\\sin(\\theta)", "\\cos(\\theta)", "\\tan(\\theta)", "\\csc(\\theta)", "\\sec(\\theta)", "\\cot(\\theta)", ] shift_vals = [ 4*LEFT+3*UP, 4*LEFT+UP, 4*LEFT+DOWN, 4*RIGHT+3*UP, 4*RIGHT+UP, 4*RIGHT+DOWN, ] equivs = [ "", "= \\sin(90^\\circ - \\theta)", "= \\frac{\\sin(\\theta)}{\\sin(90^\\circ - \\theta)}", "= \\frac{1}{\\sin(\\theta)}", "= \\frac{1}{\\sin(90^\\circ - \\theta)}", "= \\frac{\\sin(90^\\circ - \\theta)}{\\sin(\\theta)}", ] mobs = VGroup(*list(map(Tex, texs))) sin, cos, tan = mobs[:3] sin.target_color = YELLOW cos.target_color = GREEN tan.target_color = RED rhs_mobs = VGroup(*list(map(Tex, equivs))) rhs_mobs.submobjects[0] = VectorizedPoint() for mob, shift_val in zip(mobs, shift_vals): mob.shift(shift_val) self.play(Write(mobs)) self.wait() for mob, rhs_mob in zip(mobs, rhs_mobs): rhs_mob.next_to(mob) rhs_mob.set_color(sin.target_color) mob.save_state() mob.generate_target() VGroup(mob.target, rhs_mob).move_to(mob) sin.target.set_color(sin.target_color) self.play(*it.chain(*[ list(map(MoveToTarget, mobs)), [Write(rhs_mobs)] ])) self.wait(2) anims = [] for mob, rhs_mob in list(zip(mobs, rhs_mobs))[1:3]: anims += [ FadeOut(rhs_mob), mob.restore, mob.set_color, mob.target_color, ] self.play(*anims) self.wait() new_rhs_mobs = [ OldTex("=\\frac{1}{\\%s(\\theta)}"%s).set_color(color) for s, color in [ ("cos", cos.target_color), ("tan", tan.target_color), ] ] anims = [] for mob, rhs, new_rhs in zip(mobs[-2:], rhs_mobs[-2:], new_rhs_mobs): new_rhs.next_to(mob) VGroup(mob.target, new_rhs).move_to( VGroup(mob, rhs) ) anims += [ MoveToTarget(mob), Transform(rhs, new_rhs) ] self.play(*anims) self.wait(2) class MisMatchOfCoPrefix(TeacherStudentsScene): def construct(self): eq1 = OldTex( "\\text{secant}(\\theta) = \\frac{1}{\\text{cosine}(\\theta)}" ) eq2 = OldTex( "\\text{cosecant}(\\theta) = \\frac{1}{\\text{sine}(\\theta)}" ) eq1.to_corner(UP+LEFT) eq1.to_edge(LEFT) eq2.next_to(eq1, DOWN, buff = LARGE_BUFF) eqs = VGroup(eq1, eq2) self.play( self.get_teacher().change_mode, "speaking", Write(eqs), *[ ApplyMethod(pi.look_at, eqs) for pi in self.get_students() ] ) self.random_blink() self.play( VGroup(*eq1[-9:-7]).set_color, YELLOW, VGroup(*eq2[:2]).set_color, YELLOW, *[ ApplyMethod(pi.change_mode, "confused") for pi in self.get_students() ] ) self.random_blink(2) class Credit(Scene): def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) morty.to_edge(RIGHT) headphones = Headphones(height = 1) headphones.move_to(morty.eyes, aligned_edge = DOWN) headphones.shift(0.1*DOWN) url = OldTexText("www.audibletrial.com/3blue1brown") url.scale(0.8) url.to_corner(UP+RIGHT, buff = LARGE_BUFF) book = ImageMobject("zen_and_motorcycles") book.set_height(5) book.to_edge(DOWN, buff = LARGE_BUFF) border = Rectangle(color = WHITE) border.replace(book, stretch = True) self.play(PiCreatureSays( morty, "Book recommendation!", target_mode = "surprised" )) self.play(Blink(morty)) self.play( FadeIn(headphones), morty.change_mode, "thinking", FadeOut(morty.bubble), FadeOut(morty.bubble.content), ) self.play(Write(url)) self.play(morty.change_mode, "happy") self.wait(2) self.play(Blink(morty)) self.wait(2) self.play( morty.change_mode, "raise_right_hand", morty.look_at, url ) self.wait(2) self.play( morty.change_mode, "happy", morty.look_at, book ) self.play(FadeIn(book)) self.play(ShowCreation(border)) self.wait(2) self.play(Blink(morty)) self.wait() self.play( morty.change_mode, "thinking", morty.look_at, book ) self.wait(2) self.play(Blink(morty)) self.wait(4) self.play(Blink(morty))
videos_3b1b/_2017/waves.py
from manim_imports_ext import * import warnings warnings.warn(""" Warning: This file makes use of ContinualAnimation, which has since been deprecated """) E_COLOR = BLUE M_COLOR = YELLOW # Warning, much of what is below was implemented using # ConintualAnimation, which has now been deprecated. One # Should use Mobject updaters instead. # # That is, anything below implemented as a ContinualAnimation # should instead be a Mobject, where the update methods # should be added via Mobject.add_udpater. class OscillatingVector(ContinualAnimation): CONFIG = { "tail" : ORIGIN, "frequency" : 1, "A_vect" : [1, 0, 0], "phi_vect" : [0, 0, 0], "vector_to_be_added_to" : None, } def setup(self): self.vector = self.mobject def update_mobject(self, dt): f = self.frequency t = self.internal_time angle = 2*np.pi*f*t vect = np.array([ A*np.exp(complex(0, angle + phi)) for A, phi in zip(self.A_vect, self.phi_vect) ]).real self.update_tail() self.vector.put_start_and_end_on(self.tail, self.tail+vect) def update_tail(self): if self.vector_to_be_added_to is not None: self.tail = self.vector_to_be_added_to.get_end() class OscillatingVectorComponents(ContinualAnimationGroup): CONFIG = { "tip_to_tail" : False, } def __init__(self, oscillating_vector, **kwargs): digest_config(self, kwargs) vx = Vector(UP, color = GREEN).fade() vy = Vector(UP, color = RED).fade() kwargs = { "frequency" : oscillating_vector.frequency, "tail" : oscillating_vector.tail, } ovx = OscillatingVector( vx, A_x = oscillating_vector.A_x, phi_x = oscillating_vector.phi_x, A_y = 0, phi_y = 0, **kwargs ) ovy = OscillatingVector( vy, A_x = 0, phi_x = 0, A_y = oscillating_vector.A_y, phi_y = oscillating_vector.phi_y, **kwargs ) components = [ovx, ovy] self.vectors = VGroup(ovx.vector, ovy.vector) if self.tip_to_tail: ovy.vector_to_be_added_to = ovx.vector else: self.lines = VGroup() for ov1, ov2 in (ovx, ovy), (ovy, ovx): ov_line = ov1.copy() ov_line.mobject = ov_line.vector = DashedLine( UP, DOWN, color = ov1.vector.get_color() ) ov_line.vector_to_be_added_to = ov2.vector components.append(ov_line) self.lines.add(ov_line.line) ContinualAnimationGroup.__init__(self, *components, **kwargs) class EMWave(ContinualAnimationGroup): CONFIG = { "wave_number" : 1, "frequency" : 0.25, "n_vectors" : 40, "propogation_direction" : RIGHT, "start_point" : FRAME_X_RADIUS*LEFT + DOWN + OUT, "length" : FRAME_WIDTH, "amplitude" : 1, "rotation" : 0, "A_vect" : [0, 0, 1], "phi_vect" : [0, 0, 0], "requires_start_up" : False, } def __init__(self, **kwargs): digest_config(self, kwargs) if not all(self.propogation_direction == RIGHT): self.matrix_transform = np.dot( z_to_vector(self.propogation_direction), np.linalg.inv(z_to_vector(RIGHT)), ) else: self.matrix_transform = None vector_oscillations = [] self.E_vects = VGroup() self.M_vects = VGroup() self.A_vect = np.array(self.A_vect)/get_norm(self.A_vect) self.A_vect *= self.amplitude for alpha in np.linspace(0, 1, self.n_vectors): tail = interpolate(ORIGIN, self.length*RIGHT, alpha) phase = -alpha*self.length*self.wave_number kwargs = { "phi_vect" : np.array(self.phi_vect) + phase, "frequency" : self.frequency, "tail" : np.array(tail), } E_ov = OscillatingVector( Vector( OUT, color = E_COLOR, normal_vector = UP, ), A_vect = self.A_vect, **kwargs ) M_ov = OscillatingVector( Vector( UP, color = M_COLOR, normal_vector = OUT, ), A_vect = rotate_vector(self.A_vect, np.pi/2, RIGHT), **kwargs ) vector_oscillations += [E_ov, M_ov] self.E_vects.add(E_ov.vector) self.M_vects.add(M_ov.vector) ContinualAnimationGroup.__init__(self, *vector_oscillations) def update_mobject(self, dt): if self.requires_start_up: n_wave_lengths = self.length / (2*np.pi*self.wave_number) prop_time = n_wave_lengths/self.frequency middle_alpha = interpolate( 0.4, 1.4, self.external_time / prop_time ) new_smooth = squish_rate_func(smooth, 0.4, 0.6) ovs = self.continual_animations for ov, alpha in zip(ovs, np.linspace(0, 1, len(ovs))): epsilon = 0.0001 new_amplitude = np.clip( new_smooth(middle_alpha - alpha), epsilon, 1 ) norm = get_norm(ov.A_vect) if norm != 0: ov.A_vect = new_amplitude * np.array(ov.A_vect) / norm ContinualAnimationGroup.update_mobject(self, dt) self.mobject.rotate(self.rotation, RIGHT) if self.matrix_transform: self.mobject.apply_matrix(self.matrix_transform) self.mobject.shift(self.start_point) class WavePacket(Animation): CONFIG = { "EMWave_config" : { "wave_number" : 0, "start_point" : FRAME_X_RADIUS*LEFT, "phi_vect" : np.ones(3)*np.pi/4, }, "em_wave" : None, "run_time" : 4, "rate_func" : None, "packet_width" : 6, "include_E_vects" : True, "include_M_vects" : True, "filter_distance" : FRAME_X_RADIUS, "get_filtered" : False, "remover" : True, "width" : 2*np.pi, } def __init__(self, **kwargs): digest_config(self, kwargs) em_wave = self.em_wave if em_wave is None: em_wave = EMWave(**self.EMWave_config) em_wave.update(0) self.em_wave = em_wave self.vects = VGroup() if self.include_E_vects: self.vects.add(*em_wave.E_vects) if self.include_M_vects: self.vects.add(*em_wave.M_vects) for vect in self.vects: vect.save_state() u = em_wave.propogation_direction self.wave_packet_start, self.wave_packet_end = [ em_wave.start_point - u*self.packet_width/2, em_wave.start_point + u*(em_wave.length + self.packet_width/2) ] Animation.__init__(self, self.vects, **kwargs) def interpolate_mobject(self, alpha): packet_center = interpolate( self.wave_packet_start, self.wave_packet_end, alpha ) em_wave = self.em_wave for vect in self.vects: tail = vect.get_start() distance_from_packet = np.dot( tail - packet_center, em_wave.propogation_direction ) A = em_wave.amplitude*self.E_func(distance_from_packet) distance_from_start = get_norm(tail - em_wave.start_point) if self.get_filtered and distance_from_start > self.filter_distance: A = 0 epsilon = 0.05 if abs(A) < epsilon: A = 0 vect.restore() vect.scale(A/vect.get_length(), about_point = tail) def E_func(self, x): x0 = 2*np.pi*x/self.width return np.sin(x0)*np.exp(-0.25*x0*x0) class FilterLabel(Tex): def __init__(self, tex, degrees, **kwargs): Tex.__init__(self, tex + " \\uparrow", **kwargs) self[-1].rotate(-degrees * np.pi / 180) class PolarizingFilter(Circle): CONFIG = { "stroke_color" : GREY_D, "fill_color" : GREY_B, "fill_opacity" : 0.5, "label_tex" : None, "filter_angle" : 0, "include_arrow_label" : True, "arrow_length" : 0.7, } def __init__(self, **kwargs): Circle.__init__(self, **kwargs) if self.label_tex: self.label = OldTex(self.label_tex) self.label.next_to(self.get_top(), DOWN, MED_SMALL_BUFF) self.add(self.label) arrow = Arrow( ORIGIN, self.arrow_length*UP, color = WHITE, buff = 0, ) arrow.shift(self.get_top()) arrow.rotate(-self.filter_angle) self.add(arrow) self.arrow = arrow shade_in_3d(self) if self.include_arrow_label: arrow_label = OldTex( "%.1f^\\circ"%(self.filter_angle*180/np.pi) ) arrow_label.add_background_rectangle() arrow_label.next_to(arrow.get_tip(), UP) self.add(arrow_label) self.arrow_label = arrow_label ################ class FilterScene(ThreeDScene): CONFIG = { "filter_x_coordinates" : [0], "pol_filter_configs" : [{}], "EMWave_config" : { "start_point" : FRAME_X_RADIUS*LEFT + DOWN+OUT }, "axes_config" : {}, "start_phi" : 0.8*np.pi/2, "start_theta" : -0.6*np.pi, "ambient_rotation_rate" : 0.01, } def setup(self): self.axes = ThreeDAxes(**self.axes_config) self.add(self.axes) for x in range(len(self.filter_x_coordinates) - len(self.pol_filter_configs)): self.pol_filter_configs.append({}) self.pol_filters = VGroup(*[ PolarizingFilter(**config) for config in self.pol_filter_configs ]) self.pol_filters.rotate(np.pi/2, RIGHT) self.pol_filters.rotate(-np.pi/2, OUT) pol_filter_shift = np.array(self.EMWave_config["start_point"]) pol_filter_shift[0] = 0 self.pol_filters.shift(pol_filter_shift) for x, pf in zip(self.filter_x_coordinates, self.pol_filters): pf.shift(x*RIGHT) self.add(self.pol_filters) self.pol_filter = self.pol_filters[0] self.set_camera_orientation(self.start_phi, self.start_theta) if self.ambient_rotation_rate > 0: self.begin_ambient_camera_rotation(self.ambient_rotation_rate) def get_filter_absorption_animation(self, pol_filter, photon): x = pol_filter.get_center()[0] alpha = (x + FRAME_X_RADIUS) / (FRAME_WIDTH) return ApplyMethod( pol_filter.set_fill, RED, run_time = photon.run_time, rate_func = squish_rate_func(there_and_back, alpha - 0.1, alpha + 0.1) ) class DirectionOfPolarizationScene(FilterScene): CONFIG = { "pol_filter_configs" : [{ "include_arrow_label" : False, }], "target_theta" : -0.97*np.pi, "target_phi" : 0.9*np.pi/2, "ambient_rotation_rate" : 0.005, "apply_filter" : False, "quantum" : False, } def setup(self): self.reference_line = Line(ORIGIN, RIGHT) self.reference_line.set_stroke(width = 0) self.em_wave = EMWave(**self.EMWave_config) self.add(self.em_wave) FilterScene.setup(self) def change_polarization_direction(self, angle, **kwargs): added_anims = kwargs.get("added_anims", []) self.play( ApplyMethod( self.reference_line.rotate, angle, **kwargs ), *added_anims ) def setup_rectangles(self): rect1 = Rectangle( height = 2*self.em_wave.amplitude, width = FRAME_X_RADIUS + 0.25, stroke_color = BLUE, fill_color = BLUE, fill_opacity = 0.2, ) rect1.rotate(np.pi/2, RIGHT) pf_copy = self.pol_filter.deepcopy() pf_copy.remove(pf_copy.arrow) center = pf_copy.get_center() rect1.move_to(center, RIGHT) rect2 = rect1.copy() rect2.move_to(center, LEFT) self.rectangles = VGroup(rect1, rect2) def update_mobjects(self, *args, **kwargs): reference_angle = self.reference_line.get_angle() self.em_wave.rotation = reference_angle FilterScene.update_mobjects(self, *args, **kwargs) if self.apply_filter: self.apply_filters() self.update_rectangles() def apply_filters(self): vect_groups = [self.em_wave.E_vects, self.em_wave.M_vects] filters = sorted( self.pol_filters, lambda pf1, pf2 : cmp( pf1.get_center()[0], pf2.get_center()[0], ) ) for pol_filter in filters: filter_x = pol_filter.arrow.get_center()[0] for vect_group, angle in zip(vect_groups, [0, -np.pi/2]): target_angle = pol_filter.filter_angle + angle for vect_mob in vect_group: vect = vect_mob.get_vector() vect_angle = angle_of_vector([ vect[2], -vect[1] ]) angle_diff = target_angle - vect_angle angle_diff = (angle_diff+np.pi/2)%np.pi - np.pi/2 start, end = vect_mob.get_start_and_end() if start[0] > filter_x: vect_mob.rotate(angle_diff, RIGHT) if not self.quantum: vect_mob.scale( np.cos(angle_diff), about_point = start, ) def update_rectangles(self): if not hasattr(self, "rectangles") or self.rectangles not in self.mobjects: return r1, r2 = self.rectangles target_angle = self.reference_line.get_angle() anchors = r1.get_anchors() vect = anchors[0] - anchors[3] curr_angle = angle_of_vector([vect[2], -vect[1]]) r1.rotate(target_angle - curr_angle, RIGHT) epsilon = 0.001 curr_depth = max(r2.get_depth(), epsilon) target_depth = max( 2*self.em_wave.amplitude*abs(np.cos(target_angle)), epsilon ) r2.stretch_in_place(target_depth/curr_depth, 2) ################ class WantToLearnQM(TeacherStudentsScene): def construct(self): question1 = OldTex( "\\text{What does }\\qquad \\\\", "|\\!\\psi \\rangle", "=", "\\frac{1}{\\sqrt{2}}", "|\\!\\uparrow \\rangle", "+", "\\frac{1}{\\sqrt{2}}", "|\\!\\downarrow \\rangle \\\\", "\\text{mean?}\\qquad\\quad" ) question1.set_color_by_tex_to_color_map({ "psi" : BLUE, "uparrow" : GREEN, "downarrow" : RED, }) question2 = OldTexText( "Why are complex \\\\ numbers involved?" ) question3 = OldTexText( "How do you compute \\\\ quantum probabilities?" ) questions = [question1, question2, question3] bubbles = VGroup() for i, question in zip([1, 2, 0], questions): self.student_says( question, content_introduction_kwargs = {"run_time" : 2}, index = i, bubble_config = {"fill_opacity" : 1}, bubble_creation_class = FadeIn, ) bubble = self.students[i].bubble bubble.add(bubble.content) bubbles.add(bubble) self.students self.students[i].bubble = None self.wait(2) self.teacher_says( "First, lots and lots \\\\ of linear algebra", added_anims = list(map(FadeOut, bubbles)) ) self.wait() class Goal(PiCreatureScene): def construct(self): randy = self.pi_creature goal = OldTexText("Goal: ") goal.set_color(YELLOW) goal.shift(FRAME_X_RADIUS*LEFT/2 + UP) weirdness = OldTexText("Eye-catching quantum weirdness") weirdness.next_to(goal, RIGHT) cross = Cross(weirdness) foundations = OldTexText("Foundational intuitions") foundations.next_to(goal, RIGHT) goal.save_state() goal.scale(0.01) goal.move_to(randy.get_right()) self.play( goal.restore, randy.change, "raise_right_hand" ) self.play(Write(weirdness, run_time = 2)) self.play( ShowCreation(cross), randy.change, "sassy" ) self.wait() self.play( VGroup(weirdness, cross).shift, DOWN, Write(foundations, run_time = 2), randy.change, "happy" ) self.wait(2) #### def create_pi_creature(self): return Randolph().to_corner(DOWN+LEFT) class AskWhatsDifferentInQM(TeacherStudentsScene): def construct(self): self.student_says( "What's different in \\\\ quantum mechanics?" ) self.play(self.teacher.change, "pondering") self.wait(3) class VideoWrapper(Scene): CONFIG = { "title" : "" } def construct(self): title = OldTexText(self.title) title.to_edge(UP) self.add(title) rect = ScreenRectangle() rect.set_height(6) rect.next_to(title, DOWN) self.add(rect) self.wait() class BellsWrapper(VideoWrapper): CONFIG = { "title" : "Bell's inequalities" } class FromOtherVideoWrapper(VideoWrapper): CONFIG = { "title" : "See the other video..." } class OriginOfQuantumMechanicsWrapper(VideoWrapper): CONFIG = { "title" : "The origin of quantum mechanics" } class IntroduceElectricField(PiCreatureScene): CONFIG = { "vector_field_colors" : [BLUE_B, BLUE_D], "max_vector_length" : 0.9, } def construct(self): self.write_title() self.draw_field() self.add_particle() self.let_particle_wander() def write_title(self): morty = self.pi_creature title = OldTexText( "Electro", "magnetic", " field", arg_separator = "" ) title.next_to(morty, UP+LEFT) electric = OldTexText("Electric") electric.next_to(title[-1], LEFT) electric.set_color(BLUE) title.save_state() title.shift(DOWN) title.fade(1) self.play( title.restore, morty.change, "raise_right_hand", ) self.play( title[0].set_color, BLUE, title[1].set_color, YELLOW, ) self.wait() self.play( ShrinkToCenter(title[1]), Transform(title[0], electric) ) title.add_background_rectangle() self.title = title def draw_field(self): morty = self.pi_creature vector_field = self.get_vector_field() self.play( LaggedStartMap( ShowCreation, vector_field, run_time = 3 ), self.title.center, self.title.scale, 1.5, self.title.to_edge, UP, morty.change, "happy", ORIGIN, ) self.wait() self.vector_field = vector_field def add_particle(self): morty = self.pi_creature point = UP+LEFT + SMALL_BUFF*(UP+RIGHT) particle = self.get_particle() particle.move_to(point) vector = self.get_vector(particle.get_center()) vector.set_color(RED) vector.scale(1.5, about_point = point) vector.shift(SMALL_BUFF*vector.get_vector()) force = OldTexText("Force") force.next_to(ORIGIN, UP+RIGHT, SMALL_BUFF) force.rotate(vector.get_angle()) force.shift(vector.get_start()) particle.save_state() particle.move_to(morty.get_left() + 0.5*UP + 0.2*RIGHT) particle.fade(1) self.play( particle.restore, morty.change, "raise_right_hand", ) self.play(morty.change, "thinking", particle) self.play( ShowCreation(vector), Write(force, run_time = 1), ) self.wait(2) self.particle = particle self.force_vector = VGroup(vector, force) def let_particle_wander(self): possible_points = [v.get_start() for v in self.vector_field] points = random.sample(possible_points, 45) points.append(3*UP+3*LEFT) particles = VGroup(self.particle, *[ self.particle.copy().move_to(point) for point in points ]) for particle in particles: particle.velocity = np.zeros(3) self.play( FadeOut(self.force_vector), LaggedStartMap(FadeIn, VGroup(*particles[1:])) ) self.moving_particles = particles self.add_foreground_mobjects(self.moving_particles, self.pi_creature) self.always_update_mobjects = True self.wait(10) ### def update_mobjects(self, *args, **kwargs): Scene.update_mobjects(self, *args, **kwargs) if hasattr(self, "moving_particles"): dt = self.frame_duration for p in self.moving_particles: vect = self.field_function(p.get_center()) p.velocity += vect*dt p.shift(p.velocity*dt) self.pi_creature.look_at(self.moving_particles[-1]) def get_particle(self): particle = Circle(radius = 0.2) particle.set_stroke(RED, 3) particle.set_fill(RED, 0.5) plus = OldTex("+") plus.scale(0.7) plus.move_to(particle) particle.add(plus) return particle def get_vector_field(self): result = VGroup(*[ self.get_vector(point) for x in np.arange(-9, 9) for y in np.arange(-5, 5) for point in [x*RIGHT + y*UP] ]) shading_list = list(result) shading_list.sort( key=lambda m: m1.get_length() ) VGroup(*shading_list).set_color_by_gradient(*self.vector_field_colors) result.set_fill(opacity = 0.75) result.sort(get_norm) return result def get_vector(self, point): return Vector(self.field_function(point)).shift(point) def field_function(self, point): x, y = point[:2] result = y*RIGHT + np.sin(x)*UP return self.normalized(result) def normalized(self, vector): norm = get_norm(vector) or 1 target_length = self.max_vector_length * sigmoid(0.1*norm) return target_length * vector/norm class IntroduceMagneticField(IntroduceElectricField, ThreeDScene): CONFIG = { "vector_field_colors" : [YELLOW_C, YELLOW_D] } def setup(self): IntroduceElectricField.setup(self) self.remove(self.pi_creature) def construct(self): self.set_camera_orientation(0.1, -np.pi/2) self.add_title() self.add_vector_field() self.introduce_moving_charge() self.show_force() # self.many_charges() def add_title(self): title = OldTexText("Magnetic", "field") title[0].set_color(YELLOW) title.scale(1.5) title.to_edge(UP) title.add_background_rectangle() self.add(title) self.title = title def add_vector_field(self): vector_field = self.get_vector_field() self.play( LaggedStartMap(ShowCreation, vector_field, run_time = 3), Animation(self.title) ) self.wait() def introduce_moving_charge(self): point = 3*RIGHT + UP particle = self.get_particle() particle.move_to(point) velocity = Vector(2*RIGHT).shift(particle.get_right()) velocity.set_color(WHITE) velocity_word = OldTexText("Velocity") velocity_word.set_color(velocity.get_color()) velocity_word.add_background_rectangle() velocity_word.next_to(velocity, UP, 0, LEFT) M_vect = self.get_vector(point) M_vect.set_color(YELLOW) M_vect.shift(SMALL_BUFF*M_vect.get_vector()) particle.save_state() particle.shift(FRAME_WIDTH*LEFT) self.play( particle.restore, run_time = 2, rate_func=linear, ) self.add(velocity) self.play(Write(velocity_word, run_time = 0.5)) # self.play(ShowCreation(M_vect)) self.wait() self.particle = particle def show_force(self): point = self.particle.get_center() F_vect = Vector( 3*np.cross(self.field_function(point), RIGHT), color = GREEN ) F_vect.shift(point) F_word = OldTexText("Force") F_word.rotate(np.pi/2, RIGHT) F_word.next_to(F_vect, OUT) F_word.set_color(F_vect.get_color()) F_eq = OldTex( "=","q", "\\textbf{v}", "\\times", "\\textbf{B}" ) F_eq.set_color_by_tex_to_color_map({ "q" : RED, "B" : YELLOW, }) F_eq.rotate(np.pi/2, RIGHT) F_eq.next_to(F_word, RIGHT) self.move_camera(0.8*np.pi/2, -0.55*np.pi) self.begin_ambient_camera_rotation() self.play(ShowCreation(F_vect)) self.play(Write(F_word)) self.wait() self.play(Write(F_eq)) self.wait(8) def many_charges(self): charges = VGroup() for y in range(2, 3): charge = self.get_particle() charge.move_to(3*LEFT + y*UP) charge.velocity = (2*RIGHT).astype('float') charges.add(charge) self.revert_to_original_skipping_status() self.add_foreground_mobjects(*charges) self.moving_particles = charges self.wait(5) ### def update_mobjects(self, *args, **kwargs): Scene.update_mobjects(self, *args, **kwargs) if hasattr(self, "moving_particles"): dt = self.frame_duration for p in self.moving_particles: M_vect = self.field_function(p.get_center()) F_vect = 3*np.cross(p.velocity, M_vect) p.velocity += F_vect*dt p.shift(p.velocity*dt) def field_function(self, point): x, y = point[:2] y += 0.5 gauss = lambda r : np.exp(-0.5*r**2) result = (y**2 - 1)*RIGHT + x*(gauss(y+2) - gauss(y-2))*UP return self.normalized(result) class CurlRelationBetweenFields(ThreeDScene): def construct(self): self.add_axes() self.loop_in_E() self.loop_in_M() self.second_loop_in_E() def add_axes(self): self.add(ThreeDAxes(x_axis_radius = FRAME_X_RADIUS)) def loop_in_E(self): E_vects = VGroup(*[ Vector(0.5*rotate_vector(vect, np.pi/2)).shift(vect) for vect in compass_directions(8) ]) E_vects.set_color(E_COLOR) point = 1.2*RIGHT + 2*UP + OUT E_vects.shift(point) M_vect = Vector( IN, normal_vector = DOWN, color = M_COLOR ) M_vect.shift(point) M_vect.save_state() M_vect.scale(0.01, about_point = M_vect.get_start()) self.play(ShowCreation(E_vects, run_time = 2)) self.wait() self.move_camera(0.8*np.pi/2, -0.45*np.pi) self.begin_ambient_camera_rotation() self.play(M_vect.restore, run_time = 3, rate_func=linear) self.wait(3) self.E_vects = E_vects self.E_circle_center = point self.M_vect = M_vect def loop_in_M(self): M_vects = VGroup(*[ Vector( rotate_vector(vect, np.pi/2), normal_vector = IN, color = M_COLOR ).shift(vect) for vect in compass_directions(8, LEFT)[1:] ]) M_vects.rotate(np.pi/2, RIGHT) new_point = self.E_circle_center + RIGHT M_vects.shift(new_point) E_vect = self.E_vects[0] self.play( ShowCreation(M_vects, run_time = 2), *list(map(FadeOut, self.E_vects[1:])) ) self.wait() self.play( E_vect.rotate, np.pi, RIGHT, [], new_point, E_vect.scale_about_point, 3, new_point, run_time = 4, rate_func=linear, ) self.wait() self.M_circle_center = new_point M_vects.add(self.M_vect) self.M_vects = M_vects self.E_vect = E_vect def second_loop_in_E(self): E_vects = VGroup(*[ Vector(1.5*rotate_vector(vect, np.pi/2)).shift(vect) for vect in compass_directions(8, LEFT)[1:] ]) E_vects.set_color(E_COLOR) point = self.M_circle_center + RIGHT E_vects.shift(point) M_vect = self.M_vects[3] self.M_vects.remove(M_vect) self.play(FadeOut(self.M_vects)) self.play(ShowCreation(E_vects), Animation(M_vect)) self.play( M_vect.rotate, np.pi, RIGHT, [], point, run_time = 5, rate_func=linear, ) self.wait(3) class WriteCurlEquations(Scene): def construct(self): eq1 = OldTex( "\\nabla \\times", "\\textbf{E}", "=", "-\\frac{1}{c}", "\\frac{\\partial \\textbf{B}}{\\partial t}" ) eq2 = OldTex( "\\nabla \\times", "\\textbf{B}", "=^*", "\\frac{1}{c}", "\\frac{\\partial \\textbf{E}}{\\partial t}" ) eqs = VGroup(eq1, eq2) eqs.arrange(DOWN, buff = LARGE_BUFF) eqs.set_height(FRAME_HEIGHT - 1) eqs.to_edge(LEFT) for eq in eqs: eq.set_color_by_tex_to_color_map({ "E" : E_COLOR, "B" : M_COLOR, }) footnote = OldTexText("*Ignoring currents") footnote.next_to(eqs[1], RIGHT) footnote.to_edge(RIGHT) self.play(Write(eq1, run_time = 2)) self.wait(3) self.play(Write(eq2, run_time = 2)) self.play(FadeIn(footnote)) self.wait(3) class IntroduceEMWave(ThreeDScene): CONFIG = { "EMWave_config" : { "requires_start_up" : True } } def setup(self): self.axes = ThreeDAxes() self.add(self.axes) self.em_wave = EMWave(**self.EMWave_config) self.add(self.em_wave) self.set_camera_orientation(0.8*np.pi/2, -0.7*np.pi) self.begin_ambient_camera_rotation() def construct(self): words = OldTexText( "Electro", "magnetic", " radiation", arg_separator = "" ) words.set_color_by_tex_to_color_map({ "Electro" : E_COLOR, "magnetic" : M_COLOR, }) words.next_to(ORIGIN, LEFT, MED_LARGE_BUFF) words.to_edge(UP) words.rotate(np.pi/2, RIGHT) self.wait(7) self.play(Write(words, run_time = 2)) self.wait(20) ##### class SimpleEMWave(IntroduceEMWave): def construct(self): self.wait(30) class ListRelevantWaveIdeas(TeacherStudentsScene): def construct(self): title = OldTexText("Wave","topics") title.to_corner(UP + LEFT, LARGE_BUFF) title.set_color(BLUE) h_line = Line(title.get_left(), title.get_right()) h_line.next_to(title, DOWN, SMALL_BUFF) topics = VGroup(*list(map(TexText, [ "- Superposition", "- Amplitudes", "- How phase influences addition", ]))) topics.scale(0.8) topics.arrange(DOWN, aligned_edge = LEFT) topics.next_to(h_line, DOWN, aligned_edge = LEFT) quantum = OldTexText("Quantum") quantum.set_color(GREEN) quantum.move_to(title[0], LEFT) wave_point = self.teacher.get_corner(UP+LEFT) + 2*UP self.play( Animation(VectorizedPoint(wave_point)), self.teacher.change, "raise_right_hand" ) self.wait(2) self.play( Write(title, run_time = 2), ShowCreation(h_line) ) self.play_student_changes( *["pondering"]*3, added_anims = [LaggedStartMap( FadeIn, topics, run_time = 3 )], look_at = title ) self.play( Animation(title), self.teacher.change, "happy" ) self.play( title[0].next_to, quantum.copy(), UP, MED_SMALL_BUFF, LEFT, title[0].fade, 0.5, title[1].next_to, quantum.copy(), RIGHT, 2*SMALL_BUFF, Write(quantum), ) self.wait(5) class DirectWaveOutOfScreen(IntroduceEMWave): CONFIG = { "EMWave_config" : { "requires_start_up" : False, "amplitude" : 2, "start_point" : FRAME_X_RADIUS*LEFT, "A_vect" : [0, 1, 0], "start_up_time" : 0, } } def setup(self): IntroduceEMWave.setup(self) self.remove(self.axes) for ov in self.em_wave.continual_animations: ov.vector.normal_vector = RIGHT self.set_camera_orientation(0.9*np.pi/2, -0.3*np.pi) def construct(self): self.move_into_position() self.fade_M_vects() self.fade_all_but_last_E_vects() def move_into_position(self): self.wait(2) self.update_mobjects() faded_vectors = VGroup(*[ ov.vector for ov in self.em_wave.continual_animations[:-2] ]) self.move_camera( 0.99*np.pi/2, -0.01, run_time = 2, added_anims = [faded_vectors.set_fill, None, 0.5] ) self.stop_ambient_camera_rotation() self.move_camera( np.pi/2, 0, added_anims = [faded_vectors.set_fill, None, 0.05], run_time = 2, ) self.faded_vectors = faded_vectors def fade_M_vects(self): self.play( self.em_wave.M_vects.set_fill, None, 0 ) self.wait(2) def fade_all_but_last_E_vects(self): self.play(self.faded_vectors.set_fill, None, 0) self.wait(4) class ShowVectorEquation(Scene): CONFIG = { "f_color" : RED, "phi_color" : MAROON_B, "A_color" : GREEN, } def construct(self): self.add_vector() self.add_plane() self.write_horizontally_polarized() self.write_components() self.show_graph() self.add_phi() self.add_amplitude() self.add_kets() self.switch_to_vertically_polarized_light() def add_vector(self): self.vector = Vector(2*RIGHT, color = E_COLOR) self.oscillating_vector = OscillatingVector( self.vector, A_vect = [2, 0, 0], frequency = 0.25, ) self.add(self.oscillating_vector) self.wait(3) def add_plane(self): xy_plane = NumberPlane( axes_color = GREY_B, color = GREY_D, secondary_color = GREY_D, x_unit_size = 2, y_unit_size = 2, ) xy_plane.add_coordinates() xy_plane.add(xy_plane.get_axis_labels()) self.play( Write(xy_plane), Animation(self.vector) ) self.wait(2) self.xy_plane = xy_plane def write_horizontally_polarized(self): words = OldTexText( "``", "Horizontally", " polarized", "''", arg_separator = "" ) words.next_to(ORIGIN, LEFT) words.to_edge(UP) words.add_background_rectangle() self.play(Write(words, run_time = 3)) self.wait() self.horizontally_polarized_words = words def write_components(self): x, y = components = VGroup( OldTex("\\cos(", "2\\pi", "f_x", "t", "+ ", "\\phi_x", ")"), OldTex("0", "") ) components.arrange(DOWN) lb, rb = brackets = OldTex("[]") brackets.set_height(components.get_height() + SMALL_BUFF) lb.next_to(components, LEFT, buff = 0.3) rb.next_to(components, RIGHT, buff = 0.3) E, equals = E_equals = OldTex( "\\vec{\\textbf{E}}", "=" ) E.set_color(E_COLOR) E_equals.next_to(brackets, LEFT) E_equals.add_background_rectangle() brackets.add_background_rectangle() group = VGroup(E_equals, brackets, components) group.next_to( self.horizontally_polarized_words, DOWN, MED_LARGE_BUFF, RIGHT ) x_without_phi = OldTex("\\cos(", "2\\pi", "f_x", "t", ")") x_without_phi.move_to(x) for mob in x, x_without_phi: mob.set_color_by_tex_to_color_map({ "f_x" : self.f_color, "phi_x" : self.phi_color, }) def update_brace(brace): brace.stretch_to_fit_width( max(self.vector.get_width(), 0.001) ) brace.next_to(self.vector.get_center(), DOWN, SMALL_BUFF) return brace moving_brace = Mobject.add_updater( Brace(Line(LEFT, RIGHT), DOWN), update_brace ) moving_x_without_phi = Mobject.add_updater( x_without_phi.copy().add_background_rectangle(), lambda m : m.next_to(moving_brace.mobject, DOWN, SMALL_BUFF) ) self.play(Write(E_equals), Write(brackets)) y.save_state() y.move_to(self.horizontally_polarized_words) y.set_fill(opacity = 0) self.play(y.restore) self.wait() self.add(moving_brace, moving_x_without_phi) self.play( FadeIn(moving_brace.mobject), FadeIn(x_without_phi), FadeIn(moving_x_without_phi.mobject), lag_ratio = 0.5, run_time = 2, ) self.wait(3) self.play( FadeOut(moving_brace.mobject), FadeOut(moving_x_without_phi.mobject), ) self.remove(moving_brace, moving_x_without_phi) self.E_equals = E_equals self.brackets = brackets self.x_without_phi = x_without_phi self.components = components def show_graph(self): axes = Axes( x_min = -0.5, x_max = 5.2, y_min = -1.5, y_max = 1.5, ) axes.x_axis.add_numbers(*list(range(1, 6))) t = OldTex("t") t.next_to(axes.x_axis, UP, SMALL_BUFF, RIGHT) cos = self.x_without_phi.copy() cos.next_to(axes.y_axis, RIGHT, SMALL_BUFF, UP) cos_arg = VGroup(*cos[1:-1]) fx_equals_1 = OldTex("f_x", "= 1") fx_equals_fourth = OldTex("f_x", "= 0.25") fx_group = VGroup(fx_equals_1, fx_equals_fourth) for fx in fx_group: fx[0].set_color(self.f_color) fx.move_to(axes, UP+RIGHT) high_f_graph, low_f_graph = graphs = VGroup(*[ FunctionGraph( lambda x : np.cos(2*np.pi*f*x), color = E_COLOR, x_min = 0, x_max = 4/f, num_steps = 20/f, ) for f in (1, 0.25,) ]) group = VGroup(axes, t, cos, high_f_graph, *fx_group) rect = SurroundingRectangle( group, buff = MED_LARGE_BUFF, stroke_color = WHITE, stroke_width = 3, fill_color = BLACK, fill_opacity = 0.9 ) group.add_to_back(rect) group.scale(0.8) group.to_corner(UP+RIGHT, buff = -SMALL_BUFF) group.remove(*it.chain(fx_group, graphs)) low_f_graph.scale(0.8) low_f_graph.move_to(high_f_graph, LEFT) cos_arg_rect = SurroundingRectangle(cos_arg) new_ov = OscillatingVector( Vector(RIGHT, color = E_COLOR), A_vect = [2, 0, 0], frequency = 1, start_up_time = 0, ) self.play(FadeIn(group)) self.play( ReplacementTransform( self.components[0].get_part_by_tex("f_x").copy(), fx_equals_1 ), ) self.wait(4 - (self.oscillating_vector.internal_time%4)) self.remove(self.oscillating_vector) self.add(new_ov) self.play(ShowCreation( high_f_graph, run_time = 4, rate_func=linear, )) self.wait() self.play(FadeOut(new_ov.vector)) self.remove(new_ov) self.add(self.oscillating_vector) self.play( ReplacementTransform(*fx_group), ReplacementTransform(*graphs), FadeOut(new_ov.vector), FadeIn(self.vector) ) self.wait(4) self.play(ShowCreation(cos_arg_rect)) self.play(FadeOut(cos_arg_rect)) self.wait(5) self.corner_group = group self.fx_equals_fourth = fx_equals_fourth self.corner_cos = cos self.low_f_graph = low_f_graph self.graph_axes = axes def add_phi(self): corner_cos = self.corner_cos corner_phi = OldTex("+", "\\phi_x") corner_phi.set_color_by_tex("phi", self.phi_color) corner_phi.scale(0.8) corner_phi.next_to(corner_cos[-2], RIGHT, SMALL_BUFF) x, y = self.components x_without_phi = self.x_without_phi words = OldTexText("``Phase shift''") words.next_to(ORIGIN, UP+LEFT) words.set_color(self.phi_color) words.add_background_rectangle() arrow = Arrow(words.get_top(), x[-2]) arrow.set_color(WHITE) self.play( ReplacementTransform( VGroup(*x_without_phi[:-1]), VGroup(*x[:-3]), ), ReplacementTransform(x_without_phi[-1], x[-1]), Write(VGroup(*x[-3:-1])), corner_cos[-1].next_to, corner_phi.copy(), RIGHT, SMALL_BUFF, Write(corner_phi), FadeOut(self.fx_equals_fourth), ) self.play(self.low_f_graph.shift, MED_LARGE_BUFF*LEFT) self.play( Write(words, run_time = 1), ShowCreation(arrow) ) self.wait(3) self.play(*list(map(FadeOut, [words, arrow]))) self.corner_cos.add(corner_phi) def add_amplitude(self): x, y = self.components corner_cos = self.corner_cos graph = self.low_f_graph graph_y_axis = self.graph_axes.y_axis A = OldTex("A_x") A.set_color(self.A_color) A.move_to(x.get_left()) corner_A = A.copy() corner_A.scale(0.8) corner_A.move_to(corner_cos, LEFT) h_brace = Brace(Line(ORIGIN, 2*RIGHT), UP) v_brace = Brace(Line( graph_y_axis.number_to_point(0), graph_y_axis.number_to_point(1), ), LEFT, buff = SMALL_BUFF) for brace in h_brace, v_brace: brace.A = brace.get_tex("A_x") brace.A.set_color(self.A_color) v_brace.A.scale(0.5, about_point = v_brace.get_center()) all_As = VGroup(A, corner_A, h_brace.A, v_brace.A) def update_vect(vect): self.oscillating_vector.A_vect[0] = h_brace.get_width() return vect self.play( GrowFromCenter(h_brace), GrowFromCenter(v_brace), ) self.wait(2) self.play( x.next_to, A, RIGHT, SMALL_BUFF, corner_cos.next_to, corner_A, RIGHT, SMALL_BUFF, FadeIn(all_As) ) x.add(A) corner_cos.add(corner_A) self.wait() factor = 0.5 self.play( v_brace.stretch_in_place, factor, 1, v_brace.move_to, v_brace.copy(), DOWN, MaintainPositionRelativeTo(v_brace.A, v_brace), h_brace.stretch_in_place, factor, 0, h_brace.move_to, h_brace.copy(), LEFT, MaintainPositionRelativeTo(h_brace.A, h_brace), UpdateFromFunc(self.vector, update_vect), graph.stretch_in_place, factor, 1, ) self.wait(4) self.h_brace = h_brace self.v_brace = v_brace def add_kets(self): x, y = self.components E_equals = self.E_equals for mob in x, y, E_equals: mob.add_background_rectangle() mob.generate_target() right_ket = OldTex("|\\rightarrow\\rangle") up_ket = OldTex("|\\uparrow\\rangle") kets = VGroup(right_ket, up_ket) kets.set_color(YELLOW) for ket in kets: ket.add_background_rectangle() plus = OldTexText("+") group = VGroup( E_equals.target, x.target, right_ket, plus, y.target, up_ket, ) group.arrange(RIGHT) E_equals.target.shift(SMALL_BUFF*UP) group.scale(0.8) group.move_to(self.brackets, DOWN) group.to_edge(LEFT, buff = MED_SMALL_BUFF) kets_word = OldTexText("``kets''") kets_word.next_to(kets, DOWN, buff = 0.8) arrows = VGroup(*[ Arrow(kets_word.get_top(), ket, color = ket.get_color()) for ket in kets ]) ket_rects = VGroup(*list(map(SurroundingRectangle, kets))) ket_rects.set_color(WHITE) unit_vectors = VGroup(*[Vector(2*vect) for vect in (RIGHT, UP)]) unit_vectors.set_fill(YELLOW) self.play( FadeOut(self.brackets), *list(map(MoveToTarget, [E_equals, x, y])) ) self.play(*list(map(Write, [right_ket, plus, up_ket])), run_time = 1) self.play( Write(kets_word), LaggedStartMap(ShowCreation, arrows, lag_ratio = 0.7), run_time = 2, ) self.wait() for ket, ket_rect, unit_vect in zip(kets, ket_rects, unit_vectors): self.play(ShowCreation(ket_rect)) self.play(FadeOut(ket_rect)) self.play(ReplacementTransform(ket[1][1].copy(), unit_vect)) self.wait() self.play(FadeOut(unit_vectors)) self.play(*list(map(FadeOut, [kets_word, arrows]))) self.kets = kets self.plus = plus def switch_to_vertically_polarized_light(self): x, y = self.components x_ket, y_ket = self.kets plus = self.plus x.target = OldTex("0", "").add_background_rectangle() y.target = OldTex( "A_y", "\\cos(", "2\\pi", "f_y", "t", "+", "\\phi_y", ")" ) y.target.set_color_by_tex_to_color_map({ "A" : self.A_color, "f" : self.f_color, "phi" : self.phi_color, }) y.target.add_background_rectangle() VGroup(x.target, y.target).scale(0.8) for mob in [plus] + list(self.kets): mob.generate_target() movers = x, x_ket, plus, y, y_ket group = VGroup(*[m.target for m in movers]) group.arrange(RIGHT) group.move_to(x, LEFT) vector_A_vect = np.array(self.oscillating_vector.A_vect) def update_vect(vect, alpha): self.oscillating_vector.A_vect = rotate_vector( vector_A_vect, alpha*np.pi/2 ) return vect new_h_brace = Brace(Line(ORIGIN, UP), RIGHT) words = OldTexText( "``", "Vertically", " polarized", "''", arg_separator = "", ) words.add_background_rectangle() words.move_to(self.horizontally_polarized_words) self.play( UpdateFromAlphaFunc(self.vector, update_vect), Transform(self.h_brace, new_h_brace), self.h_brace.A.next_to, new_h_brace, RIGHT, SMALL_BUFF, Transform(self.horizontally_polarized_words, words), *list(map(FadeOut, [ self.corner_group, self.v_brace, self.v_brace.A, self.low_f_graph, ])) ) self.play(*list(map(MoveToTarget, movers))) self.wait(5) class ChangeFromHorizontalToVerticallyPolarized(DirectionOfPolarizationScene): CONFIG = { "filter_x_coordinates" : [], "EMWave_config" : { "start_point" : FRAME_X_RADIUS*LEFT, "A_vect" : [0, 2, 0], } } def setup(self): DirectionOfPolarizationScene.setup(self) self.axes.z_axis.rotate(np.pi/2, OUT) self.axes.y_axis.rotate(np.pi/2, UP) self.remove(self.pol_filter) self.em_wave.M_vects.set_fill(opacity = 0) for vect in self.em_wave.E_vects: vect.normal_vector = RIGHT vect.set_fill(opacity = 0.5) self.em_wave.E_vects[-1].set_fill(opacity = 1) self.set_camera_orientation(0.9*np.pi/2, -0.05*np.pi) def construct(self): self.wait(3) self.change_polarization_direction(np.pi/2) self.wait(10) class SumOfTwoWaves(ChangeFromHorizontalToVerticallyPolarized): CONFIG = { "axes_config" : { "y_max" : 1.5, "y_min" : -1.5, "z_max" : 1.5, "z_min" : -1.5, }, "EMWave_config" : { "A_vect" : [0, 0, 1], }, "ambient_rotation_rate" : 0, } def setup(self): ChangeFromHorizontalToVerticallyPolarized.setup(self) for vect in self.em_wave.E_vects[:-1]: vect.set_fill(opacity = 0.3) self.side_em_waves = [] for shift_vect, A_vect in (5*DOWN, [0, 1, 0]), (5*UP, [0, 1, 1]): axes = self.axes.copy() em_wave = copy.deepcopy(self.em_wave) axes.shift(shift_vect) em_wave.mobject.shift(shift_vect) em_wave.start_point += shift_vect for ov in em_wave.continual_animations: ov.A_vect = np.array(A_vect) self.add(axes, em_wave) self.side_em_waves.append(em_wave) self.set_camera_orientation(0.95*np.pi/2, -0.03*np.pi) def construct(self): plus, equals = pe = VGroup(*list(map(Tex, "+="))) pe.scale(2) pe.rotate(np.pi/2, RIGHT) pe.rotate(np.pi/2, OUT) plus.shift(2.5*DOWN) equals.shift(2.5*UP) self.add(pe) self.wait(16) class ShowTipToTailSum(ShowVectorEquation): def construct(self): self.force_skipping() self.add_vector() self.add_plane() self.add_vertial_vector() self.revert_to_original_skipping_status() self.add_kets() self.show_vector_sum() self.write_superposition() self.add_amplitudes() self.add_phase_shift() def add_vertial_vector(self): self.h_vector = self.vector self.h_oscillating_vector = self.oscillating_vector self.h_oscillating_vector.start_up_time = 0 self.v_oscillating_vector = self.h_oscillating_vector.copy() self.v_vector = self.v_oscillating_vector.vector self.v_oscillating_vector.A_vect = [0, 2, 0] self.v_oscillating_vector.update(0) self.d_oscillating_vector = Mobject.add_updater( Vector(UP+RIGHT, color = E_COLOR), lambda v : v.put_start_and_end_on( ORIGIN, self.v_vector.get_end()+ self.h_vector.get_end(), ) ) self.d_vector = self.d_oscillating_vector.mobject self.d_oscillating_vector.update(0) self.add(self.v_oscillating_vector) self.add_foreground_mobject(self.v_vector) def add_kets(self): h_ket, v_ket = kets = VGroup(*[ OldTex( "\\cos(", "2\\pi", "f", "t", ")", "|\\!\\%sarrow\\rangle"%s ) for s in ("right", "up") ]) for ket in kets: ket.set_color_by_tex_to_color_map({ "f" : self.f_color, "rangle" : YELLOW, }) ket.add_background_rectangle(opacity = 1) ket.scale(0.8) h_ket.next_to(2*RIGHT, UP, SMALL_BUFF) v_ket.next_to(2*UP, UP, SMALL_BUFF) self.add_foreground_mobject(kets) self.kets = kets def show_vector_sum(self): h_line = DashedLine(ORIGIN, 2*RIGHT) v_line = DashedLine(ORIGIN, 2*UP) h_line.update = self.generate_dashed_line_update( self.h_vector, self.v_vector ) v_line.update = self.generate_dashed_line_update( self.v_vector, self.h_vector ) h_ket, v_ket = self.kets for ket in self.kets: ket.generate_target() plus = OldTex("+") ket_sum = VGroup(h_ket.target, plus, v_ket.target) ket_sum.arrange(RIGHT) ket_sum.next_to(3*RIGHT + 2*UP, UP, SMALL_BUFF) self.wait(4) self.remove(self.h_oscillating_vector, self.v_oscillating_vector) self.add(self.h_vector, self.v_vector) h_line.update(h_line) v_line.update(v_line) self.play(*it.chain( list(map(MoveToTarget, self.kets)), [Write(plus)], list(map(ShowCreation, [h_line, v_line])), )) blue_black = average_color(BLUE, BLACK) self.play( GrowFromPoint(self.d_vector, ORIGIN), self.h_vector.set_fill, blue_black, self.v_vector.set_fill, blue_black, ) self.wait() self.add( self.h_oscillating_vector, self.v_oscillating_vector, self.d_oscillating_vector, Mobject.add_updater(h_line, h_line.update), Mobject.add_updater(v_line, v_line.update), ) self.wait(4) self.ket_sum = VGroup(h_ket, plus, v_ket) def write_superposition(self): superposition_words = OldTexText( "``Superposition''", "of", "$|\\!\\rightarrow\\rangle$", "and", "$|\\!\\uparrow\\rangle$", ) superposition_words.scale(0.8) superposition_words.set_color_by_tex("rangle", YELLOW) superposition_words.add_background_rectangle() superposition_words.to_corner(UP+LEFT) ket_sum = self.ket_sum ket_sum.generate_target() ket_sum.target.move_to(superposition_words) ket_sum.target.align_to(ket_sum, UP) sum_word = OldTexText("", "Sum") weighted_sum_word = OldTexText("Weighted", "sum") for word in sum_word, weighted_sum_word: word.scale(0.8) word.set_color(GREEN) word.add_background_rectangle() word.move_to(superposition_words.get_part_by_tex("Super")) self.play( Write(superposition_words, run_time = 2), MoveToTarget(ket_sum) ) self.wait(2) self.play( FadeIn(sum_word), superposition_words.shift, MED_LARGE_BUFF*DOWN, ket_sum.shift, MED_LARGE_BUFF*DOWN, ) self.wait() self.play(ReplacementTransform( sum_word, weighted_sum_word )) self.wait(2) def add_amplitudes(self): h_ket, plus, r_ket = self.ket_sum for mob in self.ket_sum: mob.generate_target() h_A, v_A = 2, 0.5 h_A_mob, v_A_mob = A_mobs = VGroup(*[ OldTex(str(A)).add_background_rectangle() for A in [h_A, v_A] ]) A_mobs.scale(0.8) A_mobs.set_color(GREEN) h_A_mob.move_to(h_ket, LEFT) VGroup(h_ket.target, plus.target).next_to( h_A_mob, RIGHT, SMALL_BUFF ) v_A_mob.next_to(plus.target, RIGHT, SMALL_BUFF) r_ket.target.next_to(v_A_mob, RIGHT, SMALL_BUFF) A_mobs.shift(0.4*SMALL_BUFF*UP) h_ov = self.h_oscillating_vector v_ov = self.v_oscillating_vector self.play(*it.chain( list(map(MoveToTarget, self.ket_sum)), list(map(Write, A_mobs)), [ UpdateFromAlphaFunc( ov.vector, self.generate_A_update( ov, A*np.array(ov.A_vect), np.array(ov.A_vect) ) ) for ov, A in [(h_ov, h_A), (v_ov, v_A)] ] )) self.wait(4) self.A_mobs = A_mobs def add_phase_shift(self): h_ket, plus, v_ket = self.ket_sum plus_phi = OldTex("+", "\\pi/2") plus_phi.set_color_by_tex("pi", self.phi_color) plus_phi.scale(0.8) plus_phi.next_to(v_ket.get_part_by_tex("t"), RIGHT, SMALL_BUFF) v_ket.generate_target() VGroup(*v_ket.target[1][-2:]).next_to(plus_phi, RIGHT, SMALL_BUFF) v_ket.target[0].replace(v_ket.target[1]) h_ov = self.h_oscillating_vector v_ov = self.v_oscillating_vector ellipse = Circle() ellipse.stretch_to_fit_height(2) ellipse.stretch_to_fit_width(8) ellipse.set_color(self.phi_color) h_A_mob, v_A_mob = self.A_mobs new_h_A_mob = v_A_mob.copy() new_h_A_mob.move_to(h_A_mob, RIGHT) self.add_foreground_mobject(plus_phi) self.play( MoveToTarget(v_ket), Write(plus_phi), UpdateFromAlphaFunc( v_ov.vector, self.generate_phi_update( v_ov, np.array([0, np.pi/2, 0]), np.array(v_ov.phi_vect) ) ) ) self.play(FadeIn(ellipse)) self.wait(5) self.play( UpdateFromAlphaFunc( h_ov.vector, self.generate_A_update( h_ov, 0.25*np.array(h_ov.A_vect), np.array(h_ov.A_vect), ) ), ellipse.stretch, 0.25, 0, Transform(h_A_mob, new_h_A_mob) ) self.wait(8) ##### def generate_A_update(self, ov, A_vect, prev_A_vect): def update(vect, alpha): ov.A_vect = interpolate( np.array(prev_A_vect), A_vect, alpha ) return vect return update def generate_phi_update(self, ov, phi_vect, prev_phi_vect): def update(vect, alpha): ov.phi_vect = interpolate( prev_phi_vect, phi_vect, alpha ) return vect return update def generate_dashed_line_update(self, v1, v2): def update_line(line): line.put_start_and_end_on_with_projection( *v1.get_start_and_end() ) line.shift(v2.get_end() - line.get_start()) return update_line class FromBracketFootnote(Scene): def construct(self): words = OldTexText( "From, ``Bra", "ket", "''", arg_separator = "" ) words.set_color_by_tex("ket", YELLOW) words.set_width(FRAME_WIDTH - 1) self.add(words) class Ay(Scene): def construct(self): sym = OldTex("A_y").set_color(GREEN) sym.scale(5) self.add(sym) class CircularlyPolarizedLight(SumOfTwoWaves): CONFIG = { "EMWave_config" : { "phi_vect" : [0, np.pi/2, 0], }, } class AlternateBasis(ShowTipToTailSum): def construct(self): self.force_skipping() self.add_vector() self.add_plane() self.add_vertial_vector() self.add_kets() self.show_vector_sum() self.remove(self.ket_sum, self.kets) self.reset_amplitude() self.revert_to_original_skipping_status() self.add_superposition_text() self.rotate_plane() self.show_vertically_polarized() def reset_amplitude(self): self.h_oscillating_vector.A_vect = np.array([1, 0, 0]) def add_superposition_text(self): self.hv_superposition, self.da_superposition = superpositions = [ OldTex( "\\vec{\\textbf{E}}", "=", "(\\dots)", "|\\!\\%sarrow\\rangle"%s1, "+", "(\\dots)", "|\\!\\%sarrow\\rangle"%s2, ) for s1, s2 in [("right", "up"), ("ne", "nw")] ] for superposition in superpositions: superposition.set_color_by_tex("rangle", YELLOW) superposition.set_color_by_tex("E", E_COLOR) superposition.add_background_rectangle(opacity = 1) superposition.to_edge(UP) self.add(self.hv_superposition) def rotate_plane(self): new_plane = NumberPlane( x_unit_size = 2, y_unit_size = 2, y_radius = FRAME_X_RADIUS, secondary_line_ratio = 0, ) new_plane.add_coordinates() new_plane.save_state() new_plane.fade(1) d = (RIGHT + UP)/np.sqrt(2) a = (LEFT + UP)/np.sqrt(2) self.wait(4) self.play( self.xy_plane.fade, 0.5, self.xy_plane.coordinate_labels.fade, 1, new_plane.restore, new_plane.rotate, np.pi/4, UpdateFromAlphaFunc( self.h_vector, self.generate_A_update( self.h_oscillating_vector, 2*d*np.dot(0.5*RIGHT + UP, d), np.array(self.h_oscillating_vector.A_vect) ) ), UpdateFromAlphaFunc( self.v_vector, self.generate_A_update( self.v_oscillating_vector, 2*a*np.dot(0.5*RIGHT + UP, a), np.array(self.v_oscillating_vector.A_vect) ) ), Transform(self.hv_superposition, self.da_superposition), run_time = 2, ) self.wait(4) def show_vertically_polarized(self): self.play( UpdateFromAlphaFunc( self.h_vector, self.generate_A_update( self.h_oscillating_vector, np.array([0.7, 0.7, 0]), np.array(self.h_oscillating_vector.A_vect) ) ), UpdateFromAlphaFunc( self.v_vector, self.generate_A_update( self.v_oscillating_vector, np.array([-0.7, 0.7, 0]), np.array(self.v_oscillating_vector.A_vect) ) ), ) self.wait(8) class WriteBasis(Scene): def construct(self): words = OldTexText("Choice of ``basis''") words.set_width(FRAME_WIDTH-1) self.play(Write(words)) self.wait() class ShowPolarizingFilter(DirectionOfPolarizationScene): CONFIG = { "EMWave_config" : { "start_point" : FRAME_X_RADIUS*LEFT, }, "apply_filter" : True, } def construct(self): self.setup_rectangles() self.fade_M_vects() self.axes.fade(0.5) self.initial_rotation() self.mention_energy_absorption() self.write_as_superposition() self.diagonal_filter() def setup_rectangles(self): DirectionOfPolarizationScene.setup_rectangles(self) self.rectangles[-1].fade(1) def fade_M_vects(self): self.em_wave.M_vects.set_fill(opacity = 0) def initial_rotation(self): self.wait() self.play(FadeIn(self.rectangles)) self.wait() self.change_polarization_direction(np.pi/2, run_time = 3) self.move_camera(phi = 0.9*np.pi/2, theta = -0.05*np.pi) def mention_energy_absorption(self): words = OldTexText("Absorbs horizontal \\\\ energy") words.set_color(RED) words.next_to(ORIGIN, UP+RIGHT, MED_LARGE_BUFF) words.rotate(np.pi/2, RIGHT) words.rotate(np.pi/2, OUT) lines = VGroup(*[ Line( np.sin(a)*RIGHT + np.cos(a)*UP, np.sin(a)*LEFT + np.cos(a)*UP, color = RED, stroke_width = 2, ) for a in np.linspace(0, np.pi, 15) ]) lines.rotate(np.pi/2, RIGHT) lines.rotate(np.pi/2, OUT) self.play( Write(words, run_time = 2), *list(map(GrowFromCenter, lines)) ) self.wait(6) self.play(FadeOut(lines)) self.play(FadeOut(words)) def write_as_superposition(self): superposition, continual_updates = self.get_superposition_tex(0, "right", "up") rect = superposition.rect self.play(Write(superposition, run_time = 2)) self.add(*continual_updates) for angle in np.pi/4, -np.pi/6: self.change_polarization_direction(angle) self.wait(3) self.move_camera( theta = -0.6*np.pi, added_anims = [ Rotate(superposition, -0.6*np.pi, axis = OUT) ] ) rect.set_stroke(YELLOW, 3) self.play(ShowCreation(rect)) arrow = Arrow( rect.get_nadir(), 3*RIGHT + 0.5*OUT, normal_vector = DOWN ) self.play(ShowCreation(arrow)) for angle in np.pi/3, -np.pi/3, np.pi/6: self.change_polarization_direction(angle) self.wait(2) self.play( FadeOut(superposition), FadeOut(arrow), *[ FadeOut(cu.mobject) for cu in continual_updates ] ) self.move_camera(theta = -0.1*np.pi) def diagonal_filter(self): superposition, continual_updates = self.get_superposition_tex(-np.pi/4, "nw", "ne") def update_filter_angle(pf, alpha): pf.filter_angle = interpolate(0, -np.pi/4, alpha) self.play( Rotate(self.pol_filter, np.pi/4, axis = LEFT), UpdateFromAlphaFunc(self.pol_filter, update_filter_angle), Animation(self.em_wave.mobject) ) superposition.rect.set_stroke(YELLOW, 2) self.play(Write(superposition, run_time = 2)) self.add(*continual_updates) for angle in np.pi/4, -np.pi/3, -np.pi/6: self.change_polarization_direction(np.pi/4) self.wait(2) ####### def get_superposition_tex(self, angle, s1, s2): superposition = OldTex( "0.00", "\\cos(", "2\\pi", "f", "t", ")", "|\\! \\%sarrow \\rangle"%s1, "+", "1.00", "\\cos(", "2\\pi", "f", "t", ")", "|\\! \\%sarrow \\rangle"%s2, ) A_x = DecimalNumber(0) A_y = DecimalNumber(1) A_x.move_to(superposition[0]) A_y.move_to(superposition[8]) superposition.submobjects[0] = A_x superposition.submobjects[8] = A_y VGroup(A_x, A_y).set_color(GREEN) superposition.set_color_by_tex("f", RED) superposition.set_color_by_tex("rangle", YELLOW) plus = superposition.get_part_by_tex("+") plus.add_to_back(BackgroundRectangle(plus)) v_part = VGroup(*superposition[8:]) rect = SurroundingRectangle(v_part) rect.fade(1) superposition.rect = rect superposition.add(rect) superposition.shift(3*UP + SMALL_BUFF*LEFT) superposition.rotate(np.pi/2, RIGHT) superposition.rotate(np.pi/2, OUT) def generate_decimal_update(trig_func): def update_decimal(decimal): new_decimal = DecimalNumber(abs(trig_func( self.reference_line.get_angle() - angle ))) new_decimal.rotate(np.pi/2, RIGHT) new_decimal.rotate(np.pi/2, OUT) new_decimal.rotate(self.camera.get_theta(), OUT) new_decimal.set_depth(decimal.get_depth()) new_decimal.move_to(decimal, UP) new_decimal.set_color(decimal.get_color()) decimal.align_data_and_family(new_decimal) families = [ mob.family_members_with_points() for mob in (decimal, new_decimal) ] for sm1, sm2 in zip(*families): sm1.interpolate(sm1, sm2, 1) return decimal return update_decimal continual_updates = [ Mobject.add_updater( A_x, generate_decimal_update(np.sin), ), Mobject.add_updater( A_y, generate_decimal_update(np.cos), ), ] return superposition, continual_updates class NamePolarizingFilter(Scene): def construct(self): words = OldTexText("Polarizing filter") words.set_width(FRAME_WIDTH - 1) self.play(Write(words)) self.wait() class EnergyOfWavesWavePortion(DirectWaveOutOfScreen): CONFIG = { "EMWave_config" : { "A_vect" : [0, 1, 1], "amplitude" : 4, "start_point" : FRAME_X_RADIUS*LEFT + 2*DOWN, } } def construct(self): self.grow_arrows() self.move_into_position() self.fade_M_vects() self.label_A() self.add_components() self.scale_up_and_down() def grow_arrows(self): for ov in self.em_wave.continual_animations: ov.vector.rectangular_stem_width = 0.1 ov.vector.tip_length = 0.5 def label_A(self): brace = Brace(Line(ORIGIN, 4*RIGHT)) brace.rotate(np.pi/4, OUT) brace.A = brace.get_tex("A", buff = MED_SMALL_BUFF) brace.A.scale(2) brace.A.set_color(GREEN) brace_group = VGroup(brace, brace.A) self.position_brace_group(brace_group) self.play(Write(brace_group, run_time = 1)) self.wait(12) self.brace = brace def add_components(self): h_wave = self.em_wave.copy() h_wave.A_vect = [0, 1, 0] v_wave = self.em_wave.copy() v_wave.A_vect = [0, 0, 1] length = 4/np.sqrt(2) for wave in h_wave, v_wave: for ov in wave.continual_animations: ov.A_vect = length*np.array(wave.A_vect) h_brace = Brace(Line(ORIGIN, length*RIGHT)) v_brace = Brace(Line(ORIGIN, length*UP), LEFT) for brace, c in (h_brace, "x"), (v_brace, "y"): brace.A = brace.get_tex("A_%s"%c, buff = MED_LARGE_BUFF) brace.A.scale(2) brace.A.set_color(GREEN) brace_group = VGroup(h_brace, h_brace.A, v_brace, v_brace.A) self.position_brace_group(brace_group) rhs = OldTex("= \\sqrt{A_x^2 + A_y^2}") rhs.scale(2) for i in 3, 5, 7, 9: rhs[i].set_color(GREEN) rhs.rotate(np.pi/2, RIGHT) rhs.rotate(np.pi/2, OUT) period = 1./self.em_wave.frequency self.add(h_wave, v_wave) self.play( FadeIn(h_wave.mobject), FadeIn(v_wave.mobject), self.brace.A.move_to, self.brace, self.brace.A.shift, SMALL_BUFF*(2*UP+IN), ReplacementTransform(self.brace, h_brace), Write(h_brace.A) ) self.wait(6) self.play( ReplacementTransform(h_brace.copy(), v_brace), Write(v_brace.A) ) self.wait(6) rhs.next_to(self.brace.A, UP, SMALL_BUFF) self.play(Write(rhs)) self.wait(2*period) self.h_brace = h_brace self.v_brace = v_brace self.h_wave = h_wave self.v_wave = v_wave def scale_up_and_down(self): for scale_factor in 1.25, 0.4, 1.5, 0.3, 2: self.scale_wave(scale_factor) self.wait() self.wait(4) ###### def position_brace_group(self, brace_group): brace_group.rotate(np.pi/2, RIGHT) brace_group.rotate(np.pi/2, OUT) brace_group.shift(2*DOWN) def scale_wave(self, factor): def generate_vect_update(ov): prev_A = np.array(ov.A_vect) new_A = factor*prev_A def update(vect, alpha): ov.A_vect = interpolate( prev_A, new_A, alpha ) return vect return update h_brace = self.h_brace v_brace = self.v_brace h_brace.generate_target() h_brace.target.stretch_about_point( factor, 1, h_brace.get_bottom() ) v_brace.generate_target() v_brace.target.stretch_about_point( factor, 2, v_brace.get_nadir() ) self.play( MoveToTarget(h_brace), MoveToTarget(v_brace), *[ UpdateFromAlphaFunc(ov.vector, generate_vect_update(ov)) for ov in it.chain( self.em_wave.continual_animations, self.h_wave.continual_animations, self.v_wave.continual_animations, ) ] ) class EnergyOfWavesTeacherPortion(TeacherStudentsScene): def construct(self): self.show_energy_equation() self.show_both_ways_of_thinking_about_it() def show_energy_equation(self): dot = Dot(self.teacher.get_top() + 2*(UP+LEFT)) dot.fade(1) self.dot = dot energy = OldTex( "\\frac{\\text{Energy}}{\\text{Volume}}", "=", "\\epsilon_0", "A", "^2" ) energy.set_color_by_tex("A", GREEN) energy.to_corner(UP+LEFT) component_energy = OldTex( "=", "\\epsilon_0", "A_x", "^2", "+", "\\epsilon_0", "A_y", "^2", ) for i in 2, 6: component_energy[i][0].set_color(GREEN) component_energy[i+1].set_color(GREEN) component_energy.next_to(energy[1], DOWN, MED_LARGE_BUFF, LEFT) self.play( Animation(dot), self.teacher.change, "raise_right_hand", dot, ) self.play_student_changes( *["pondering"]*3, look_at = dot ) self.wait(2) self.play(Write(energy)) self.play(self.teacher.change, "happy") self.wait(3) self.play( ReplacementTransform( VGroup(*energy[-4:]).copy(), VGroup(*component_energy[:4]) ), ReplacementTransform( VGroup(*energy[-4:]).copy(), VGroup(*component_energy[4:]) ) ) self.play_student_changes(*["happy"]*3, look_at = energy) self.wait() def show_both_ways_of_thinking_about_it(self): s1, s2 = self.get_students()[:2] b1, b2 = [ ThoughtBubble(direction = v).scale(0.5) for v in (LEFT, RIGHT) ] b1.pin_to(s1) b2.pin_to(s2) b1.write("Add \\\\ components") b2.write("Pythagorean \\\\ theorem") for b, s in (b1, s1), (b2, s2): self.play( ShowCreation(b), Write(b.content, run_time = 2), s.change, "thinking" ) self.wait(2) self.play_student_changes( *["plain"]*3, look_at = self.dot, added_anims = [ self.teacher.change, "raise_right_hand", self.dot ] ) self.play(self.teacher.look_at, self.dot) self.wait(5) class DescribePhoton(ThreeDScene): CONFIG = { "x_color" : RED, "y_color" : GREEN, } def setup(self): self.axes = ThreeDAxes() self.add(self.axes) self.set_camera_orientation(phi = 0.8*np.pi/2, theta = -np.pi/4) em_wave = EMWave( start_point = FRAME_X_RADIUS*LEFT, A_vect = [0, 1, 1], wave_number = 0, amplitude = 3, ) for ov in em_wave.continual_animations: ov.vector.normal_vector = RIGHT ov.vector.set_fill(opacity = 0.7) for M_vect in em_wave.M_vects: M_vect.set_fill(opacity = 0) em_wave.update(0) photon = WavePacket( em_wave = em_wave, run_time = 2, ) self.photon = photon self.em_wave = em_wave def construct(self): self.add_ket_equation() self.shoot_a_few_photons() self.freeze_photon() self.reposition_to_face_photon_head_on() self.show_components() self.show_amplitude_and_phase() self.change_basis() self.write_different_meaning() self.write_components() self.describe_via_energy() self.components_not_possible_in_isolation() self.ask_what_they_mean() self.change_camera() def add_ket_equation(self): equation = OldTex( "|\\!\\psi\\rangle", "=", "\\alpha", "|\\!\\rightarrow \\rangle", "+", "\\beta", "|\\!\\uparrow \\rangle", ) equation.to_edge(UP) equation.set_color_by_tex("psi", E_COLOR) equation.set_color_by_tex("alpha", self.x_color) equation.set_color_by_tex("beta", self.y_color) rect = SurroundingRectangle(equation.get_part_by_tex("psi")) rect.set_color(E_COLOR) words = OldTexText("Polarization\\\\", "state") words.next_to(rect, DOWN) for part in words: bg_rect = BackgroundRectangle(part) bg_rect.stretch_in_place(2, 1) part.add_to_back(bg_rect) equation.rect = rect equation.words = words equation.add_background_rectangle() equation.add(rect, words) VGroup(rect, words).fade(1) equation.rotate(np.pi/2, RIGHT) equation.rotate(np.pi/2 + self.camera.get_theta(), OUT) self.add(equation) self.equation = equation self.superposition = VGroup(*equation[1][2:]) def shoot_a_few_photons(self): for x in range(2): self.play(self.photon) def freeze_photon(self): self.play( self.photon, rate_func = lambda x : 0.55*x, run_time = 1 ) self.add(self.photon.mobject) self.photon.rate_func = lambda x : x self.photon.run_time = 2 def reposition_to_face_photon_head_on(self): plane = NumberPlane( color = GREY_B, secondary_color = GREY_D, x_unit_size = 2, y_unit_size = 2, y_radius = FRAME_X_RADIUS, ) plane.add_coordinates(x_vals = list(range(-3, 4)), y_vals = []) plane.rotate(np.pi/2, RIGHT) plane.rotate(np.pi/2, OUT) self.play(self.em_wave.M_vects.set_fill, None, 0) self.move_camera( phi = np.pi/2, theta = 0, added_anims = [ Rotate(self.equation, -self.camera.get_theta()) ] ) self.play( Write(plane, run_time = 1), Animation(self.equation) ) self.xy_plane = plane def show_components(self): h_arrow, v_arrow = [ Vector( 1.38*direction, color = color, normal_vector = RIGHT, ) for color, direction in [(self.x_color, UP), (self.y_color, OUT)] ] v_arrow.move_to(h_arrow.get_end(), IN) h_part = VGroup(*self.equation[1][2:4]).copy() v_part = VGroup(*self.equation[1][5:7]).copy() self.play( self.equation.rect.set_stroke, BLUE, 4, self.equation.words.set_fill, WHITE, 1, ) for part, arrow, d in (h_part, h_arrow, IN), (v_part, v_arrow, UP): self.play( part.next_to, arrow.get_center(), d, ShowCreation(arrow) ) part.rotate(np.pi/2, DOWN) bg_rect = BackgroundRectangle(part) bg_rect.stretch_in_place(1.3, 0) part.add_to_back(bg_rect) part.rotate(np.pi/2, UP) self.add(part) self.wait() self.h_part_tex = h_part self.h_arrow = h_arrow self.v_part_tex = v_part self.v_arrow = v_arrow def show_amplitude_and_phase(self): alpha = self.h_part_tex[1] new_alpha = alpha.copy().shift(IN) rhs = OldTex( "=", "A_x", "e", "^{i", "(2\\pi", "f", "t", "+", "\\phi_x)}" ) A_rect = SurroundingRectangle(rhs.get_part_by_tex("A_x"), buff = 0.5*SMALL_BUFF) A_word = OldTexText("Amplitude") A_word.add_background_rectangle() A_word.next_to(A_rect, DOWN, aligned_edge = LEFT) A_group = VGroup(A_rect, A_word) A_group.set_color(YELLOW) phase_rect = SurroundingRectangle(VGroup(*rhs[4:]), buff = 0.5*SMALL_BUFF) phase_word = OldTexText("Phase") phase_word.add_background_rectangle() phase_word.next_to(phase_rect, UP) phase_group = VGroup(phase_word, phase_rect) phase_group.set_color(MAROON_B) rhs.add_background_rectangle() group = VGroup(rhs, A_group, phase_group) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/2, OUT) group.next_to(new_alpha, UP, SMALL_BUFF) self.play( ReplacementTransform(alpha.copy(), new_alpha), FadeIn(rhs) ) for word, rect in A_group, phase_group: self.play( ShowCreation(rect), Write(word, run_time = 1) ) self.wait() self.play(*list(map(FadeOut, [new_alpha, group]))) def change_basis(self): superposition = self.superposition plane = self.xy_plane h_arrow = self.h_arrow v_arrow = self.v_arrow h_part = self.h_part_tex v_part = self.v_part_tex axes = self.axes movers = [ plane, axes, h_arrow, v_arrow, h_part, v_part, self.equation, superposition, ] for mob in movers: mob.save_state() superposition.target = OldTex( "\\gamma", "|\\! \\nearrow \\rangle", "+", "\\delta", "|\\! \\nwarrow \\rangle", ) superposition.target.set_color_by_tex("gamma", TEAL_D) superposition.target.set_color_by_tex("delta", MAROON) for part in superposition.target.get_parts_by_tex("rangle"): part[1].rotate(-np.pi/12) superposition.target.rotate(np.pi/2, RIGHT) superposition.target.rotate(np.pi/2, OUT) superposition.target.move_to(superposition) for mob in plane, axes: mob.generate_target() mob.target.rotate(np.pi/6, RIGHT) A = 1.9 h_arrow.target = Vector( A*np.cos(np.pi/12)*rotate_vector(UP, np.pi/6, RIGHT), normal_vector = RIGHT, color = TEAL ) v_arrow.target = Vector( A*np.sin(np.pi/12)*rotate_vector(OUT, np.pi/6, RIGHT), normal_vector = RIGHT, color = MAROON ) v_arrow.target.shift(h_arrow.target.get_vector()) h_part.target = VGroup(*superposition.target[:2]).copy() v_part.target = VGroup(*superposition.target[3:]).copy() h_part.target.next_to( h_arrow.target.get_center(), IN+UP, SMALL_BUFF ) v_part.target.next_to( v_arrow.target.get_center(), UP, SMALL_BUFF ) for part in h_part.target, v_part.target: part.rotate(np.pi/2, DOWN) part.add_to_back(BackgroundRectangle(part)) part.rotate(np.pi/2, UP) self.equation.generate_target() self.play(*list(map(MoveToTarget, movers))) self.wait(2) self.play(*[mob.restore for mob in movers]) self.wait() def write_different_meaning(self): superposition = self.superposition superposition.rotate(np.pi/2, DOWN) rect = SurroundingRectangle(superposition) VGroup(superposition, rect).rotate(np.pi/2, UP) morty = Mortimer(mode = "confused") blinked = morty.copy().blink() words = OldTexText("Means something \\\\ different...") for mob in morty, blinked, words: mob.rotate(np.pi/2, RIGHT) mob.rotate(np.pi/2, OUT) words.next_to(rect, UP) VGroup(morty, blinked).next_to(words, IN) self.play( ShowCreation(rect), Write(words, run_time = 2) ) self.play(FadeIn(morty)) self.play(Transform( morty, blinked, rate_func = squish_rate_func(there_and_back) )) self.wait() self.play(*list(map(FadeOut, [ morty, words, rect, self.equation.rect, self.equation.words, ]))) def write_components(self): d_brace = Brace(Line(ORIGIN, 2*RIGHT), UP, buff = SMALL_BUFF) h_brace = Brace(Line(ORIGIN, (2/np.sqrt(2))*RIGHT), DOWN, buff = SMALL_BUFF) v_brace = Brace(Line(ORIGIN, (2/np.sqrt(2))*UP), RIGHT, buff = SMALL_BUFF) d_brace.rotate(np.pi/4) v_brace.shift((2/np.sqrt(2))*RIGHT) braces = VGroup(d_brace, h_brace, v_brace) group = VGroup(braces) tex = ["1"] + 2*["\\sqrt{1/2}"] colors = BLUE, self.x_color, self.y_color for brace, tex, color in zip(braces, tex, colors): brace.label = brace.get_tex(tex, buff = SMALL_BUFF) brace.label.add_background_rectangle() brace.label.set_color(color) group.add(brace.label) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/2, OUT) self.play( GrowFromCenter(d_brace), Write(d_brace.label) ) self.wait() self.play( FadeOut(self.h_part_tex), FadeOut(self.v_part_tex), GrowFromCenter(h_brace), GrowFromCenter(v_brace), ) self.play( Write(h_brace.label), Write(v_brace.label), ) self.wait() self.d_brace = d_brace self.h_brace = h_brace self.v_brace = v_brace def describe_via_energy(self): energy = OldTex( "&\\text{Energy}", "=", "(hf)", "(", "1", ")^2\\\\", "&=", "(hf)", "\\left(", "\\sqrt{1/2}", "\\right)^2", "+", "(hf)", "\\left(", "\\sqrt{1/2}", "\\right)^2", ) energy.scale(0.8) one = energy.get_part_by_tex("1", substring = False) one.set_color(BLUE) halves = energy.get_parts_by_tex("1/2") halves[0].set_color(self.x_color) halves[1].set_color(self.y_color) indices = [0, 3, 6, len(energy)] parts = VGroup(*[ VGroup(*energy[i1:i2]) for i1, i2 in zip(indices, indices[1:]) ]) for part in parts: bg_rect = BackgroundRectangle(part) bg_rect.stretch_in_place(1.5, 1) part.add_to_back(bg_rect) parts.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) parts.shift(DOWN) parts.rotate(np.pi/2, RIGHT) parts.rotate(np.pi/2, OUT) self.play(Write(parts[0]), run_time = 2) self.play(Indicate(energy.get_part_by_tex("hf"))) self.play( Transform( self.d_brace.label.copy(), one.copy(), remover = True ), Write(parts[1], run_time = 1), ) self.wait() self.play( Transform( self.h_brace.label[1].copy(), halves[0].copy(), remover = True, rate_func = squish_rate_func(smooth, 0, 0.75) ), Transform( self.v_brace.label[1].copy(), halves[1].copy(), remover = True, rate_func = squish_rate_func(smooth, 0.25, 1) ), Write(parts[2]), run_time = 2 ) self.wait() self.energy_equation_parts = parts def components_not_possible_in_isolation(self): half_hf = VGroup(*self.energy_equation_parts[2][1:6]) half_hf.rotate(np.pi/2, DOWN) rect = SurroundingRectangle(half_hf) VGroup(half_hf, rect).rotate(np.pi/2, UP) randy = Randolph() randy.scale(0.7) randy.look(UP) randy.rotate(np.pi/2, RIGHT) randy.rotate(np.pi/2, OUT) randy.next_to(rect, IN) self.play( ShowCreation(rect), FadeIn(randy) ) self.play( randy.rotate, np.pi/2, IN, randy.rotate, np.pi/2, LEFT, randy.change, "maybe", randy.rotate, np.pi/2, RIGHT, randy.rotate, np.pi/2, OUT, ) self.wait() def ask_what_they_mean(self): morty = Mortimer(mode = "confused") morty.scale(0.7) morty.to_edge(LEFT) bubble = morty.get_bubble() bubble.write("?!?") bubble.resize_to_content() bubble.add(bubble.content) bubble.pin_to(morty) group = VGroup(morty, bubble) group.to_corner(DOWN+RIGHT) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/2, OUT) component = VGroup(self.h_arrow, self.h_brace, self.h_brace.label) self.play( FadeIn(morty), component.next_to, morty, DOWN, OUT, component.shift, MED_LARGE_BUFF*(DOWN + OUT), ) component.rotate(np.pi/2, DOWN) cross = Cross(component) VGroup(component, cross).rotate(np.pi/2, UP) cross.set_color("#ff0000") self.play(ShowCreation(cross)) bubble.remove(bubble.content) self.play( ShowCreation(bubble), Write(bubble.content), morty.look_at, component, ) self.wait() def change_camera(self): everything = VGroup(*self.get_top_level_mobjects()) everything.remove(self.photon.mobject) everything.remove(self.axes) self.play(*list(map(FadeOut, everything))) self.move_camera( phi = 0.8*np.pi/2, theta = -0.3*np.pi, run_time = 2 ) self.play( self.photon, rate_func = lambda x : min(x + 0.55, 1), run_time = 2, ) self.photon.rate_func = lambda x : x self.play(self.photon) self.wait() class SeeCommentInDescription(Scene): def construct(self): words = OldTexText(""" \\begin{flushleft} $^*$See comment in the \\\\ description on single-headed \\\\ vs. double-headed arrows \\end{flushleft} """) words.set_width(FRAME_WIDTH - 1) words.to_corner(DOWN+LEFT) self.add(words) class SeeCommentInDescriptionAgain(Scene): def construct(self): words = OldTexText("$^*$Again, see description") words.set_width(FRAME_WIDTH - 1) words.to_corner(DOWN+LEFT) self.add(words) class GetExperimental(TeacherStudentsScene): def construct(self): self.teacher_says("Get experimental!", target_mode = "hooray") self.play_student_changes(*["hooray"]*3) self.wait(3) class ShootPhotonThroughFilter(DirectionOfPolarizationScene): CONFIG = { "EMWave_config" : { "wave_number" : 0, "A_vect" : [0, 1, 1], "start_point" : FRAME_X_RADIUS*LEFT, "amplitude" : np.sqrt(2), }, "pol_filter_configs" : [{ "label_tex" : "\\text{Filter}", "include_arrow_label" : False, }], "apply_filter" : True, "quantum" : True, "pre_filter_alpha" : 0.35, "ambient_rotation_rate" : 0, } def setup(self): DirectionOfPolarizationScene.setup(self) self.em_wave.update(0) self.remove(self.em_wave) def construct(self): self.force_skipping() self.add_superposition_tex() self.ask_what_would_happen() self.expect_half_energy_to_be_absorbed() self.probabalistic_passing_and_blocking() # self.note_change_in_polarization() def add_superposition_tex(self): superposition_tex = OldTex( "|\\!\\nearrow\\rangle", "=", "(\\sqrt{1/2})", "|\\!\\rightarrow \\rangle", "+", "(\\sqrt{1/2})", "|\\!\\uparrow \\rangle", ) superposition_tex.scale(0.9) superposition_tex[0].set_color(E_COLOR) halves = superposition_tex.get_parts_by_tex("1/2") for half, color in zip(halves, [RED, GREEN]): half.set_color(color) h_rect = SurroundingRectangle(VGroup(*superposition_tex[2:4])) v_rect = SurroundingRectangle(VGroup(*superposition_tex[5:7])) VGroup(h_rect, v_rect).fade(1) superposition_tex.h_rect = h_rect superposition_tex.v_rect = v_rect superposition_tex.add(h_rect, v_rect) superposition_tex.next_to(ORIGIN, LEFT) superposition_tex.to_edge(UP) superposition_tex.rotate(np.pi/2, RIGHT) self.superposition_tex = superposition_tex def ask_what_would_happen(self): photon = self.get_photon( rate_func = lambda t : self.pre_filter_alpha*t, remover = False, run_time = 0.6, ) question = OldTexText("What's going to happen?") question.add_background_rectangle() question.set_color(YELLOW) question.rotate(np.pi/2, RIGHT) question.next_to(self.superposition_tex, IN) self.pol_filter.add( self.pol_filter.arrow.copy().rotate(np.pi/2, OUT) ) self.pol_filter.save_state() self.pol_filter.shift(5*OUT) self.set_camera_orientation(theta = -0.9*np.pi) self.play(self.pol_filter.restore) self.move_camera( theta = -0.6*np.pi, ) self.play( photon, FadeIn(self.superposition_tex) ) self.play(Write(question, run_time = 1)) self.wait() self.play(FadeOut(self.pol_filter.label)) self.pol_filter.remove(self.pol_filter.label) self.add(self.pol_filter) self.question = question self.frozen_photon = photon def expect_half_energy_to_be_absorbed(self): words = OldTexText("Absorbs horizontal \\\\ energy") words.set_color(RED) words.next_to(ORIGIN, UP+RIGHT, MED_LARGE_BUFF) words.rotate(np.pi/2, RIGHT) words.rotate(np.pi/2, OUT) lines = VGroup(*[ Line( np.sin(a)*RIGHT + np.cos(a)*UP, np.sin(a)*LEFT + np.cos(a)*UP, color = RED, stroke_width = 2, ) for a in np.linspace(0, np.pi, 15) ]) lines.rotate(np.pi/2, RIGHT) lines.rotate(np.pi/2, OUT) self.move_camera( phi = np.pi/2, theta = 0, added_anims = [ Rotate(self.superposition_tex, np.pi/2), ] + [ ApplyMethod( v.rotate, -np.pi/2, method_kwargs = {"axis" : v.get_vector()} ) for v in self.frozen_photon.mobject ] ) self.play( Write(words, run_time = 2), self.superposition_tex.h_rect.set_stroke, RED, 3, *list(map(GrowFromCenter, lines))+\ [ Animation(self.pol_filter), Animation(self.frozen_photon.mobject) ] ) self.wait(2) self.move_camera( phi = 0.8*np.pi/2, theta = -0.7*np.pi, added_anims = [ FadeOut(words), Animation(lines), Rotate(self.superposition_tex, -np.pi/2), ] + [ ApplyMethod( v.rotate, np.pi/2, method_kwargs = {"axis" : v.get_vector()} ) for v in self.frozen_photon.mobject ] ) self.play( FadeOut(lines), FadeOut(self.question), self.superposition_tex.h_rect.fade, 1, Animation(self.pol_filter) ) self.wait() self.absorption_words = words def probabalistic_passing_and_blocking(self): absorption = self.get_filter_absorption_animation( self.pol_filter, self.get_blocked_photon() ) prob = OldTex("P(", "\\text{pass}", ")", "=", "1/2") prob.set_color_by_tex("pass", GREEN) prob.rotate(np.pi/2, RIGHT) prob.next_to(self.superposition_tex, IN, MED_SMALL_BUFF, RIGHT) self.remove(self.frozen_photon.mobject) self.play( self.get_photon(), rate_func = lambda t : min(t+self.pre_filter_alpha, 1), ) self.play( FadeIn(prob), self.get_blocked_photon(), absorption ) bools = 6*[True] + 6*[False] self.revert_to_original_skipping_status() random.shuffle(bools) for should_pass in bools: if should_pass: self.play(self.get_photon(), run_time = 1) else: self.play( self.get_blocked_photon(), Animation(self.axes), absorption, run_time = 1 ) self.play(FadeOut(prob)) def note_change_in_polarization(self): words = OldTexText( "``Collapses'' \\\\ from", "$|\\!\\nearrow\\rangle$", "to", "$|\\!\\uparrow\\rangle$" ) words.set_color_by_tex("nearrow", E_COLOR) words.set_color_by_tex("uparrow", GREEN) words.next_to(ORIGIN, RIGHT, MED_LARGE_BUFF) words.shift(2*UP) words.rotate(np.pi/2, RIGHT) photon = self.get_photon(run_time = 4) for vect in photon.mobject: if vect.get_center()[0] > 0: vect.saved_state.set_fill(GREEN) self.play(FadeIn(words), photon) for x in range(3): self.play(photon) ###### def get_photon(self, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 1) kwargs["include_M_vects"] = False return WavePacket(em_wave = self.em_wave.copy(), **kwargs) def get_blocked_photon(self, **kwargs): kwargs["get_filtered"] = True return self.get_photon(self, **kwargs) class PhotonPassesCompletelyOrNotAtAllStub(ExternallyAnimatedScene): pass class YouCanSeeTheCollapse(TeacherStudentsScene): def construct(self): self.teacher_says( "You can literally \\\\ \\emph{see} the collapse", target_mode = "hooray" ) self.play_student_changes("confused", "hooray", "erm") self.wait(3) class ThreeFilters(ShootPhotonThroughFilter): CONFIG = { "filter_x_coordinates" : [-4, 0, 4], "pol_filter_configs" : [ {"filter_angle" : 0}, {"filter_angle" : np.pi/4}, {"filter_angle" : np.pi/2}, ], "EMWave_config" : { "A_vect" : [0, 0, 1], "amplitude" : 1.5, "n_vectors" : 60, }, "line_start_length" : 8, "line_end_length" : 8, "n_lines" : 20, "lines_depth" : 1.8, "lines_shift_vect" : SMALL_BUFF*OUT, "random_seed" : 6, } def construct(self): self.remove(self.axes) self.setup_filters() self.setup_lines() self.setup_arrows() self.fifty_percent_pass_second() self.show_changed_to_diagonal() self.fifty_percent_to_pass_third() self.show_lines_with_middle() self.remove_middle_then_put_back() def setup_filters(self): for pf in self.pol_filters: pf.arrow_label.rotate(np.pi/2, OUT) pf.arrow_label.next_to(pf.arrow, RIGHT) pf.arrow_label.rotate(np.pi/2, LEFT) pf.arrow_label.add_background_rectangle() pf.arrow_label.rotate(np.pi/2, RIGHT) self.add_foreground_mobject(pf.arrow_label) def setup_lines(self): lines_group = VGroup(*[ self.get_lines(pf1, pf2, ratio) for pf1, pf2, ratio in zip( [None] + list(self.pol_filters), list(self.pol_filters) + [None], [1, 1, 0.5, 0.25] ) ]) lines = lines_group[0] spacing = lines[1].get_start() - lines[0].get_start() lines.add(lines.copy().shift(spacing/2)) self.lines_group = lines_group self.A_to_C_lines = self.get_lines( self.pol_filters[0], self.pol_filters[2], ) def setup_arrows(self): for E_vect in self.em_wave.E_vects: E_vect.normal_vector = IN+DOWN self.em_wave.update(0) def fifty_percent_pass_second(self): arrow = Arrow( ORIGIN, 3*RIGHT, use_rectangular_stem = False, path_arc = -0.8*np.pi ) label = OldTex("50\\%") label.next_to(arrow, UP) group = VGroup(arrow, label) group.rotate(np.pi/2, RIGHT) group.next_to(self.pol_filters[1], OUT, buff = 0) group.set_color(BLUE) l1, l2, l3 = self.lines_group[:3] pf1, pf2, pf3 = self.pol_filters kwargs = { "lag_ratio" : 0, "rate_func" : None, } self.play(ShowCreation(l1, run_time = 1, **kwargs)) self.play( ShowCreation(l2, **kwargs), Animation(VGroup(pf1, l1)), ShowCreation(arrow), run_time = 0.5, ) self.play( ShowCreation(l3, **kwargs), Animation(VGroup(pf2, l2, pf1, l1)), FadeIn(label), run_time = 0.5, ) self.wait(2) self.play( FadeOut(l3), Animation(pf2), FadeOut(l2), Animation(pf1), FadeOut(l1) ) self.fifty_percent_arrow_group = group def show_changed_to_diagonal(self): photon = self.get_photon( run_time = 2, rate_func = lambda x : 0.6*x, remover = False, ) brace = Brace(Line(1.5*LEFT, 1.5*RIGHT), DOWN) label = brace.get_text( "Changed to", "$|\\!\\nearrow\\rangle$" ) label.set_color_by_tex("rangle", BLUE) group = VGroup(brace, label) group.rotate(np.pi/2, RIGHT) group.shift(2*RIGHT + 0.5*IN) self.play(photon) self.play( GrowFromCenter(brace), Write(label, run_time = 1) ) kwargs = { "run_time" : 3, "rate_func" : there_and_back_with_pause, } self.move_camera( phi = np.pi/2, theta = 0, added_anims = [ Animation(VGroup(*self.pol_filters[:2])) ] + [ Rotate( v, np.pi/2, axis = v.get_vector(), in_place = True, **kwargs ) for v in photon.mobject ] + [ Animation(self.pol_filters[2]), Rotate( label, np.pi/2, axis = OUT, in_place = True, **kwargs ), ], **kwargs ) self.wait() self.photon = photon self.brace_group = VGroup(brace, label) def fifty_percent_to_pass_third(self): arrow_group = self.fifty_percent_arrow_group.copy() arrow_group.shift(4*RIGHT) arrow, label = arrow_group a = self.photon.rate_func(1) new_photon = self.get_photon( rate_func = lambda x : (1-a)*x + a, run_time = 1 ) self.revert_to_original_skipping_status() self.play( ShowCreation(arrow), Write(label, run_time = 1) ) self.remove(self.photon.mobject) self.play(new_photon) self.second_fifty_percent_arrow_group = arrow_group def show_lines_with_middle(self): l1, l2, l3, l4 = self.lines_group pf1, pf2, pf3 = self.pol_filters self.play( FadeIn(l4), Animation(pf3), FadeIn(l3), Animation(pf2), FadeIn(l2), Animation(pf1), FadeIn(l1), FadeOut(self.brace_group) ) self.wait(2) def remove_middle_then_put_back(self): l1, l2, l3, l4 = self.lines_group pf1, pf2, pf3 = self.pol_filters mid_lines = self.A_to_C_lines mover = VGroup( pf2, self.fifty_percent_arrow_group, self.second_fifty_percent_arrow_group, ) arrow = Arrow( ORIGIN, 7*RIGHT, path_arc = 0.5*np.pi, ) labels = VGroup(*list(map(Tex, ["0\\%", "25\\%"]))) labels.scale(1.5) labels.next_to(arrow, DOWN) group = VGroup(arrow, labels) group.rotate(np.pi/2, RIGHT) group.shift(2*LEFT + IN) group.set_color(GREEN) self.remove(l2, l3) self.play( FadeOut(l4), Animation(pf3), FadeOut(l3), ApplyMethod( mover.shift, 3*OUT, rate_func = running_start ), ReplacementTransform(l2.copy(), mid_lines), Animation(pf1), Animation(l1) ) self.play( ShowCreation(arrow), Write(labels[0], run_time = 1) ) self.wait(2) self.play( FadeIn(l4), Animation(pf3), FadeOut(mid_lines), FadeIn(l3), mover.shift, 3*IN, FadeIn(l2), Animation(pf1), Animation(l1) ) self.play(ReplacementTransform(*labels)) self.wait(3) #### def get_photon(self, **kwargs): return ShootPhotonThroughFilter.get_photon(self, width = 4, **kwargs) def get_lines(self, filter1 = None, filter2 = None, ratio = 1.0): n = self.n_lines start, end = [ (f.point_from_proportion(0.75) if f is not None else None) for f in (filter1, filter2) ] if start is None: start = end + self.line_start_length*LEFT if end is None: end = start + self.line_end_length*RIGHT nudge = (float(self.lines_depth)/self.n_lines)*OUT lines = VGroup(*[ Line(start, end).shift(z*nudge) for z in range(n) ]) lines.set_stroke(YELLOW, 2) lines.move_to(start, IN+LEFT) lines.shift(self.lines_shift_vect) n_to_block = int((1-ratio)*self.n_lines) random.seed(self.random_seed) indices_to_block = random.sample( list(range(self.n_lines)), n_to_block ) VGroup(*[lines[i] for i in indices_to_block]).set_stroke(width = 0) return lines class PhotonAtSlightAngle(ThreeFilters): CONFIG = { "filter_x_coordinates" : [3], "pol_filter_configs" : [{ "label_tex" : "", "include_arrow_label" : False, "radius" : 1.4, }], "EMWave_config" : { "wave_number" : 0, "A_vect" : [0, np.sin(np.pi/8), np.cos(np.pi/8)], "start_point" : FRAME_X_RADIUS*LEFT, "amplitude" : 2, }, "axes_config" : { "z_max" : 2.5, }, "radius" : 1.3, "lines_depth" : 2.5, "line_start_length" : 12, } def construct(self): self.force_skipping() self.shoot_photon() self.reposition_camera_to_head_on() self.write_angle() self.write_components() self.classical_energy_conception() self.reposition_camera_back() self.rewrite_15_percent_meaning() self.probabalistic_passing() def shoot_photon(self): photon = self.get_photon( rate_func = lambda x : 0.5*x, remover = False, ) self.play(photon) self.photon = photon def reposition_camera_to_head_on(self): self.move_camera( phi = np.pi/2, theta = 0, added_anims = list(it.chain(*[ [ v.rotate, np.pi/2, v.get_vector(), v.set_fill, None, 0.7, ] for v in self.photon.mobject ])) + [Animation(self.pol_filter)] ) def write_angle(self): arc = Arc( start_angle = np.pi/2, angle = -np.pi/8, radius = self.pol_filter.radius, ) label = OldTex("22.5^\\circ") label.next_to(arc.get_center(), UP+RIGHT, SMALL_BUFF) group = VGroup(arc, label) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/2, OUT) self.play( FadeOut(self.pol_filter), ShowCreation(arc), Write(label, run_time = 1) ) self.wait() self.arc = arc self.angle_label = label def write_components(self): d_brace = Brace(Line(ORIGIN, self.radius*RIGHT), UP, buff = SMALL_BUFF) d_brace.rotate(np.pi/2 - np.pi/8) d_brace.label = d_brace.get_tex("1", buff = SMALL_BUFF) d_brace.label.add_background_rectangle() h_arrow = Vector( self.radius*np.sin(np.pi/8)*RIGHT, color = RED, ) h_label = OldTex("\\sin(22.5^\\circ)") h_label.scale(0.7) h_label.set_color(RED) h_label.next_to(h_arrow.get_center(), DOWN, aligned_edge = LEFT) v_arrow = Vector( self.radius*np.cos(np.pi/8)*UP, color = GREEN ) v_arrow.shift(h_arrow.get_vector()) v_label = OldTex("\\cos(22.5^\\circ)") v_label.scale(0.7) v_label.set_color(GREEN) v_label.next_to(v_arrow, RIGHT, SMALL_BUFF) state = OldTex( "|\\!\\psi\\rangle", "=", "\\sin(22.5^\\circ)", "|\\!\\rightarrow\\rangle", "+", "\\cos(22.5^\\circ)", "|\\!\\uparrow\\rangle", ) state.set_color_by_tex_to_color_map({ "psi" : BLUE, "rightarrow" : RED, "uparrow" : GREEN, }) # state.add_background_rectangle() state.to_edge(UP) sin_brace = Brace(state.get_part_by_tex("sin"), DOWN, buff = SMALL_BUFF) sin_brace.label = sin_brace.get_tex("%.2f"%np.sin(np.pi/8), buff = SMALL_BUFF) cos_brace = Brace(state.get_part_by_tex("cos"), DOWN, buff = SMALL_BUFF) cos_brace.label = cos_brace.get_tex("%.2f"%np.cos(np.pi/8), buff = SMALL_BUFF) group = VGroup( d_brace, d_brace.label, h_arrow, h_label, v_arrow, v_label, state, sin_brace, sin_brace.label, cos_brace, cos_brace.label, ) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/2, OUT) self.play( GrowFromCenter(d_brace), Write(d_brace.label) ) self.wait() self.play( GrowFromPoint(h_arrow, ORIGIN), Write(h_label, run_time = 1) ) self.play( Write(VGroup(*state[:2])), ReplacementTransform( h_label.copy(), state.get_part_by_tex("sin") ), ReplacementTransform( h_arrow.copy(), state.get_part_by_tex("rightarrow") ), Write(state.get_part_by_tex("+")) ) self.play( GrowFromCenter(sin_brace), Write(sin_brace.label, run_time = 1) ) self.wait() self.play( GrowFromPoint(v_arrow, h_arrow.get_end()), Write(v_label, run_time = 1) ) self.play( ReplacementTransform( v_label.copy(), state.get_part_by_tex("cos") ), ReplacementTransform( v_arrow.copy(), state.get_part_by_tex("uparrow") ), ) self.play( GrowFromCenter(cos_brace), Write(cos_brace.label, run_time = 1) ) self.wait() self.d_brace = d_brace self.state_equation = state self.state_equation.add( sin_brace, sin_brace.label, cos_brace, cos_brace.label, ) self.sin_brace = sin_brace self.cos_brace = cos_brace self.h_arrow = h_arrow self.h_label = h_label self.v_arrow = v_arrow self.v_label = v_label def classical_energy_conception(self): randy = Randolph(mode = "pondering").flip() randy.scale(0.7) randy.next_to(ORIGIN, LEFT) randy.to_edge(DOWN) bubble = ThoughtBubble(direction = RIGHT) h_content = OldTex( "0.38", "^2", "= 0.15", "\\text{ energy}\\\\", "\\text{in the }", "\\rightarrow", "\\text{ direction}" ) alt_h_content = OldTex( "0.38", "^2", "=& 15\\%", "\\text{ of energy}\\\\", "&\\text{absorbed}", "", "", ) h_content.set_color_by_tex("rightarrow", RED) alt_h_content.set_color_by_tex("rightarrow", RED) alt_h_content.scale(0.8) v_content = OldTex( "0.92", "^2", "= 0.85", "\\text{ energy}\\\\", "\\text{in the }", "\\uparrow", "\\text{ direction}" ) v_content.set_color_by_tex("uparrow", GREEN) bubble.add_content(h_content) bubble.resize_to_content() v_content.move_to(h_content) bubble_group = VGroup(bubble, h_content, v_content) bubble_group.scale(0.8) bubble_group.next_to(randy, UP+LEFT, SMALL_BUFF) classically = OldTexText("Classically...") classically.next_to(bubble[-1], UP) classically.set_color(YELLOW) alt_h_content.next_to(classically, DOWN) group = VGroup(randy, bubble_group, classically, alt_h_content) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/2, OUT) filter_lines = self.get_filter_lines(self.pol_filter) self.play( FadeIn(randy), FadeIn(classically), ShowCreation(bubble), ) self.play( ReplacementTransform( self.sin_brace.label.copy(), h_content[0] ), ReplacementTransform( self.state_equation.get_part_by_tex("rightarrow").copy(), h_content.get_part_by_tex("rightarrow") ) ) self.play( Write(VGroup(*h_content[1:5])), Write(h_content.get_part_by_tex("direction")), run_time = 2, ) self.wait(2) self.play(h_content.shift, 2*IN) self.play( ReplacementTransform( self.cos_brace.label.copy(), v_content[0] ), ReplacementTransform( self.state_equation.get_part_by_tex("uparrow").copy(), v_content.get_part_by_tex("uparrow") ) ) self.play( Write(VGroup(*v_content[1:5])), Write(v_content.get_part_by_tex("direction")), run_time = 2, ) self.wait(2) self.play( FadeOut(randy), FadeOut(bubble), FadeOut(v_content), Transform(h_content, alt_h_content), FadeIn(self.pol_filter), Animation(self.arc) ) self.play(ShowCreation(filter_lines, lag_ratio = 0)) self.play(FadeOut(filter_lines)) self.wait() self.classically = VGroup(classically, h_content) def reposition_camera_back(self): self.move_camera( phi = 0.8*np.pi/2, theta = -0.6*np.pi, added_anims = [ FadeOut(self.h_arrow), FadeOut(self.h_label), FadeOut(self.v_arrow), FadeOut(self.v_label), FadeOut(self.d_brace), FadeOut(self.d_brace.label), FadeOut(self.arc), FadeOut(self.angle_label), Rotate(self.state_equation, np.pi/2, IN), Rotate(self.classically, np.pi/2, IN), ] + [ Rotate( v, np.pi/2, axis = v.get_vector(), in_place = True, ) for v in self.photon.mobject ], run_time = 1.5 ) def rewrite_15_percent_meaning(self): self.classically.rotate(np.pi/2, LEFT) cross = Cross(self.classically) cross.set_color("#ff0000") VGroup(self.classically, cross).rotate(np.pi/2, RIGHT) new_conception = OldTexText( "$0.38^2 = 15\\%$ chance of \\\\ getting blocked" ) new_conception.scale(0.8) new_conception.rotate(np.pi/2, RIGHT) new_conception.move_to(self.classically, OUT) a = self.photon.rate_func(1) finish_photon = self.get_blocked_photon( rate_func = lambda t : a + (1-a)*t ) finish_photon.mobject.set_fill(opacity = 0.7) self.play(ShowCreation(cross)) self.classically.add(cross) self.play( self.classically.shift, 4*IN, FadeIn(new_conception), ) self.remove(self.photon.mobject) self.revert_to_original_skipping_status() self.play( finish_photon, ApplyMethod( self.pol_filter.set_color, RED, rate_func = squish_rate_func(there_and_back, 0, 0.3), run_time = finish_photon.run_time ) ) def probabalistic_passing(self): # photons = [ # self.get_photon() # for x in range(3) # ] + [self.get_blocked_photon()] # random.shuffle(photons) # for photon in photons: # added_anims = [] # if photon.get_filtered: # added_anims.append( # self.get_filter_absorption_animation( # self.pol_filter, photon, # ) # ) # self.play(photon, *added_anims) # self.wait() l1 = self.get_lines(None, self.pol_filter) l2 = self.get_lines(self.pol_filter, None, 0.85) for line in it.chain(l1, l2): if line.get_stroke_width() > 0: line.set_stroke(width = 3) arrow = Arrow( 2*LEFT, 2*RIGHT, path_arc = 0.8*np.pi, ) label = OldTex("15\\% \\text{ absorbed}") label.next_to(arrow, DOWN) group = VGroup(arrow, label) group.set_color(RED) group.rotate(np.pi/2, RIGHT) group.shift(3*RIGHT + 1.5*IN) kwargs = { "rate_func" : None, "lag_ratio" : 0, } self.play( ShowCreation(arrow), Write(label, run_time = 1), ShowCreation(l1, **kwargs) ) self.play( ShowCreation(l2, run_time = 0.5, **kwargs), Animation(self.pol_filter), Animation(l1) ) self.wait() ### def get_filter_lines(self, pol_filter): lines = VGroup(*[ Line( np.sin(a)*RIGHT + np.cos(a)*UP, np.sin(a)*LEFT + np.cos(a)*UP, color = RED, stroke_width = 2, ) for a in np.linspace(0, np.pi, 15) ]) lines.scale(pol_filter.radius) lines.rotate(np.pi/2, RIGHT) lines.rotate(np.pi/2, OUT) lines.shift(pol_filter.get_center()[0]*RIGHT) return lines def get_blocked_photon(self, **kwargs): return self.get_photon( filter_distance = FRAME_X_RADIUS + 3, get_filtered = True, **kwargs ) class CompareWaveEquations(TeacherStudentsScene): def construct(self): self.add_equation() self.show_complex_plane() self.show_interpretations() def add_equation(self): equation = OldTex( "|\\!\\psi\\rangle", "=", "\\alpha", "|\\!\\rightarrow\\rangle", "+", "\\beta", "|\\!\\uparrow\\rangle", ) equation.set_color_by_tex_to_color_map({ "psi" : BLUE, "rightarrow" : RED, "uparrow" : GREEN, }) equation.next_to(ORIGIN, LEFT) equation.to_edge(UP) psi_rect = SurroundingRectangle(equation.get_part_by_tex("psi")) psi_rect.set_color(WHITE) state_words = OldTexText("Polarization \\\\ state") state_words.set_color(BLUE) state_words.scale(0.8) state_words.next_to(psi_rect, DOWN) equation.save_state() equation.scale(0.01) equation.fade(1) equation.move_to(self.teacher.get_left()) equation.shift(SMALL_BUFF*UP) self.play( equation.restore, self.teacher.change, "raise_right_hand", ) self.play_student_changes( *["pondering"]*3, look_at = psi_rect, added_anims = [ ShowCreation(psi_rect), Write(state_words, run_time = 1) ], run_time = 1 ) self.play(FadeOut(psi_rect)) self.equation = equation self.state_words = state_words def show_complex_plane(self): new_alpha, new_beta = terms = [ self.equation.get_part_by_tex(tex).copy() for tex in ("alpha", "beta") ] for term in terms: term.save_state() term.generate_target() term.target.scale(0.7) plane = ComplexPlane( x_radius = 1.5, y_radius = 1.5, ) plane.add_coordinates() plane.scale(1.3) plane.next_to(ORIGIN, RIGHT, MED_LARGE_BUFF) plane.to_edge(UP) alpha_dot, beta_dot = [ Dot( plane.coords_to_point(x, 0.5), radius = 0.05, color = color ) for x, color in [(-0.5, RED), (0.5, GREEN)] ] new_alpha.target.next_to(alpha_dot, UP+LEFT, 0.5*SMALL_BUFF) new_alpha.target.set_color(RED) new_beta.target.next_to(beta_dot, UP+RIGHT, 0.5*SMALL_BUFF) new_beta.target.set_color(GREEN) rhs = OldTex( "=", "A_y", "e", "^{i(", "2\\pi", "f", "t", "+", "\\phi_y", ")}" ) rhs.scale(0.7) rhs.next_to(new_beta.target, RIGHT, SMALL_BUFF) rhs.shift(0.5*SMALL_BUFF*UP) rhs.set_color_by_tex_to_color_map({ "A_y" : GREEN, "phi" : MAROON_B, }) A_copy = rhs.get_part_by_tex("A_y").copy() phi_copy = rhs.get_part_by_tex("phi_y").copy() A_line = Line( plane.coords_to_point(0, 0), plane.coords_to_point(0.5, 0.5), color = GREEN, stroke_width = 2, ) arc = Arc(angle = np.pi/4, radius = 0.5) arc.shift(plane.get_center()) self.play( Write(plane, run_time = 2), MoveToTarget(new_alpha), MoveToTarget(new_beta), DrawBorderThenFill(alpha_dot, run_time = 1), DrawBorderThenFill(beta_dot, run_time = 1), ) self.play( Write(rhs), ShowCreation(A_line), ShowCreation(arc) ) self.play( phi_copy.next_to, arc, RIGHT, SMALL_BUFF, phi_copy.shift, 0.5*SMALL_BUFF*UP ) self.play( A_copy.next_to, A_line.get_center(), UP, SMALL_BUFF, A_copy.shift, 0.5*SMALL_BUFF*(UP+LEFT), ) self.wait() def show_interpretations(self): c_words = OldTex( "\\text{Classically: }", "&|\\beta|^2", "\\rightarrow", "\\text{Component of} \\\\", "&\\text{energy in }", "|\\!\\uparrow\\rangle", "\\text{ direction}", ) qm_words = OldTex( "\\text{Quantum: }", "&|\\beta|^2", "\\rightarrow", "\\text{Probability that}", "\\text{ \\emph{all}} \\\\", "&\\text{energy is measured in }", "|\\!\\uparrow\\rangle", "\\text{ direction}", ) for words in c_words, qm_words: words.set_color_by_tex_to_color_map({ "Classically" : YELLOW, "Quantum" : BLUE, "{all}" : BLUE, "beta" : GREEN, "uparrow" : GREEN, }) words.scale(0.7) c_words.to_edge(LEFT) c_words.shift(2*UP) qm_words.next_to(c_words, DOWN, MED_LARGE_BUFF, LEFT) self.play( FadeOut(self.state_words), Write(c_words), self.teacher.change, "happy" ) self.play_student_changes( *["happy"]*3, look_at = c_words ) self.play(Write(qm_words)) self.play_student_changes( "erm", "confused", "pondering", look_at = qm_words ) self.wait() class CircularPhotons(ShootPhotonThroughFilter): CONFIG = { "EMWave_config" : { "phi_vect" : [0, -np.pi/2, 0], "wave_number" : 1, "start_point" : 10*LEFT, "length" : 20, "n_vectors" : 60, }, "apply_filter" : False, } def construct(self): self.set_camera_orientation(theta = -0.75*np.pi) self.setup_filter() self.show_phase_difference() self.shoot_circular_photons() self.show_filter() self.show_vertically_polarized_light() def setup_filter(self): pf = self.pol_filter pf.remove(pf.label) pf.remove(pf.arrow) self.remove(pf.label, pf.arrow) arrows = VGroup(*[ Arrow( v1, v2, color = WHITE, path_arc = np.pi, ) for v1, v2 in [(LEFT, RIGHT), (RIGHT, LEFT)] ]) arrows.scale(0.7) arrows.rotate(np.pi/2, RIGHT) arrows.rotate(np.pi/2, OUT) arrows.move_to(center_of_mass(pf.get_points())) pf.label = arrows pf.add(arrows) self.remove(pf) def show_phase_difference(self): equation = OldTex( "|\\!\\circlearrowright\\rangle", "=", "\\frac{1}{\\sqrt{2}}", "|\\!\\rightarrow\\rangle", "+", "\\frac{i}{\\sqrt{2}}", "|\\!\\uparrow\\rangle", ) equation.set_color_by_tex_to_color_map({ "circlearrowright" : BLUE, "rightarrow" : RED, "uparrow" : GREEN, }) equation.next_to(ORIGIN, LEFT, LARGE_BUFF) equation.to_edge(UP) rect = SurroundingRectangle(equation.get_part_by_tex("frac{i}")) words = OldTexText("Phase shift") words.next_to(rect, DOWN) words.set_color(YELLOW) group = VGroup(equation, rect, words) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/4, IN) self.play(FadeIn(equation)) self.play(self.get_circular_photon()) self.play( ShowCreation(rect), Write(words, run_time = 1) ) self.circ_equation_group = group def shoot_circular_photons(self): for x in range(2): self.play(self.get_circular_photon()) def show_filter(self): pf = self.pol_filter pf.save_state() pf.shift(4*OUT) pf.fade(1) self.play(pf.restore) self.play( self.get_circular_photon(), Animation(self.circ_equation_group) ) self.play(FadeOut(self.circ_equation_group)) def show_vertically_polarized_light(self): equation = OldTex( "|\\!\\uparrow \\rangle", "=", "\\frac{i}{\\sqrt{2}}", "|\\!\\circlearrowleft \\rangle", "+", "\\frac{-i}{\\sqrt{2}}", "|\\!\\circlearrowright \\rangle", ) equation.set_color_by_tex_to_color_map({ "circlearrowright" : BLUE, "frac{-i}" : BLUE, "circlearrowleft" : YELLOW, "frac{i}" : YELLOW, "uparrow" : GREEN, }) equation.next_to(ORIGIN, LEFT, LARGE_BUFF) equation.to_edge(UP) prob = OldTex( "P(", "\\text{passing}", ")", "=", "\\left(", "\\frac{-i}{\\sqrt{2}}", "\\right)^2" ) prob.set_color_by_tex("sqrt{2}", BLUE) prob.next_to(equation, DOWN) group = VGroup(equation, prob) group.rotate(np.pi/2, RIGHT) group.rotate(np.pi/4, IN) em_wave = EMWave( wave_number = 0, amplitude = 2, start_point = 10*LEFT, length = 20, ) v_photon = WavePacket( em_wave = em_wave, include_M_vects = False, run_time = 2 ) c_photon = self.get_circular_photon() for v_vect in v_photon.mobject: v_vect.saved_state.set_fill(GREEN) if v_vect.get_start()[0] > 0: v_vect.saved_state.set_fill(opacity = 0) for c_vect in c_photon.mobject: if c_vect.get_start()[0] < 0: c_vect.saved_state.set_fill(opacity = 0) blocked_v_photon = copy.deepcopy(v_photon) blocked_v_photon.get_filtered = True blocked_v_photon.filter_distance = 10 self.play(Write(equation, run_time = 1)) self.play(v_photon, c_photon) self.play(FadeIn(prob)) bools = 3*[True] + 3*[False] random.shuffle(bools) for should_pass in bools: if should_pass: self.play(v_photon, c_photon) else: self.play( blocked_v_photon, self.get_filter_absorption_animation( self.pol_filter, blocked_v_photon ) ) self.wait() #### def get_circular_photon(self, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 2) photon = ShootPhotonThroughFilter.get_photon(self, **kwargs) photon.E_func = lambda x : np.exp(-0.25*(2*np.pi*x/photon.width)**2) return photon class ClockwisePhotonInsert(Scene): def construct(self): eq = OldTex( "\\left| \\frac{-i}{\\sqrt{2}} \\right|^2" ) eq.set_color(BLUE) VGroup(*it.chain(eq[:4], eq[-5:])).set_color(WHITE) eq.set_height(FRAME_HEIGHT - 1) eq.to_edge(LEFT) self.add(eq) class OrClickHere(Scene): def construct(self): words = OldTexText("Or click here") words.scale(3) arrow = Vector( 2*UP + 2*RIGHT, rectangular_stem_width = 0.1, tip_length = 0.5 ) arrow.next_to(words, UP).shift(RIGHT) self.play( Write(words), ShowCreation(arrow) ) self.wait() class WavesPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Desmos", "CrypticSwarm", "Burt Humburg", "Charlotte", "Juan Batiz-Benet", "Ali Yahya", "William", "Mayank M. Mehrotra", "Lukas Biewald", "Samantha D. Suplee", "James Park", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "dave nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Ed Kellett", "Joseph John Cox", "Dan Rose", "Luc Ritchie", "Harsev Singh", "Mads Elvheim", "Erik Sundell", "Xueqi Li", "David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "Michael McGuffin", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], } class Footnote(Scene): def construct(self): words = OldTexText(""" \\begin{flushleft} \\Large By the way, in the quantum mechanical description of polarization, states are written like $|\\! \\leftrightarrow \\rangle$ with a double-headed arrow, rather than $|\\! \\rightarrow \\rangle$ with a single-headed arrow. This conveys how there's no distinction between left and right; they each have the same measurable state: horizontal. \\\\ \\quad \\\\ Because of how I chose to motivate things with classical waves, I'll stick with the single-headed $|\\! \\rightarrow \\rangle$ for this video, but just keep in mind that this differs from quantum mechanics conventions. \\end{flushleft} """) words.set_width(FRAME_WIDTH - 2) self.add(words)
videos_3b1b/_2017/cba.py
from manim_imports_ext import * class EnumerableSaveScene(Scene): def setup(self): self.save_count = 0 def save_enumerated_image(self): file_path = self.file_writer.get_image_file_path() file_path = file_path.replace( ".png", "{:02}.png".format(self.save_count) ) self.update_frame(ignore_skipping=True) image = self.get_image() image.save(file_path) self.save_count += 1 class LayersOfAbstraction(EnumerableSaveScene): def construct(self): self.save_count = 0 # self.add_title() self.show_layers() self.show_pairwise_relations() self.circle_certain_pairs() def add_title(self): title = OldTexText("Layers of abstraction") title.scale(1.5) title.to_edge(UP, buff=MED_SMALL_BUFF) line = Line(LEFT, RIGHT) line.set_width(FRAME_WIDTH) line.next_to(title, DOWN, SMALL_BUFF) self.add(title, line) def show_layers(self): layers = self.layers = self.get_layers() for layer in layers: self.add(layer[0]) self.save_enumerated_image() for layer in layers: self.add(layer) self.save_enumerated_image() def show_pairwise_relations(self): p1, p2 = [l.get_left() for l in self.layers[2:4]] down_arrow = Arrow(p2, p1, path_arc=PI) down_words = OldTexText("``For example''") down_words.scale(0.8) down_words.next_to(down_arrow, LEFT) up_arrow = Arrow(p1, p2, path_arc=-PI) up_words = OldTexText("``In general''") up_words.scale(0.8) up_words.next_to(up_arrow, LEFT) VGroup(up_words, down_words).set_color(YELLOW) self.add(down_arrow, down_words) self.save_enumerated_image() self.remove(down_arrow, down_words) self.add(up_arrow, up_words) self.save_enumerated_image() self.remove(up_arrow, up_words) def circle_certain_pairs(self): layers = self.layers for l1, l2 in zip(layers, layers[1:]): group = VGroup(l1, l2) group.save_state() layers.save_state() layers.fade(0.75) rect = SurroundingRectangle(group) rect.set_stroke(YELLOW, 5) group.restore() self.add(rect) self.save_enumerated_image() self.remove(rect) layers.restore() # def get_layers(self): layers = VGroup(*[ VGroup(Rectangle(height=1, width=5)) for x in range(6) ]) layers.arrange(UP, buff=0) layers.set_stroke(GREY, 2) layers.set_sheen(1, UL) # Layer 0: Quantities triangle = Triangle().set_height(0.25) tri_dots = VGroup(*[Dot(v) for v in triangle.get_vertices()]) dots_rect = VGroup(*[Dot() for x in range(12)]) dots_rect.arrange_in_grid(3, 4, buff=SMALL_BUFF) for i, color in enumerate([RED, GREEN, BLUE]): dots_rect[i::4].set_color(color) pi_chart = VGroup(*[ Sector(start_angle=a, angle=TAU / 3) for a in np.arange(0, TAU, TAU / 3) ]) pi_chart.set_fill(opacity=0) pi_chart.set_stroke(WHITE, 2) pi_chart[0].set_fill(BLUE, 1) pi_chart.rotate(PI / 3) pi_chart.match_height(dots_rect) quantities = VGroup(tri_dots, dots_rect, pi_chart) quantities.arrange(RIGHT, buff=LARGE_BUFF) # Layer 1: Numbers numbers = VGroup( OldTex("3"), OldTex("3 \\times 4"), OldTex("1 / 3"), ) for number, quantity in zip(numbers, quantities): number.move_to(quantity) # Layer 2: Algebra algebra = VGroup( OldTex("x^2 - 1 = (x + 1)(x - 1)") ) algebra.set_width(layers.get_width() - MED_LARGE_BUFF) # Layer 3: Functions functions = VGroup( OldTex("f(x) = 0"), OldTex("\\frac{df}{dx}"), ) functions.set_height(layers[0].get_height() - 2 * SMALL_BUFF) functions.arrange(RIGHT, buff=LARGE_BUFF) # functions.match_width(algebra) # Layer 4: Vector space t2c_map = { "\\textbf{v}": YELLOW, "\\textbf{w}": PINK, } vector_spaces = VGroup( OldTex( "\\textbf{v} + \\textbf{w} =" "\\textbf{w} + \\textbf{v}", tex_to_color_map=t2c_map, ), OldTex( "s(\\textbf{v} + \\textbf{w}) =" "s\\textbf{v} + s\\textbf{w}", tex_to_color_map=t2c_map, ), ) vector_spaces.arrange(DOWN, buff=MED_SMALL_BUFF) vector_spaces.set_height(layers[0].get_height() - MED_LARGE_BUFF) v, w = vectors = VGroup( Vector([2, 1, 0], color=YELLOW), Vector([1, 2, 0], color=PINK), ) vectors.add(DashedLine(v.get_end(), v.get_end() + w.get_vector())) vectors.add(DashedLine(w.get_end(), w.get_end() + v.get_vector())) vectors.match_height(vector_spaces) vectors.next_to(vector_spaces, RIGHT) vectors.set_stroke(width=2) # vector_spaces.add(vectors) inner_product = OldTex( "\\langle f, g \\rangle =" "\\int f(x)g(x)dx" ) inner_product.match_height(vector_spaces) inner_product.next_to(vector_spaces, RIGHT) vector_spaces.add(inner_product) # Layer 5: Categories dots = VGroup(Dot(UP), Dot(UR), Dot(RIGHT)) arrows = VGroup( Arrow(dots[0], dots[1], buff=SMALL_BUFF), Arrow(dots[1], dots[2], buff=SMALL_BUFF), Arrow(dots[0], dots[2], buff=SMALL_BUFF), ) arrows.set_stroke(width=2) arrow_labels = VGroup( OldTex("m_1").next_to(arrows[0], UP, SMALL_BUFF), OldTex("m_2").next_to(arrows[1], RIGHT, SMALL_BUFF), OldTex("m_2 \\circ m_1").rotate(-45 * DEGREES).move_to( arrows[2] ).shift(MED_SMALL_BUFF * DL) ) categories = VGroup(dots, arrows, arrow_labels) categories.set_height(layers[0].get_height() - MED_SMALL_BUFF) # Put it all together all_content = [ quantities, numbers, algebra, functions, vector_spaces, categories, ] for layer, content in zip(layers, all_content): content.move_to(layer) layer.add(content) layer.content = content layer_titles = VGroup(*map(TexText, [ "Quantities", "Numbers", "Algebra", "Functions", "Vector spaces", "Categories", ])) for layer, title in zip(layers, layer_titles): title.next_to(layer, RIGHT) layer.add(title) layer.title = title layers.titles = layer_titles layers.center() layers.to_edge(DOWN) layers.shift(0.5 * RIGHT) return layers class DifferenceOfSquares(Scene): def construct(self): squares = VGroup(*[ VGroup(*[ Square() for x in range(8) ]).arrange(RIGHT, buff=0) for y in range(8) ]).arrange(DOWN, buff=0) squares.set_height(4) squares.set_stroke(BLUE, 3) squares.set_fill(BLUE, 0.5) last_row_parts = VGroup() for row in squares[-3:]: row[-3:].set_color(RED) row[:-3].set_color(BLUE_B) last_row_parts.add(row[:-3]) squares.to_edge(LEFT) arrow = Vector(RIGHT, color=WHITE) arrow.shift(1.5 * LEFT) squares.next_to(arrow, LEFT) new_squares = squares[:-3].copy() new_squares.next_to(arrow, RIGHT) new_squares.align_to(squares, UP) x1 = OldTex("x").set_color(BLUE) x2 = x1.copy() x1.next_to(squares, UP) x2.next_to(squares, LEFT) y1 = OldTex("y").set_color(RED) y2 = y1.copy() y1.next_to(squares[-2], RIGHT) y2.next_to(squares[-1][-2], DOWN) xpy = OldTex("x", "+", "y") xmy = OldTex("x", "-", "y") for mob in xpy, xmy: mob[0].set_color(BLUE) mob[2].set_color(RED) xpy.next_to(new_squares, UP) # xmy.rotate(90 * DEGREES) xmy.next_to(new_squares, RIGHT) xmy.to_edge(RIGHT) self.add(squares, x1, x2, y1, y2) self.play( ReplacementTransform( squares[:-3].copy().set_fill(opacity=0), new_squares ), ShowCreation(arrow), lag_ratio=0, ) last_row_parts = last_row_parts.copy() last_row_parts.save_state() last_row_parts.set_fill(opacity=0) self.play( last_row_parts.restore, last_row_parts.rotate, -90 * DEGREES, last_row_parts.next_to, new_squares, RIGHT, {"buff": 0}, lag_ratio=0, ) self.play(Write(xmy), Write(xpy)) self.wait() class Lightbulbs(EnumerableSaveScene): def construct(self): dots = VGroup(*[Dot() for x in range(4)]) dots.set_height(0.5) dots.arrange(RIGHT, buff=2) dots.set_fill(opacity=0) dots.set_stroke(width=2, color=WHITE) dot_radius = dots[0].get_width() / 2 connections = VGroup() for d1, d2 in it.product(dots, dots): line = Line( d1.get_center(), d2.get_center(), path_arc=30 * DEGREES, buff=dot_radius, color=YELLOW, ) connections.add(line) lower_dots = dots[:3].copy() lower_dots.next_to(dots, DOWN, buff=2) lower_lines = VGroup(*[ Line(d.get_center(), ld.get_center(), buff=dot_radius) for d, ld in it.product(dots, lower_dots[1:]) ]) lower_lines.match_style(connections) top_dot = dots[0].copy() top_dot.next_to(dots, UP, buff=2) top_lines = VGroup(*[ Line(d.get_center(), top_dot.get_center(), buff=dot_radius) for d in dots ]) top_lines.match_style(connections) self.add(dots) self.add(top_dot) self.save_enumerated_image() dots.set_fill(YELLOW, 1) self.save_enumerated_image() self.add(connections) self.save_enumerated_image() self.add(lower_dots) self.add(lower_lines) lower_dots[1:].set_fill(YELLOW, 1) self.save_enumerated_image() self.add(top_lines) connections.set_stroke(width=1) lower_lines.set_stroke(width=1) top_dot.set_fill(YELLOW, 1) self.save_enumerated_image() self.remove(connections) self.remove(top_lines) self.remove(lower_lines) dots.set_fill(opacity=0) lower_dots.set_fill(opacity=0) class LayersOfLightbulbs(Scene): CONFIG = { "random_seed": 1, } def construct(self): layers = VGroup() for x in range(6): n_dots = 5 + (x % 2) dots = VGroup(*[Dot() for x in range(n_dots)]) dots.scale(2) dots.arrange(RIGHT, buff=MED_LARGE_BUFF) dots.set_stroke(WHITE, 2) for dot in dots: dot.set_fill(YELLOW, np.random.random()) layers.add(dots) layers.arrange(UP, buff=LARGE_BUFF) lines = VGroup() for l1, l2 in zip(layers, layers[1:]): for d1, d2 in it.product(l1, l2): color = interpolate_color( YELLOW, GREEN, np.random.random() ) line = Line( d1.get_center(), d2.get_center(), buff=(d1.get_width() / 2), color=color, stroke_width=2 * np.random.random(), ) lines.add(line) self.add(layers, lines) class Test(Scene): def construct(self): # self.play_all_student_changes("hooray") # self.teacher.change("raise_right_hand") # self.look_at(3 * UP) randy = Randolph() randy.change("pondering") randy.set_height(6) randy.look(RIGHT) self.add(randy) # eq = OldTex("143", "=", "11 \\cdot 13") # eq[0].set_color(YELLOW) # eq.scale(0.7) # self.add(eq)
videos_3b1b/_2017/putnam.py
from manim_imports_ext import * class ShowExampleTest(ExternallyAnimatedScene): pass class IntroducePutnam(Scene): CONFIG = { "dont_animate" : False, } def construct(self): title = OldTexText("Putnam Competition") title.to_edge(UP, buff = MED_SMALL_BUFF) title.set_color(BLUE) six_hours = OldTexText("6", "hours") three_hours = OldTexText("3", "hours") for mob in six_hours, three_hours: mob.next_to(title, DOWN, MED_LARGE_BUFF) # mob.set_color(BLUE) three_hours.shift(FRAME_X_RADIUS*LEFT/2) three_hours_copy = three_hours.copy() three_hours_copy.shift(FRAME_X_RADIUS*RIGHT) question_groups = VGroup(*[ VGroup(*[ OldTexText("%s%d)"%(c, i)) for i in range(1, 7) ]).arrange(DOWN, buff = MED_LARGE_BUFF) for c in ("A", "B") ]).arrange(RIGHT, buff = FRAME_X_RADIUS - MED_SMALL_BUFF) question_groups.to_edge(LEFT) question_groups.to_edge(DOWN, MED_LARGE_BUFF) flat_questions = VGroup(*it.chain(*question_groups)) rects = VGroup() for questions in question_groups: rect = SurroundingRectangle(questions, buff = MED_SMALL_BUFF) rect.set_stroke(WHITE, 2) rect.stretch_to_fit_width(FRAME_X_RADIUS - 1) rect.move_to(questions.get_left() + MED_SMALL_BUFF*LEFT, LEFT) rects.add(rect) out_of_tens = VGroup() for question in flat_questions: out_of_ten = OldTex("/10") out_of_ten.set_color(GREEN) out_of_ten.move_to(question) dist = rects[0].get_width() - 1.2 out_of_ten.shift(dist*RIGHT) out_of_tens.add(out_of_ten) out_of_120 = OldTex("/120") out_of_120.next_to(title, RIGHT, LARGE_BUFF) out_of_120.set_color(GREEN) out_of_120.generate_target() out_of_120.target.to_edge(RIGHT, LARGE_BUFF) median = OldTex("2") median.next_to(out_of_120.target, LEFT, SMALL_BUFF) median.set_color(RED) median.align_to(out_of_120[-1]) median_words = OldTexText("Typical median $\\rightarrow$") median_words.next_to(median, LEFT) difficulty_strings = [ "Pretty hard", "Hard", "Harder", "Very hard", "Ughhh", "Can I go home?" ] colors = color_gradient([YELLOW, RED], len(difficulty_strings)) difficulties = VGroup() for i, s, color in zip(it.count(), difficulty_strings, colors): for question_group in question_groups: question = question_group[i] text = OldTexText("\\dots %s \\dots"%s) text.scale(0.7) text.next_to(question, RIGHT) text.set_color(color) difficulties.add(text) if self.dont_animate: test = VGroup() test.rect = rects[0] test.questions = question_groups[0] test.out_of_tens = VGroup(*out_of_tens[:6]) test.difficulties = VGroup(*difficulties[::2]) test.digest_mobject_attrs() self.test = test return self.add(title) self.play(Write(six_hours)) self.play(LaggedStartMap( GrowFromCenter, flat_questions, run_time = 3, )) self.play( ReplacementTransform(six_hours, three_hours), ReplacementTransform(six_hours.copy(), three_hours_copy), *list(map(ShowCreation, rects)) ) self.wait() self.play(LaggedStartMap( DrawBorderThenFill, out_of_tens, run_time = 3, stroke_color = YELLOW )) self.wait() self.play(ReplacementTransform( out_of_tens.copy(), VGroup(out_of_120), lag_ratio = 0.5, run_time = 2, )) self.wait() self.play( title.next_to, median_words.copy(), LEFT, LARGE_BUFF, MoveToTarget(out_of_120), Write(median_words) ) self.play(Write(median)) for difficulty in difficulties: self.play(FadeIn(difficulty)) self.wait() class NatureOf5sAnd6s(TeacherStudentsScene): CONFIG = { "test_scale_val" : 0.65 } def construct(self): test = self.get_test() self.students.fade(1) self.play( test.scale, self.test_scale_val, test.to_corner, UP+LEFT, FadeIn(self.teacher), self.change_students( *["horrified"]*3, look_at = test ) ) self.wait() mover = VGroup( test.questions[-1].copy(), test.difficulties[-1].copy(), ) mover.generate_target() mover.target.scale(1./self.test_scale_val) mover.target.next_to( self.teacher.get_corner(UP+LEFT), UP, ) new_words = OldTexText("\\dots Potentially very elegant \\dots") new_words.set_color(GREEN) new_words.set_height(mover.target[1].get_height()) new_words.next_to(mover.target[0], RIGHT, SMALL_BUFF) self.play( MoveToTarget(mover), self.teacher.change, "raise_right_hand", ) self.play_student_changes(*["pondering"]*3) self.play(Transform(mover[1], new_words)) self.look_at((FRAME_X_RADIUS*RIGHT + FRAME_Y_RADIUS*UP)/2) self.wait(4) ### def get_test(self): prev_scene = IntroducePutnam(dont_animate = True) return prev_scene.test class OtherVideoClips(Scene): def construct(self): rect = ScreenRectangle() rect.set_height(6.5) rect.center() rect.to_edge(DOWN) titles = list(map(TexText, [ "Essence of calculus, chapter 1", "Pi hiding in prime regularities", "How do cryptocurrencies work?" ])) self.add(rect) last_title = None for title in titles: title.to_edge(UP, buff = MED_SMALL_BUFF) if last_title: self.play(ReplacementTransform(last_title, title)) else: self.play(FadeIn(title)) self.wait(3) last_title = title class IntroduceTetrahedron(ExternallyAnimatedScene): pass class IntroduceTetrahedronSupplement(Scene): def construct(self): title = OldTexText("4", "random$^*$ points on sphere") title.set_color(YELLOW) question = OldTexText("Probability that this tetrahedron \\\\ contains the sphere's center?") question.next_to(title, DOWN, MED_LARGE_BUFF) group = VGroup(title, question) group.set_width(FRAME_WIDTH-1) group.to_edge(DOWN) for n in range(1, 4): num = OldTexText(str(n)) num.replace(title[0], dim_to_match = 1) num.set_color(YELLOW) self.add(num) self.wait(0.7) self.remove(num) self.add(title[0]) self.play(FadeIn(title[1], lag_ratio = 0.5)) self.wait(2) self.play(Write(question)) self.wait(2) class IntroduceTetrahedronFootnote(Scene): def construct(self): words = OldTexText(""" $^*$Chosen independently with a \\\\ uniform distribution on the sphere. """) words.to_corner(UP+LEFT) self.add(words) self.wait(2) class HowDoYouStart(TeacherStudentsScene): def construct(self): self.student_says( "How do you even start?", target_mode = "raise_left_hand" ) self.play_student_changes("confused", "raise_left_hand", "erm") self.wait() self.teacher_says("Try a simpler case.") self.play_student_changes(*["thinking"]*3) self.wait(2) class TwoDCase(Scene): CONFIG = { "center" : ORIGIN, "random_seed" : 4, "radius" : 2.5, "center_color" : BLUE, "point_color" : YELLOW, "positive_triangle_color" : BLUE, "negative_triangle_color" : RED, "triangle_fill_opacity" : 0.25, "n_initial_random_choices" : 9, "n_p3_random_moves" : 4, } def construct(self): self.add_title() self.add_circle() self.choose_three_random_points() self.simplify_further() self.fix_two_points_in_place() self.note_special_region() self.draw_lines_through_center() self.ask_about_probability_p3_lands_in_this_arc() self.various_arc_sizes_for_p1_p2_placements() self.ask_about_average_arc_size() self.fix_p1_in_place() self.overall_probability() def add_title(self): title = OldTexText("2D Case") title.to_corner(UP+LEFT) self.add(title) self.set_variables_as_attrs(title) def add_circle(self): circle = Circle(radius = self.radius, color = WHITE) center_dot = Dot(color = self.center_color).center() radius = DashedLine(ORIGIN, circle.radius*RIGHT) VGroup(circle, center_dot, radius).shift(self.center) self.add(center_dot) self.play(ShowCreation(radius)) self.play( ShowCreation(circle), Rotating(radius, angle = 2*np.pi, about_point = self.center), rate_func = smooth, run_time = 2, ) self.play(ShowCreation( radius, rate_func = lambda t : smooth(1-t), remover = True )) self.wait() self.set_variables_as_attrs(circle, center_dot) def choose_three_random_points(self): point_mobs = self.get_point_mobs() point_labels = self.get_point_mob_labels() triangle = self.get_triangle() self.point_labels_update = self.get_labels_update(point_mobs, point_labels) self.triangle_update = self.get_triangle_update(point_mobs, triangle) self.update_animations = [ self.triangle_update, self.point_labels_update, ] for anim in self.update_animations: anim.update(0) question = OldTexText( "Probability that \\\\ this triangle \\\\", "contains the center", "?", arg_separator = "", ) question.set_color_by_tex("center", self.center_color) question.scale(0.8) question.to_corner(UP+RIGHT) self.question = question self.play(LaggedStartMap(DrawBorderThenFill, point_mobs)) self.play(FadeIn(triangle)) self.wait() self.play(LaggedStartMap(Write, point_labels)) self.wait() self.play(Write(question)) for x in range(self.n_initial_random_choices): self.change_point_mobs_randomly() self.wait() angles = self.get_point_mob_angles() target_angles = [5*np.pi/8, 7*np.pi/8, 0] self.change_point_mobs([ta - a for a, ta in zip(angles, target_angles)]) self.wait() def simplify_further(self): morty = Mortimer().flip() morty.scale(0.75) morty.to_edge(DOWN) morty.shift(3.5*LEFT) bubble = SpeechBubble( direction = RIGHT, height = 3, width = 3 ) bubble.pin_to(morty) bubble.to_edge(LEFT, SMALL_BUFF) bubble.write("Simplify \\\\ more!") self.play(FadeIn(morty)) self.play( morty.change, "hooray", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.wait() self.play( morty.change, "happy", morty.fade, 1, *list(map(FadeOut, [bubble, bubble.content])) ) self.remove(morty) def fix_two_points_in_place(self): push_pins = VGroup() for point_mob in self.point_mobs[:-1]: push_pin = SVGMobject(file_name = "push_pin") push_pin.set_height(0.5) push_pin.move_to(point_mob.get_center(), DOWN) line = Line(ORIGIN, UP) line.set_stroke(WHITE, 2) line.set_height(0.1) line.move_to(push_pin, UP) line.shift(0.3*SMALL_BUFF*(2*DOWN+LEFT)) push_pin.add(line) push_pin.set_fill(GREY_B) push_pin.save_state() push_pin.shift(UP) push_pin.fade(1) push_pins.add(push_pin) self.play(LaggedStartMap( ApplyMethod, push_pins, lambda mob : (mob.restore,) )) self.add_foreground_mobjects(push_pins) d_thetas = 2*np.pi*np.random.random(self.n_p3_random_moves) for d_theta in d_thetas: self.change_point_mobs([0, 0, d_theta]) self.wait() self.set_variables_as_attrs(push_pins) def note_special_region(self): point_mobs = self.point_mobs angles = self.get_point_mob_angles() all_arcs = self.get_all_arcs() arc = all_arcs[-1] arc_lines = VGroup() for angle in angles[:2]: line = Line(LEFT, RIGHT).scale(SMALL_BUFF) line.shift(self.radius*RIGHT) line.rotate(angle + np.pi) line.shift(self.center) line.set_stroke(arc.get_color()) arc_lines.add(line) self.play(ShowCreation(arc_lines)) self.change_point_mobs([0, 0, angles[0]+np.pi-angles[2]]) self.change_point_mobs( [0, 0, arc.angle], ShowCreation(arc, run_time = 2) ) self.change_point_mobs([0, 0, np.pi/4 - angles[1]]) self.change_point_mobs([0, 0, 0.99*np.pi], run_time = 4) self.wait() self.set_variables_as_attrs(all_arcs, arc, arc_lines) def draw_lines_through_center(self): point_mobs = self.point_mobs angles = self.get_point_mob_angles() all_arcs = self.all_arcs lines = self.get_center_lines() self.add_foreground_mobjects(self.center_dot) for line in lines: self.play(ShowCreation(line)) self.play(FadeIn(all_arcs), Animation(point_mobs)) self.remove(self.circle) self.wait() self.play( all_arcs.space_out_submobjects, 1.5, Animation(point_mobs), rate_func = there_and_back, run_time = 1.5, ) self.wait() self.change_point_mobs( [0, 0, np.mean(angles[:2])+np.pi-angles[2]] ) self.wait() for x in range(3): self.change_point_mobs([0, 0, np.pi/2]) self.wait() def ask_about_probability_p3_lands_in_this_arc(self): arc = self.arc arrow = Vector(LEFT, color = BLUE) arrow.next_to(arc.get_center(), RIGHT, MED_LARGE_BUFF) question = OldTexText("Probability of landing \\\\ in this arc?") question.scale(0.8) question.next_to(arrow, RIGHT) question.shift_onto_screen() question.shift(SMALL_BUFF*UP) answer = OldTex( "{\\text{Length of arc}", "\\over", "\\text{Circumference}}" ) answer.set_color_by_tex("arc", BLUE) answer.scale(0.8) answer.next_to(arrow, RIGHT) equals = OldTex("=") equals.rotate(np.pi/2) equals.next_to(answer, UP, buff = 0.35) self.play(FadeIn(question), GrowArrow(arrow)) self.have_p3_jump_around_randomly(15) self.play( question.next_to, answer, UP, LARGE_BUFF, Write(equals), FadeIn(answer) ) self.have_p3_jump_around_randomly(4) angles = self.get_point_mob_angles() self.change_point_mobs( [0, 0, 1.35*np.pi - angles[2]], run_time = 0, ) self.wait() question.add(equals) self.arc_prob_question = question self.arc_prob = answer self.arc_size_arrow = arrow def various_arc_sizes_for_p1_p2_placements(self): arc = self.arc self.triangle.save_state() self.play(*list(map(FadeOut, [ self.push_pins, self.triangle, self.arc_lines ]))) self.update_animations.remove(self.triangle_update) self.update_animations += [ self.get_center_lines_update(self.point_mobs, self.center_lines), self.get_arcs_update(self.all_arcs) ] #90 degree angle self.change_point_mobs_to_angles([np.pi/2, np.pi], run_time = 1) elbow = VGroup( Line(DOWN, DOWN+RIGHT), Line(DOWN+RIGHT, RIGHT), ) elbow.scale(0.25) elbow.shift(self.center) ninety_degrees = OldTex("90^\\circ") ninety_degrees.next_to(elbow, DOWN+RIGHT, buff = 0) proportion = DecimalNumber(0.25) proportion.set_color(self.center_color) # proportion.next_to(arc.point_from_proportion(0.5), DOWN, MED_LARGE_BUFF) proportion.next_to(self.arc_size_arrow, DOWN) def proportion_update_func(alpha): angles = self.get_point_mob_angles() diff = abs(angles[1]-angles[0])/(2*np.pi) return min(diff, 1-diff) proportion_update = ChangingDecimal(proportion, proportion_update_func) self.play(ShowCreation(elbow), FadeIn(ninety_degrees)) self.wait() self.play( ApplyMethod( arc.rotate, np.pi/12, rate_func = wiggle, ) ) self.play(LaggedStartMap(FadeIn, proportion, run_time = 1)) self.wait() #Non right angles angle_pairs = [ (0.26*np.pi, 1.24*np.pi), (0.73*np.pi, 0.78*np.pi), (0.5*np.pi, np.pi), ] self.update_animations.append(proportion_update) for angle_pair in angle_pairs: self.change_point_mobs_to_angles( angle_pair, VGroup(elbow, ninety_degrees).fade, 1, ) self.remove(elbow, ninety_degrees) self.wait() self.set_variables_as_attrs(proportion, proportion_update) def ask_about_average_arc_size(self): proportion = self.proportion brace = Brace(proportion, DOWN, buff = SMALL_BUFF) average = brace.get_text("Average?", buff = SMALL_BUFF) self.play( GrowFromCenter(brace), Write(average) ) for x in range(6): self.change_point_mobs_to_angles( 2*np.pi*np.random.random(2) ) self.change_point_mobs_to_angles( [1.2*np.pi, 0.3*np.pi] ) self.wait() self.set_variables_as_attrs(brace, average) def fix_p1_in_place(self): push_pin = self.push_pins[0] P1, P2, P3 = point_mobs = self.point_mobs self.change_point_mobs_to_angles([0.9*np.pi]) push_pin.move_to(P1.get_center(), DOWN) push_pin.save_state() push_pin.shift(UP) push_pin.fade(1) self.play(push_pin.restore) for angle in [0.89999*np.pi, -0.09999*np.pi, 0.4*np.pi]: self.change_point_mobs_to_angles( [0.9*np.pi, angle], run_time = 4, ) self.play(FadeOut(self.average[-1])) def overall_probability(self): point_mobs = self.point_mobs triangle = self.triangle one_fourth = OldTex("1/4") one_fourth.set_color(BLUE) one_fourth.next_to(self.question, DOWN) self.triangle_update.update(1) self.play( FadeIn(triangle), Animation(point_mobs) ) self.update_animations.append(self.triangle_update) self.have_p3_jump_around_randomly(8, wait_time = 0.25) self.play(ReplacementTransform( self.proportion.copy(), VGroup(one_fourth) )) self.have_p3_jump_around_randomly(32, wait_time = 0.25) ##### def get_point_mobs(self): points = np.array([ self.center + rotate_vector(self.radius*RIGHT, theta) for theta in 2*np.pi*np.random.random(3) ]) for index in 0, 1, 0: if self.points_contain_center(points): break points[index] -= self.center points[index] *= -1 points[index] += self.center point_mobs = self.point_mobs = VGroup(*[ Dot().move_to(point) for point in points ]) point_mobs.set_color(self.point_color) return point_mobs def get_point_mob_labels(self): point_labels = VGroup(*[ OldTex("P_%d"%(i+1)) for i in range(len(self.point_mobs)) ]) point_labels.set_color(self.point_mobs.get_color()) self.point_labels = point_labels return point_labels def get_triangle(self): triangle = self.triangle = RegularPolygon(n = 3) triangle.set_fill(WHITE, opacity = self.triangle_fill_opacity) return triangle def get_center_lines(self): angles = self.get_point_mob_angles() lines = VGroup() for angle in angles[:2]: line = DashedLine( self.radius*RIGHT, self.radius*LEFT ) line.rotate(angle) line.shift(self.center) line.set_color(self.point_color) lines.add(line) self.center_lines = lines return lines def get_labels_update(self, point_mobs, labels): def update_labels(labels): for point_mob, label in zip(point_mobs, labels): label.move_to(point_mob) vect = point_mob.get_center() - self.center vect /= get_norm(vect) label.shift(MED_LARGE_BUFF*vect) return labels return UpdateFromFunc(labels, update_labels) def get_triangle_update(self, point_mobs, triangle): def update_triangle(triangle): points = [pm.get_center() for pm in point_mobs] triangle.set_points_as_corners(points) if self.points_contain_center(points): triangle.set_color(self.positive_triangle_color) else: triangle.set_color(self.negative_triangle_color) return triangle return UpdateFromFunc(triangle, update_triangle) def get_center_lines_update(self, point_mobs, center_lines): def update_lines(center_lines): for point_mob, line in zip(point_mobs, center_lines): point = point_mob.get_center() - self.center line.rotate( angle_of_vector(point) - line.get_angle() ) line.move_to(self.center) return center_lines return UpdateFromFunc(center_lines, update_lines) def get_arcs_update(self, all_arcs): def update_arcs(arcs): new_arcs = self.get_all_arcs() Transform(arcs, new_arcs).update(1) return arcs return UpdateFromFunc(all_arcs, update_arcs) def get_all_arcs(self): angles = self.get_point_mob_angles() all_arcs = VGroup() for da0, da1 in it.product(*[[0, np.pi]]*2): arc_angle = (angles[1]+da1) - (angles[0]+da0) arc_angle = (arc_angle+np.pi)%(2*np.pi)-np.pi arc = Arc( start_angle = angles[0]+da0, angle = arc_angle, radius = self.radius, stroke_width = 5, ) arc.shift(self.center) all_arcs.add(arc) all_arcs.set_color_by_gradient(RED, MAROON_B, PINK, BLUE) self.all_arcs = all_arcs return all_arcs def points_contain_center(self, points): p0, p1, p2 = points v1 = p1 - p0 v2 = p2 - p0 c = self.center - p0 M = np.matrix([v1[:2], v2[:2]]).T M_inv = np.linalg.inv(M) coords = np.dot(M_inv, c[:2]) return np.all(coords > 0) and (np.sum(coords.flatten()) <= 1) def get_point_mob_theta_change_anim(self, point_mob, d_theta): curr_theta = angle_of_vector(point_mob.get_center() - self.center) d_theta = (d_theta + np.pi)%(2*np.pi) - np.pi new_theta = curr_theta + d_theta def update_point(point_mob, alpha): theta = interpolate(curr_theta, new_theta, alpha) point_mob.move_to(self.center + self.radius*( np.cos(theta)*RIGHT + np.sin(theta)*UP )) return point_mob return UpdateFromAlphaFunc(point_mob, update_point, run_time = 2) def change_point_mobs(self, d_thetas, *added_anims, **kwargs): anims = it.chain( self.update_animations, [ self.get_point_mob_theta_change_anim(pm, dt) for pm, dt in zip(self.point_mobs, d_thetas) ], added_anims ) self.play(*anims, **kwargs) for update in self.update_animations: update.update(1) def change_point_mobs_randomly(self, *added_anims, **kwargs): d_thetas = 2*np.pi*np.random.random(len(self.point_mobs)) self.change_point_mobs(d_thetas, *added_anims, **kwargs) def change_point_mobs_to_angles(self, target_angles, *added_anims, **kwargs): angles = self.get_point_mob_angles() n_added_targets = len(angles) - len(target_angles) target_angles = list(target_angles) + list(angles[-n_added_targets:]) self.change_point_mobs( [ta-a for a, ta in zip(angles, target_angles)], *added_anims, **kwargs ) def get_point_mob_angles(self): point_mobs = self.point_mobs points = [pm.get_center() - self.center for pm in point_mobs] return np.array(list(map(angle_of_vector, points))) def have_p3_jump_around_randomly(self, n_jumps, wait_time = 0.75, run_time = 0): for x in range(n_jumps): self.change_point_mobs( [0, 0, 2*np.pi*random.random()], run_time = run_time ) self.wait(wait_time) class FixThreePointsOnSphere(ExternallyAnimatedScene): pass class AddCenterLinesAndPlanesToSphere(ExternallyAnimatedScene): pass class AverageSizeOfSphericalTriangleSection(ExternallyAnimatedScene): pass class AverageSizeOfSphericalTriangleSectionSupplement(Scene): def construct(self): words = OldTexText( "Average size of \\\\", "this section", "?", arg_separator = "" ) words.set_color_by_tex("section", GREEN) words.set_width(FRAME_WIDTH - 1) words.to_edge(DOWN) self.play(Write(words)) self.wait(3) class TryASurfaceIntegral(TeacherStudentsScene): def construct(self): self.student_says("Can you do \\\\ a surface integral?") self.play_student_changes("confused", "raise_left_hand", "confused") self.wait() self.teacher_says( "I mean...you can \\emph{try}", target_mode = "sassy", ) self.wait(2) class RevisitTwoDCase(TwoDCase): CONFIG = { "random_seed" : 4, "center" : 3*LEFT + 0.5*DOWN, "radius" : 2, "n_random_trials" : 200, } def construct(self): self.force_skipping() self.setup_circle() self.show_probability() self.add_lines_and_comment_on_them() self.rewrite_random_procedure() self.four_possibilities_for_coin_flips() def setup_circle(self): point_mobs = self.get_point_mobs() point_labels = self.get_point_mob_labels() triangle = self.get_triangle() circle = Circle(radius = self.radius, color = WHITE) center_dot = Dot(color = self.center_color) VGroup(circle, center_dot).shift(self.center) self.point_labels_update = self.get_labels_update(point_mobs, point_labels) self.triangle_update = self.get_triangle_update(point_mobs, triangle) self.update_animations = [ self.triangle_update, self.point_labels_update, ] for anim in self.update_animations: anim.update(1) self.add( center_dot, circle, triangle, point_mobs, point_labels ) self.add_foreground_mobjects(center_dot) self.set_variables_as_attrs(circle, center_dot) def show_probability(self): title = OldTex( "P(\\text{triangle contains the center})", "=", "1/4" ) title.to_edge(UP, buff = MED_SMALL_BUFF) title.set_color_by_tex("1/4", BLUE) four = title[-1][-1] four_circle = Circle(color = YELLOW) four_circle.replace(four, dim_to_match = 1) four_circle.scale(1.2) self.n_in = 0 self.n_out = 0 frac = OldTex( "{0", "\\over", "\\quad 0", "+", "0 \\quad}", "=" ) placeholders = frac.get_parts_by_tex("0") positions = [ORIGIN, RIGHT, LEFT] frac.next_to(self.circle, RIGHT, 1.5*LARGE_BUFF) def place_random_triangles(n, wait_time): for x in range(n): self.change_point_mobs_randomly(run_time = 0) contain_center = self.points_contain_center( [pm.get_center() for pm in self.point_mobs] ) if contain_center: self.n_in += 1 else: self.n_out += 1 nums = list(map(Integer, [self.n_in, self.n_in, self.n_out])) VGroup(*nums[:2]).set_color(self.positive_triangle_color) VGroup(*nums[2:]).set_color(self.negative_triangle_color) for num, placeholder, position in zip(nums, placeholders, positions): num.move_to(placeholder, position) decimal = DecimalNumber(float(self.n_in)/(self.n_in + self.n_out)) decimal.next_to(frac, RIGHT, SMALL_BUFF) self.add(decimal, *nums) self.wait(wait_time) self.remove(decimal, *nums) return VGroup(decimal, *nums) self.play(Write(title)) self.add(frac) self.remove(*placeholders) place_random_triangles(10, 0.25) nums = place_random_triangles(self.n_random_trials, 0.05) self.add(nums) self.wait() self.play(*list(map(FadeOut, [frac, nums, title]))) def add_lines_and_comment_on_them(self): center_lines = self.get_center_lines() center_lines.save_state() center_line_shadows = center_lines.copy() center_line_shadows.set_stroke(GREY_B, 2) arcs = self.get_all_arcs() center_lines.generate_target() center_lines.target.to_edge(RIGHT, buff = LARGE_BUFF) rect = SurroundingRectangle(center_lines.target, buff = MED_SMALL_BUFF) rect.set_stroke(WHITE, 2) words1 = OldTexText("Helpful new objects") words2 = OldTexText("Reframe problem around these") for words in words1, words2: words.scale(0.8) words.next_to(rect, UP) words.shift_onto_screen() self.play(LaggedStartMap(ShowCreation, center_lines, run_time = 1)) self.play( LaggedStartMap(FadeIn, arcs, run_time = 1), Animation(self.point_mobs), ) self.wait() self.add(center_line_shadows) self.play(MoveToTarget(center_lines)) self.play(ShowCreation(rect), Write(words1)) self.wait(2) self.play(ReplacementTransform(words1, words2)) self.wait(2) self.play( center_lines.restore, center_lines.fade, 1, *list(map(FadeOut, [ rect, words2, center_line_shadows, self.triangle, arcs, self.point_mobs, self.point_labels, ])) ) center_lines.restore() self.remove(center_lines) def rewrite_random_procedure(self): point_mobs = self.point_mobs center_lines = self.center_lines random_procedure = OldTexText("Random procedure") underline = Line(LEFT, RIGHT) underline.stretch_to_fit_width(random_procedure.get_width()) underline.scale(1.1) underline.next_to(random_procedure, DOWN) group = VGroup(random_procedure, underline) group.to_corner(UP+RIGHT) words = VGroup(*list(map(TexText, [ "Choose 3 random points", "Choose 2 random lines", "Flip coin for each line \\\\ to get $P_1$ and $P_2$", "Choose $P_3$ at random" ]))) words.scale(0.8) words.arrange(DOWN, buff = MED_LARGE_BUFF) words.next_to(underline, DOWN) words[1].set_color(YELLOW) point_label_groups = VGroup() for point_mob, label in zip(self.point_mobs, self.point_labels): group = VGroup(point_mob, label) group.save_state() group.move_to(words[0], LEFT) group.fade(1) point_label_groups.add(group) self.point_label_groups = point_label_groups cross = Cross(words[0]) cross.set_stroke(RED, 6) self.center_lines_update = self.get_center_lines_update( point_mobs, center_lines ) self.update_animations.append(self.center_lines_update) self.update_animations.remove(self.triangle_update) #Choose random points self.play( Write(random_procedure), ShowCreation(underline) ) self.play(FadeIn(words[0])) self.play(LaggedStartMap( ApplyMethod, point_label_groups, lambda mob : (mob.restore,), )) self.play( ShowCreation(cross), point_label_groups.fade, 1, ) self.wait() #Choose two random lines self.center_lines_update.update(1) self.play( FadeIn(words[1]), LaggedStartMap(GrowFromCenter, center_lines) ) for x in range(3): self.change_point_mobs_randomly(run_time = 1) self.change_point_mobs_to_angles([0.8*np.pi, 1.3*np.pi]) #Flip a coin for each line def flip_point_label_back_and_forth(point_mob, label): for x in range(6): point_mob.rotate(np.pi, about_point = self.center) self.point_labels_update.update(1) self.wait(0.5) self.wait(0.5) def choose_p1_and_p2(): for group in point_label_groups[:2]: group.set_fill(self.point_color, 1) flip_point_label_back_and_forth(*group) choose_p1_and_p2() self.play(Write(words[2])) #Seems convoluted randy = Randolph().flip() randy.scale(0.5) randy.to_edge(DOWN) randy.shift(2*RIGHT) self.play(point_label_groups.fade, 1) self.change_point_mobs_randomly(run_time = 1) choose_p1_and_p2() point_label_groups.fade(1) self.change_point_mobs_randomly(FadeIn(randy)) self.play( PiCreatureSays( randy, "Seems \\\\ convoluted", bubble_config = {"height" : 2, "width" : 2}, target_mode = "confused" ) ) choose_p1_and_p2() self.play( FadeOut(randy.bubble), FadeOut(randy.bubble.content), randy.change, "pondering", ) self.play(Blink(randy)) self.play(FadeOut(randy)) #Choosing the third point self.change_point_mobs([0, 0, -np.pi/2], run_time = 0) p3_group = point_label_groups[2] p3_group.save_state() p3_group.move_to(words[3], LEFT) self.play(Write(words[3], run_time = 1)) self.play( p3_group.restore, p3_group.set_fill, YELLOW, 1 ) self.wait() self.play(Swap(*words[2:4])) self.wait() #Once the continuous randomness is handled rect = SurroundingRectangle(VGroup(words[1], words[3])) rect.set_stroke(WHITE, 2) brace = Brace(words[2], DOWN) brace_text = brace.get_text("4 equally likely outcomes") brace_text.scale(0.8) self.play(ShowCreation(rect)) self.play(GrowFromCenter(brace)) self.play(Write(brace_text)) self.wait() self.random_procedure_words = words def four_possibilities_for_coin_flips(self): arcs = self.all_arcs point_mobs = self.point_mobs arc = arcs[-1] point_label_groups = self.point_label_groups arc_update = self.get_arcs_update(arcs) arc_update.update(1) self.update_animations.append(arc_update) def second_arc_update_func(arcs): VGroup(*arcs[:-1]).set_stroke(width = 0) arcs[-1].set_stroke(PINK, 6) return arcs second_arc_update = UpdateFromFunc(arcs, second_arc_update_func) second_arc_update.update(1) self.update_animations.append(second_arc_update) self.update_animations.append(Animation(point_label_groups)) def do_the_rounds(): for index in 0, 1, 0, 1: point_mob = point_mobs[index] point_mob.generate_target() point_mob.target.rotate( np.pi, about_point = self.center, ) self.play( MoveToTarget(point_mob), *self.update_animations, run_time = np.sqrt(2)/4 #Hacky reasons to be irrational ) self.wait() self.revert_to_original_skipping_status() do_the_rounds() self.triangle_update.update(1) self.remove(arcs) self.update_animations.remove(arc_update) self.update_animations.remove(second_arc_update) self.play(FadeIn(self.triangle)) self.wait() self.update_animations.insert(0, self.triangle_update) do_the_rounds() self.wait() self.change_point_mobs_randomly() for x in range(2): do_the_rounds() class ThisIsWhereItGetsGood(TeacherStudentsScene): def construct(self): self.teacher_says( "This is where \\\\ things get good", target_mode = "hooray" ) self.play_student_changes(*["hooray"]*3) self.wait(2) class ContrastTwoRandomProcesses(TwoDCase): CONFIG = { "radius" : 1.5, "random_seed" : 0, } def construct(self): circle = Circle(color = WHITE, radius = self.radius) point_mobs = self.get_point_mobs() for point in point_mobs: point.scale(1.5) point.set_stroke(RED, 1) labels = self.get_point_mob_labels() self.get_labels_update(point_mobs, labels).update(1) center_lines = self.get_center_lines() point_label_groups = VGroup(*[ VGroup(*pair) for pair in zip(point_mobs, labels) ]) right_circles = VGroup(*[ VGroup(circle, *point_label_groups[:i+1]).copy() for i in range(3) ]) left_circles = VGroup( VGroup(circle, center_lines).copy(), VGroup( circle, center_lines, point_label_groups[2] ).copy(), VGroup( circle, center_lines, *point_label_groups[2::-1] ).copy(), ) for circles in left_circles, right_circles: circles.scale(0.5) circles[0].to_edge(UP, buff = MED_LARGE_BUFF) circles[2].to_edge(DOWN, buff = MED_LARGE_BUFF) for c1, c2 in zip(circles, circles[1:]): circles.add(Arrow(c1[0], c2[0], color = GREEN)) left_circles.shift(3*LEFT) right_circles.shift(3*RIGHT) vs = OldTexText("vs.") self.show_creation_of_circle_group(left_circles) self.play(Write(vs)) self.show_creation_of_circle_group(right_circles) self.wait() def show_creation_of_circle_group(self, group): circles = group[:3] arrows = group[3:] self.play( ShowCreation(circles[0][0]), FadeIn(VGroup(*circles[0][1:])), ) for c1, c2, arrow in zip(circles, circles[1:], arrows): self.play( GrowArrow(arrow), ApplyMethod( c1.copy().shift, c2[0].get_center() - c1[0].get_center(), remover = True ) ) self.add(c2) n = len(c2) - len(c1) self.play(*list(map(GrowFromCenter, c2[-n:]))) class Rewrite3DRandomProcedure(Scene): def construct(self): random_procedure = OldTexText("Random procedure") underline = Line(LEFT, RIGHT) underline.stretch_to_fit_width(random_procedure.get_width()) underline.scale(1.1) underline.next_to(random_procedure, DOWN) group = VGroup(random_procedure, underline) group.to_corner(UP+LEFT) words = VGroup(*list(map(TexText, [ "Choose 4 random points", "Choose 3 random lines", "Choose $P_4$ at random", "Flip coin for each line \\\\ to get $P_1$, $P_2$, $P_3$", ]))) words.scale(0.8) words.arrange(DOWN, buff = MED_LARGE_BUFF) words.next_to(underline, DOWN) words[1].set_color(YELLOW) cross = Cross(words[0]) cross.set_stroke(RED, 6) self.play( Write(random_procedure), ShowCreation(underline) ) self.play(FadeIn(words[0])) self.play(ShowCreation(cross)) self.wait() self.play(LaggedStartMap(FadeIn, words[1])) self.play(LaggedStartMap(FadeIn, words[2])) self.wait(2) self.play(Write(words[3])) self.wait(3) class AntipodalViewOfThreeDCase(ExternallyAnimatedScene): pass class ThreeDAnswer(Scene): def construct(self): words = OldTexText( "Probability that the tetrahedron contains center:", "$\\frac{1}{8}$" ) words.set_width(FRAME_WIDTH - 1) words.to_edge(DOWN) words[1].set_color(BLUE) self.play(Write(words)) self.wait(2) class FormalWriteupScreenCapture(ExternallyAnimatedScene): pass class Formality(TeacherStudentsScene): def construct(self): words = OldTexText( "Write-up by Ralph Howard and Paul Sisson (link below)" ) words.scale(0.7) words.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) self.student_says( "How would you \\\\ write that down?", target_mode = "sassy" ) self.play_student_changes("confused", "sassy", "erm") self.wait() self.play( Write(words), FadeOut(self.students[1].bubble), FadeOut(self.students[1].bubble.content), self.teacher.change, "raise_right_hand" ) self.play_student_changes( *["pondering"]*3, look_at = words ) self.wait(8) class ProblemSolvingTakeaways(Scene): def construct(self): title = OldTexText("Problem solving takeaways") underline = Line(LEFT, RIGHT) underline.set_width(title.get_width()*1.1) underline.next_to(title, DOWN) group = VGroup(title, underline) group.to_corner(UP+LEFT) points = VGroup(*[ OldTexText(string, alignment = "") for string in [ "Ask a simpler version \\\\ of the question", "Try reframing the question \\\\ around new constructs", ] ]) points[0].set_color(BLUE) points[1].set_color(YELLOW) points.arrange( DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) points.next_to(group, DOWN, LARGE_BUFF) self.play(Write(title), ShowCreation(underline)) self.wait() for point in points: self.play(Write(point)) self.wait(3) class BrilliantPuzzle(PiCreatureScene): CONFIG = { "random_seed" : 2, } def construct(self): students = self.students tests = VGroup() for student in students: test = self.get_test() test.move_to(0.75*student.get_center()) tests.add(test) student.test = test for i, student in enumerate(students): student.right = students[(i+1)%len(students)] student.left = students[(i-1)%len(students)] arrows = VGroup() for s1, s2 in adjacent_pairs(self.students): arrow = Arrow( s1.get_center(), s2.get_center(), path_arc = np.pi/2, buff = 0.8 ) arrow.tip.shift(SMALL_BUFF*arrow.get_vector()) arrow.tip.shift(-0.1*SMALL_BUFF*arrow.tip.get_center()) # arrow.shift(-MED_SMALL_BUFF*arrow.get_vector()) arrow.set_color(RED) arrow.pointing_right = True arrows.add(arrow) s1.arrow = arrow arrow.student = s1 title = OldTexText("Puzzle from Brilliant") title.scale(0.75) title.to_corner(UP+LEFT) question = OldTexText("Expected number of \\\\ circled students?") question.to_corner(UP+RIGHT) self.remove(students) self.play(Write(title)) self.play(LaggedStartMap(GrowFromCenter, students)) self.play( LaggedStartMap(Write, tests), LaggedStartMap( ApplyMethod, students, lambda m : (m.change, "horrified", m.test) ) ) self.wait() self.play(LaggedStartMap( ApplyMethod, students, lambda m : (m.change, "conniving") )) self.play(LaggedStartMap(ShowCreation, arrows)) for x in range(2): self.swap_arrows_randomly(arrows) self.wait() circles = self.circle_students() self.play(Write(question)) for x in range(10): self.swap_arrows_randomly(arrows, FadeOut(circles)) circles = self.circle_students() self.wait() #### def get_test(self): lines = VGroup(*[Line(ORIGIN, 0.5*RIGHT) for x in range(6)]) lines.arrange(DOWN, buff = SMALL_BUFF) rect = SurroundingRectangle(lines) rect.set_stroke(WHITE) lines.set_stroke(WHITE, 2) test = VGroup(rect, lines) test.set_height(0.5) return test def create_pi_creatures(self): self.students = VGroup(*[ PiCreature( color = random.choice([BLUE_C, BLUE_D, BLUE_E, GREY_BROWN]) ).scale(0.25).move_to(3*vect) for vect in compass_directions(8) ]) return self.students def get_arrow_swap_anim(self, arrow): arrow.generate_target() if arrow.pointing_right: target_color = GREEN target_angle = np.pi - np.pi/4 else: target_color = RED target_angle = np.pi + np.pi/4 arrow.target.set_color(target_color) arrow.target.rotate( target_angle, about_point = arrow.student.get_center() ) arrow.pointing_right = not arrow.pointing_right return MoveToTarget(arrow, path_arc = np.pi) def swap_arrows_randomly(self, arrows, *added_anims): anims = [] for arrow in arrows: if random.choice([True, False]): anims.append(self.get_arrow_swap_anim(arrow)) self.play(*anims + list(added_anims)) def circle_students(self): circles = VGroup() circled_students = list(self.students) for student in self.students: if student.arrow.pointing_right: to_remove = student.right else: to_remove = student.left if to_remove in circled_students: circled_students.remove(to_remove) for student in circled_students: circle = Circle(color = YELLOW) circle.set_height(1.2*student.get_height()) circle.move_to(student) circles.add(circle) self.play(ShowCreation(circle)) return circles class ScrollThroughBrilliantCourses(ExternallyAnimatedScene): pass class BrilliantProbability(ExternallyAnimatedScene): pass class Promotion(PiCreatureScene): CONFIG = { "seconds_to_blink" : 5, } def construct(self): url = OldTexText("https://brilliant.org/3b1b/") url.to_corner(UP+LEFT) rect = Rectangle(height = 9, width = 16) rect.set_height(5.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) self.play( Write(url), self.pi_creature.change, "raise_right_hand" ) self.play(ShowCreation(rect)) self.wait(2) self.change_mode("thinking") self.wait() self.look_at(url) self.wait(10) self.change_mode("happy") self.wait(10) self.change_mode("raise_right_hand") self.wait(10) self.remove(rect) self.play( url.next_to, self.pi_creature, UP+LEFT ) url_rect = SurroundingRectangle(url) self.play(ShowCreation(url_rect)) self.play(FadeOut(url_rect)) self.wait(3) class AddedPromoWords(Scene): def construct(self): words = OldTexText( "First", "$2^8$", "vistors get", "$(e^\\pi - \\pi)\\%$", "off" ) words.set_width(FRAME_WIDTH - 1) words.to_edge(DOWN) words.set_color_by_tex("2^8", YELLOW) words.set_color_by_tex("pi", PINK) self.play(Write(words)) self.wait() class PatreonThanks(PatreonEndScreen): CONFIG = { "specific_patrons" : [ "Randall Hunt", "Burt Humburg", "CrypticSwarm", "Juan Benet", "David Kedmey", "Marcus Schiebold", "Ali Yahya", "Mayank M. Mehrotra", "Lukas Biewald", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Jordan Scales", "Markus Persson", "Egor Gumenuk", "Yoni Nazarathy", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "James Park", "Samantha D. Suplee", "Delton", "Thomas Tarler", "Jake Alzapiedi", "Jonathan Eppele", "Taro Yoshioka", "1stViewMaths", "Jacob Magnuson", "Mark Govea", "Dagan Harrington", "Clark Gaebel", "Eric Chow", "Mathias Jansson", "David Clark", "Michael Gardner", "Erik Sundell", "Awoo", "Dr. David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] }
videos_3b1b/_2017/leibniz.py
from manim_imports_ext import * from functools import reduce # revert_to_original_skipping_status def chi_func(n): if n%2 == 0: return 0 if n%4 == 1: return 1 else: return -1 class LatticePointScene(Scene): CONFIG = { "y_radius" : 6, "x_radius" : None, "plane_center" : ORIGIN, "max_lattice_point_radius" : 6, "dot_radius" : 0.075, "secondary_line_ratio" : 0, "plane_color" : BLUE_E, "dot_color" : YELLOW, "dot_drawing_stroke_color" : PINK, "circle_color" : MAROON_D, "radial_line_color" : RED, } def setup(self): if self.x_radius is None: self.x_radius = self.y_radius*FRAME_X_RADIUS/FRAME_Y_RADIUS plane = ComplexPlane( y_radius = self.y_radius, x_radius = self.x_radius, secondary_line_ratio = self.secondary_line_ratio, radius = self.plane_color ) plane.set_height(FRAME_HEIGHT) plane.shift(self.plane_center) self.add(plane) self.plane = plane self.setup_lattice_points() def setup_lattice_points(self): M = self.max_lattice_point_radius int_range = list(range(-M, M+1)) self.lattice_points = VGroup() for x, y in it.product(*[int_range]*2): r_squared = x**2 + y**2 if r_squared > M**2: continue dot = Dot( self.plane.coords_to_point(x, y), color = self.dot_color, radius = self.dot_radius, ) dot.r_squared = r_squared self.lattice_points.add(dot) self.lattice_points.sort( lambda p : get_norm(p - self.plane_center) ) def get_circle(self, radius = None, color = None): if radius is None: radius = self.max_lattice_point_radius if color is None: color = self.circle_color radius *= self.plane.get_space_unit_to_y_unit() circle = Circle( color = color, radius = radius, ) circle.move_to(self.plane.get_center()) return circle def get_radial_line_with_label(self, radius = None, color = None): if radius is None: radius = self.max_lattice_point_radius if color is None: color = self.radial_line_color radial_line = Line( self.plane_center, self.plane.coords_to_point(radius, 0), color = color ) r_squared = int(np.round(radius**2)) root_label = OldTex("\\sqrt{%d}"%r_squared) root_label.add_background_rectangle() root_label.next_to(radial_line, UP, SMALL_BUFF) return radial_line, root_label def get_lattice_points_on_r_squared_circle(self, r_squared): points = VGroup(*[dot for dot in self.lattice_points if dot.r_squared == r_squared]) points.sort( lambda p : angle_of_vector(p-self.plane_center)%(2*np.pi) ) return points def draw_lattice_points(self, points = None, run_time = 4): if points is None: points = self.lattice_points self.play(*[ DrawBorderThenFill( dot, stroke_width = 4, stroke_color = self.dot_drawing_stroke_color, run_time = run_time, rate_func = squish_rate_func( double_smooth, a, a + 0.25 ), ) for dot, a in zip( points, np.linspace(0, 0.75, len(points)) ) ]) def add_axis_labels(self, spacing = 2): x_max = int(self.plane.point_to_coords(FRAME_X_RADIUS*RIGHT)[0]) y_max = int(self.plane.point_to_coords(FRAME_Y_RADIUS*UP)[1]) x_range = list(range(spacing, x_max, spacing)) y_range = list(range(spacing, y_max, spacing)) for r in x_range, y_range: r += [-n for n in r] tick = Line(ORIGIN, MED_SMALL_BUFF*UP) x_ticks = VGroup(*[ tick.copy().move_to(self.plane.coords_to_point(x, 0)) for x in x_range ]) tick.rotate(-np.pi/2) y_ticks = VGroup(*[ tick.copy().move_to(self.plane.coords_to_point(0, y)) for y in y_range ]) x_labels = VGroup(*[ OldTex(str(x)) for x in x_range ]) y_labels = VGroup(*[ OldTex(str(y) + "i") for y in y_range ]) for labels, ticks in (x_labels, x_ticks), (y_labels, y_ticks): labels.scale(0.6) for tex_mob, tick in zip(labels, ticks): tex_mob.add_background_rectangle() tex_mob.next_to( tick, tick.get_start() - tick.get_end(), SMALL_BUFF ) self.add(x_ticks, y_ticks, x_labels, y_labels) digest_locals(self, [ "x_ticks", "y_ticks", "x_labels", "y_labels", ]) def point_to_int_coords(self, point): x, y = self.plane.point_to_coords(point)[:2] return (int(np.round(x)), int(np.round(y))) def dot_to_int_coords(self, dot): return self.point_to_int_coords(dot.get_center()) ###### class Introduction(PiCreatureScene): def construct(self): self.introduce_three_objects() self.show_screen() def introduce_three_objects(self): primes = self.get_primes() primes.to_corner(UP+RIGHT) primes.shift(DOWN) plane = self.get_complex_numbers() plane.shift(2*LEFT) pi_group = self.get_pi_group() pi_group.next_to(primes, DOWN, buff = MED_LARGE_BUFF) pi_group.shift_onto_screen() morty = self.get_primary_pi_creature() video = VideoIcon() video.set_color(TEAL) video.next_to(morty.get_corner(UP+LEFT), UP) self.play( morty.change_mode, "raise_right_hand", DrawBorderThenFill(video) ) self.wait() self.play( Write(primes, run_time = 2), morty.change_mode, "happy", video.set_height, FRAME_WIDTH, video.center, video.set_fill, None, 0 ) self.wait() self.play( Write(plane, run_time = 2), morty.change, "raise_right_hand" ) self.wait() self.remove(morty) morty = morty.copy() self.add(morty) self.play( ReplacementTransform( morty.body, pi_group.get_part_by_tex("pi"), run_time = 1 ), FadeOut(VGroup(morty.eyes, morty.mouth)), Write(VGroup(*pi_group[1:])) ) self.wait(2) self.play( plane.set_width, pi_group.get_width(), plane.next_to, pi_group, DOWN, MED_LARGE_BUFF ) def show_screen(self): screen = ScreenRectangle(height = 4.3) screen.to_edge(LEFT) titles = VGroup( OldTexText("From zeta video"), OldTexText("Coming up") ) for title in titles: title.next_to(screen, UP) title.set_color(YELLOW) self.play( ShowCreation(screen), FadeIn(titles[0]) ) self.show_frame() self.wait(2) self.play(Transform(*titles)) self.wait(3) def get_primes(self): return OldTex("2, 3, 5, 7, 11, 13, \\dots") def get_complex_numbers(self): plane = ComplexPlane( x_radius = 3, y_radius = 2.5, ) plane.add_coordinates() point = plane.number_to_point(complex(1, 2)) dot = Dot(point, radius = YELLOW) label = OldTex("1 + 2i") label.add_background_rectangle() label.next_to(dot, UP+RIGHT, buff = SMALL_BUFF) label.set_color(YELLOW) plane.label = label plane.add(dot, label) return plane def get_pi_group(self): result = OldTex("\\pi", "=", "%.8f\\dots"%np.pi) pi = result.get_part_by_tex("pi") pi.scale(2, about_point = pi.get_right()) pi.set_color(MAROON_B) return result class ShowSum(TeacherStudentsScene): CONFIG = { "num_terms_to_add" : 40, } def construct(self): self.say_words() self.show_sum() def say_words(self): self.teacher_says("This won't be easy") self.play_student_changes( "hooray", "sassy", "angry" ) self.wait(2) def show_sum(self): line = UnitInterval() line.add_numbers(0, 1) # line.shift(UP) sum_point = line.number_to_point(np.pi/4) numbers = [0] + [ ((-1)**n)/(2.0*n + 1) for n in range(self.num_terms_to_add) ] partial_sums = np.cumsum(numbers) points = list(map(line.number_to_point, partial_sums)) arrows = [ Arrow( p1, p2, tip_length = 0.2*min(1, get_norm(p1-p2)), buff = 0 ) for p1, p2 in zip(points, points[1:]) ] dot = Dot(points[0]) sum_mob = OldTex( "1", "-\\frac{1}{3}", "+\\frac{1}{5}", "-\\frac{1}{7}", "+\\frac{1}{9}", "-\\frac{1}{11}", "+\\cdots" ) sum_mob.to_corner(UP+RIGHT) lhs = OldTex( "\\frac{\\pi}{4}", "=", ) lhs.next_to(sum_mob, LEFT) lhs.set_color_by_tex("pi", YELLOW) sum_arrow = Arrow( lhs.get_part_by_tex("pi").get_bottom(), sum_point ) fading_terms = [ OldTex(sign + "\\frac{1}{%d}"%(2*n + 1)) for n, sign in zip( list(range(self.num_terms_to_add)), it.cycle("+-") ) ] for fading_term, arrow in zip(fading_terms, arrows): fading_term.next_to(arrow, UP) terms = it.chain(sum_mob, it.repeat(None)) last_arrows = it.chain([None], arrows) last_fading_terms = it.chain([None], fading_terms) self.play_student_changes( *["pondering"]*3, look_at = line, added_anims = [ FadeIn(VGroup(line, dot)), FadeIn(lhs), RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand" ) ] ) run_time = 1 for term, arrow, last_arrow, fading_term, last_fading_term in zip( terms, arrows, last_arrows, fading_terms, last_fading_terms ): anims = [] if term: anims.append(Write(term)) if last_arrow: anims.append(FadeOut(last_arrow)) if last_fading_term: anims.append(FadeOut(last_fading_term)) dot_movement = ApplyMethod(dot.move_to, arrow.get_end()) anims.append(ShowCreation(arrow)) anims.append(dot_movement) anims.append(FadeIn(fading_term)) self.play(*anims, run_time = run_time) if term: self.wait() else: run_time *= 0.8 self.play( FadeOut(arrow), FadeOut(fading_term), dot.move_to, sum_point ) self.play(ShowCreation(sum_arrow)) self.wait() self.play_student_changes("erm", "confused", "maybe") self.play(self.teacher.change_mode, "happy") self.wait(2) class FermatsDreamExcerptWrapper(Scene): def construct(self): words = OldTexText( "From ``Fermat's dream'' by Kato, Kurokawa and Saito" ) words.scale(0.8) words.to_edge(UP) self.add(words) self.wait() class ShowCalculus(PiCreatureScene): def construct(self): frac_sum = OldTex( "1 - \\frac{1}{3} + \\frac{1}{5} - \\frac{1}{7} + \\cdots", ) int1 = OldTex( "= \\int_0^1 (1 - x^2 + x^4 - \\dots )\\,dx" ) int2 = OldTex( "= \\int_0^1 \\frac{1}{1+x^2}\\,dx" ) arctan = OldTex("= \\tan^{-1}(1)") pi_fourths = OldTex("= \\frac{\\pi}{4}") frac_sum.to_corner(UP+LEFT) frac_sum.shift(RIGHT) rhs_group = VGroup(int1, int2, arctan, pi_fourths) rhs_group.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) rhs_group.shift( frac_sum.get_right() + MED_SMALL_BUFF*RIGHT \ -int1[0].get_left() ) self.add(frac_sum) modes = it.chain(["plain"], it.cycle(["confused"])) for rhs, mode in zip(rhs_group, modes): self.play( FadeIn(rhs), self.pi_creature.change, mode ) self.wait() self.change_mode("maybe") self.wait() self.look_at(rhs_group[-1]) self.wait() self.pi_creature_says( "Where's the \\\\ circle?", bubble_config = {"width" : 4, "height" : 3}, target_mode = "maybe" ) self.look_at(rhs_group[0]) self.wait() def create_pi_creature(self): return Randolph(color = BLUE_C).to_corner(DOWN+LEFT) class CertainRegularityInPrimes(LatticePointScene): CONFIG = { "y_radius" : 8, "x_radius" : 20, "max_lattice_point_radius" : 8, "plane_center" : 2.5*RIGHT, "primes" : [5, 13, 17, 29, 37, 41, 53], "include_pi_formula" : True, } def construct(self): if self.include_pi_formula: self.add_pi_formula() self.walk_through_primes() def add_pi_formula(self): formula = OldTex( "\\frac{\\pi}{4}", "=", "1", "-", "\\frac{1}{3}", "+", "\\frac{1}{5}", "-", "\\frac{1}{7}", "+\\cdots" ) formula.set_color_by_tex("pi", YELLOW) formula.add_background_rectangle() formula.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) self.add_foreground_mobject(formula) def walk_through_primes(self): primes = self.primes lines_and_labels = [ self.get_radial_line_with_label(np.sqrt(p)) for p in primes ] lines, labels = list(zip(*lines_and_labels)) circles = [ self.get_circle(np.sqrt(p)) for p in primes ] dots_list = [ self.get_lattice_points_on_r_squared_circle(p) for p in primes ] groups = [ VGroup(*mobs) for mobs in zip(lines, labels, circles, dots_list) ] curr_group = groups[0] self.play(Write(curr_group, run_time = 2)) self.wait() for group in groups[1:]: self.play(Transform(curr_group, group)) self.wait(2) class Outline(PiCreatureScene): def construct(self): self.generate_list() self.wonder_at_pi() self.count_lattice_points() self.write_steps_2_and_3() self.show_chi() self.show_complicated_formula() self.show_last_step() def generate_list(self): steps = VGroup( OldTexText("1. Count lattice points"), OldTex("2. \\text{ Things like }17 = ", "4", "^2 + ", "1", "^2"), OldTex("3. \\text{ Things like }17 = (", "4", " + ", "i", ")(", "4", " - ", "i", ")"), OldTexText("4. Introduce $\\chi$"), OldTexText("5. Shift perspective"), ) for step in steps[1:3]: step.set_color_by_tex("1", RED, substring = False) step.set_color_by_tex("i", RED, substring = False) step.set_color_by_tex("4", GREEN, substring = False) steps.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) steps.to_corner(UP+LEFT) self.steps = steps def wonder_at_pi(self): question = OldTex("\\pi", "=???") pi = question.get_part_by_tex("pi") pi.scale(2, about_point = pi.get_right()) pi.set_color(YELLOW) question.next_to(self.pi_creature.body, LEFT, aligned_edge = UP) self.think( "Who am I really?", look_at = question, added_anims = [ FadeIn(question) ] ) self.wait(2) self.play( RemovePiCreatureBubble(self.pi_creature), question.to_corner, UP+RIGHT ) self.question = question self.pi = question.get_part_by_tex("pi") def count_lattice_points(self): step = self.steps[0] plane = NumberPlane( x_radius = 10, y_radius = 10, secondary_line_ratio = 0, color = BLUE_E, ) plane.set_height(6) plane.next_to(step, DOWN) plane.to_edge(LEFT) circle = Circle( color = YELLOW, radius = get_norm( plane.coords_to_point(10, 0) - \ plane.coords_to_point(0, 0) ) ) plane_center = plane.coords_to_point(0, 0) circle.move_to(plane_center) lattice_points = VGroup(*[ Dot( plane.coords_to_point(a, b), radius = 0.05, color = PINK, ) for a in range(-10, 11) for b in range(-10, 11) if a**2 + b**2 <= 10**2 ]) lattice_points.sort( lambda p : get_norm(p - plane_center) ) lattice_group = VGroup(plane, circle, lattice_points) self.play(ShowCreation(circle)) self.play(Write(plane, run_time = 2), Animation(circle)) self.play( *[ DrawBorderThenFill( dot, stroke_width = 4, stroke_color = YELLOW, run_time = 4, rate_func = squish_rate_func( double_smooth, a, a + 0.25 ) ) for dot, a in zip( lattice_points, np.linspace(0, 0.75, len(lattice_points)) ) ] ) self.play( FadeIn(step) ) self.wait() self.play( lattice_group.set_height, 2.5, lattice_group.next_to, self.question, DOWN, lattice_group.to_edge, RIGHT ) def write_steps_2_and_3(self): for step in self.steps[1:3]: self.play(FadeIn(step)) self.wait(2) self.wait() def show_chi(self): input_range = list(range(1, 7)) chis = VGroup(*[ OldTex("\\chi(%d)"%n) for n in input_range ]) chis.arrange(RIGHT, buff = LARGE_BUFF) chis.set_stroke(WHITE, width = 1) numerators = VGroup() arrows = VGroup() for chi, n in zip(chis, input_range): arrow = OldTex("\\Downarrow") arrow.next_to(chi, DOWN, SMALL_BUFF) arrows.add(arrow) value = OldTex(str(chi_func(n))) value.set_color_by_tex("1", BLUE) value.set_color_by_tex("-1", GREEN) value.next_to(arrow, DOWN) numerators.add(value) group = VGroup(chis, arrows, numerators) group.set_width(1.3*FRAME_X_RADIUS) group.to_corner(DOWN+LEFT) self.play(FadeIn(self.steps[3])) self.play(*[ FadeIn( mob, run_time = 3, lag_ratio = 0.5 ) for mob in [chis, arrows, numerators] ]) self.change_mode("pondering") self.wait() self.chis = chis self.arrows = arrows self.numerators = numerators def show_complicated_formula(self): rhs = OldTex( " = \\lim_{N \\to \\infty}", " \\frac{4}{N}", "\\sum_{n = 1}^N", "\\sum_{d | n} \\chi(d)", ) pi = self.pi self.add(pi.copy()) pi.generate_target() pi.target.next_to(self.steps[3], RIGHT, MED_LARGE_BUFF) pi.target.shift(MED_LARGE_BUFF*DOWN) rhs.next_to(pi.target, RIGHT) self.play( MoveToTarget(pi), Write(rhs) ) self.change_mode("confused") self.wait(2) self.complicated_formula = rhs def show_last_step(self): expression = OldTex( "=", "\\frac{\\quad}{1}", *it.chain(*[ ["+", "\\frac{\\quad}{%d}"%d] for d in range(2, len(self.numerators)+1) ] + [["+ \\cdots"]]) ) over_four = OldTex("\\quad \\over 4") over_four.to_corner(DOWN+LEFT) over_four.shift(UP) pi = self.pi pi.generate_target() pi.target.scale(0.75) pi.target.next_to(over_four, UP) expression.next_to(over_four, RIGHT, align_using_submobjects = True) self.numerators.generate_target() for num, denom in zip(self.numerators.target, expression[1::2]): num.scale(1.2) num.next_to(denom, UP, MED_SMALL_BUFF) self.play( MoveToTarget(self.numerators), MoveToTarget(pi), Write(over_four), FadeOut(self.chis), FadeOut(self.arrows), FadeOut(self.complicated_formula), ) self.play( Write(expression), self.pi_creature.change_mode, "pondering" ) self.wait(3) ######## def create_pi_creature(self): return Randolph(color = BLUE_C).flip().to_corner(DOWN+RIGHT) class CountLatticePoints(LatticePointScene): CONFIG = { "y_radius" : 11, "max_lattice_point_radius" : 10, "dot_radius" : 0.05, "example_coords" : (7, 5), } def construct(self): self.introduce_lattice_point() self.draw_lattice_points_in_circle() self.turn_points_int_units_of_area() self.write_pi_R_squared() self.allude_to_alternate_counting_method() def introduce_lattice_point(self): x, y = self.example_coords example_dot = Dot( self.plane.coords_to_point(x, y), color = self.dot_color, radius = 1.5*self.dot_radius, ) label = OldTex(str(self.example_coords)) label.add_background_rectangle() label.next_to(example_dot, UP+RIGHT, buff = 0) h_line = Line( ORIGIN, self.plane.coords_to_point(x, 0), color = GREEN ) v_line = Line( h_line.get_end(), self.plane.coords_to_point(x, y), color = RED ) lines = VGroup(h_line, v_line) dots = self.lattice_points.copy() random.shuffle(dots.submobjects) self.play(*[ ApplyMethod( dot.set_fill, None, 0, run_time = 3, rate_func = squish_rate_func( lambda t : 1 - there_and_back(t), a, a + 0.5 ), remover = True ) for dot, a in zip(dots, np.linspace(0, 0.5, len(dots))) ]) self.play( Write(label), ShowCreation(lines), DrawBorderThenFill(example_dot), run_time = 2, ) self.wait(2) self.play(*list(map(FadeOut, [label, lines, example_dot]))) def draw_lattice_points_in_circle(self): circle = self.get_circle() radius = Line(ORIGIN, circle.get_right()) radius.set_color(RED) brace = Brace(radius, DOWN, buff = SMALL_BUFF) radius_label = brace.get_text( str(self.max_lattice_point_radius), buff = SMALL_BUFF ) radius_label.add_background_rectangle() brace.add(radius_label) self.play( ShowCreation(circle), Rotating(radius, about_point = ORIGIN), run_time = 2, rate_func = smooth, ) self.play(FadeIn(brace)) self.add_foreground_mobject(brace) self.draw_lattice_points() self.wait() self.play(*list(map(FadeOut, [brace, radius]))) self.circle = circle def turn_points_int_units_of_area(self): square = Square(fill_opacity = 0.9) unit_line = Line( self.plane.coords_to_point(0, 0), self.plane.coords_to_point(1, 0), ) square.set_width(unit_line.get_width()) squares = VGroup(*[ square.copy().move_to(point) for point in self.lattice_points ]) squares.set_color_by_gradient(BLUE_E, GREEN_E) squares.set_stroke(WHITE, 1) point_copies = self.lattice_points.copy() self.play( ReplacementTransform( point_copies, squares, run_time = 3, lag_ratio = 0.5, ), Animation(self.lattice_points) ) self.wait() self.play(FadeOut(squares), Animation(self.lattice_points)) def write_pi_R_squared(self): equations = VGroup(*[ VGroup( OldTexText( "\\# Lattice points\\\\", "within radius ", R, alignment = "" ), OldTex( "\\approx \\pi", "(", R, ")^2" ) ).arrange(RIGHT) for R in ("10", "1{,}000{,}000", "R") ]) radius_10_eq, radius_million_eq, radius_R_eq = equations for eq in equations: for tex_mob in eq: tex_mob.set_color_by_tex("0", BLUE) radius_10_eq.to_corner(UP+LEFT) radius_million_eq.next_to(radius_10_eq, DOWN, LARGE_BUFF) radius_million_eq.to_edge(LEFT) brace = Brace(radius_million_eq, DOWN) brace.add(brace.get_text("More accurate")) brace.set_color(YELLOW) background = FullScreenFadeRectangle(opacity = 0.9) self.play( FadeIn(background), Write(radius_10_eq) ) self.wait(2) self.play(ReplacementTransform( radius_10_eq.copy(), radius_million_eq )) self.play(FadeIn(brace)) self.wait(3) self.radius_10_eq = radius_10_eq self.million_group = VGroup(radius_million_eq, brace) self.radius_R_eq = radius_R_eq def allude_to_alternate_counting_method(self): alt_count = OldTexText( "(...something else...)", "$R^2$", "=", arg_separator = "" ) alt_count.to_corner(UP+LEFT) alt_count.set_color_by_tex("something", MAROON_B) self.radius_R_eq.next_to(alt_count, RIGHT) final_group = VGroup( alt_count.get_part_by_tex("something"), self.radius_R_eq[1].get_part_by_tex("pi"), ).copy() self.play( FadeOut(self.million_group), Write(alt_count), ReplacementTransform( self.radius_10_eq, self.radius_R_eq ) ) self.wait(2) self.play( final_group.arrange, RIGHT, final_group.next_to, ORIGIN, UP ) rect = BackgroundRectangle(final_group) self.play(FadeIn(rect), Animation(final_group)) self.wait(2) class SoYouPlay(TeacherStudentsScene): def construct(self): self.teacher_says( "So you play!", run_time = 2 ) self.play_student_changes("happy", "thinking", "hesitant") self.wait() self.look_at(Dot().to_corner(UP+LEFT)) self.wait(3) class CountThroughRings(LatticePointScene): CONFIG = { "example_coords" : (3, 2), "num_rings_to_show_explicitly" : 7, "x_radius" : 15, "plane_center" : 2*RIGHT, "max_lattice_point_radius" : 5, } def construct(self): self.add_lattice_points() self.preview_rings() self.isolate_single_ring() self.show_specific_lattice_point_distance() self.count_through_rings() def add_lattice_points(self): big_circle = self.get_circle() self.add(big_circle) self.add(self.lattice_points) self.big_circle = big_circle def preview_rings(self): radii = list(set([ np.sqrt(p.r_squared) for p in self.lattice_points ])) radii.sort() circles = VGroup(*[ self.get_circle(radius = r) for r in radii ]) circles.set_stroke(width = 2) self.add_foreground_mobject(self.lattice_points) self.play(FadeIn(circles)) self.play(LaggedStartMap( ApplyMethod, circles, arg_creator = lambda m : (m.set_stroke, PINK, 4), rate_func = there_and_back, )) self.wait() self.remove_foreground_mobject(self.lattice_points) digest_locals(self, ["circles", "radii"]) def isolate_single_ring(self): x, y = self.example_coords example_circle = self.circles[ self.radii.index(np.sqrt(x**2 + y**2)) ] self.circles.remove(example_circle) points_on_example_circle = self.get_lattice_points_on_r_squared_circle( x**2 + y**2 ).copy() self.play( FadeOut(self.circles), self.lattice_points.set_fill, GREY, 0.5, Animation(points_on_example_circle) ) self.wait() digest_locals(self, ["points_on_example_circle", "example_circle"]) def show_specific_lattice_point_distance(self): x, y = self.example_coords dot = Dot( self.plane.coords_to_point(x, y), color = self.dot_color, radius = self.dot_radius ) label = OldTex("(a, b)") num_label = OldTex(str(self.example_coords)) for mob in label, num_label: mob.add_background_rectangle() mob.next_to(dot, UP + RIGHT, SMALL_BUFF) a, b = label[1][1].copy(), label[1][3].copy() x_spot = self.plane.coords_to_point(x, 0) radial_line = Line(self.plane_center, dot) h_line = Line(self.plane_center, x_spot) h_line.set_color(GREEN) v_line = Line(x_spot, dot) v_line.set_color(RED) distance = OldTex("\\sqrt{a^2 + b^2}") distance_num = OldTex("\\sqrt{%d}"%(x**2 + y**2)) for mob in distance, distance_num: mob.scale(0.75) mob.add_background_rectangle() mob.next_to(radial_line.get_center(), UP, SMALL_BUFF) mob.rotate( radial_line.get_angle(), about_point = mob.get_bottom() ) self.play(Write(label)) self.play( ApplyMethod(a.next_to, h_line, DOWN, SMALL_BUFF), ApplyMethod(b.next_to, v_line, RIGHT, SMALL_BUFF), ShowCreation(h_line), ShowCreation(v_line), ) self.play(ShowCreation(radial_line)) self.play(Write(distance)) self.wait(2) a_num, b_num = [ OldTex(str(coord))[0] for coord in self.example_coords ] a_num.move_to(a, UP) b_num.move_to(b, LEFT) self.play( Transform(label, num_label), Transform(a, a_num), Transform(b, b_num), ) self.wait() self.play(Transform(distance, distance_num)) self.wait(3) self.play(*list(map(FadeOut, [ self.example_circle, self.points_on_example_circle, distance, a, b, radial_line, h_line, v_line, label ]))) def count_through_rings(self): counts = [ len(self.get_lattice_points_on_r_squared_circle(N)) for N in range(self.max_lattice_point_radius**2 + 1) ] left_list = VGroup(*[ OldTex( "\\sqrt{%d} \\Rightarrow"%n, str(count) ) for n, count in zip( list(range(self.num_rings_to_show_explicitly)), counts ) ]) left_counts = VGroup() left_roots = VGroup() for mob in left_list: mob[1].set_color(YELLOW) left_counts.add(VGroup(mob[1])) mob.add_background_rectangle() left_roots.add(VGroup(mob[0], mob[1][0])) left_list.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT, ) left_list.to_corner(UP + LEFT) top_list = VGroup(*[ OldTex("%d, "%count) for count in counts ]) top_list.set_color(YELLOW) top_list.arrange(RIGHT, aligned_edge = DOWN) top_list.set_width(FRAME_WIDTH - MED_LARGE_BUFF) top_list.to_edge(UP, buff = SMALL_BUFF) top_rect = BackgroundRectangle(top_list) for r_squared, count_mob, root in zip(it.count(), left_counts, left_roots): self.show_ring_count( r_squared, count_mob, added_anims = [FadeIn(root)] ) self.wait(2) self.play( FadeOut(left_roots), FadeIn(top_rect), *[ ReplacementTransform( lc, VGroup(tc), path_arc = np.pi/2 ) for lc, tc in zip(left_counts, top_list) ] ) for r_squared in range(len(left_counts), self.max_lattice_point_radius**2 + 1): self.show_ring_count( r_squared, top_list[r_squared], ) self.wait(3) def show_ring_count( self, radius_squared, target, added_anims = None, run_time = 1 ): added_anims = added_anims or [] radius = np.sqrt(radius_squared) points = self.get_lattice_points_on_r_squared_circle(radius_squared) points.save_state() circle = self.get_circle(radius) radial_line = Line( self.plane_center, self.plane.coords_to_point(radius, 0), color = RED ) root = OldTex("\\sqrt{%d}"%radius_squared) root.add_background_rectangle() root.set_width( min(0.7*radial_line.get_width(), root.get_width()) ) root.next_to(radial_line, DOWN, SMALL_BUFF) if not hasattr(self, "little_circle"): self.little_circle = circle if not hasattr(self, "radial_line"): self.radial_line = radial_line if not hasattr(self, "root"): self.root = root if hasattr(self, "last_points"): added_anims += [self.last_points.restore] self.last_points = points if radius_squared == 0: points.set_fill(YELLOW, 1) self.play( DrawBorderThenFill(points, stroke_color = PINK), *added_anims, run_time = run_time ) self.play(ReplacementTransform( points.copy(), target )) return points.set_fill(YELLOW, 1) self.play( Transform(self.little_circle, circle), Transform(self.radial_line, radial_line), Transform(self.root, root), DrawBorderThenFill( points, stroke_width = 4, stroke_color = PINK, ), *added_anims, run_time = run_time ) self.wait(run_time) if len(points) > 0: mover = points.copy() else: mover = VectorizedPoint(self.plane_center) self.play(ReplacementTransform(mover, target, run_time = run_time)) class LookAtExampleRing(LatticePointScene): CONFIG = { "dot_radius" : 0.1, "plane_center" : 2*LEFT, "x_radius" : 17, "y_radius" : 7, } def construct(self): self.analyze_25() self.analyze_11() def analyze_25(self): x_color = GREEN y_color = RED circle = self.get_circle(radius = 5) points = self.get_lattice_points_on_r_squared_circle(25) radius, root_label = self.get_radial_line_with_label(5) coords_list = [(5, 0), (4, 3), (3, 4), (0, 5), (-3, 4), (-4, 3)] labels = [ OldTex("(", str(x), ",", str(y), ")") for x, y in coords_list ] for label in labels: label.x = label[1] label.y = label[3] label.x.set_color(x_color) label.y.set_color(y_color) label.add_background_rectangle() for label, point in zip(labels, points): x_coord = (point.get_center() - self.plane_center)[0] vect = UP+RIGHT if x_coord >= 0 else UP+LEFT label.next_to(point, vect, SMALL_BUFF) label.point = point def special_str(n): return "(%d)"%n if n < 0 else str(n) sums_of_squares = [ OldTex( special_str(x), "^2", "+", special_str(y), "^2", "= 25" ) for x, y in coords_list ] for tex_mob in sums_of_squares: tex_mob.x = tex_mob[0] tex_mob.y = tex_mob[3] tex_mob.x.set_color(x_color) tex_mob.y.set_color(y_color) tex_mob.add_background_rectangle() tex_mob.to_corner(UP+RIGHT) self.play( ShowCreation(radius), Write(root_label) ) self.play( ShowCreation(circle), Rotating( radius, about_point = self.plane_center, rate_func = smooth, ), FadeIn(points, lag_ratio = 0.5), run_time = 2, ) self.wait() curr_label = labels[0] curr_sum_of_squares = sums_of_squares[0] self.play( Write(curr_label), curr_label.point.set_color, PINK ) x, y = curr_label.x.copy(), curr_label.y.copy() self.play( Transform(x, curr_sum_of_squares.x), Transform(y, curr_sum_of_squares.y), ) self.play( Write(curr_sum_of_squares), Animation(VGroup(x, y)) ) self.remove(x, y) self.wait() for label, sum_of_squares in zip(labels, sums_of_squares)[1:]: self.play( ReplacementTransform(curr_label, label), label.point.set_color, PINK, curr_label.point.set_color, self.dot_color ) curr_label = label self.play( ReplacementTransform( curr_sum_of_squares, sum_of_squares ) ) curr_sum_of_squares = sum_of_squares self.wait() points.save_state() points.generate_target() for i, point in enumerate(points.target): point.move_to( self.plane.coords_to_point(i%3, i//3) ) points.target.next_to(circle, RIGHT) self.play(MoveToTarget( points, run_time = 2, )) self.wait() self.play(points.restore, run_time = 2) self.wait() self.play(*list(map(FadeOut, [ curr_label, curr_sum_of_squares, circle, points, radius, root_label ]))) def analyze_11(self): R = np.sqrt(11) circle = self.get_circle(radius = R) radius, root_label = self.get_radial_line_with_label(R) equation = OldTex("11 \\ne ", "a", "^2", "+", "b", "^2") equation.set_color_by_tex("a", GREEN) equation.set_color_by_tex("b", RED) equation.add_background_rectangle() equation.to_corner(UP+RIGHT) self.play( Write(root_label), ShowCreation(radius), run_time = 1 ) self.play( ShowCreation(circle), Rotating( radius, about_point = self.plane_center, rate_func = smooth, ), run_time = 2, ) self.wait() self.play(Write(equation)) self.wait(3) class Given2DThinkComplex(TeacherStudentsScene): def construct(self): tex = OldTexText("2D $\\Leftrightarrow$ Complex numbers") plane = ComplexPlane( x_radius = 0.6*FRAME_X_RADIUS, y_radius = 0.6*FRAME_Y_RADIUS, ) plane.add_coordinates() plane.set_height(FRAME_Y_RADIUS) plane.to_corner(UP+LEFT) self.teacher_says(tex) self.play_student_changes("pondering", "confused", "erm") self.wait() self.play( Write(plane), RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand" ) ) self.play_student_changes( *["thinking"]*3, look_at = plane ) self.wait(3) class IntroduceComplexConjugate(LatticePointScene): CONFIG = { "y_radius" : 20, "x_radius" : 30, "plane_scale_factor" : 1.7, "plane_center" : 2*LEFT, "example_coords" : (3, 4), "x_color" : GREEN, "y_color" : RED, } def construct(self): self.resize_plane() self.write_points_with_complex_coords() self.introduce_complex_conjugate() self.show_confusion() self.expand_algebraically() self.discuss_geometry() self.show_geometrically() def resize_plane(self): self.plane.scale( self.plane_scale_factor, about_point = self.plane_center ) self.plane.set_stroke(width = 1) self.plane.axes.set_stroke(width = 3) def write_points_with_complex_coords(self): x, y = self.example_coords x_color = self.x_color y_color = self.y_color point = self.plane.coords_to_point(x, y) dot = Dot(point, color = self.dot_color) x_point = self.plane.coords_to_point(x, 0) h_arrow = Arrow(self.plane_center, x_point, buff = 0) v_arrow = Arrow(x_point, point, buff = 0) h_arrow.set_color(x_color) v_arrow.set_color(y_color) x_coord = OldTex(str(x)) x_coord.next_to(h_arrow, DOWN, SMALL_BUFF) x_coord.set_color(x_color) x_coord.add_background_rectangle() y_coord = OldTex(str(y)) imag_y_coord = OldTex(str(y) + "i") for coord in y_coord, imag_y_coord: coord.next_to(v_arrow, RIGHT, SMALL_BUFF) coord.set_color(y_color) coord.add_background_rectangle() tuple_label = OldTex(str((x, y))) tuple_label[1].set_color(x_color) tuple_label[3].set_color(y_color) complex_label = OldTex("%d+%di"%(x, y)) complex_label[0].set_color(x_color) complex_label[2].set_color(y_color) for label in tuple_label, complex_label: label.add_background_rectangle() label.next_to(dot, UP+RIGHT, buff = 0) y_range = list(range(-9, 10, 3)) ticks = VGroup(*[ Line( ORIGIN, MED_SMALL_BUFF*RIGHT ).move_to(self.plane.coords_to_point(0, y)) for y in y_range ]) imag_coords = VGroup() for y, tick in zip(y_range, ticks): if y == 0: continue if y == 1: tex = "i" elif y == -1: tex = "-i" else: tex = "%di"%y imag_coord = OldTex(tex) imag_coord.scale(0.75) imag_coord.add_background_rectangle() imag_coord.next_to(tick, LEFT, SMALL_BUFF) imag_coords.add(imag_coord) self.add(dot) self.play( ShowCreation(h_arrow), Write(x_coord) ) self.play( ShowCreation(v_arrow), Write(y_coord) ) self.play(FadeIn(tuple_label)) self.wait() self.play(*list(map(FadeOut, [tuple_label, y_coord]))) self.play(*list(map(FadeIn, [complex_label, imag_y_coord]))) self.play(*list(map(Write, [imag_coords, ticks]))) self.wait() self.play(*list(map(FadeOut, [ v_arrow, h_arrow, x_coord, imag_y_coord, ]))) self.complex_label = complex_label self.example_dot = dot def introduce_complex_conjugate(self): x, y = self.example_coords equation = VGroup( OldTex("25 = ", str(x), "^2", "+", str(y), "^2", "="), OldTex("(", str(x), "+", str(y), "i", ")"), OldTex("(", str(x), "-", str(y), "i", ")"), ) equation.arrange( RIGHT, buff = SMALL_BUFF, ) VGroup(*equation[-2:]).shift(0.5*SMALL_BUFF*DOWN) equation.scale(0.9) equation.to_corner(UP+RIGHT, buff = MED_SMALL_BUFF) equation.shift(MED_LARGE_BUFF*DOWN) for tex_mob in equation: tex_mob.set_color_by_tex(str(x), self.x_color) tex_mob.set_color_by_tex(str(y), self.y_color) tex_mob.add_background_rectangle() dot = Dot( self.plane.coords_to_point(x, -y), color = self.dot_color ) label = OldTex("%d-%di"%(x, y)) label[0].set_color(self.x_color) label[2].set_color(self.y_color) label.add_background_rectangle() label.next_to(dot, DOWN+RIGHT, buff = 0) brace = Brace(equation[-1], DOWN) conjugate_words = OldTexText("Complex \\\\ conjugate") conjugate_words.scale(0.8) conjugate_words.add_background_rectangle() conjugate_words.next_to(brace, DOWN) self.play(FadeIn( equation, run_time = 3, lag_ratio = 0.5 )) self.wait(2) self.play( GrowFromCenter(brace), Write(conjugate_words, run_time = 2) ) self.wait() self.play(*[ ReplacementTransform(m1.copy(), m2) for m1, m2 in [ (self.example_dot, dot), (self.complex_label, label), ] ]) self.wait(2) self.conjugate_label = VGroup(brace, conjugate_words) self.equation = equation self.conjugate_dot = dot def show_confusion(self): randy = Randolph(color = BLUE_C).to_corner(DOWN+LEFT) morty = Mortimer().to_edge(DOWN) randy.make_eye_contact(morty) self.play(*list(map(FadeIn, [randy, morty]))) self.play(PiCreatureSays( randy, "Wait \\dots why?", target_mode = "confused", )) self.play(Blink(randy)) self.wait(2) self.play( RemovePiCreatureBubble( randy, target_mode = "erm", ), PiCreatureSays( morty, "Now it's a \\\\ factoring problem!", target_mode = "hooray", bubble_config = {"width" : 5, "height" : 3} ) ) self.play( morty.look_at, self.equation, randy.look_at, self.equation, ) self.play(Blink(morty)) self.play(randy.change_mode, "pondering") self.play(RemovePiCreatureBubble(morty)) self.play(*list(map(FadeOut, [randy, morty]))) def expand_algebraically(self): x, y = self.example_coords expansion = VGroup( OldTex(str(x), "^2"), OldTex("-", "(", str(y), "i", ")^2") ) expansion.arrange(RIGHT, buff = SMALL_BUFF) expansion.next_to( VGroup(*self.equation[-2:]), DOWN, LARGE_BUFF ) alt_y_term = OldTex("+", str(y), "^2") alt_y_term.move_to(expansion[1], LEFT) for tex_mob in list(expansion) + [alt_y_term]: tex_mob.set_color_by_tex(str(x), self.x_color) tex_mob.set_color_by_tex(str(y), self.y_color) tex_mob.rect = BackgroundRectangle(tex_mob) x1 = self.equation[-2][1][1] x2 = self.equation[-1][1][1] y1 = VGroup(*self.equation[-2][1][3:5]) y2 = VGroup(*self.equation[-1][1][2:5]) vect = MED_LARGE_BUFF*UP self.play(FadeOut(self.conjugate_label)) group = VGroup(x1, x2) self.play(group.shift, -vect) self.play( FadeIn(expansion[0].rect), ReplacementTransform(group.copy(), expansion[0]), ) self.play(group.shift, vect) group = VGroup(x1, y2) self.play(group.shift, -vect) self.wait() self.play(group.shift, vect) group = VGroup(x2, y1) self.play(group.shift, -vect) self.wait() self.play(group.shift, vect) group = VGroup(*it.chain(y1, y2)) self.play(group.shift, -vect) self.wait() self.play( FadeIn(expansion[1].rect), ReplacementTransform(group.copy(), expansion[1]), ) self.play(group.shift, vect) self.wait(2) self.play( Transform(expansion[1].rect, alt_y_term.rect), Transform(expansion[1], alt_y_term), ) self.wait() self.play(*list(map(FadeOut, [ expansion[0].rect, expansion[1].rect, expansion ]))) def discuss_geometry(self): randy = Randolph(color = BLUE_C) randy.scale(0.8) randy.to_corner(DOWN+LEFT) morty = Mortimer() morty.set_height(randy.get_height()) morty.next_to(randy, RIGHT) randy.make_eye_contact(morty) screen = ScreenRectangle(height = 3.5) screen.to_corner(DOWN+RIGHT, buff = MED_SMALL_BUFF) self.play(*list(map(FadeIn, [randy, morty]))) self.play(PiCreatureSays( morty, "More geometry!", target_mode = "hooray", run_time = 2, bubble_config = {"height" : 2, "width" : 4} )) self.play(Blink(randy)) self.play( RemovePiCreatureBubble( morty, target_mode = "plain", ), PiCreatureSays( randy, "???", target_mode = "maybe", bubble_config = {"width" : 3, "height" : 2} ) ) self.play( ShowCreation(screen), morty.look_at, screen, randy.look_at, screen, ) self.play(Blink(morty)) self.play(RemovePiCreatureBubble(randy, target_mode = "pondering")) self.wait() self.play(*list(map(FadeOut, [randy, morty, screen]))) def show_geometrically(self): dots = [self.example_dot, self.conjugate_dot] top_dot, low_dot = dots for dot in dots: dot.line = Line( self.plane_center, dot.get_center(), color = BLUE ) dot.angle = dot.line.get_angle() dot.arc = Arc( dot.angle, radius = 0.75, color = YELLOW ) dot.arc.shift(self.plane_center) dot.arc.add_tip(tip_length = 0.2) dot.rotate_word = OldTexText("Rotate") dot.rotate_word.scale(0.5) dot.rotate_word.next_to(dot.arc, RIGHT, SMALL_BUFF) dot.magnitude_word = OldTexText("Length 5") dot.magnitude_word.scale(0.6) dot.magnitude_word.next_to( ORIGIN, np.sign(dot.get_center()[1])*UP, buff = SMALL_BUFF ) dot.magnitude_word.add_background_rectangle() dot.magnitude_word.rotate(dot.angle) dot.magnitude_word.shift(dot.line.get_center()) twenty_five_label = OldTex("25") twenty_five_label.add_background_rectangle() twenty_five_label.next_to( self.plane.coords_to_point(25, 0), DOWN ) self.play(ShowCreation(top_dot.line)) mover = VGroup( top_dot.line.copy().set_color(PINK), top_dot.copy() ) self.play(FadeIn( top_dot.magnitude_word, lag_ratio = 0.5 )) self.wait() self.play(ShowCreation(top_dot.arc)) self.wait(2) self.play(ShowCreation(low_dot.line)) self.play( ReplacementTransform( top_dot.arc, low_dot.arc ), FadeIn(low_dot.rotate_word) ) self.play( Rotate( mover, low_dot.angle, about_point = self.plane_center ), run_time = 2 ) self.play( FadeOut(low_dot.arc), FadeOut(low_dot.rotate_word), FadeIn(low_dot.magnitude_word), ) self.play( mover[0].scale_about_point, 5, self.plane_center, mover[1].move_to, self.plane.coords_to_point(25, 0), run_time = 2 ) self.wait() self.play(Write(twenty_five_label)) self.wait(3) class NameGaussianIntegers(LatticePointScene): CONFIG = { "max_lattice_point_radius" : 15, "dot_radius" : 0.05, "plane_center" : 2*LEFT, "x_radius" : 15, } def construct(self): self.add_axis_labels() self.add_a_plus_bi() self.draw_lattice_points() self.add_name() self.restrict_to_one_circle() self.show_question_algebraically() def add_a_plus_bi(self): label = OldTex( "a", "+", "b", "i" ) a = label.get_part_by_tex("a") b = label.get_part_by_tex("b") a.set_color(GREEN) b.set_color(RED) label.add_background_rectangle() label.to_corner(UP+RIGHT) integers = OldTexText("Integers") integers.next_to(label, DOWN, LARGE_BUFF) integers.add_background_rectangle() arrows = VGroup(*[ Arrow(integers.get_top(), mob, tip_length = 0.15) for mob in (a, b) ]) self.add_foreground_mobjects(label, integers, arrows) self.a_plus_bi = label self.integers_label = VGroup(integers, arrows) def add_name(self): gauss_name = OldTexText( "Carl Friedrich Gauss" ) gauss_name.add_background_rectangle() gauss_name.next_to(ORIGIN, UP, MED_LARGE_BUFF) gauss_name.to_edge(LEFT) gaussian_integers = OldTexText("``Gaussian integers'': ") gaussian_integers.scale(0.9) gaussian_integers.next_to(self.a_plus_bi, LEFT) gaussian_integers.add_background_rectangle() self.play(FadeIn(gaussian_integers)) self.add_foreground_mobject(gaussian_integers) self.play(FadeIn( gauss_name, run_time = 2, lag_ratio = 0.5 )) self.wait(3) self.play(FadeOut(gauss_name)) self.gaussian_integers = gaussian_integers def restrict_to_one_circle(self): dots = self.get_lattice_points_on_r_squared_circle(25).copy() for dot in dots: dot.scale(2) circle = self.get_circle(5) radius, root_label = self.get_radial_line_with_label(5) self.play( FadeOut(self.lattice_points), ShowCreation(circle), Rotating( radius, run_time = 1, rate_func = smooth, about_point = self.plane_center ), *list(map(GrowFromCenter, dots)) ) self.play(Write(root_label)) self.wait() self.circle_dots = dots def show_question_algebraically(self): for i, dot in enumerate(self.circle_dots): x, y = self.dot_to_int_coords(dot) x_str = str(x) y_str = str(y) if y >= 0 else "(%d)"%y label = OldTex(x_str, "+", y_str, "i") label.scale(0.8) label.next_to( dot, dot.get_center()-self.plane_center + SMALL_BUFF*(UP+RIGHT), buff = 0, ) label.add_background_rectangle() dot.label = label equation = OldTex( "25 = " "(", x_str, "+", y_str, "i", ")", "(", x_str, "-", y_str, "i", ")", ) equation.scale(0.9) equation.add_background_rectangle() equation.to_corner(UP + RIGHT) dot.equation = equation for mob in label, equation: mob.set_color_by_tex(x_str, GREEN, substring = False) mob.set_color_by_tex(y_str, RED, substring = False) dot.line_pair = VGroup(*[ Line( self.plane_center, self.plane.coords_to_point(x, u*y), color = PINK, ) for u in (1, -1) ]) dot.conjugate_dot = self.circle_dots[-i] self.play(*list(map(FadeOut, [ self.a_plus_bi, self.integers_label, self.gaussian_integers, ]))) last_dot = None for dot in self.circle_dots: anims = [ dot.set_color, PINK, dot.conjugate_dot.set_color, PINK, ] if last_dot is None: anims += [ FadeIn(dot.equation), FadeIn(dot.label), ] anims += list(map(ShowCreation, dot.line_pair)) else: anims += [ last_dot.set_color, self.dot_color, last_dot.conjugate_dot.set_color, self.dot_color, ReplacementTransform(last_dot.equation, dot.equation), ReplacementTransform(last_dot.label, dot.label), ReplacementTransform(last_dot.line_pair, dot.line_pair), ] self.play(*anims) self.wait() last_dot = dot class FactorOrdinaryNumber(TeacherStudentsScene): def construct(self): equation = OldTex( "2{,}250", "=", "2 \\cdot 3^2 \\cdot 5^3" ) equation.next_to(self.get_pi_creatures(), UP, LARGE_BUFF) number = equation[0] alt_rhs_list = list(it.starmap(Tex, [ ("\\ne", "2^2 \\cdot 563"), ("\\ne", "2^2 \\cdot 3 \\cdot 11 \\cdot 17"), ("\\ne", "2 \\cdot 7^2 \\cdot 23"), ("=", "(-2) \\cdot (-3) \\cdot (3) \\cdot 5^3"), ("=", "2 \\cdot (-3) \\cdot (3) \\cdot (-5) \\cdot 5^2"), ])) for alt_rhs in alt_rhs_list: if "\\ne" in alt_rhs.get_tex(): alt_rhs.set_color(RED) else: alt_rhs.set_color(GREEN) alt_rhs.move_to(equation.get_right()) number.save_state() number.next_to(self.teacher, UP+LEFT) title = OldTexText("Almost", "Unique factorization") title.set_color_by_tex("Almost", YELLOW) title.to_edge(UP) self.play( self.teacher.change_mode, "raise_right_hand", Write(number) ) self.wait(2) self.play( number.restore, Write(VGroup(*equation[1:])), Write(title[1]) ) self.play_student_changes( *["pondering"]*3, look_at = equation, added_anims = [self.teacher.change_mode, "happy"] ) self.wait() last_alt_rhs = None for alt_rhs in alt_rhs_list: equation.generate_target() equation.target.next_to(alt_rhs, LEFT) anims = [MoveToTarget(equation)] if last_alt_rhs: anims += [ReplacementTransform(last_alt_rhs, alt_rhs)] else: anims += [FadeIn(alt_rhs)] self.play(*anims) if alt_rhs is alt_rhs_list[-2]: self.play_student_changes( *["sassy"]*3, look_at = alt_rhs, added_anims = [Write(title[0])] ) self.wait(2) last_alt_rhs = alt_rhs self.play( FadeOut(VGroup(equation, alt_rhs)), PiCreatureSays( self.teacher, "It's similar for \\\\ Gaussian integers", bubble_config = {"height" : 3.5} ) ) self.play_student_changes(*["happy"]*3) self.wait(3) class IntroduceGaussianPrimes(LatticePointScene, PiCreatureScene): CONFIG = { "plane_center" : LEFT, "x_radius" : 13, } def create_pi_creature(self): morty = Mortimer().flip() morty.scale(0.7) morty.next_to(ORIGIN, UP, buff = 0) morty.to_edge(LEFT) return morty def setup(self): LatticePointScene.setup(self) PiCreatureScene.setup(self) self.remove(self.pi_creature) def construct(self): self.plane.set_stroke(width = 2) morty = self.pi_creature dots = [ Dot(self.plane.coords_to_point(*coords)) for coords in [ (5, 0), (2, 1), (2, -1), (-1, 2), (-1, -2), (-2, -1), (-2, 1), ] ] five_dot = dots[0] five_dot.set_color(YELLOW) p_dots = VGroup(*dots[1:]) p1_dot, p2_dot, p3_dot, p4_dot, p5_dot, p6_dot = p_dots VGroup(p1_dot, p3_dot, p5_dot).set_color(PINK) VGroup(p2_dot, p4_dot, p6_dot).set_color(RED) labels = [ OldTex(tex).add_background_rectangle() for tex in ("5", "2+i", "2-i", "-1+2i", "-1-2i", "-2-i", "-2+i") ] five_label, p1_label, p2_label, p3_label, p4_label, p5_label, p6_label = labels vects = [ DOWN, UP+RIGHT, DOWN+RIGHT, UP+LEFT, DOWN+LEFT, DOWN+LEFT, UP+LEFT, ] for dot, label, vect in zip(dots, labels, vects): label.next_to(dot, vect, SMALL_BUFF) arc_angle = 0.8*np.pi times_i_arc = Arrow( p1_dot.get_top(), p3_dot.get_top(), path_arc = arc_angle ) times_neg_i_arc = Arrow( p2_dot.get_bottom(), p4_dot.get_bottom(), path_arc = -arc_angle ) times_i = OldTex("\\times i") times_i.add_background_rectangle() times_i.next_to( times_i_arc.point_from_proportion(0.5), UP ) times_neg_i = OldTex("\\times (-i)") times_neg_i.add_background_rectangle() times_neg_i.next_to( times_neg_i_arc.point_from_proportion(0.5), DOWN ) VGroup( times_i, times_neg_i, times_i_arc, times_neg_i_arc ).set_color(MAROON_B) gaussian_prime = OldTexText("$\\Rightarrow$ ``Gaussian prime''") gaussian_prime.add_background_rectangle() gaussian_prime.scale(0.9) gaussian_prime.next_to(p1_label, RIGHT) factorization = OldTex( "5", "= (2+i)(2-i)" ) factorization.to_corner(UP+RIGHT) factorization.shift(1.5*LEFT) factorization.add_background_rectangle() neg_alt_factorization = OldTex("=(-2-i)(-2+i)") i_alt_factorization = OldTex("=(-1+2i)(-1-2i)") for alt_factorization in neg_alt_factorization, i_alt_factorization: alt_factorization.next_to( factorization.get_part_by_tex("="), DOWN, aligned_edge = LEFT ) alt_factorization.add_background_rectangle() for dot in dots: dot.add(Line( self.plane_center, dot.get_center(), color = dot.get_color() )) self.add(factorization) self.play( DrawBorderThenFill(five_dot), FadeIn(five_label) ) self.wait() self.play( ReplacementTransform( VGroup(five_dot).copy(), VGroup(p1_dot, p2_dot) ) ) self.play(*list(map(Write, [p1_label, p2_label]))) self.wait() self.play(Write(gaussian_prime)) self.wait() #Show morty self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, "\\emph{Almost} unique", bubble_config = {"height" : 2, "width" : 5}, )) self.wait() self.play(RemovePiCreatureBubble(morty, target_mode = "pondering")) #Show neg_alternate expression movers = [p1_dot, p2_dot, p1_label, p2_label] for mover in movers: mover.save_state() self.play( Transform(p1_dot, p5_dot), Transform(p1_label, p5_label), ) self.play( Transform(p2_dot, p6_dot), Transform(p2_label, p6_label), ) self.play(Write(neg_alt_factorization)) self.wait() self.play( FadeOut(neg_alt_factorization), *[m.restore for m in movers] ) self.wait() ##Show i_alternate expression self.play( ShowCreation(times_i_arc), FadeIn(times_i), *[ ReplacementTransform( mob1.copy(), mob2, path_arc = np.pi/2 ) for mob1, mob2 in [ (p1_dot, p3_dot), (p1_label, p3_label), ] ] ) self.wait() self.play( ShowCreation(times_neg_i_arc), FadeIn(times_neg_i), *[ ReplacementTransform( mob1.copy(), mob2, path_arc = -np.pi/2 ) for mob1, mob2 in [ (p2_dot, p4_dot), (p2_label, p4_label), ] ] ) self.wait() self.play(Write(i_alt_factorization)) self.change_mode("hesitant") self.wait(3) class FromIntegerFactorsToGaussianFactors(TeacherStudentsScene): def construct(self): expression = OldTex( "30", "=", "2", "\\cdot", "3", "\\cdot", "5" ) expression.shift(2*UP) two = expression.get_part_by_tex("2") five = expression.get_part_by_tex("5") two.set_color(BLUE) five.set_color(GREEN) two.factors = OldTex("(1+i)", "(1-i)") five.factors = OldTex("(2+i)", "(2-i)") for mob, vect in (two, DOWN), (five, UP): mob.factors.next_to(mob, vect, LARGE_BUFF) mob.factors.set_color(mob.get_color()) mob.arrows = VGroup(*[ Arrow( mob.get_edge_center(vect), factor.get_edge_center(-vect), color = mob.get_color(), tip_length = 0.15 ) for factor in mob.factors ]) self.add(expression) for mob in two, five: self.play( ReplacementTransform( mob.copy(), mob.factors ), *list(map(ShowCreation, mob.arrows)) ) self.wait() self.play(*[ ApplyMethod(pi.change, "pondering", expression) for pi in self.get_pi_creatures() ]) self.wait(5) group = VGroup( expression, two.arrows, two.factors, five.arrows, five.factors, ) self.teacher_says( "Now for a \\\\ surprising fact...", added_anims = [FadeOut(group)] ) self.wait(2) class FactorizationPattern(Scene): def construct(self): self.force_skipping() self.add_number_line() self.show_one_mod_four_primes() self.show_three_mod_four_primes() self.ask_why_this_is_true() self.show_two() def add_number_line(self): line = NumberLine( x_min = 0, x_max = 36, unit_size = 0.4, numbers_to_show = list(range(0, 33, 4)), numbers_with_elongated_ticks = list(range(0, 33, 4)), ) line.shift(2*DOWN) line.to_edge(LEFT) line.add_numbers() self.add(line) self.number_line = line def show_one_mod_four_primes(self): primes = [5, 13, 17, 29] dots = VGroup(*[ Dot(self.number_line.number_to_point(prime)) for prime in primes ]) dots.set_color(GREEN) prime_mobs = VGroup(*list(map(Tex, list(map(str, primes))))) arrows = VGroup() for prime_mob, dot in zip(prime_mobs, dots): prime_mob.next_to(dot, UP, LARGE_BUFF) prime_mob.set_color(dot.get_color()) arrow = Arrow(prime_mob, dot, buff = SMALL_BUFF) arrow.set_color(dot.get_color()) arrows.add(arrow) factorizations = VGroup(*[ OldTex("=(%d+%si)(%d-%si)"%(x, y_str, x, y_str)) for x, y in [(2, 1), (3, 2), (4, 1), (5, 2)] for y_str in [str(y) if y is not 1 else ""] ]) factorizations.arrange(DOWN, aligned_edge = LEFT) factorizations.to_corner(UP+LEFT) factorizations.shift(RIGHT) movers = VGroup() for p_mob, factorization in zip(prime_mobs, factorizations): mover = p_mob.copy() mover.generate_target() mover.target.next_to(factorization, LEFT) movers.add(mover) v_dots = OldTex("\\vdots") v_dots.next_to(factorizations[-1][0], DOWN) factorization.add(v_dots) self.play(*it.chain( list(map(Write, prime_mobs)), list(map(ShowCreation, arrows)), list(map(DrawBorderThenFill, dots)), )) self.wait() self.play(*[ MoveToTarget( mover, run_time = 2, path_arc = np.pi/2, ) for mover in movers ]) self.play(FadeIn( factorizations, run_time = 2, lag_ratio = 0.5 )) self.wait(4) self.play(*list(map(FadeOut, [movers, factorizations]))) def show_three_mod_four_primes(self): primes = [3, 7, 11, 19, 23, 31] dots = VGroup(*[ Dot(self.number_line.number_to_point(prime)) for prime in primes ]) dots.set_color(RED) prime_mobs = VGroup(*list(map(Tex, list(map(str, primes))))) arrows = VGroup() for prime_mob, dot in zip(prime_mobs, dots): prime_mob.next_to(dot, UP, LARGE_BUFF) prime_mob.set_color(dot.get_color()) arrow = Arrow(prime_mob, dot, buff = SMALL_BUFF) arrow.set_color(dot.get_color()) arrows.add(arrow) words = OldTexText("Already Gaussian primes") words.to_corner(UP+LEFT) word_arrows = VGroup(*[ Line( words.get_bottom(), p_mob.get_top(), color = p_mob.get_color(), buff = MED_SMALL_BUFF ) for p_mob in prime_mobs ]) self.play(*it.chain( list(map(Write, prime_mobs)), list(map(ShowCreation, arrows)), list(map(DrawBorderThenFill, dots)), )) self.wait() self.play( Write(words), *list(map(ShowCreation, word_arrows)) ) self.wait(4) self.play(*list(map(FadeOut, [words, word_arrows]))) def ask_why_this_is_true(self): randy = Randolph(color = BLUE_C) randy.scale(0.7) randy.to_edge(LEFT) randy.shift(0.8*UP) links_text = OldTexText("(See links in description)") links_text.scale(0.7) links_text.to_corner(UP+RIGHT) links_text.shift(DOWN) self.play(FadeIn(randy)) self.play(PiCreatureBubbleIntroduction( randy, "Wait...why?", bubble_type = ThoughtBubble, bubble_config = {"height" : 2, "width" : 3}, target_mode = "confused", look_at = self.number_line, )) self.play(Blink(randy)) self.wait() self.play(FadeIn(links_text)) self.wait(2) self.play(*list(map(FadeOut, [ randy, randy.bubble, randy.bubble.content, links_text ]))) def show_two(self): two_dot = Dot(self.number_line.number_to_point(2)) two = OldTex("2") two.next_to(two_dot, UP, LARGE_BUFF) arrow = Arrow(two, two_dot, buff = SMALL_BUFF) VGroup(two_dot, two, arrow).set_color(YELLOW) mover = two.copy() mover.generate_target() mover.target.to_corner(UP+LEFT) factorization = OldTex("=", "(1+i)", "(1-i)") factorization.next_to(mover.target, RIGHT) factors = VGroup(*factorization[1:]) time_i_arrow = Arrow( factors[1].get_bottom(), factors[0].get_bottom(), path_arc = -np.pi ) times_i = OldTex("\\times i") # times_i.scale(1.5) times_i.next_to(time_i_arrow, DOWN) times_i.set_color(time_i_arrow.get_color()) words = OldTexText("You'll see why this matters...") words.next_to(times_i, DOWN) words.shift_onto_screen() self.play( Write(two), ShowCreation(arrow), DrawBorderThenFill(two_dot) ) self.wait() self.play( MoveToTarget(mover), Write(factorization) ) self.revert_to_original_skipping_status() self.wait(2) self.play(ShowCreation(time_i_arrow)) self.play(Write(times_i)) self.wait(2) self.play(FadeIn(words)) self.wait(2) class RingsWithOneModFourPrimes(CertainRegularityInPrimes): CONFIG = { "plane_center" : ORIGIN, "primes" : [5, 13, 17, 29, 37, 41, 53], "include_pi_formula" : False, } class RingsWithThreeModFourPrimes(CertainRegularityInPrimes): CONFIG = { "plane_center" : ORIGIN, "primes" : [3, 7, 11, 19, 23, 31, 43], "include_pi_formula" : False, } class FactorTwo(LatticePointScene): CONFIG = { "y_radius" : 3, } def construct(self): two_dot = Dot(self.plane.coords_to_point(2, 0)) two_dot.set_color(YELLOW) factor_dots = VGroup(*[ Dot(self.plane.coords_to_point(1, u)) for u in (1, -1) ]) two_label = OldTex("2").next_to(two_dot, DOWN) two_label.set_color(YELLOW) two_label.add_background_rectangle() factor_labels = VGroup(*[ OldTex(tex).add_background_rectangle().next_to(dot, vect) for tex, dot, vect in zip( ["1+i", "1-i"], factor_dots, [UP, DOWN] ) ]) VGroup(factor_labels, factor_dots).set_color(MAROON_B) for dot in it.chain(factor_dots, [two_dot]): line = Line(self.plane_center, dot.get_center()) line.set_color(dot.get_color()) dot.add(line) self.play( ShowCreation(two_dot), Write(two_label), ) self.play(*[ ReplacementTransform( VGroup(mob1.copy()), mob2 ) for mob1, mob2 in [ (two_label, factor_labels), (two_dot, factor_dots), ] ]) self.wait(2) dot_copy = factor_dots[1].copy() dot_copy.set_color(RED) for angle in np.pi/2, -np.pi/2: self.play(Rotate(dot_copy, angle, run_time = 2)) self.wait(2) class CountThroughRingsCopy(CountThroughRings): pass class NameGaussianIntegersCopy(NameGaussianIntegers): pass class IntroduceRecipe(Scene): CONFIG = { "N_string" : "25", "integer_factors" : [5, 5], "gaussian_factors" : [ complex(2, 1), complex(2, -1), complex(2, 1), complex(2, -1), ], "x_color" : GREEN, "y_color" : RED, "N_color" : WHITE, "i_positive_color" : BLUE, "i_negative_color" : YELLOW, "i_zero_color" : MAROON_B, "T_chart_width" : 8, "T_chart_height" : 6, } def construct(self): self.add_title() self.show_ordinary_factorization() self.subfactor_ordinary_factorization() self.organize_factors_into_columns() self.mention_conjugate_rule() self.take_product_of_columns() self.mark_left_product_as_result() self.swap_factors() def add_title(self): title = OldTex( "\\text{Recipe for }", "a", "+", "b", "i", "\\text{ satisfying }", "(", "a", "+", "b", "i", ")", "(", "a", "-", "b", "i", ")", "=", self.N_string ) strings = ("a", "b", self.N_string) colors = (self.x_color, self.y_color, self.N_color) for tex, color in zip(strings, colors): title.set_color_by_tex(tex, color, substring = False) title.to_edge(UP, buff = MED_SMALL_BUFF) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title, h_line) N_mob = title.get_part_by_tex(self.N_string) digest_locals(self, ["title", "h_line", "N_mob"]) def show_ordinary_factorization(self): N_mob = self.N_mob.copy() N_mob.generate_target() N_mob.target.next_to(self.h_line, DOWN) N_mob.target.to_edge(LEFT) factors = self.integer_factors symbols = ["="] + ["\\cdot"]*(len(factors)-1) factorization = OldTex(*it.chain(*list(zip( symbols, list(map(str, factors)) )))) factorization.next_to(N_mob.target, RIGHT) self.play(MoveToTarget( N_mob, run_time = 2, path_arc = -np.pi/6 )) self.play(Write(factorization)) self.wait() self.factored_N_mob = N_mob self.integer_factorization = factorization def subfactor_ordinary_factorization(self): factors = self.gaussian_factors factorization = OldTex( "=", *list(map(self.complex_number_to_tex, factors)) ) max_width = FRAME_WIDTH - 2 if factorization.get_width() > max_width: factorization.set_width(max_width) factorization.next_to( self.integer_factorization, DOWN, aligned_edge = LEFT ) for factor, mob in zip(factors, factorization[1:]): mob.underlying_number = factor y = complex(factor).imag if y == 0: mob.set_color(self.i_zero_color) elif y > 0: mob.set_color(self.i_positive_color) elif y < 0: mob.set_color(self.i_negative_color) movers = VGroup() mover = self.integer_factorization[0].copy() mover.target = factorization[0] movers.add(mover) index = 0 for prime_mob in self.integer_factorization[1::2]: gauss_prime = factors[index] gauss_prime_mob = factorization[index+1] mover = prime_mob.copy() mover.target = gauss_prime_mob movers.add(mover) if abs(complex(gauss_prime).imag) > 0: index += 1 mover = prime_mob.copy() mover.target = factorization[index+1] movers.add(mover) index += 1 self.play(LaggedStartMap( MoveToTarget, movers, replace_mobject_with_target_in_scene = True )) self.wait() self.gaussian_factorization = factorization def organize_factors_into_columns(self): T_chart = self.get_T_chart() factors = self.gaussian_factorization.copy()[1:] left_factors, right_factors = self.get_left_and_right_factors() for group in left_factors, right_factors: group.generate_target() group.target.arrange(DOWN) left_factors.target.next_to(T_chart.left_h_line, DOWN) right_factors.target.next_to(T_chart.right_h_line, DOWN) self.play(ShowCreation(T_chart)) self.wait() self.play(MoveToTarget(left_factors)) self.play(MoveToTarget(right_factors)) self.wait() digest_locals(self, ["left_factors", "right_factors"]) def mention_conjugate_rule(self): left_factors = self.left_factors right_factors = self.right_factors double_arrows = VGroup() for lf, rf in zip(left_factors.target, right_factors.target): arrow = DoubleArrow( lf, rf, buff = SMALL_BUFF, tip_length = SMALL_BUFF, color = GREEN ) word = OldTexText("Conjugates") word.scale(0.75) word.add_background_rectangle() word.next_to(arrow, DOWN, SMALL_BUFF) arrow.add(word) double_arrows.add(arrow) main_arrow = double_arrows[0] self.play(Write(main_arrow, run_time = 1)) self.wait() for new_arrow in double_arrows[1:]: self.play(Transform(main_arrow, new_arrow)) self.wait() self.wait() self.play(FadeOut(main_arrow)) def take_product_of_columns(self): arrows = self.get_product_multiplication_lines() products = self.get_product_mobjects() factor_groups = [self.left_factors, self.right_factors] for arrow, product, group in zip(arrows, products, factor_groups): self.play(ShowCreation(arrow)) self.play(ReplacementTransform( group.copy(), VGroup(product) )) self.wait() self.wait(3) def mark_left_product_as_result(self): rect = self.get_result_surrounding_rect() words = OldTexText("Output", " of recipe") words.next_to(rect, DOWN, buff = MED_LARGE_BUFF) words.to_edge(LEFT) arrow = Arrow(words.get_top(), rect.get_left()) self.play(ShowCreation(rect)) self.play( Write(words, run_time = 2), ShowCreation(arrow) ) self.wait(3) self.play(*list(map(FadeOut, [words, arrow]))) self.output_label_group = VGroup(words, arrow) def swap_factors(self): for i in range(len(self.left_factors)): self.swap_factors_at_index(i) self.wait() ######### def get_left_and_right_factors(self): factors = self.gaussian_factorization.copy()[1:] return VGroup(*factors[::2]), VGroup(*factors[1::2]) def get_T_chart(self): T_chart = VGroup() h_lines = VGroup(*[ Line(ORIGIN, self.T_chart_width*RIGHT/2.0) for x in range(2) ]) h_lines.arrange(RIGHT, buff = 0) h_lines.shift(UP) v_line = Line(self.T_chart_height*UP, ORIGIN) v_line.move_to(h_lines.get_center(), UP) T_chart.left_h_line, T_chart.right_h_line = h_lines T_chart.v_line = v_line T_chart.digest_mobject_attrs() return T_chart def complex_number_to_tex(self, z): z = complex(z) x, y = z.real, z.imag if y == 0: return "(%d)"%x y_sign_tex = "+" if y >= 0 else "-" if abs(y) == 1: y_str = y_sign_tex + "i" else: y_str = y_sign_tex + "%di"%abs(y) return "(%d%s)"%(x, y_str) def get_product_multiplication_lines(self): lines = VGroup() for factors in self.left_factors, self.right_factors: line = Line(ORIGIN, 3*RIGHT) line.next_to(factors, DOWN, SMALL_BUFF) times = OldTex("\\times") times.next_to(line.get_left(), UP+RIGHT, SMALL_BUFF) line.add(times) lines.add(line) self.multiplication_lines = lines return lines def get_product_mobjects(self): factor_groups = [self.left_factors, self.right_factors] product_mobjects = VGroup() for factors, line in zip(factor_groups, self.multiplication_lines): product = reduce(op.mul, [ factor.underlying_number for factor in factors ]) color = average_color(*[ factor.get_color() for factor in factors ]) product_mob = OldTex( self.complex_number_to_tex(product) ) product_mob.set_color(color) product_mob.next_to(line, DOWN) product_mobjects.add(product_mob) self.product_mobjects = product_mobjects return product_mobjects def swap_factors_at_index(self, index): factor_groups = self.left_factors, self.right_factors factors_to_swap = [group[index] for group in factor_groups] self.play(*[ ApplyMethod( factors_to_swap[i].move_to, factors_to_swap[1-i], path_arc = np.pi/2, ) for i in range(2) ]) for i, group in enumerate(factor_groups): group.submobjects[index] = factors_to_swap[1-i] self.play(FadeOut(self.product_mobjects)) self.get_product_mobjects() rect = self.result_surrounding_rect new_rect = self.get_result_surrounding_rect() self.play(*[ ReplacementTransform(group.copy(), VGroup(product)) for group, product in zip( factor_groups, self.product_mobjects, ) ]+[ ReplacementTransform(rect, new_rect) ]) self.wait() def get_result_surrounding_rect(self, product = None): if product is None: product = self.product_mobjects[0] rect = SurroundingRectangle(product) self.result_surrounding_rect = rect return rect def write_last_step(self): output_words, arrow = self.output_label_group final_step = OldTexText( "Multiply by $1$, $i$, $-1$ or $-i$" ) final_step.scale(0.9) final_step.next_to(arrow.get_start(), DOWN, SMALL_BUFF) final_step.shift_onto_screen() anims = [Write(final_step)] if arrow not in self.get_mobjects(): # arrow = Arrow( # final_step.get_top(), # self.result_surrounding_rect.get_left() # ) anims += [ShowCreation(arrow)] self.play(*anims) self.wait(2) class StateThreeChoices(TeacherStudentsScene): def construct(self): self.teacher_says( "$5^2$ gives 3 choices." ) self.wait(3) class ThreeOutputsAsLatticePoints(LatticePointScene): CONFIG = { "coords_list" : [(3, 4), (5, 0), (3, -4)], "dot_radius" : 0.1, "colors" : [YELLOW, GREEN, PINK, MAROON_B], } def construct(self): self.add_circle() self.add_dots_and_labels() def add_circle(self): radius = np.sqrt(self.radius_squared) circle = self.get_circle(radius) radial_line, root_label = self.get_radial_line_with_label(radius) self.add(radial_line, root_label, circle) self.add_foreground_mobject(root_label) def add_dots_and_labels(self): dots = VGroup(*[ Dot( self.plane.coords_to_point(*coords), radius = self.dot_radius, color = self.colors[0], ) for coords in self.coords_list ]) labels = VGroup() for x, y in self.coords_list: if y == 0: y_str = "" vect = DOWN+RIGHT elif y > 1: y_str = "+%di"%y vect = UP+RIGHT else: y_str = "%di"%y vect = DOWN+RIGHT label = OldTex("%d%s"%(x, y_str)) label.add_background_rectangle() point = self.plane.coords_to_point(x, y) label.next_to(point, vect) labels.add(label) for dot, label in zip(dots, labels): self.play( FadeIn(label), DrawBorderThenFill( dot, stroke_color = PINK, stroke_width = 4 ) ) self.wait(2) self.original_dots = dots class LooksLikeYoureMissingSome(TeacherStudentsScene): def construct(self): self.student_says( "Looks like you're \\\\ missing a few", target_mode = "sassy", index = 0, ) self.play(self.teacher.change, "guilty") self.wait(3) class ShowAlternateFactorizationOfTwentyFive(IntroduceRecipe): CONFIG = { "gaussian_factors" : [ complex(-1, 2), complex(-1, -2), complex(2, 1), complex(2, -1), ], } def construct(self): self.add_title() self.show_ordinary_factorization() self.subfactor_ordinary_factorization() self.organize_factors_into_columns() self.take_product_of_columns() self.mark_left_product_as_result() self.swap_factors() class WriteAlternateLastStep(IntroduceRecipe): def construct(self): self.force_skipping() self.add_title() self.show_ordinary_factorization() self.subfactor_ordinary_factorization() self.organize_factors_into_columns() self.take_product_of_columns() self.mark_left_product_as_result() self.revert_to_original_skipping_status() self.cross_out_output_words() self.write_last_step() def cross_out_output_words(self): output_words, arrow = self.output_label_group cross = OldTex("\\times") cross.replace(output_words, stretch = True) cross.set_color(RED) self.add(output_words, arrow) self.play(Write(cross)) output_words.add(cross) self.play(output_words.to_edge, DOWN) class ThreeOutputsAsLatticePointsContinued(ThreeOutputsAsLatticePoints): def construct(self): self.force_skipping() ThreeOutputsAsLatticePoints.construct(self) self.revert_to_original_skipping_status() self.show_multiplication_by_units() def show_multiplication_by_units(self): original_dots = self.original_dots lines = VGroup() for dot in original_dots: line = Line(self.plane_center, dot.get_center()) line.set_stroke(dot.get_color(), 6) lines.add(line) dot.add(line) words_group = VGroup(*[ OldTexText("Multiply by $%s$"%s) for s in ("1", "i", "-1", "-i") ]) for words, color in zip(words_group, self.colors): words.add_background_rectangle() words.set_color(color) words_group.arrange(DOWN, aligned_edge = LEFT) words_group.to_corner(UP+LEFT, buff = MED_SMALL_BUFF) angles = [np.pi/2, np.pi, -np.pi/2] self.play( FadeIn(words_group[0]), *list(map(ShowCreation, lines)) ) for words, angle, color in zip(words_group[1:], angles, self.colors[1:]): self.play(FadeIn(words)) dots_copy = original_dots.copy() self.play( dots_copy.rotate, angle, dots_copy.set_color, color, path_arc = angle ) self.wait() self.wait(2) class RecipeFor125(IntroduceRecipe): CONFIG = { "N_string" : "125", "integer_factors" : [5, 5, 5], "gaussian_factors" : [ complex(2, -1), complex(2, 1), complex(2, -1), complex(2, 1), complex(2, -1), complex(2, 1), ], } def construct(self): self.force_skipping() self.add_title() self.show_ordinary_factorization() self.subfactor_ordinary_factorization() self.revert_to_original_skipping_status() self.organize_factors_into_columns() # self.take_product_of_columns() # self.mark_left_product_as_result() # self.swap_factors() # self.write_last_step() class StateFourChoices(TeacherStudentsScene): def construct(self): self.teacher_says( "$5^3$ gives 4 choices." ) self.wait(3) class Show125Circle(ThreeOutputsAsLatticePointsContinued): CONFIG = { "radius_squared" : 125, "coords_list" : [(2, 11), (10, 5), (10, -5), (2, -11)], "y_radius" : 15, } def construct(self): self.draw_circle() self.add_dots_and_labels() self.show_multiplication_by_units() self.ask_about_two() def draw_circle(self): self.plane.scale(2) radius = np.sqrt(self.radius_squared) circle = self.get_circle(radius) radial_line, root_label = self.get_radial_line_with_label(radius) self.play( Write(root_label), ShowCreation(radial_line) ) self.add_foreground_mobject(root_label) self.play( Rotating( radial_line, rate_func = smooth, about_point = self.plane_center ), ShowCreation(circle), run_time = 2, ) group = VGroup( self.plane, radial_line, circle, root_label ) self.play(group.scale, 0.5) class RecipeFor375(IntroduceRecipe): CONFIG = { "N_string" : "375", "integer_factors" : [3, 5, 5, 5], "gaussian_factors" : [ 3, complex(2, 1), complex(2, -1), complex(2, 1), complex(2, -1), complex(2, 1), complex(2, -1), ], } def construct(self): self.add_title() self.show_ordinary_factorization() self.subfactor_ordinary_factorization() self.organize_factors_into_columns() self.express_trouble_with_three() self.take_product_of_columns() def express_trouble_with_three(self): morty = Mortimer().flip().to_corner(DOWN+LEFT) three = self.gaussian_factorization[1].copy() three.generate_target() three.target.next_to(morty, UP, MED_LARGE_BUFF) self.play(FadeIn(morty)) self.play( MoveToTarget(three), morty.change, "angry", three.target ) self.play(Blink(morty)) self.wait() for factors in self.left_factors, self.right_factors: self.play( three.next_to, factors, DOWN, morty.change, "sassy", factors.get_bottom() ) self.wait() self.right_factors.add(three) self.play(morty.change_mode, "pondering") #### def get_left_and_right_factors(self): factors = self.gaussian_factorization.copy()[1:] return VGroup(*factors[1::2]), VGroup(*factors[2::2]) class Show375Circle(LatticePointScene): CONFIG = { "y_radius" : 20, } def construct(self): radius = np.sqrt(375) circle = self.get_circle(radius) radial_line, root_label = self.get_radial_line_with_label(radius) self.play( ShowCreation(radial_line), Write(root_label, run_time = 1) ) self.add_foreground_mobject(root_label) self.play( Rotating( radial_line, rate_func = smooth, about_point = self.plane_center ), ShowCreation(circle), run_time = 2, ) group = VGroup( self.plane, radial_line, root_label, circle ) self.wait(2) class RecipeFor1125(IntroduceRecipe): CONFIG = { "N_string" : "1125", "integer_factors" : [3, 3, 5, 5, 5], "gaussian_factors" : [ 3, 3, complex(2, 1), complex(2, -1), complex(2, 1), complex(2, -1), complex(2, 1), complex(2, -1), ], } def construct(self): self.add_title() self.show_ordinary_factorization() self.subfactor_ordinary_factorization() self.organize_factors_into_columns() self.mention_conjugate_rule() self.take_product_of_columns() self.mark_left_product_as_result() self.swap_factors() self.write_last_step() def write_last_step(self): words = OldTexText( "Multiply by \\\\ ", "$1$, $i$, $-1$ or $-i$" ) words.scale(0.7) words.to_corner(DOWN+LEFT) product = self.product_mobjects[0] self.play(Write(words)) self.wait() class Show125CircleSimple(LatticePointScene): CONFIG = { "radius_squared" : 125, "y_radius" : 12, "max_lattice_point_radius" : 12, } def construct(self): self.plane.set_stroke(width = 1) radius = np.sqrt(self.radius_squared) circle = self.get_circle(radius) radial_line, root_label = self.get_radial_line_with_label(radius) dots = self.get_lattice_points_on_r_squared_circle(self.radius_squared) self.play( ShowCreation(radial_line), Write(root_label, run_time = 1) ) self.add_foreground_mobject(root_label) self.play( Rotating( radial_line, rate_func = smooth, about_point = self.plane_center ), ShowCreation(circle), LaggedStartMap( DrawBorderThenFill, dots, stroke_width = 4, stroke_color = PINK, ), run_time = 2, ) self.wait(2) class Show1125Circle(Show125CircleSimple): CONFIG = { "radius_squraed" : 1125, "y_radius" : 35, "max_lattice_point_radius" : 35, } class SummarizeCountingRule(Show125Circle): CONFIG = { "dot_radius" : 0.075, "N_str" : "N", "rect_opacity" : 1, } def construct(self): self.add_count_words() self.draw_circle() self.add_full_screen_rect() self.talk_through_rules() self.ask_about_two() def add_count_words(self): words = OldTexText( "\\# Lattice points \\\\ on $\\sqrt{%s}$ circle"%self.N_str ) words.to_corner(UP+LEFT) words.add_background_rectangle() self.add(words) self.count_words = words def draw_circle(self): radius = np.sqrt(self.radius_squared) circle = self.get_circle(radius) radial_line, num_root_label = self.get_radial_line_with_label(radius) root_label = OldTex("\\sqrt{%s}"%self.N_str) root_label.next_to(radial_line, UP, SMALL_BUFF) dots = VGroup(*[ Dot( self.plane.coords_to_point(*coords), radius = self.dot_radius, color = self.dot_color ) for coords in self.coords_list ]) for angle in np.pi/2, np.pi, -np.pi/2: dots.add(*dots.copy().rotate(angle)) self.play( Write(root_label), ShowCreation(radial_line) ) self.play( Rotating( radial_line, rate_func = smooth, about_point = self.plane_center ), ShowCreation(circle), run_time = 2, ) self.play(LaggedStartMap( DrawBorderThenFill, dots, stroke_width = 4, stroke_color = PINK )) self.wait(2) def add_full_screen_rect(self): rect = FullScreenFadeRectangle( fill_opacity = self.rect_opacity ) self.play( FadeIn(rect), Animation(self.count_words) ) def talk_through_rules(self): factorization = OldTex( "N =", "3", "^4", "\\cdot", "5", "^3", "\\cdot", "13", "^2" ) factorization.next_to(ORIGIN, RIGHT) factorization.to_edge(UP) three, five, thirteen = [ factorization.get_part_by_tex(str(n), substring = False) for n in (3, 5, 13) ] three_power = factorization.get_part_by_tex("^4") five_power = factorization.get_part_by_tex("^3") thirteen_power = factorization.get_part_by_tex("^2") alt_three_power = five_power.copy().move_to(three_power) three_brace = Brace(VGroup(*factorization[1:3]), DOWN) five_brace = Brace(VGroup(*factorization[3:6]), DOWN) thirteen_brace = Brace(VGroup(*factorization[6:9]), DOWN) three_choices = three_brace.get_tex("(", "1", ")") five_choices = five_brace.get_tex( "(", "3", "+", "1", ")" ) thirteen_choices = thirteen_brace.get_tex( "(", "2", "+", "1", ")" ) all_choices = VGroup(three_choices, five_choices, thirteen_choices) for choices in all_choices: choices.scale(0.75, about_point = choices.get_top()) thirteen_choices.next_to(five_choices, RIGHT) three_choices.next_to(five_choices, LEFT) alt_three_choices = OldTex("(", "0", ")") alt_three_choices.scale(0.75) alt_three_choices.move_to(three_choices, RIGHT) self.play(FadeIn(factorization)) self.wait() self.play( five.set_color, GREEN, thirteen.set_color, GREEN, FadeIn(five_brace), FadeIn(thirteen_brace), ) self.wait() for choices, power in (five_choices, five_power), (thirteen_choices, thirteen_power): self.play( Write(VGroup(choices[0], *choices[2:])), ReplacementTransform( power.copy(), choices[1] ) ) self.wait() self.play( three.set_color, RED, FadeIn(three_brace) ) self.wait() self.play( Write(VGroup(three_choices[0], three_choices[2])), ReplacementTransform( three_power.copy(), three_choices[1] ) ) self.wait() movers = three_power, three_choices for mob in movers: mob.save_state() self.play( Transform( three_power, alt_three_power, path_arc = np.pi ), Transform(three_choices, alt_three_choices) ) self.wait() self.play( *[mob.restore for mob in movers], path_arc = -np.pi ) self.wait() equals_four = OldTex("=", "4") four = equals_four.get_part_by_tex("4") four.set_color(YELLOW) final_choice_words = OldTexText( "Mutiply", "by $1$, $i$, $-1$ or $-i$" ) final_choice_words.set_color(YELLOW) final_choice_words.next_to(four, DOWN, LARGE_BUFF, LEFT) final_choice_words.to_edge(RIGHT) final_choice_arrow = Arrow( final_choice_words[0].get_top(), four.get_bottom(), buff = SMALL_BUFF ) choices_copy = all_choices.copy() choices_copy.generate_target() choices_copy.target.scale(1./0.75) choices_copy.target.arrange(RIGHT, buff = SMALL_BUFF) choices_copy.target.next_to(equals_four, RIGHT, SMALL_BUFF) choices_copy.target.shift(0.25*SMALL_BUFF*DOWN) self.play( self.count_words.next_to, equals_four, LEFT, MoveToTarget(choices_copy), FadeIn(equals_four) ) self.play(*list(map(FadeIn, [final_choice_words, final_choice_arrow]))) self.wait() def ask_about_two(self): randy = Randolph(color = BLUE_C) randy.scale(0.7) randy.to_edge(LEFT) self.play(FadeIn(randy)) self.play(PiCreatureBubbleIntroduction( randy, "What about \\\\ factors of 2?", bubble_type = ThoughtBubble, bubble_config = {"height" : 3, "width" : 3}, target_mode = "confused", look_at = self.count_words )) self.play(Blink(randy)) self.wait() class ThisIsTheHardestPart(TeacherStudentsScene): def construct(self): self.play_student_changes("horrified", "confused", "pleading") self.teacher_says("This is the \\\\ hardest part") self.play_student_changes("thinking", "happy", "pondering") self.wait(2) class RecipeFor10(IntroduceRecipe): CONFIG = { "N_string" : "10", "integer_factors" : [2, 5], "gaussian_factors" : [ complex(1, 1), complex(1, -1), complex(2, 1), complex(2, -1), ], } def construct(self): self.add_title() self.show_ordinary_factorization() self.subfactor_ordinary_factorization() self.organize_factors_into_columns() self.take_product_of_columns() self.mark_left_product_as_result() self.swap_two_factors() self.write_last_step() def swap_two_factors(self): left = self.left_factors[0] right = self.right_factors[0] arrow = Arrow(right, left, buff = SMALL_BUFF) times_i = OldTex("\\times i") times_i.next_to(arrow, DOWN, 0) times_i.add_background_rectangle() curr_product = self.product_mobjects[0].copy() for x in range(2): self.swap_factors_at_index(0) self.play( ShowCreation(arrow), Write(times_i, run_time = 1) ) self.wait() self.play(curr_product.to_edge, LEFT) self.swap_factors_at_index(0) new_arrow = Arrow( self.result_surrounding_rect, curr_product, buff = SMALL_BUFF ) self.play( Transform(arrow, new_arrow), MaintainPositionRelativeTo(times_i, arrow) ) self.wait(2) self.play(*list(map(FadeOut, [arrow, times_i, curr_product]))) class FactorsOfTwoNeitherHelpNorHurt(TeacherStudentsScene): def construct(self): words = OldTexText( "Factors of", "$2^k$", "neither \\\\ help nor hurt" ) words.set_color_by_tex("2", YELLOW) self.teacher_says(words) self.play_student_changes(*["pondering"]*3) self.wait(3) class EffectOfPowersOfTwo(LatticePointScene): CONFIG = { "y_radius" : 9, "max_lattice_point_radius" : 9, "square_radii" : [5, 10, 20, 40, 80], } def construct(self): radii = list(map(np.sqrt, self.square_radii)) circles = list(map(self.get_circle, radii)) radial_lines, root_labels = list(zip(*list(map( self.get_radial_line_with_label, radii )))) dots_list = list(map( self.get_lattice_points_on_r_squared_circle, self.square_radii )) groups = [ VGroup(*mobs) for mobs in zip(radial_lines, circles, root_labels, dots_list) ] group = groups[0] self.add(group) self.play(LaggedStartMap( DrawBorderThenFill, dots_list[0], stroke_width = 4, stroke_color = PINK )) self.wait() for new_group in groups[1:]: self.play(Transform(group, new_group)) self.wait(2) class NumberTheoryAtItsBest(TeacherStudentsScene): def construct(self): self.teacher_says( "Number theory at its best!", target_mode = "hooray", run_time = 2, ) self.play_student_changes(*["hooray"]*3) self.wait(3) class IntroduceChi(FactorizationPattern): CONFIG = { "numbers_list" : [ list(range(i, 36, d)) for i, d in [(1, 4), (3, 4), (2, 2)] ], "colors" : [GREEN, RED, YELLOW] } def construct(self): self.add_number_line() self.add_define_chi_label() for index in range(3): self.describe_values(index) self.fade_out_labels() self.cyclic_pattern() self.write_multiplicative_label() self.show_multiplicative() def add_define_chi_label(self): label = OldTexText("Define $\\chi(n)$:") chi_expressions = VGroup(*[ self.get_chi_expression(numbers, color) for numbers, color in zip( self.numbers_list, self.colors ) ]) chi_expressions.scale(0.9) chi_expressions.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) chi_expressions.to_corner(UP+RIGHT) brace = Brace(chi_expressions, LEFT) label.next_to(brace, LEFT) self.play( Write(label), GrowFromCenter(brace) ) self.define_chi_label = label self.chi_expressions = chi_expressions def describe_values(self, index): numbers = self.numbers_list[index] color = self.colors[index] dots, arrows, labels = self.get_dots_arrows_and_labels( numbers, color ) chi_expression = self.chi_expressions[index] self.introduce_dots_arrows_and_labels(dots, arrows, labels) self.wait() self.play( Write(VGroup(*[ part for part in chi_expression if part not in chi_expression.inputs ])), *[ ReplacementTransform(label.copy(), num_mob) for label, num_mob in zip( labels, chi_expression.inputs ) ]) self.wait() def fade_out_labels(self): self.play(*list(map(FadeOut, [ self.last_dots, self.last_arrows, self.last_labels, self.number_line ]))) def cyclic_pattern(self): input_range = list(range(1, 9)) chis = VGroup(*[ OldTex("\\chi(%d)"%n) for n in input_range ]) chis.arrange(RIGHT, buff = LARGE_BUFF) chis.set_stroke(WHITE, width = 1) numbers = VGroup() arrows = VGroup() for chi, n in zip(chis, input_range): arrow = OldTex("\\Uparrow") arrow.next_to(chi, UP, SMALL_BUFF) arrows.add(arrow) value = OldTex(str(chi_func(n))) for tex, color in zip(["1", "-1", "0"], self.colors): value.set_color_by_tex(tex, color) value.next_to(arrow, UP) numbers.add(value) group = VGroup(chis, arrows, numbers) group.set_width(FRAME_WIDTH - LARGE_BUFF) group.to_edge(DOWN, buff = LARGE_BUFF) self.play(*[ FadeIn( mob, run_time = 3, lag_ratio = 0.5 ) for mob in [chis, arrows, numbers] ]) self.play(LaggedStartMap( ApplyMethod, numbers, lambda m : (m.shift, MED_SMALL_BUFF*UP), rate_func = there_and_back, lag_ratio = 0.2, run_time = 6 )) self.wait() self.play(*list(map(FadeOut, [chis, arrows, numbers]))) def write_multiplicative_label(self): morty = Mortimer() morty.scale(0.7) morty.to_corner(DOWN+RIGHT) self.play(PiCreatureSays( morty, "$\\chi$ is ``multiplicative''", bubble_config = {"height" : 2.5, "width" : 5} )) self.play(Blink(morty)) self.morty = morty def show_multiplicative(self): pairs = [(3, 5), (5, 5), (2, 13), (3, 11)] expressions = VGroup() for x, y in pairs: expression = OldTex( "\\chi(%d)"%x, "\\cdot", "\\chi(%d)"%y, "=", "\\chi(%d)"%(x*y) ) braces = [ Brace(expression[i], UP) for i in (0, 2, 4) ] for brace, n in zip(braces, [x, y, x*y]): output = chi_func(n) label = brace.get_tex(str(output)) label.set_color(self.number_to_color(output)) brace.add(label) expression.add(brace) expressions.add(expression) expressions.next_to(ORIGIN, LEFT) expressions.shift(DOWN) expression = expressions[0] self.play( FadeIn(expression), self.morty.change, "pondering", expression ) self.wait(2) for new_expression in expressions[1:]: self.play(Transform(expression, new_expression)) self.wait(2) ######### def get_dots_arrows_and_labels(self, numbers, color): dots = VGroup() arrows = VGroup() labels = VGroup() for number in numbers: point = self.number_line.number_to_point(number) dot = Dot(point) label = OldTex(str(number)) label.scale(0.8) label.next_to(dot, UP, LARGE_BUFF) arrow = Arrow(label, dot, buff = SMALL_BUFF) VGroup(dot, label, arrow).set_color(color) dots.add(dot) arrows.add(arrow) labels.add(label) return dots, arrows, labels def introduce_dots_arrows_and_labels(self, dots, arrows, labels): if hasattr(self, "last_dots"): self.play( ReplacementTransform(self.last_dots, dots), ReplacementTransform(self.last_arrows, arrows), ReplacementTransform(self.last_labels, labels), ) else: self.play( Write(labels), FadeIn(arrows, lag_ratio = 0.5), LaggedStartMap( DrawBorderThenFill, dots, stroke_width = 4, stroke_color = YELLOW ), run_time = 2 ) self.last_dots = dots self.last_arrows = arrows self.last_labels = labels def get_chi_expression(self, numbers, color, num_terms = 4): truncated_numbers = numbers[:num_terms] output = str(chi_func(numbers[0])) result = OldTex(*it.chain(*[ ["\\chi(", str(n), ")", "="] for n in truncated_numbers ] + [ ["\\cdots =", output] ])) result.inputs = VGroup() for n in truncated_numbers: num_mob = result.get_part_by_tex(str(n), substring = False) num_mob.set_color(color) result.inputs.add(num_mob) result.set_color_by_tex(output, color, substring = False) return result def number_to_color(self, n): output = chi_func(n) if n == 1: return self.colors[0] elif n == -1: return self.colors[1] else: return self.colors[2] class WriteCountingRuleWithChi(SummarizeCountingRule): CONFIG = { "colors" : [GREEN, RED, YELLOW] } def construct(self): self.add_count_words() self.draw_circle() self.add_full_screen_rect() self.add_factorization_and_rule() self.write_chi_expression() self.walk_through_expression_terms() self.circle_four() def add_factorization_and_rule(self): factorization = OldTex( "N", "=", "2", "^2", "\\cdot", "3", "^4", "\\cdot", "5", "^3", ) for tex, color in zip(["5", "3", "2"], self.colors): factorization.set_color_by_tex(tex, color, substring = False) factorization.to_edge(UP) factorization.shift(LEFT) count = VGroup( OldTex("=", "4"), OldTex("(", "1", ")"), OldTex("(", "1", ")"), OldTex("(", "3+1", ")"), ) count.arrange(RIGHT, buff = SMALL_BUFF) for i, color in zip([3, 2, 1], self.colors): count[i][1].set_color(color) count.next_to( factorization.get_part_by_tex("="), DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) self.play( FadeIn(factorization), self.count_words.next_to, count, LEFT ) self.wait() self.play(*[ ReplacementTransform( VGroup(factorization.get_part_by_tex( tex, substring = False )).copy(), part ) for tex, part in zip(["=", "2", "3", "5"], count) ]) self.wait() self.factorization = factorization self.count = count def write_chi_expression(self): equals_four = OldTex("=", "4") expression = VGroup(equals_four) for n, k, color in zip([2, 3, 5], [2, 4, 3], reversed(self.colors)): args = ["(", "\\chi(", "1", ")", "+"] for i in range(1, k+1): args += ["\\chi(", str(n), "^%d"%i, ")", "+"] args[-1] = ")" factor = OldTex(*args) factor.set_color_by_tex(str(n), color, substring = False) factor.set_color_by_tex("1", color, substring = False) factor.scale(0.8) expression.add(factor) expression.arrange( DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT ) equals_four.next_to(expression[1], LEFT, SMALL_BUFF) expression.shift( self.count[0].get_center() + LARGE_BUFF*DOWN -\ equals_four.get_center() ) count_copy = self.count.copy() self.play(*[ ApplyMethod( c_part.move_to, e_part, LEFT, path_arc = -np.pi/2, run_time = 2 ) for c_part, e_part in zip(count_copy, expression) ]) self.wait() self.play(ReplacementTransform( count_copy, expression, run_time = 2 )) self.wait() self.chi_expression = expression def walk_through_expression_terms(self): rect = FullScreenFadeRectangle() groups = [ VGroup( self.chi_expression[index], self.count[index], self.factorization.get_part_by_tex(tex1, substring = False), self.factorization.get_part_by_tex(tex2, substring = False), ) for index, tex1, tex2 in [ (-1, "5", "^3"), (-2, "3", "^4"), (-3, "2", "^2") ] ] evaluation_strings = [ "(1+1+1+1)", "(1-1+1-1+1)", "(1+0+0)", ] for group, tex in zip(groups, evaluation_strings): chi_sum, count, base, exp = group brace = Brace(chi_sum, DOWN) evaluation = brace.get_tex(*tex) evaluation.set_color(base.get_color()) evaluation_rect = BackgroundRectangle(evaluation) self.play(FadeIn(rect), Animation(group)) self.play(GrowFromCenter(brace)) self.play( FadeIn(evaluation_rect), ReplacementTransform(chi_sum.copy(), evaluation), ) self.wait(2) self.play(Indicate(count, color = PINK)) self.wait() if base.get_tex() is "3": new_exp = OldTex("3") new_exp.replace(exp) count_num = count[1] new_count = OldTex("0") new_count.replace(count_num, dim_to_match = 1) new_count.set_color(count_num.get_color()) evaluation_point = VectorizedPoint(evaluation[-4].get_right()) chi_sum_point = VectorizedPoint(chi_sum[-7].get_right()) new_brace = Brace(VGroup(*chi_sum[:-6]), DOWN) to_save = [brace, exp, evaluation, count_num, chi_sum] for mob in to_save: mob.save_state() self.play(FocusOn(exp)) self.play(Transform(exp, new_exp)) self.play( Transform(brace, new_brace), Transform( VGroup(*evaluation[-3:-1]), evaluation_point ), evaluation[-1].next_to, evaluation_point, RIGHT, SMALL_BUFF, Transform( VGroup(*chi_sum[-6:-1]), chi_sum_point ), chi_sum[-1].next_to, chi_sum_point, RIGHT, SMALL_BUFF ) self.play(Transform(count_num, new_count)) self.play(Indicate(count_num, color = PINK)) self.wait() self.play(*[mob.restore for mob in to_save]) self.play( FadeOut(VGroup( rect, brace, evaluation_rect, evaluation )), Animation(group) ) def circle_four(self): four = self.chi_expression[0][1] rect = SurroundingRectangle(four) self.revert_to_original_skipping_status() self.play(ShowCreation(rect)) self.wait(3) class WeAreGettingClose(TeacherStudentsScene): def construct(self): self.teacher_says("We're getting close...") self.play_student_changes(*["hooray"]*3) self.wait(2) class ExpandCountWith45(SummarizeCountingRule): CONFIG = { "N_str" : "45", "coords_list" : [(3, 6), (6, 3)], "radius_squared" : 45, "y_radius" : 7, "rect_opacity" : 0.75, } def construct(self): self.add_count_words() self.draw_circle() self.add_full_screen_rect() self.add_factorization_and_count() self.expand_expression() self.show_divisor_sum() def add_factorization_and_count(self): factorization = OldTex( "45", "=", "3", "^2", "\\cdot", "5", ) for tex, color in zip(["5", "3",], [GREEN, RED]): factorization.set_color_by_tex(tex, color, substring = False) factorization.to_edge(UP) factorization.shift(1.7*LEFT) equals_four = OldTex("=", "4") expression = VGroup(equals_four) for n, k, color in zip([3, 5], [2, 1], [RED, GREEN]): args = ["("] ["\\chi(1)", "+"] for i in range(k+1): if i == 0: input_str = "1" elif i == 1: input_str = str(n) else: input_str = "%d^%d"%(n, i) args += ["\\chi(%s)"%input_str, "+"] args[-1] = ")" factor = OldTex(*args) for part in factor[1::2]: part[2].set_color(color) factor.scale(0.8) expression.add(factor) expression.arrange(RIGHT, buff = SMALL_BUFF) expression.next_to( factorization[1], DOWN, buff = LARGE_BUFF, aligned_edge = LEFT, ) braces = VGroup(*[ Brace(part, UP) for part in expression[1:] ]) for brace, num, color in zip(braces, [1, 2], [RED, GREEN]): num_mob = brace.get_tex(str(num), buff = SMALL_BUFF) num_mob.set_color(color) brace.add(num_mob) self.play( FadeIn(factorization), self.count_words.next_to, expression, LEFT ) self.wait() self.play(*[ ReplacementTransform( VGroup(factorization.get_part_by_tex( tex, substring = False )).copy(), part ) for tex, part in zip(["=", "3", "5"], expression) ]) self.play(FadeIn(braces)) self.wait() self.chi_expression = expression self.factorization = factorization def expand_expression(self): equals, four, lp, rp = list(map(Tex, [ "=", "4", "\\big(", "\\big)" ])) expansion = VGroup(equals, four, lp) chi_pairs = list(it.product(*[ factor[1::2] for factor in self.chi_expression[1:] ])) num_pairs = list(it.product([1, 3, 9], [1, 5])) products = list(it.starmap(op.mul, num_pairs)) sorted_indices = np.argsort(products) mover_groups = [VGroup(), VGroup()] plusses = VGroup() prime_pairs = VGroup() for index in sorted_indices: pair = chi_pairs[index] prime_pair = VGroup() for chi, movers in zip(pair, mover_groups): mover = chi.copy() mover.generate_target() expansion.add(mover.target) movers.add(mover) prime_pair.add(mover.target[2]) prime_pairs.add(prime_pair) if index != sorted_indices[-1]: plus = OldTex("+") plusses.add(plus) expansion.add(plus) expansion.add(rp) expansion.arrange(RIGHT, buff = SMALL_BUFF) expansion.set_width(FRAME_WIDTH - LARGE_BUFF) expansion.next_to(ORIGIN, UP) rect = BackgroundRectangle(expansion) rect.stretch_in_place(1.5, 1) self.play( FadeIn(rect), *[ ReplacementTransform( self.chi_expression[i][j].copy(), mob ) for i, j, mob in [ (0, 0, equals), (0, 1, four), (1, 0, lp), (2, -1, rp), ] ] ) for movers in mover_groups: self.wait() self.play(movers.next_to, rect, DOWN) self.play(*list(map(MoveToTarget, movers))) self.play(Write(plusses)) self.wait() self.expansion = expansion self.prime_pairs = prime_pairs def show_divisor_sum(self): equals, four, lp, rp = list(map(Tex, [ "=", "4", "\\big(", "\\big)" ])) divisor_sum = VGroup(equals, four, lp) num_pairs = list(it.product([1, 3, 9], [1, 5])) products = list(it.starmap(op.mul, num_pairs)) products.sort() color = BLACK product_mobs = VGroup() chi_mobs = VGroup() for product in products: chi_mob = OldTex("\\chi(", str(product), ")") product_mob = chi_mob.get_part_by_tex(str(product)) product_mob.set_color(color) product_mobs.add(product_mob) divisor_sum.add(chi_mob) chi_mobs.add(chi_mob) if product != products[-1]: divisor_sum.add(OldTex("+")) divisor_sum.add(rp) divisor_sum.arrange(RIGHT, buff = SMALL_BUFF) divisor_sum.next_to(self.expansion, DOWN, MED_LARGE_BUFF) rect = BackgroundRectangle(divisor_sum) prime_pairs = self.prime_pairs.copy() for prime_pair, product_mob in zip(prime_pairs, product_mobs): prime_pair.target = product_mob.copy() prime_pair.target.set_color(YELLOW) braces = VGroup(*[Brace(m, DOWN) for m in chi_mobs]) for brace, product in zip(braces, products): value = brace.get_tex(str(chi_func(product))) brace.add(value) self.play( FadeIn(rect), Write(divisor_sum, run_time = 2) ) self.play(LaggedStartMap( MoveToTarget, prime_pairs, run_time = 4, lag_ratio = 0.25, )) self.remove(prime_pairs) product_mobs.set_color(YELLOW) self.wait(2) self.play(LaggedStartMap( ApplyMethod, product_mobs, lambda m : (m.shift, MED_LARGE_BUFF*DOWN), rate_func = there_and_back )) self.play(FadeIn( braces, run_time = 2, lag_ratio = 0.5, )) self.wait(2) class CountLatticePointsInBigCircle(LatticePointScene): CONFIG = { "y_radius" : 2*11, "max_lattice_point_radius" : 10, "dot_radius" : 0.05 } def construct(self): self.resize_plane() self.introduce_points() self.show_rings() self.ignore_center_dot() def resize_plane(self): self.plane.set_stroke(width = 2) self.plane.scale(2) self.lattice_points.scale(2) for point in self.lattice_points: point.scale(0.5) def introduce_points(self): circle = self.get_circle(radius = self.max_lattice_point_radius) radius = Line(ORIGIN, circle.get_right()) radius.set_color(RED) R = OldTex("R").next_to(radius, UP) R_rect = BackgroundRectangle(R) R_group = VGroup(R_rect, R) pi_R_squared = OldTex("\\pi", "R", "^2") pi_R_squared.next_to(ORIGIN, UP) pi_R_squared.to_edge(RIGHT) pi_R_squared_rect = BackgroundRectangle(pi_R_squared) pi_R_squared_group = VGroup(pi_R_squared_rect, pi_R_squared) self.play(*list(map(FadeIn, [circle, radius, R_group]))) self.add_foreground_mobject(R_group) self.draw_lattice_points() self.wait() self.play( FadeOut(R_rect), FadeIn(pi_R_squared_rect), ReplacementTransform(R, pi_R_squared.get_part_by_tex("R")), Write(VGroup(*[ part for part in pi_R_squared if part is not pi_R_squared.get_part_by_tex("R") ])) ) self.remove(R_group) self.add_foreground_mobject(pi_R_squared_group) self.wait() self.circle = circle self.radius = radius def show_rings(self): N_range = list(range(self.max_lattice_point_radius**2)) rings = VGroup(*[ self.get_circle(radius = np.sqrt(N)) for N in N_range ]) rings.set_color_by_gradient(TEAL, GREEN) rings.set_stroke(width = 2) dot_groups = VGroup(*[ self.get_lattice_points_on_r_squared_circle(N) for N in N_range ]) radicals = self.get_radicals() self.play( LaggedStartMap(FadeIn, rings), Animation(self.lattice_points), LaggedStartMap(FadeIn, radicals), run_time = 3 ) self.add_foreground_mobject(radicals) self.play( LaggedStartMap( ApplyMethod, dot_groups, lambda m : (m.set_stroke, PINK, 5), rate_func = there_and_back, run_time = 4, lag_ratio = 0.1, ), ) self.wait() self.rings = rings def ignore_center_dot(self): center_dot = self.lattice_points[0] circle = Circle(color = RED) circle.replace(center_dot) circle.scale(2) arrow = Arrow(ORIGIN, UP+RIGHT, color = RED) arrow.next_to(circle, DOWN+LEFT, SMALL_BUFF) new_max = 2*self.max_lattice_point_radius new_dots = VGroup(*[ Dot( self.plane.coords_to_point(x, y), color = self.dot_color, radius = self.dot_radius, ) for x in range(-new_max, new_max+1) for y in range(-new_max, new_max+1) if (x**2 + y**2) > self.max_lattice_point_radius**2 if (x**2 + y**2) < new_max**2 ]) new_dots.sort(get_norm) self.play(*list(map(ShowCreation, [circle, arrow]))) self.play(*list(map(FadeOut, [circle, arrow]))) self.play(FadeOut(center_dot)) self.lattice_points.remove(center_dot) self.wait() self.play(*[ ApplyMethod(m.scale, 0.5) for m in [ self.plane, self.circle, self.radius, self.rings, self.lattice_points ] ]) new_dots.scale(0.5) self.play(FadeOut(self.rings)) self.play( ApplyMethod( VGroup(self.circle, self.radius).scale, 2, rate_func=linear, ), LaggedStartMap( DrawBorderThenFill, new_dots, stroke_width = 4, stroke_color = PINK, lag_ratio = 0.2, ), run_time = 4, ) self.wait(2) ##### @staticmethod def get_radicals(): radicals = VGroup(*[ OldTex("\\sqrt{%d}"%N) for N in range(1, 13) ]) radicals.add( OldTex("\\vdots"), OldTex("\\sqrt{R^2}") ) radicals.arrange(DOWN, buff = MED_SMALL_BUFF) radicals.set_height(FRAME_HEIGHT - MED_LARGE_BUFF) radicals.to_edge(DOWN, buff = MED_SMALL_BUFF) radicals.to_edge(LEFT) for radical in radicals: radical.add_background_rectangle() return radicals class AddUpGrid(Scene): def construct(self): self.add_radicals() self.add_row_lines() self.add_chi_sums() self.put_four_in_corner() self.talk_through_rows() self.organize_into_columns() self.add_count_words() self.collapse_columns() self.factor_out_R() self.show_chi_sum_values() self.compare_to_pi_R_squared() self.celebrate() def add_radicals(self): self.radicals = CountLatticePointsInBigCircle.get_radicals() self.add(self.radicals) def add_row_lines(self): h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS - MED_LARGE_BUFF) h_line.set_stroke(WHITE, 1) row_lines = VGroup(*[ h_line.copy().next_to( radical, DOWN, buff = SMALL_BUFF, aligned_edge = LEFT ) for radical in self.radicals ]) row_lines[-2].shift( row_lines[-1].get_left()[0]*RIGHT -\ row_lines[-2].get_left()[0]*RIGHT ) self.play(LaggedStartMap(ShowCreation, row_lines)) self.wait() self.row_lines = row_lines def add_chi_sums(self): chi_sums = VGroup() chi_mobs = VGroup() plusses = VGroup() fours = VGroup() parens = VGroup() arrows = VGroup() for N, radical in zip(list(range(1, 13)), self.radicals): arrow, four, lp, rp = list(map(Tex, [ "\\Rightarrow", "4", "\\big(", "\\big)" ])) fours.add(four) parens.add(lp, rp) arrows.add(arrow) chi_sum = VGroup(arrow, four, lp) for d in range(1, N+1): if N%d != 0: continue chi_mob = OldTex("\\chi(", str(d), ")") chi_mob[1].set_color(YELLOW) chi_mob.d = d chi_mobs.add(chi_mob) chi_sum.add(chi_mob) if d != N: plus = OldTex("+") plus.chi_mob = chi_mob plusses.add(plus) chi_sum.add(plus) chi_sum.add(rp) chi_sum.arrange(RIGHT, buff = SMALL_BUFF) chi_sum.scale(0.7) chi_sum.next_to(radical, RIGHT) chi_sums.add(chi_sum) radical.chi_sum = chi_sum self.play(LaggedStartMap( Write, chi_sums, run_time = 5, rate_func = lambda t : t, )) self.wait() digest_locals(self, [ "chi_sums", "chi_mobs", "plusses", "fours", "parens", "arrows", ]) def put_four_in_corner(self): corner_four = OldTex("4") corner_four.to_corner(DOWN+RIGHT, buff = MED_SMALL_BUFF) rect = SurroundingRectangle(corner_four, color = BLUE) corner_four.rect = rect self.play( ReplacementTransform( self.fours, VGroup(corner_four), run_time = 2, ), FadeOut(self.parens) ) self.play(ShowCreation(rect)) self.corner_four = corner_four def talk_through_rows(self): rect = Rectangle( stroke_width = 0, fill_color = BLUE_C, fill_opacity = 0.3, ) rect.stretch_to_fit_width( VGroup(self.radicals, self.chi_mobs).get_width() ) rect.stretch_to_fit_height(self.radicals[0].get_height()) composite_rects, prime_rects = [ VGroup(*[ rect.copy().move_to(self.radicals[N-1], LEFT) for N in numbers ]) for numbers in ([6, 12], [2, 3, 5, 7, 11]) ] prime_rects.set_color(GREEN) randy = Randolph().flip() randy.next_to(self.chi_mobs, RIGHT) self.play(FadeIn(randy)) self.play(randy.change_mode, "pleading") self.play( FadeIn(composite_rects), randy.look_at, composite_rects.get_bottom() ) self.wait(2) self.play( FadeOut(composite_rects), FadeIn(prime_rects), randy.look_at, prime_rects.get_top(), ) self.play(Blink(randy)) self.wait() self.play(*list(map(FadeOut, [prime_rects, randy]))) def organize_into_columns(self): left_x = self.arrows.get_right()[0] + SMALL_BUFF spacing = self.chi_mobs[-1].get_width() + SMALL_BUFF for chi_mob in self.chi_mobs: y = chi_mob.get_left()[1] x = left_x + (chi_mob.d - 1)*spacing chi_mob.generate_target() chi_mob.target.move_to(x*RIGHT + y*UP, LEFT) for plus in self.plusses: plus.generate_target() plus.target.scale(0.5) plus.target.next_to( plus.chi_mob.target, RIGHT, SMALL_BUFF ) self.play(*it.chain( list(map(MoveToTarget, self.chi_mobs)), list(map(MoveToTarget, self.plusses)), ), run_time = 2) self.wait() def add_count_words(self): rect = Rectangle( stroke_color = WHITE, stroke_width = 2, fill_color = average_color(BLUE_E, BLACK), fill_opacity = 1, height = 1.15, width = FRAME_WIDTH - 2*MED_SMALL_BUFF, ) rect.move_to(3*LEFT, LEFT) rect.to_edge(UP, buff = SMALL_BUFF) words = OldTexText("Total") words.scale(0.8) words.next_to(rect.get_left(), RIGHT, SMALL_BUFF) approx = OldTex("\\approx") approx.scale(0.7) approx.next_to(words, RIGHT, SMALL_BUFF) words.add(approx) self.play(*list(map(FadeIn, [rect, words]))) self.wait() self.count_rect = rect self.count_words = words def collapse_columns(self): chi_mob_columns = [VGroup() for i in range(12)] for chi_mob in self.chi_mobs: chi_mob_columns[chi_mob.d - 1].add(chi_mob) full_sum = VGroup() for d in range(1, 7): R_args = ["{R^2"] if d != 1: R_args.append("\\over %d}"%d) term = VGroup( OldTex(*R_args), OldTex("\\chi(", str(d), ")"), OldTex("+") ) term.arrange(RIGHT, SMALL_BUFF) term[1][1].set_color(YELLOW) full_sum.add(term) full_sum.arrange(RIGHT, SMALL_BUFF) full_sum.scale(0.7) full_sum.next_to(self.count_words, RIGHT, SMALL_BUFF) for column, term in zip(chi_mob_columns, full_sum): rect = SurroundingRectangle(column) rect.stretch_to_fit_height(FRAME_HEIGHT) rect.move_to(column, UP) rect.set_stroke(width = 0) rect.set_fill(YELLOW, 0.3) self.play(FadeIn(rect)) self.wait() self.play( ReplacementTransform( column.copy(), VGroup(term[1]), run_time = 2 ), Write(term[0]), Write(term[2]), ) self.wait() if term is full_sum[2]: vect = sum([ self.count_rect.get_left()[0], FRAME_X_RADIUS, -MED_SMALL_BUFF, ])*LEFT self.play(*[ ApplyMethod(m.shift, vect) for m in [ self.count_rect, self.count_words, ]+list(full_sum[:3]) ]) VGroup(*full_sum[3:]).shift(vect) self.play(FadeOut(rect)) self.full_sum = full_sum def factor_out_R(self): self.corner_four.generate_target() R_squared = OldTex("R^2") dots = OldTex("\\cdots") lp, rp = list(map(Tex, ["\\big(", "\\big)"])) new_sum = VGroup( self.corner_four.target, R_squared, lp ) R_fracs, chi_terms, plusses = full_sum_parts = [ VGroup(*[term[i] for term in self.full_sum]) for i in range(3) ] targets = [] for part in full_sum_parts: part.generate_target() targets.append(part.target) for R_frac, chi_term, plus in zip(*targets): chi_term.scale(0.9) chi_term.move_to(R_frac[0], DOWN) if R_frac is R_fracs.target[0]: new_sum.add(chi_term) else: new_sum.add(VGroup(chi_term, R_frac[1])) new_sum.add(plus) new_sum.add(dots) new_sum.add(rp) new_sum.arrange(RIGHT, buff = SMALL_BUFF) new_sum.next_to(self.count_words, RIGHT, SMALL_BUFF) R_squared.shift(0.5*SMALL_BUFF*UP) R_movers = VGroup() for R_frac in R_fracs.target: if R_frac is R_fracs.target[0]: mover = R_frac else: mover = R_frac[0] Transform(mover, R_squared).update(1) R_movers.add(mover) self.play(*it.chain( list(map(Write, [lp, rp, dots])), list(map(MoveToTarget, full_sum_parts)), ), run_time = 2) self.remove(R_movers) self.add(R_squared) self.wait() self.play( MoveToTarget(self.corner_four, run_time = 2), FadeOut(self.corner_four.rect) ) self.wait(2) self.remove(self.full_sum, self.corner_four) self.add(new_sum) self.new_sum = new_sum def show_chi_sum_values(self): alt_rhs = OldTex( "\\approx", "4", "R^2", "\\left(1 - \\frac{1}{3} + \\frac{1}{5}" + \ "-\\frac{1}{7} + \\frac{1}{9} - \\frac{1}{11}" + \ "+ \\cdots \\right)", ) alt_rhs.scale(0.9) alt_rhs.next_to( self.count_words[-1], DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) self.play( *list(map(FadeOut, [ self.chi_mobs, self.plusses, self.arrows, self.radicals, self.row_lines ])) + [ FadeOut(self.count_rect), Animation(self.new_sum), Animation(self.count_words), ] ) self.play(Write(alt_rhs)) self.wait(2) self.alt_rhs = alt_rhs def compare_to_pi_R_squared(self): approx, pi, R_squared = area_rhs = OldTex( "\\approx", "\\pi", "R^2" ) area_rhs.next_to(self.alt_rhs, RIGHT) brace = Brace( VGroup(self.alt_rhs, area_rhs), DOWN ) brace.add(brace.get_text( "Arbitrarily good as $R \\to \\infty$" )) pi_sum = OldTex( "4", self.alt_rhs[-1].get_tex(), "=", "\\pi" ) pi_sum.scale(0.9) pi = pi_sum.get_part_by_tex("pi") pi.scale(2, about_point = pi.get_left()) pi.set_color(YELLOW) pi_sum.shift( self.alt_rhs[-1].get_bottom(), MED_SMALL_BUFF*DOWN, -pi_sum[1].get_top() ) self.play(Write(area_rhs)) self.wait() self.play(FadeIn(brace)) self.wait(2) self.play(FadeOut(brace)) self.play(*[ ReplacementTransform(m.copy(), pi_sum_part) for pi_sum_part, m in zip(pi_sum, [ self.alt_rhs.get_part_by_tex("4"), self.alt_rhs[-1], area_rhs[0], area_rhs[1], ]) ]) def celebrate(self): creatures = TeacherStudentsScene().get_pi_creatures() self.play(FadeIn(creatures)) self.play(*[ ApplyMethod(pi.change, "hooray", self.alt_rhs) for pi in creatures ]) self.wait() for i in 0, 2, 3: self.play(Blink(creatures[i])) self.wait() class IntersectionOfTwoFields(TeacherStudentsScene): def construct(self): circles = VGroup() for vect, color, adj in (LEFT, BLUE, "Algebraic"), (RIGHT, YELLOW, "Analytic"): circle = Circle(color = WHITE) circle.set_fill(color, opacity = 0.3) circle.stretch_to_fit_width(7) circle.stretch_to_fit_height(4) circle.shift(FRAME_X_RADIUS*vect/3.0 + LEFT) title = OldTexText("%s \\\\ number theory"%adj) title.scale(0.7) title.move_to(circle) title.to_edge(UP, buff = SMALL_BUFF) circle.next_to(title, DOWN, SMALL_BUFF) title.set_color(color) circle.title = title circles.add(circle) new_number_systems = OldTexText( "New \\\\ number systems" ) gaussian_integers = OldTexText( "e.g. Gaussian \\\\ integers" ) new_number_systems.next_to(circles[0].get_top(), DOWN, MED_SMALL_BUFF) new_number_systems.shift(MED_LARGE_BUFF*(DOWN+2*LEFT)) gaussian_integers.next_to(new_number_systems, DOWN) gaussian_integers.set_color(BLUE) circles[0].words = VGroup(new_number_systems, gaussian_integers) zeta = OldTex("\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}") L_function = OldTex( "L(s, \\chi) = \\sum_{n=1}^\\infty \\frac{\\chi(n)}{n^s}" ) for mob in zeta, L_function: mob.scale(0.8) zeta.next_to(circles[1].get_top(), DOWN, MED_LARGE_BUFF) zeta.shift(MED_LARGE_BUFF*RIGHT) L_function.next_to(zeta, DOWN, MED_LARGE_BUFF) L_function.set_color(YELLOW) circles[1].words = VGroup(zeta, L_function) mid_words = OldTexText("Where\\\\ we \\\\ were") mid_words.scale(0.7) mid_words.move_to(circles) for circle in circles: self.play( Write(circle.title, run_time = 2), DrawBorderThenFill(circle, run_time = 2), self.teacher.change_mode, "raise_right_hand" ) self.wait() for circle in circles: for word in circle.words: self.play( Write(word, run_time = 2), self.teacher.change, "speaking", *[ ApplyMethod(pi.change, "pondering") for pi in self.get_students() ] ) self.wait() self.play( Write(mid_words), self.teacher.change, "raise_right_hand" ) self.play_student_changes( *["thinking"]*3, look_at = mid_words ) self.wait(3) class LeibnizPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Burt Humburg", "CrypticSwarm", "Erik Sundell", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Yoni Nazarathy", "Joseph John Cox", "Dan Buchoff", "Luc Ritchie", "Guido Gambardella", "Julian Pulgarin", "John Haley", "Jeff Linse", "Suraj Pratap", "Cooper Jones", "Ryan Dahl", "Ahmad Bamieh", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], } class Sponsorship(PiCreatureScene): def construct(self): morty = self.pi_creature logo = SVGMobject( file_name = "remix_logo", ) logo.set_height(1) logo.center() logo.set_stroke(width = 0) logo.set_fill(BLUE_D, 1) VGroup(*logo[6:]).set_color_by_gradient(BLUE_B, BLUE_E) logo.next_to(morty.get_corner(UP+LEFT), UP) url = OldTexText("www.remix.com") url.to_corner(UP+LEFT) rect = ScreenRectangle(height = 5) rect.next_to(url, DOWN, aligned_edge = LEFT) self.play( morty.change_mode, "raise_right_hand", LaggedStartMap(DrawBorderThenFill, logo, run_time = 3) ) self.wait() self.play( ShowCreation(rect), logo.scale, 0.8, logo.to_corner, UP+RIGHT, morty.change, "happy" ) self.wait() self.play(Write(url)) self.wait(3) for mode in "confused", "pondering", "happy": self.play(morty.change_mode, mode) self.wait(3) class Thumbnail(Scene): def construct(self): randy = Randolph() randy.set_height(5) body_copy = randy.body.copy() body_copy.set_stroke(YELLOW, width = 3) body_copy.set_fill(opacity = 0) self.add(randy) primes = [ n for n in range(2, 1000) if all(n%k != 0 for k in list(range(2, n))) ] prime_mobs = VGroup() x_spacing = 1.7 y_spacing = 1.5 n_rows = 10 n_cols = 8 for i, prime in enumerate(primes[:n_rows*n_cols]): prime_mob = Integer(prime) prime_mob.scale(1.5) x = i%n_cols y = i//n_cols prime_mob.shift(x*x_spacing*RIGHT + y*y_spacing*DOWN) prime_mobs.add(prime_mob) prime_mob.set_color({ -1 : YELLOW, 0 : RED, 1 : BLUE_C, }[chi_func(prime)]) prime_mobs.center().to_edge(UP) for i in range(7): self.add(SurroundingRectangle( VGroup(*prime_mobs[n_cols*i:n_cols*(i+1)]), fill_opacity = 0.7, fill_color = BLACK, stroke_width = 0, buff = 0, )) self.add(prime_mobs) self.add(body_copy)
videos_3b1b/_2017/crypto.py
from manim_imports_ext import * from hashlib import sha256 import binascii #force_skipping #revert_to_original_skipping_status BITCOIN_COLOR = "#f7931a" def get_cursive_name(name): result = OldTexText("\\normalfont\\calligra %s"%name) result.set_stroke(width = 0.5) return result def sha256_bit_string(message): hexdigest = sha256(message.encode('utf-8')).hexdigest() return bin(int(hexdigest, 16))[2:] def bit_string_to_mobject(bit_string): line = OldTex("0"*32) pre_result = VGroup(*[ line.copy() for row in range(8) ]) pre_result.arrange(DOWN, buff = SMALL_BUFF) result = VGroup(*it.chain(*pre_result)) result.scale(0.7) bit_string = (256 - len(bit_string))*"0" + bit_string for i, (bit, part) in enumerate(zip(bit_string, result)): if bit == "1": one = OldTex("1")[0] one.replace(part, dim_to_match = 1) result.submobjects[i] = one return result def sha256_tex_mob(message, n_forced_start_zeros = 0): true_bit_string = sha256_bit_string(message) n = n_forced_start_zeros bit_string = "0"*n + true_bit_string[n:] return bit_string_to_mobject(bit_string) class EthereumLogo(SVGMobject): CONFIG = { "file_name" : "ethereum_logo", "stroke_width" : 0, "fill_opacity" : 1, "color_chars" : "8B8B48", "height" : 0.5, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) for part, char in zip(self.submobjects, self.color_chars): part.set_color("#" + 6*char) class LitecoinLogo(SVGMobject): CONFIG = { "file_name" : "litecoin_logo", "stroke_width" : 0, "fill_opacity" : 1, "fill_color" : GREY_B, "height" : 0.5, } class TenDollarBill(VGroup): CONFIG = { "color" : GREEN, "height" : 0.5, "mark_paths_closed" : False, } def __init__(self, **kwargs): VGroup.__init__(self, **kwargs) rect = Rectangle( height = 2.61, width = 6.14, color = self.color, mark_paths_closed = False, fill_color = BLACK, fill_opacity = 1, ) rect.set_height(self.height) oval = Circle() oval.stretch_to_fit_height(0.7*self.height) oval.stretch_to_fit_width(0.4*self.height) rect.add_subpath(oval.get_points()) pi = Randolph( mode = "pondering", color = GREEN_B ) pi.set_width(oval.get_width()) pi.move_to(oval) pi.shift(0.1*pi.get_height()*DOWN) self.add(pi, rect) for vect in UP+LEFT, DOWN+RIGHT: ten = OldTex("\\$10") ten.set_height(0.25*self.height) ten.next_to(self.get_corner(vect), -vect, SMALL_BUFF) ten.set_color(GREEN_C) self.add(ten) ################## class AskQuestion(Scene): CONFIG = { "time_per_char" : 0.06, } def construct(self): strings = [ "What", "does", "it", "mean ", "to", "have ", "a", "Bitcoin?" ] question = OldTexText(*strings) question.set_color_by_tex("have", YELLOW) self.wait() for word, part in zip(strings, question): n_chars = len(word.strip()) n_spaces = len(word) - n_chars self.play( LaggedStartMap(FadeIn, part), run_time = self.time_per_char * len(word), rate_func = squish_rate_func(smooth, 0, 0.5) ) self.wait(self.time_per_char*n_spaces) self.wait(2) class ListOfAttributes(Scene): def construct(self): logo = BitcoinLogo() digital = OldTexText("Digital") government, bank = buildings = [ SVGMobject( file_name = "%s_building"%word, height = 2, fill_color = GREY_B, fill_opacity = 1, stroke_width = 0, ) for word in ("government", "bank") ] attributes = VGroup(digital, *buildings) attributes.arrange(RIGHT, buff = LARGE_BUFF) for building in buildings: building.cross = Cross(building) building.cross.set_stroke(width = 12) self.play(DrawBorderThenFill(logo)) self.play( logo.to_corner, UP+LEFT, Write(digital, run_time = 2) ) for building in buildings: self.play(FadeIn(building)) self.play(ShowCreation(building.cross)) self.wait() class UnknownAuthor(Scene): CONFIG = { "camera_config" : { "background_image" : "bitcoin_paper" } } def construct(self): rect = Rectangle(height = 0.4, width = 2.5) rect.shift(2.45*UP) question = OldTexText("Who is this?") question.next_to(rect, RIGHT, buff = 1.5) arrow = Arrow(question, rect, buff = SMALL_BUFF) VGroup(question, arrow, rect).set_color(RED_D) self.play(ShowCreation(rect)) self.play( Write(question), ShowCreation(arrow) ) self.wait() class DisectQuestion(TeacherStudentsScene): def construct(self): self.hold_up_question() self.list_topics() self.isolate_you() def hold_up_question(self): question = OldTexText( "What does it mean to", "have", "a", "Bitcoin?" ) question.set_color_by_tex("have", YELLOW) question.next_to(self.teacher, UP) question.to_edge(RIGHT, buff = LARGE_BUFF) question.save_state() question.shift(DOWN) question.set_fill(opacity = 0) self.play( self.teacher.change, "raise_right_hand", question.restore ) self.play_student_changes(*["pondering"]*3) self.wait() self.bitcoin_word = question.get_part_by_tex("Bitcoin") def list_topics(self): topics = OldTexText( "Digital signatures, ", "Proof of work, ", "Cryptographic hash functions, \\dots" ) topics.set_width(FRAME_WIDTH - LARGE_BUFF) topics.to_edge(UP) topics.set_color_by_tex("Digital", BLUE) topics.set_color_by_tex("Proof", GREEN) topics.set_color_by_tex("hash", YELLOW) for word in topics: anims = [Write(word, run_time = 1)] self.play_student_changes( *["confused"]*3, added_anims = anims, look_at = word ) def isolate_you(self): self.pi_creatures = VGroup() you = self.students[1] rect = FullScreenFadeRectangle() words = OldTexText("Invent your own") arrow = Arrow(UP, DOWN) arrow.next_to(you, UP) words.next_to(arrow, UP) self.revert_to_original_skipping_status() self.play(FadeIn(rect), Animation(you)) self.play( Write(words), ShowCreation(arrow), you.change, "erm", words ) self.play(Blink(you)) self.wait() class CryptocurrencyEquation(Scene): def construct(self): parts = OldTexText( "Ledger", "- Trust", "+ Cryptography", "= Cryptocurrency" ) VGroup(*parts[-1][1:]).set_color(YELLOW) parts.set_width(FRAME_WIDTH - LARGE_BUFF) for part in parts: self.play(FadeIn(part)) self.wait(2) class CryptocurrencyMarketCaps(ExternallyAnimatedScene): pass class ListRecentCurrencies(Scene): def construct(self): footnote = OldTexText("$^*$Listed by market cap") footnote.scale(0.5) footnote.to_corner(DOWN+RIGHT) self.add(footnote) logos = VGroup( BitcoinLogo(), EthereumLogo(), ImageMobject("ripple_logo"), LitecoinLogo(), EthereumLogo().set_color_by_gradient(GREEN_B, GREEN_D), ) for logo in logos: logo.set_height(0.75) logos.arrange(DOWN, buff = MED_LARGE_BUFF) logos.shift(LEFT) logos.to_edge(UP) names = list(map( TexText, [ "Bitcoin", "Ethereum", "Ripple", "Litecoin", "Ethereum Classic" ], )) for logo, name in zip(logos, names): name.next_to(logo, RIGHT) anims = [] if isinstance(logo, SVGMobject): anims.append(DrawBorderThenFill(logo, run_time = 1)) else: anims.append(FadeIn(logo)) anims.append(Write(name, run_time = 2)) self.play(*anims) dots = OldTex("\\vdots") dots.next_to(logos, DOWN) self.play(LaggedStartMap(FadeIn, dots, run_time = 1)) self.wait() class Hype(TeacherStudentsScene): def construct(self): self.teacher.change_mode("guilty") phrases = list(map(TexText, [ "I want some!", "I'll get rich, right?", "Buy them all!" ])) modes = ["hooray", "conniving", "surprised"] for student, phrase, mode in zip(self.students, phrases, modes): bubble = SpeechBubble() bubble.set_fill(BLACK, 1) bubble.add_content(phrase) bubble.resize_to_content() bubble.pin_to(student) bubble.add(phrase) self.play( student.change_mode, mode, FadeIn(bubble), ) self.wait(3) class NoCommentOnSpeculation(TeacherStudentsScene): def construct(self): axes = VGroup( Line(0.25*LEFT, 4*RIGHT), Line(0.25*DOWN, 3*UP), ) times = np.arange(0, 4.25, 0.25) prices = [ 0.1, 0.5, 1.75, 1.5, 2.75, 2.2, 1.3, 0.8, 1.1, 1.3, 1.2, 1.4, 1.5, 1.7, 1.2, 1.3, ] graph = VMobject() graph.set_points_as_corners([ time*RIGHT + price*UP for time, price in zip(times, prices) ]) graph.set_stroke(BLUE) group = VGroup(axes, graph) group.next_to(self.teacher, UP+LEFT) cross = Cross(group) mining_graphic = ImageMobject("bitcoin_mining_graphic") mining_graphic.set_height(2) mining_graphic.next_to(self.teacher, UP+LEFT) mining_cross = Cross(mining_graphic) mining_cross.set_stroke(RED, 8) axes.save_state() axes.shift(DOWN) axes.fade(1) self.play( self.teacher.change, "sassy", axes.restore, ) self.play(ShowCreation( graph, run_time = 2, rate_func=linear )) self.wait() self.play(ShowCreation(cross)) group.add(cross) self.play( group.shift, FRAME_WIDTH*RIGHT, self.teacher.change, "happy" ) self.wait() self.student_says( "But...what are they?", index = 0, target_mode = "confused" ) self.wait(2) self.play( FadeIn(mining_graphic), RemovePiCreatureBubble(self.students[0]), self.teacher.change, "sassy", ) self.play(ShowCreation(mining_cross)) self.wait() self.play( VGroup(mining_graphic, mining_cross).shift, FRAME_WIDTH*RIGHT ) black_words = OldTexText("Random words\\\\Blah blah") black_words.set_color(BLACK) self.teacher_thinks(black_words) self.zoom_in_on_thought_bubble() class MiningIsALotteryCopy(ExternallyAnimatedScene): pass class LedgerScene(PiCreatureScene): CONFIG = { "ledger_width" : 6, "ledger_height" : 7, "denomination" : "USD", "ledger_line_height" : 0.4, "sign_transactions" : False, "enumerate_lines" : False, "line_number_color" : YELLOW, } def setup(self): PiCreatureScene.setup(self) self.remove(self.pi_creatures) def add_ledger_and_network(self): self.add(self.get_ledger(), self.get_network()) def get_ledger(self): title = OldTexText("Ledger") rect = Rectangle( width = self.ledger_width, height = self.ledger_height ) title.next_to(rect.get_top(), DOWN) h_line = Line(rect.get_left(), rect.get_right()) h_line.scale(0.8) h_line.set_stroke(width = 2) h_line.next_to(title, DOWN) content = VGroup(h_line) self.ledger = VGroup(rect, title, content) self.ledger.content = content self.ledger.to_corner(UP+LEFT) return self.ledger def add_line_to_ledger(self, string_or_mob): if isinstance(string_or_mob, str): mob = OldTexText(string_or_mob) elif isinstance(string_or_mob, Mobject): mob = string_or_mob else: raise Exception("Invalid input") items = self.ledger.content mob.set_height(self.ledger_line_height) if self.enumerate_lines: num = OldTex(str(len(items)) + ".") num.scale(0.8) num.set_color(self.line_number_color) num.next_to(mob, LEFT, MED_SMALL_BUFF) mob.add_to_back(num) mob.next_to( items[-1], DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT ) if self.enumerate_lines and len(items) == 1: mob.shift(MED_LARGE_BUFF * LEFT) items.add(mob) return mob def add_payment_line_to_ledger(self, from_name, to_name, amount): amount_str = str(amount) if self.denomination == "USD": amount_str = "\\$" + amount_str else: amount_str += " " + self.denomination line_tex_parts = [ from_name.capitalize(), "pays" if from_name.lower() != "you" else "pay", to_name.capitalize(), amount_str, ] if self.sign_transactions: line_tex_parts.append(self.get_signature_tex()) line = OldTexText(*line_tex_parts) for name in from_name, to_name: color = self.get_color_from_name(name) line.set_color_by_tex(name.capitalize(), color) if self.sign_transactions: from_part = line.get_part_by_tex(from_name.capitalize()) line[-1].set_color(from_part.get_color()) amount_color = { "USD" : GREEN, "BTC" : YELLOW, "LD" : YELLOW, }.get(self.denomination, WHITE) line.set_color_by_tex(amount_str, amount_color) return self.add_line_to_ledger(line) def get_color_from_name(self, name): if hasattr(self, name.lower()): creature = getattr(self, name.lower()) color = creature.get_color() if np.mean(color.get_rgb()) < 0.5: color = average_color(color, color, WHITE) return color return WHITE def animate_payment_addition(self, *args, **kwargs): line = self.add_payment_line_to_ledger(*args, **kwargs) self.play(LaggedStartMap( FadeIn, VGroup(*it.chain(*line)), run_time = 1 )) def get_network(self): creatures = self.pi_creatures lines = VGroup(*[ Line( VGroup(pi1, pi1.label), VGroup(pi2, pi2.label), buff = MED_SMALL_BUFF, stroke_width = 2, ) for pi1, pi2 in it.combinations(creatures, 2) ]) labels = VGroup(*[pi.label for pi in creatures]) self.network = VGroup(creatures, labels, lines) self.network.lines = lines return self.network def create_pi_creatures(self): creatures = VGroup(*[ PiCreature(color = color, height = 1).shift(2*vect) for color, vect in zip( [BLUE_C, MAROON_D, GREY_BROWN, BLUE_E], [UP+LEFT, UP+RIGHT, DOWN+LEFT, DOWN+RIGHT], ) ]) creatures.to_edge(RIGHT) names = self.get_names() for name, creature in zip(names, creatures): setattr(self, name, creature) label = OldTexText(name.capitalize()) label.scale(0.75) label.next_to(creature, DOWN, SMALL_BUFF) creature.label = label if (creature.get_center() - creatures.get_center())[0] > 0: creature.flip() creature.look_at(creatures.get_center()) return creatures def get_names(self): return ["alice", "bob", "charlie", "you"] def get_signature_tex(self): if not hasattr(self, "nonce"): self.nonce = 0 binary = bin(hash(str(self.nonce)))[-8:] self.nonce += 1 return binary + "\\dots" def get_signature(self, color = BLUE_C): result = OldTex(self.get_signature_tex()) result.set_color(color) return result def add_ellipsis(self): last_item = self.ledger.content[-1] dots = OldTex("\\vdots") dots.next_to(last_item.get_left(), DOWN) last_item.add(dots) self.add(last_item) class LayOutPlan(LedgerScene): def construct(self): self.ask_question() self.show_ledger() self.become_skeptical() def ask_question(self): btc = BitcoinLogo() group = VGroup(btc, OldTex("= ???")) group.arrange(RIGHT) self.play( DrawBorderThenFill(btc), Write(group[1], run_time = 2) ) self.wait() self.play( group.scale, 0.7, group.next_to, ORIGIN, RIGHT, group.to_edge, UP ) def show_ledger(self): network = self.get_network() ledger = self.get_ledger() payments = [ ("Alice", "Bob", 20), ("Bob", "Charlie", 40), ("Alice", "You", 50), ] self.play(*list(map(FadeIn, [network, ledger]))) for payment in payments: new_line = self.add_payment_line_to_ledger(*payment) from_name, to_name, amount = payment from_pi = getattr(self, from_name.lower()) to_pi = getattr(self, to_name.lower()) cash = OldTex("\\$"*(amount/10)) cash.scale(0.5) cash.move_to(from_pi) cash.set_color(GREEN) self.play( cash.move_to, to_pi, to_pi.change_mode, "hooray" ) self.play( FadeOut(cash), Write(new_line, run_time = 1) ) self.wait() def become_skeptical(self): creatures = self.pi_creatures self.play(*[ ApplyMethod(pi.change_mode, "sassy") for pi in creatures ]) for k in range(3): self.play(*[ ApplyMethod( creatures[i].look_at, creatures[k*(i+1)%4] ) for i in range(4) ]) self.wait(2) class UnderlyingSystemVsUserFacing(Scene): def construct(self): underlying = OldTexText("Underlying \\\\ system") underlying.shift(DOWN).to_edge(LEFT) user_facing = OldTexText("User-facing") user_facing.next_to(underlying, UP, LARGE_BUFF, LEFT) protocol = OldTexText("Bitcoin protocol") protocol.next_to(underlying, RIGHT, MED_LARGE_BUFF) protocol.set_color(BITCOIN_COLOR) banking = OldTexText("Banking system") banking.next_to(protocol, RIGHT, MED_LARGE_BUFF) banking.set_color(GREEN) phone = SVGMobject( file_name = "phone", fill_color = WHITE, fill_opacity = 1, height = 1, stroke_width = 0, ) phone.next_to(protocol, UP, LARGE_BUFF) card = SVGMobject( file_name = "credit_card", fill_color = GREY_B, fill_opacity = 1, stroke_width = 0, height = 1 ) card.next_to(banking, UP, LARGE_BUFF) btc = BitcoinLogo() btc.next_to(phone, UP, MED_LARGE_BUFF) dollar = OldTex("\\$") dollar.set_height(1) dollar.set_color(GREEN) dollar.next_to(card, UP, MED_LARGE_BUFF) card.save_state() card.shift(2*RIGHT) card.set_fill(opacity = 0) h_line = Line(underlying.get_left(), banking.get_right()) h_line.next_to(underlying, DOWN, MED_SMALL_BUFF, LEFT) h_line2 = h_line.copy() h_line2.next_to(user_facing, DOWN, MED_LARGE_BUFF, LEFT) h_line3 = h_line.copy() h_line3.next_to(user_facing, UP, MED_LARGE_BUFF, LEFT) v_line = Line(5*UP, ORIGIN) v_line.next_to(underlying, RIGHT, MED_SMALL_BUFF) v_line.shift(1.7*UP) v_line2 = v_line.copy() v_line2.next_to(protocol, RIGHT, MED_SMALL_BUFF) v_line2.shift(1.7*UP) self.add(h_line, h_line2, h_line3, v_line, v_line2) self.add(underlying, user_facing, btc) self.play(Write(protocol)) self.wait(2) self.play( card.restore, Write(dollar) ) self.play(Write(banking)) self.wait(2) self.play(DrawBorderThenFill(phone)) self.wait(2) class FromBankToDecentralizedSystemCopy(ExternallyAnimatedScene): pass class IntroduceLedgerSystem(LedgerScene): CONFIG = { "payments" : [ ("Alice", "Bob", 20), ("Bob", "Charlie", 40), ("Charlie", "You", 30), ("You", "Alice", 10), ] } def construct(self): self.add(self.get_network()) self.exchange_money() self.add_ledger() self.tally_it_all_up() def exchange_money(self): for from_name, to_name, num in self.payments: from_pi = getattr(self, from_name.lower()) to_pi = getattr(self, to_name.lower()) cash = OldTex("\\$"*(num/10)).set_color(GREEN) cash.set_height(0.5) cash.move_to(from_pi) self.play( cash.move_to, to_pi, to_pi.change_mode, "hooray" ) self.play(FadeOut(cash)) self.wait() def add_ledger(self): ledger = self.get_ledger() self.play( Write(ledger), *[ ApplyMethod(pi.change, "pondering", ledger) for pi in self.pi_creatures ] ) for payment in self.payments: self.animate_payment_addition(*payment) self.wait(3) def tally_it_all_up(self): accounts = dict() names = "alice", "bob", "charlie", "you" for name in names: accounts[name] = 0 for from_name, to_name, amount in self.payments: accounts[from_name.lower()] -= amount accounts[to_name.lower()] += amount results = VGroup() debtors = VGroup() creditors = VGroup() for name in names: amount = accounts[name] creature = getattr(self, name) creature.cash = OldTex("\\$"*abs(amount/10)) creature.cash.next_to(creature, UP+LEFT, SMALL_BUFF) creature.cash.set_color(GREEN) if amount < 0: verb = "Owes" debtors.add(creature) else: verb = "Gets" creditors.add(creature) if name == "you": verb = verb[:-1] result = OldTexText( verb, "\\$%d"%abs(amount) ) result.set_color_by_tex("Owe", RED) result.set_color_by_tex("Get", GREEN) result.add_background_rectangle() result.scale(0.7) result.next_to(creature.label, DOWN) results.add(result) brace = Brace(VGroup(*self.ledger.content[1:]), RIGHT) tally_up = brace.get_text("Tally up") tally_up.add_background_rectangle() self.play( GrowFromCenter(brace), FadeIn(tally_up) ) self.play( LaggedStartMap(FadeIn, results), *[ ApplyMethod(pi.change, "happy") for pi in creditors ] + [ ApplyMethod(pi.change, "plain") for pi in debtors ] ) self.wait() debtor_cash, creditor_cash = [ VGroup(*it.chain(*[pi.cash for pi in group])) for group in (debtors, creditors) ] self.play(FadeIn(debtor_cash)) self.play( debtor_cash.arrange, RIGHT, SMALL_BUFF, debtor_cash.move_to, self.pi_creatures, ) self.wait() self.play(ReplacementTransform( debtor_cash, creditor_cash )) self.wait(2) class InitialProtocol(Scene): def construct(self): self.add_title() self.show_first_two_items() def add_title(self): title = OldTexText("Protocol") title.scale(1.5) title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(4) h_line.next_to(title, DOWN) self.h_line = h_line self.title = title self.add(title, h_line) def show_first_two_items(self): items = VGroup(*list(map(self.get_new_item, [ "Anyone can add lines to the Ledger", "Settle up with real money each month" ]))) for item in items: self.wait() self.play(LaggedStartMap(FadeIn, item)) self.wait(2) def get_new_item(self, item_string): item = OldTexText("$\\cdot$ %s"%item_string) if not hasattr(self, "items"): self.items = VGroup(item) self.items.next_to(self.h_line, DOWN, MED_LARGE_BUFF) else: item.next_to(self.items, DOWN, MED_LARGE_BUFF, LEFT) self.items.add(item) return item class AddFraudulentLine(LedgerScene): def construct(self): self.add_ledger_and_network() self.anyone_can_add_a_line() self.bob_adds_lines() self.alice_reacts() def anyone_can_add_a_line(self): words = OldTexText("Anyone can add a line") words.to_corner(UP+RIGHT) words.set_color(YELLOW) arrow = Arrow( words.get_left(), self.ledger.content.get_center() + DOWN, ) self.play(Write(words, run_time = 1)) self.play(ShowCreation(arrow)) self.wait() self.play( FadeOut(words), FadeOut(arrow), FocusOn(self.bob), ) def bob_adds_lines(self): line = self.add_payment_line_to_ledger("Alice", "Bob", 100) line.save_state() line.scale(0.001) line.move_to(self.bob) self.play(self.bob.change, "conniving") self.play(line.restore) self.wait() def alice_reacts(self): bubble = SpeechBubble( height = 1.5, width = 2, direction = LEFT, ) bubble.next_to(self.alice, UP+RIGHT, buff = 0) bubble.write("Hey!") self.play( Animation(self.bob.pupils), self.alice.change, "angry", FadeIn(bubble), Write(bubble.content, run_time = 1) ) self.wait(3) self.play( FadeOut(bubble), FadeOut(bubble.content), self.alice.change_mode, "pondering" ) class AnnounceDigitalSignatures(TeacherStudentsScene): def construct(self): words = OldTexText("Digital \\\\ signatures!") words.scale(1.5) self.teacher_says( words, target_mode = "hooray", ) self.play_student_changes(*["hooray"]*3) self.wait(2) class IntroduceSignatures(LedgerScene): CONFIG = { "payments" : [ ("Alice", "Bob", 100), ("Charlie", "You", 20), ("Bob", "You", 30), ], } def construct(self): self.add_ledger_and_network() self.add_transactions() self.add_signatures() def add_transactions(self): transactions = VGroup(*[ self.add_payment_line_to_ledger(*payment) for payment in self.payments ]) self.play(LaggedStartMap(FadeIn, transactions)) self.wait() def add_signatures(self): signatures = VGroup(*[ get_cursive_name(payments[0].capitalize()) for payments in self.payments ]) for signature, transaction in zip(signatures, self.ledger.content[1:]): signature.next_to(transaction, RIGHT) signature.set_color(transaction[0].get_color()) self.play(Write(signature, run_time = 2)) transaction.add(signature) self.wait(2) rect = SurroundingRectangle(self.ledger.content[1]) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.wait() self.play(Indicate(signatures[0])) self.wait() class AskHowDigitalSignaturesArePossible(TeacherStudentsScene): def construct(self): signature = get_cursive_name("Alice") signature.scale(1.5) signature.set_color(BLUE_C) signature.to_corner(UP+LEFT) signature_copy = signature.copy() signature_copy.shift(3*RIGHT) bits = OldTex("01100001") bits.next_to(signature, DOWN) bits.shift_onto_screen() bits_copy = bits.copy() bits_copy.next_to(signature_copy, DOWN) self.student_says( "Couldn't you just \\\\ copy the signature?", target_mode = "confused", run_time = 1 ) self.play_student_changes("pondering", "confused", "erm") self.play(Write(signature)) self.play(LaggedStartMap(FadeIn, bits, run_time = 1)) self.wait() self.play(ReplacementTransform( bits.copy(), bits_copy, path_arc = np.pi/2 )) self.play(Write(signature_copy)) self.wait(3) class DescribeDigitalSignatures(LedgerScene): CONFIG = { "public_color" : GREEN, "private_color" : RED, "signature_color" : BLUE_C, } def construct(self): self.reorganize_pi_creatures() self.generate_key_pairs() self.keep_secret_key_secret() self.show_handwritten_signatures() self.show_digital_signatures() self.show_signing_functions() def reorganize_pi_creatures(self): self.pi_creatures.remove(self.you) creature_groups = VGroup(*[ VGroup(pi, pi.label).scale(1.7) for pi in self.pi_creatures ]) creature_groups.arrange(RIGHT, buff = 2) creature_groups.to_edge(DOWN) self.add(creature_groups) for pi in self.pi_creatures: if pi.is_flipped(): pi.flip() def generate_key_pairs(self): title = OldTexText("Private", "key /", "Public", "key") title.to_edge(UP) private, public = list(map(title.get_part_by_tex, ["Private", "Public"])) private.set_color(self.private_color) public.set_color(self.public_color) secret = OldTexText("Secret") secret.move_to(private, RIGHT) secret.set_color(self.private_color) names = self.get_names()[:-1] public_key_strings = [ bin(256+ord(name[0].capitalize()))[3:] for name in names ] private_key_strings = [ bin(hash(name))[2:10] for name in names ] public_keys, private_keys = [ VGroup(*[ OldTexText(key_name+":"," $%s\\dots$"%key) for key in keys ]) for key_name, keys in [ ("pk", public_key_strings), ("sk", private_key_strings) ] ] key_pairs = [ VGroup(*pair).arrange(DOWN, aligned_edge = LEFT) for pair in zip(public_keys, private_keys) ] for key_pair, pi in zip(key_pairs, self.pi_creatures): key_pair.next_to(pi, UP, MED_LARGE_BUFF) for key in key_pair: key.set_color_by_tex("sk", self.private_color) key.set_color_by_tex("pk", self.public_color) self.play(Write(title, run_time = 2)) self.play(ReplacementTransform( VGroup(VGroup(public.copy())), public_keys )) self.play(ReplacementTransform( VGroup(VGroup(private.copy())), private_keys )) self.wait() self.play(private.shift, DOWN) self.play(FadeIn(secret)) self.play(FadeOut(private)) self.wait() title.remove(private) title.add(secret) self.title = title self.private_keys = private_keys self.public_keys = public_keys def keep_secret_key_secret(self): keys = self.private_keys rects = VGroup(*list(map(SurroundingRectangle, keys))) rects.set_color(self.private_color) lock = SVGMobject( file_name = "lock", height = rects.get_height(), fill_color = GREY_B, fill_opacity = 1, stroke_width = 0, ) locks = VGroup(*[ lock.copy().next_to(rect, LEFT, SMALL_BUFF) for rect in rects ]) self.play(ShowCreation(rects)) self.play(LaggedStartMap(DrawBorderThenFill, locks)) self.wait() self.private_key_rects = rects self.locks = locks def show_handwritten_signatures(self): lines = VGroup(*[Line(LEFT, RIGHT) for x in range(5)]) lines.arrange(DOWN) last_line = lines[-1] last_line.scale(0.7, about_point = last_line.get_left()) signature_line = lines[0].copy() signature_line.set_stroke(width = 2) signature_line.next_to(lines, DOWN, LARGE_BUFF) ex = OldTex("\\times") ex.scale(0.7) ex.next_to(signature_line, UP, SMALL_BUFF, LEFT) lines.add(ex, signature_line) rect = SurroundingRectangle( lines, color = GREY_B, buff = MED_SMALL_BUFF ) document = VGroup(rect, lines) documents = VGroup(*[ document.copy() for x in range(2) ]) documents.arrange(RIGHT, buff = MED_LARGE_BUFF) documents.to_corner(UP+LEFT) signatures = VGroup() for document in documents: signature = get_cursive_name("Alice") signature.set_color(self.signature_color) line = document[1][-1] signature.next_to(line, UP, SMALL_BUFF) signatures.add(signature) self.play( FadeOut(self.title), LaggedStartMap(FadeIn, documents, run_time = 1) ) self.play(Write(signatures)) self.wait() self.signatures = signatures self.documents = documents def show_digital_signatures(self): rect = SurroundingRectangle(VGroup( self.public_keys[0], self.private_key_rects[0], self.locks[0] )) digital_signatures = VGroup() for i, signature in enumerate(self.signatures): bits = bin(hash(str(i)))[-8:] digital_signature = OldTex(bits + "\\dots") digital_signature.scale(0.7) digital_signature.set_color(signature.get_color()) digital_signature.move_to(signature, DOWN) digital_signatures.add(digital_signature) arrows = VGroup(*[ Arrow( rect.get_corner(UP), sig.get_bottom(), tip_length = 0.15, color = WHITE ) for sig in digital_signatures ]) words = VGroup(*list(map( TexText, ["Different messages", "Completely different signatures"] ))) words.arrange(DOWN, aligned_edge = LEFT) words.scale(1.3) words.next_to(self.documents, RIGHT) self.play(FadeIn(rect)) self.play(*list(map(ShowCreation, arrows))) self.play(Transform(self.signatures, digital_signatures)) self.play(*[ ApplyMethod(pi.change, "pondering", digital_signatures) for pi in self.pi_creatures ]) for word in words: self.play(FadeIn(word)) self.wait() self.play(FadeOut(words)) def show_signing_functions(self): sign = OldTexText( "Sign(", "Message", ", ", "sk", ") = ", "Signature", arg_separator = "" ) sign.to_corner(UP+RIGHT) verify = OldTexText( "Verify(", "Message", ", ", "Signature", ", ", "pk", ") = ", "T/F", arg_separator = "" ) for mob in sign, verify: mob.set_color_by_tex("sk", self.private_color) mob.set_color_by_tex("pk", self.public_color) mob.set_color_by_tex( "Signature", self.signature_color, ) for name in "Message", "sk", "Signature", "pk": part = mob.get_part_by_tex(name) if part is not None: setattr(mob, name.lower(), part) verify.next_to(sign, DOWN, MED_LARGE_BUFF, LEFT) VGroup(sign, verify).to_corner(UP+RIGHT) private_key = self.private_key_rects[0] public_key = self.public_keys[0] message = self.documents[0] signature = self.signatures[0] self.play(*[ FadeIn(part) for part in sign if part not in [sign.message, sign.sk, sign.signature] ]) self.play(ReplacementTransform( message.copy(), VGroup(sign.message) )) self.wait() self.play(ReplacementTransform( private_key.copy(), sign.sk )) self.wait() self.play(ReplacementTransform( VGroup(sign.sk, sign.message).copy(), VGroup(sign.signature) )) self.wait() self.play(Indicate(sign.sk)) self.wait() self.play(Indicate(sign.message)) self.wait() self.play(*[ FadeIn(part) for part in verify if part not in [ verify.message, verify.signature, verify.pk, verify[-1] ] ]) self.wait() self.play( ReplacementTransform( sign.message.copy(), verify.message ), ReplacementTransform( sign.signature.copy(), verify.signature ) ) self.wait() self.play(ReplacementTransform( public_key.copy(), VGroup(verify.pk) )) self.wait() self.play(Write(verify[-1])) self.wait() class TryGuessingDigitalSignature(Scene): def construct(self): verify = OldTexText( "Verify(", "Message", ", ", "256 bit Signature", ", ", "pk", ")", arg_separator = "" ) verify.scale(1.5) verify.shift(DOWN) signature = verify.get_part_by_tex("Signature") verify.set_color_by_tex("Signature", BLUE) verify.set_color_by_tex("pk", GREEN) brace = Brace(signature, UP) zeros_row = OldTex("0"*32) zeros = VGroup(*[zeros_row.copy() for x in range(8)]) zeros.arrange(DOWN, buff = SMALL_BUFF) zeros.next_to(brace, UP) self.add(verify) self.play( GrowFromCenter(brace), FadeIn( zeros, lag_ratio = 0.5, run_time = 3 ) ) self.wait() for n in range(2**10): last_row = zeros[-1] binary = bin(n)[2:] for i, bit_str in enumerate(reversed(binary)): curr_bit = last_row.submobjects[-i-1] new_bit = OldTex(bit_str) new_bit.replace(curr_bit, dim_to_match = 1) last_row.submobjects[-i-1] = new_bit self.remove(curr_bit) self.add(last_row) self.wait(1./30) class WriteTwoTo256PossibleSignatures(Scene): def construct(self): words = OldTexText( "$2^{256}$", "possible\\\\", "signatures" ) words.scale(2) words.set_color_by_tex("256", BLUE) self.play(Write(words)) self.wait() class SupplementVideoWrapper(Scene): def construct(self): title = OldTexText("How secure is 256 bit security?") title.scale(1.5) title.to_edge(UP) rect = ScreenRectangle(height = 6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class FeelConfidentWithVerification(PiCreatureScene): def construct(self): self.show_verification() self.show_secret_key() def show_verification(self): verify = OldTexText( "Verify(", "Message", ", ", "256 bit Signature", ", ", "pk", ")", arg_separator = "" ) signature_word = verify.get_part_by_tex("Signature") verify.set_color_by_tex("Signature", BLUE) verify.set_color_by_tex("pk", GREEN) brace = Brace(signature_word, UP) signature = sha256_tex_mob("Signature") signature.next_to(brace, UP) signature.set_color(BLUE_C) rhs = OldTexText("=", "True") rhs.set_color_by_tex("True", YELLOW) rhs.next_to(verify, RIGHT) pk = verify.get_part_by_tex("pk") sk = OldTexText("sk") sk.set_color(RED) arrow = OldTex("\\Updownarrow") arrow.next_to(pk, DOWN) sk.next_to(arrow, DOWN) sk_group = VGroup(arrow, sk) lock_box = SurroundingRectangle(sk_group, buff = SMALL_BUFF) lock_box.set_color(RED) lock = SVGMobject( file_name = "lock", fill_color = GREY_B, height = 0.5, ) lock.next_to(lock_box, LEFT, SMALL_BUFF) self.add(verify) self.play( GrowFromCenter(brace), Write(signature), self.pi_creature.change, "pondering" ) self.play(ReplacementTransform( verify.copy(), rhs )) self.wait() self.play(self.pi_creature.change, "happy") self.play(Write(sk_group)) self.play( ShowCreation(lock_box), DrawBorderThenFill(lock, run_time = 1) ) self.wait(2) def show_secret_key(self): pass ##### def create_pi_creature(self): return Randolph().to_corner(DOWN+LEFT) class IncludeTransactionNumber(LedgerScene): CONFIG = { "ledger_width" : 7, } def construct(self): self.add_ledger_and_network() self.add_signed_payment() self.fail_to_sign_new_transaction() self.copy_payment_many_times() self.add_ids() def add_signed_payment(self): line = self.add_payment_line_to_ledger( "Alice", "Bob", 100 ) signature = self.get_signature() signature.scale(0.7) signature.next_to(line, RIGHT) signature.save_state() signature.scale(0.1) signature.move_to(self.alice) self.play(Write(line, run_time = 1)) self.play( signature.restore, self.alice.change, "raise_left_hand" ) self.wait() self.play(self.alice.change, "happy") self.wait() line.add(signature) def fail_to_sign_new_transaction(self): payment = self.add_payment_line_to_ledger("Alice", "Bob", 3000) q_marks = OldTex("???") q_marks.next_to(payment, RIGHT) cross = Cross(payment) payment.save_state() payment.move_to(self.bob.get_corner(UP+LEFT)) payment.set_fill(opacity = 0) self.play( self.bob.change, "raise_right_hand", payment.restore, ) self.play( self.bob.change, "confused", Write(q_marks) ) self.play(ShowCreation(cross)) self.wait() self.play(*list(map(FadeOut, [payment, cross, q_marks]))) self.ledger.content.remove(payment) def copy_payment_many_times(self): line = self.ledger.content[-1] copies = VGroup(*[line.copy() for x in range(4)]) copies.arrange(DOWN, buff = MED_SMALL_BUFF) copies.next_to(line, DOWN, buff = MED_SMALL_BUFF) self.play( LaggedStartMap(FadeIn, copies, run_time = 3), self.bob.change, "conniving", ) self.play(self.alice.change, "angry") self.wait() self.copies = copies def add_ids(self): top_line = self.ledger.content[-1] lines = VGroup(top_line, *self.copies) numbers = VGroup() old_signatures = VGroup() new_signatures = VGroup() colors = list(Color(BLUE_B).range_to(GREEN_B, len(lines))) for i, line in enumerate(lines): number = OldTex(str(i)) number.scale(0.7) number.set_color(YELLOW) number.next_to(line, LEFT) numbers.add(number) line.add_to_back(number) old_signature = line[-1] new_signature = self.get_signature() new_signature.replace(old_signature) new_signature.set_color(colors[i]) old_signatures.add(old_signature) new_signatures.add(VGroup(new_signature)) line.remove(old_signature) self.play( Write(numbers), self.alice.change, "thinking" ) self.play(FadeOut(old_signatures)) self.play(ReplacementTransform( lines.copy(), new_signatures, lag_ratio = 0.5, run_time = 2, )) self.play(self.bob.change, "erm") self.wait(2) class ProtocolWithDigitalSignatures(InitialProtocol): def construct(self): self.force_skipping() InitialProtocol.construct(self) self.revert_to_original_skipping_status() rect = SurroundingRectangle(self.items[-1]) rect.set_color(RED) new_item = self.get_new_item( "Only signed transactions are valid" ) new_item.set_color(YELLOW) self.play(Write(new_item)) self.wait() self.play(ShowCreation(rect)) self.wait() class SignedLedgerScene(LedgerScene): CONFIG = { "sign_transactions" : True, "enumerate_lines" : True, "ledger_width" : 7.5, } class CharlieRacksUpDebt(SignedLedgerScene): CONFIG = { "payments" : [ ("Charlie", "Alice", 100), ("Charlie", "Bob", 200), ("Charlie", "You", 800), ("Charlie", "Bob", 600), ("Charlie", "Alice", 900), ], } def construct(self): self.add_ledger_and_network() lines = VGroup(*[ self.add_payment_line_to_ledger(*payment) for payment in self.payments ]) self.play(LaggedStartMap( FadeIn, lines, run_time = 3, lag_ratio = 0.25 )) self.play(*[ ApplyMethod(pi.change, "sassy", self.charlie) for pi in self.pi_creatures if pi is not self.charlie ]) self.play( self.charlie.shift, FRAME_X_RADIUS*RIGHT, rate_func = running_start ) self.play(*[ ApplyMethod(pi.change, "angry", self.charlie) for pi in self.get_pi_creatures() ]) self.wait() class CharlieFeelsGuilty(Scene): def construct(self): charlie = PiCreature(color = GREY_BROWN) charlie.scale(2) self.play(FadeIn(charlie)) self.play(charlie.change, "sad") for x in range(2): self.play(Blink(charlie)) self.wait(2) class ThinkAboutSettlingUp(Scene): def construct(self): randy = Randolph() randy.to_corner(DOWN+LEFT) self.play(PiCreatureBubbleIntroduction( randy, "You don't \\emph{actually} \\\\" + \ "need to settle up $\\dots$", bubble_type = ThoughtBubble, target_mode = "thinking" )) self.play(Blink(randy)) self.wait() class DontAllowOverdrawing(InitialProtocol): def construct(self): self.add_title() lines = list(map(self.get_new_item, [ "Anyone can add lines to the Ledger \\,", "Only signed transactions are valid \\,", "No overspending" ])) lines[2].set_color(YELLOW) self.add(*lines[:2]) self.wait() self.play(Write(lines[2])) self.wait() class LedgerWithInitialBuyIn(SignedLedgerScene): def construct(self): self.add_ledger_and_network() self.everyone_buys_in() self.add_initial_lines() self.add_charlie_payments() self.point_out_charlie_is_broke() self.running_balance() def everyone_buys_in(self): center = self.network.get_center() moneys = VGroup(*[ OldTex("\\$100") for pi in self.pi_creatures ]) moneys.set_color(GREEN) for pi, money in zip(reversed(self.pi_creatures), moneys): vect = pi.get_center() - center money.next_to(center, vect, SMALL_BUFF) money.add_background_rectangle() money.save_state() money.scale(0.01) corner = pi.get_corner(UP + np.sign(vect[0])*LEFT) money.move_to(corner) self.play( LaggedStartMap( ApplyMethod, moneys, lambda m : (m.restore,) ), self.charlie.change, "raise_right_hand", self.you.change, "raise_right_hand", ) self.network.add(moneys) def add_initial_lines(self): lines = VGroup() for name in self.get_names(): new_line = OldTexText( name.capitalize(), "get" if name == "you" else "gets", "\\$100" ) new_line.set_color_by_tex( name.capitalize(), self.get_color_from_name(name) ) new_line.set_color_by_tex("100", GREEN) self.add_line_to_ledger(new_line) lines.add(new_line) line = Line(LEFT, RIGHT) line.set_width(self.ledger.get_width()) line.scale(0.9) line.next_to(lines[-1], DOWN, SMALL_BUFF, LEFT) line.set_stroke(width = 1) lines[-1].add(line) self.play( LaggedStartMap(FadeIn, lines), *[ ApplyMethod(pi.change, "thinking", self.ledger) for pi in self.pi_creatures ] ) self.wait() def add_charlie_payments(self): payments = [ ("Charlie", "Alice", 50), ("Charlie", "Bob", 50), ("Charlie", "You", 20), ] new_lines = VGroup(*[ self.add_payment_line_to_ledger(*payment) for payment in payments ]) for line in new_lines: self.play(Write(line, run_time = 1)) self.wait() def point_out_charlie_is_broke(self): charlie_lines = VGroup(*[ VGroup(*self.ledger.content[i][1:5]) for i in (3, 5, 6, 7) ]) rects = VGroup(*[ SurroundingRectangle(line) for line in charlie_lines ]) rects.set_color(YELLOW) rects.set_stroke(width = 2) last_rect = rects[-1] last_rect.set_stroke(RED, 4) rects.remove(last_rect) invalid = OldTexText("Invalid") invalid.set_color(RED) invalid.next_to(last_rect, DOWN) self.play(ShowCreation(rects)) self.play(self.charlie.change_mode, "guilty") self.wait() self.play(ShowCreation(last_rect)) self.play(*[ ApplyMethod(pi.change, "sassy", self.charlie) for pi in self.pi_creatures if pi is not self.charlie ]) self.play(Write(invalid)) self.wait(2) self.play(*list(map(FadeOut, [rects, last_rect, invalid]))) def running_balance(self): charlie_lines = VGroup(*[ VGroup(*self.ledger.content[i][1:5]) for i in (3, 5, 6, 7) ]) signatures = VGroup(*[ self.ledger.content[i][5] for i in (5, 6, 7) ]) rect = Rectangle(color = WHITE) rect.set_fill(BLACK, 0.8) rect.stretch_to_fit_height(self.ledger.get_height() - 2*MED_SMALL_BUFF) title = OldTexText("Charlie's running \\\\ balance") rect.stretch_to_fit_width(title.get_width() + 2*MED_SMALL_BUFF) rect.move_to(self.ledger.get_right()) title.next_to(rect.get_top(), DOWN) balance = VGroup(rect, title) lines = VGroup(*list(map(TexText, [ "\\$100", "\\$50", "\\$0", "Overdrawn" ]))) lines.set_color(GREEN) lines[-1].set_color(RED) arrows = VGroup() for line, c_line in zip(lines, charlie_lines): line.next_to(rect.get_left(), RIGHT, LARGE_BUFF) line.shift( (c_line.get_center() - line.get_center())[1]*UP ) arrow = Arrow(c_line, line) arrows.add(arrow) self.pi_creatures.remove(self.alice, self.charlie) self.play( FadeOut(signatures), FadeIn(balance) ) self.play( LaggedStartMap(FadeIn, lines, run_time = 3), LaggedStartMap(ShowCreation, arrows, run_time = 3), ) self.wait() class RemovedConnectionBetweenLedgerAndCash(TeacherStudentsScene): def construct(self): ledger = Rectangle( height = 2, width = 1.5, color = WHITE ) ledger_name = OldTexText("Ledger") ledger_name.set_width(ledger.get_width() - MED_SMALL_BUFF) ledger_name.next_to(ledger.get_top(), DOWN) ledger.add(ledger_name) arrow = OldTex("\\leftrightarrow") cash = OldTex("\\$\\$\\$") cash.set_color(GREEN) arrow.next_to(ledger, RIGHT) cash.next_to(arrow, RIGHT) group = VGroup(ledger, arrow, cash) group.next_to(self.teacher, UP+LEFT) self.add(group) self.play( Animation(group), self.teacher.change, "raise_right_hand" ) self.play( arrow.shift, 2*UP, arrow.set_fill, None, 0 ) self.play( ledger.shift, LEFT, cash.shift, RIGHT ) self.play_student_changes( *["pondering"]*3, look_at = ledger, added_anims = [self.teacher.change, "happy"] ) self.wait(3) class RenameToLedgerDollars(LedgerScene): CONFIG = { "payments" : [ ("Alice", "Bob", 20), ("Charlie", "You", 80), ("Bob", "Charlie", 60), ("Bob", "Alice", 30), ("Alice", "You", 100), ], "enumerate_lines" : True, "line_number_color" : WHITE, } def construct(self): self.add(self.get_ledger()) self.add_bubble() self.jump_in_to_middle() self.add_payments_in_dollars() self.rewrite_as_ledger_dollars() def add_bubble(self): randy = self.pi_creature bubble = SpeechBubble(direction = RIGHT) bubble.write("Who needs \\\\ cash?") bubble.resize_to_content() bubble.add(bubble.content) bubble.pin_to(randy) bubble.shift(MED_LARGE_BUFF*RIGHT) self.bubble = bubble self.add(randy, bubble) self.add_foreground_mobject(bubble) def jump_in_to_middle(self): h_line = self.ledger.content[0] dots = OldTex("\\vdots") dots.next_to(h_line.get_left(), DOWN) h_line.add(dots) self.add(h_line) point = VectorizedPoint(h_line.get_corner(DOWN+LEFT)) point.shift(MED_SMALL_BUFF*LEFT) self.ledger.content.add(*[ point.copy() for x in range(103) ]) def add_payments_in_dollars(self): lines = VGroup(*[ self.add_payment_line_to_ledger(*payment) for payment in self.payments ]) self.play(LaggedStartMap( FadeIn, lines, run_time = 4, lag_ratio = 0.3 )) self.wait() self.payment_lines = lines def rewrite_as_ledger_dollars(self): curr_lines = self.payment_lines amounts = VGroup(*[line[4] for line in curr_lines]) amounts.target = VGroup() for amount in amounts: dollar_sign = amount[0] amount.remove(dollar_sign) amount.add(dollar_sign) tex_string = amount.get_tex() ld = OldTexText(tex_string[2:] + " LD") ld.set_color(YELLOW) ld.scale(0.8) ld.move_to(amount, LEFT) amounts.target.add(ld) ledger_dollars = OldTexText("Ledger Dollars \\\\ ``LD'' ") ledger_dollars.set_color(YELLOW) ledger_dollars.next_to(self.ledger, RIGHT) self.play( Write(ledger_dollars), FadeOut(self.bubble), self.pi_creature.change, "thinking", ledger_dollars ) self.play(MoveToTarget(amounts)) self.wait(2) ### def create_pi_creatures(self): LedgerScene.create_pi_creatures(self) randy = Randolph(mode = "shruggie").flip() randy.to_corner(DOWN+RIGHT) return VGroup(randy) class ExchangeCashForLedgerDollars(LedgerScene): CONFIG = { "sign_transactions" : True, "denomination" : "LD", "ledger_width" : 7.5, "ledger_height" : 6, } def construct(self): self.add_ledger_and_network() self.add_ellipsis() self.add_title() self.give_ten_dollar_bill() self.add_bob_pays_alice_line() self.everyone_thinks() def add_title(self): self.ledger.shift(DOWN) title = OldTexText( "Exchange", "LD", "for", "\\$\\$\\$" ) title.set_color_by_tex("LD", YELLOW) title.set_color_by_tex("\\$", GREEN) title.scale(1.3) title.to_edge(UP).shift(LEFT) self.play(Write(title)) self.wait() def give_ten_dollar_bill(self): bill = TenDollarBill() bill.next_to(self.alice.get_corner(UP+RIGHT), UP) bill.generate_target() bill.target.next_to(self.bob.get_corner(UP+LEFT), UP) arrow = Arrow(bill, bill.target, color = GREEN) small_bill = bill.copy() small_bill.scale(0.01, about_point = bill.get_bottom()) self.play( ReplacementTransform(small_bill, bill), self.alice.change, "raise_right_hand" ) self.play(ShowCreation(arrow)) self.play(MoveToTarget(bill)) self.play(self.bob.change, "happy", bill) self.wait() def add_bob_pays_alice_line(self): line = self.add_payment_line_to_ledger( "Bob", "Alice", 10 ) line.save_state() line.scale(0.01) line.move_to(self.bob.get_corner(UP+LEFT)) self.play(self.bob.change, "raise_right_hand", line) self.play(line.restore, run_time = 2) self.wait() def everyone_thinks(self): self.play(*[ ApplyMethod(pi.change, "thinking", self.ledger) for pi in self.pi_creatures ]) self.wait(4) class BitcoinIsALedger(Scene): def construct(self): self.add_btc_to_ledger() self.add_currency_to_tx_history() def add_btc_to_ledger(self): logo = BitcoinLogo() ledger = self.get_ledger() arrow = OldTex("\\Leftrightarrow") group = VGroup(logo, arrow, ledger) group.arrange(RIGHT) self.play(DrawBorderThenFill(logo)) self.wait() self.play( Write(arrow), Write(ledger) ) self.wait() self.btc_to_ledger = group def add_currency_to_tx_history(self): equation = OldTexText( "Currency", "=", "Transaction history" ) equation.set_color_by_tex("Currency", BITCOIN_COLOR) equation.shift( self.btc_to_ledger[1].get_center() - \ equation[1].get_center() + 2*UP ) for part in reversed(equation): self.play(FadeIn(part)) self.wait() def get_ledger(self): rect = Rectangle(height = 2, width = 1.5) title = OldTexText("Ledger") title.set_width(0.8*rect.get_width()) title.next_to(rect.get_top(), DOWN, SMALL_BUFF) lines = VGroup(*[ Line(LEFT, RIGHT) for x in range(8) ]) lines.arrange(DOWN, buff = SMALL_BUFF) lines.stretch_to_fit_width(title.get_width()) lines.next_to(title, DOWN) return VGroup(rect, title, lines) class BigDifferenceBetweenLDAndCryptocurrencies(Scene): def construct(self): ld = OldTexText("LD").scale(1.5).set_color(YELLOW) btc = BitcoinLogo() eth = EthereumLogo() ltc = LitecoinLogo() logos = VGroup(ltc, eth, ld, btc) cryptos = VGroup(btc, eth, ltc) for logo in cryptos: logo.set_height(1) vects = compass_directions(4, DOWN+LEFT) for logo, vect in zip(logos, vects): logo.move_to(0.75*vect) centralized = OldTexText("Centralized") decentralized = OldTexText("Decentralized") words = VGroup(centralized, decentralized) words.scale(1.5) words.to_edge(UP) for word, vect in zip(words, [RIGHT, LEFT]): word.shift(FRAME_X_RADIUS*vect/2) self.add(logos) self.wait() self.play( cryptos.next_to, decentralized, DOWN, LARGE_BUFF, ld.next_to, centralized, DOWN, LARGE_BUFF, ) self.play(*list(map(Write, words))) self.wait(2) class DistributedLedgerScene(LedgerScene): def get_large_network(self): network = self.get_network() network.set_height(FRAME_HEIGHT - LARGE_BUFF) network.center() for pi in self.pi_creatures: pi.label.scale(0.8, about_point = pi.get_bottom()) return network def get_distributed_ledgers(self): ledger = self.get_ledger() title = ledger[1] h_line = ledger.content title.set_width(0.7*ledger.get_width()) title.next_to(ledger.get_top(), DOWN, MED_LARGE_BUFF) h_line.next_to(title, DOWN) added_lines = VGroup(*[h_line.copy() for x in range(5)]) added_lines.arrange(DOWN, buff = MED_LARGE_BUFF) added_lines.next_to(h_line, DOWN, MED_LARGE_BUFF) ledger.content.add(added_lines) ledgers = VGroup() for pi in self.pi_creatures: pi.ledger = ledger.copy() pi.ledger.set_height(pi.get_height()) pi.ledger[0].set_color(pi.get_color()) vect = pi.get_center()-self.pi_creatures.get_center() x_vect = vect[0]*RIGHT pi.ledger.next_to(pi, x_vect, SMALL_BUFF) ledgers.add(pi.ledger) return ledgers def add_large_network_and_distributed_ledger(self): self.add(self.get_large_network()) self.add(self.get_distributed_ledgers()) class TransitionToDistributedLedger(DistributedLedgerScene): CONFIG = { "sign_transactions" : True, "ledger_width" : 7.5, "ledger_height" : 6, "enumerate_lines" : True, "denomination" : "LD", "line_number_color" : WHITE, "ledger_line_height" : 0.35, } def construct(self): self.add_ledger_and_network() self.ledger.shift(DOWN) self.add_ellipsis() self.ask_where_is_ledger() self.add_various_payements() self.ask_who_controls_ledger() self.distribute_ledger() self.broadcast_transaction() self.ask_about_ledger_consistency() def ask_where_is_ledger(self): question = OldTexText("Where", "is", "this?!") question.set_color(RED) question.scale(1.5) question.next_to(self.ledger, UP) self.play(Write(question)) self.wait() self.question = question def add_various_payements(self): payments = VGroup(*[ self.add_payment_line_to_ledger(*payment) for payment in [ ("Alice", "Bob", 20), ("Charlie", "You", 100), ("You", "Alice", 50), ("Bob", "You", 30), ] ]) for payment in payments: self.play(LaggedStartMap(FadeIn, payment, run_time = 1)) self.wait() def ask_who_controls_ledger(self): new_question = OldTexText("Who", "controls", "this?!") new_question.scale(1.3) new_question.move_to(self.question) new_question.set_color(RED) self.play(Transform(self.question, new_question)) self.play(*[ ApplyMethod(pi.change, "confused", new_question) for pi in self.pi_creatures ]) self.wait(2) def distribute_ledger(self): ledger = self.ledger self.ledger_width = 6 self.ledger_height = 7 distribute_ledgers = self.get_distributed_ledgers() group = VGroup(self.network, distribute_ledgers) self.play(FadeOut(self.question)) self.play(ReplacementTransform( VGroup(ledger), distribute_ledgers )) self.play(*[ ApplyMethod(pi.change, "pondering", pi.ledger) for pi in self.pi_creatures ]) self.play( group.set_height, FRAME_HEIGHT - 2, group.center ) self.wait(2) def broadcast_transaction(self): payment = OldTexText( "Alice", "pays", "Bob", "100 LD" ) payment.set_color_by_tex("Alice", self.alice.get_color()) payment.set_color_by_tex("Bob", self.bob.get_color()) payment.set_color_by_tex("LD", YELLOW) payment.scale(0.75) payment.add_background_rectangle() payment_copies = VGroup(*[ payment.copy().next_to(pi, UP) for pi in self.pi_creatures ]) payment = payment_copies[0] self.play( self.alice.change, "raise_right_hand", payment, Write(payment, run_time = 2) ) self.wait() self.play( ReplacementTransform( VGroup(payment), payment_copies, run_time = 3, rate_func = squish_rate_func(smooth, 0.5, 1) ), Broadcast(self.alice.get_corner(UP+RIGHT)), self.alice.change, "happy" ) self.wait() pairs = list(zip(payment_copies, self.pi_creatures)) Scene.play(self, *it.chain(*[ [ pi.look_at, pi.ledger[-1], line.scale, 0.2, line.next_to, pi.ledger[-1], DOWN, SMALL_BUFF, ] for line, pi in pairs ])) self.wait(3) for line, pi in pairs: pi.ledger.add(line) def ask_about_ledger_consistency(self): ledgers = VGroup(*[ pi.ledger for pi in self.pi_creatures ]) self.play( FadeOut(self.network), ledgers.scale, 2, ledgers.arrange, RIGHT, ledgers.space_out_submobjects, ) question = OldTexText("Are these the same?") question.scale(1.5) question.to_edge(UP) arrows = VGroup(*[ Arrow(question.get_bottom(), ledger.get_top()) for ledger in ledgers ]) self.play(*list(map(ShowCreation, arrows))) self.play(Write(question)) self.wait() class BobDoubtsBroadcastTransaction(DistributedLedgerScene): def construct(self): self.setup_bob_and_charlie() self.bob_receives_transaction() self.bob_tries_to_pay_charlie() def setup_bob_and_charlie(self): bob, charlie = self.bob, self.charlie self.pi_creatures = VGroup(bob, charlie) for pi in self.pi_creatures: pi.flip() self.pi_creatures.scale(2) self.pi_creatures.arrange(RIGHT, buff = 5) for name in "bob", "charlie": label = OldTexText(name.capitalize()) pi = getattr(self, name) label.next_to(pi, DOWN) pi.label = label bob.make_eye_contact(charlie) self.get_distributed_ledgers() self.add(bob, bob.label, bob.ledger) def bob_receives_transaction(self): bob, charlie = self.bob, self.charlie corner = FRAME_Y_RADIUS*UP + FRAME_X_RADIUS*LEFT payment = OldTexText( "Alice", "pays", "Bob", "10 LD" ) payment.set_color_by_tex("Alice", self.alice.get_color()) payment.set_color_by_tex("Bob", self.bob.get_color()) payment.set_color_by_tex("LD", YELLOW) payment.next_to(corner, UP+LEFT) self.play( Broadcast(corner), ApplyMethod( payment.next_to, bob, UP, run_time = 3, rate_func = squish_rate_func(smooth, 0.3, 1) ), ) self.play(bob.look_at, payment) self.play( payment.scale, 0.3, payment.next_to, bob.ledger[-1], DOWN, SMALL_BUFF ) def bob_tries_to_pay_charlie(self): bob, charlie = self.bob, self.charlie chralie_group = VGroup( charlie, charlie.label, charlie.ledger ) self.play( PiCreatureSays( bob, "Did you hear that?", target_mode = "sassy" ), FadeIn(chralie_group) ) self.play(charlie.change, "maybe", bob.eyes) self.wait(2) class YouListeningToBroadcasts(LedgerScene): CONFIG = { "denomination" : "LD" } def construct(self): ledger = self.get_ledger() payments = VGroup(*[ self.add_payment_line_to_ledger(*payment) for payment in [ ("Alice", "You", 20), ("Bob", "You", 50), ("Charlie", "You", 30), ] ]) self.remove(self.ledger) corners = [ FRAME_X_RADIUS*RIGHT*u1 + FRAME_Y_RADIUS*UP*u2 for u1, u2 in [(-1, 1), (1, 1), (-1, -1)] ] you = self.you you.scale(2) you.center() self.add(you) for payment, corner in zip(payments, corners): vect = corner/get_norm(corner) payment.next_to(corner, vect) self.play( Broadcast(corner), ApplyMethod( payment.next_to, you, vect, run_time = 3, rate_func = squish_rate_func(smooth, 0.3, 1) ), you.change_mode, "pondering" ) self.wait() class AskWhatToAddToProtocol(InitialProtocol): def construct(self): self.add_title() items = VGroup(*list(map(self.get_new_item, [ "Broadcast transactions", "Only accept signed transactions", "No overspending", ] + [""]*6))) brace = Brace(VGroup(*items[3:]), LEFT) question = OldTexText("What to \\\\ add here?") question.set_color(RED) question.scale(1.5) brace.set_color(RED) question.next_to(brace, LEFT) self.add(*items[:3]) self.play(GrowFromCenter(brace)) self.play(Write(question)) self.wait() class TrustComputationalWork(DistributedLedgerScene): def construct(self): self.add_ledger() self.show_work() def add_ledger(self): ledgers = self.get_distributed_ledgers() ledger = ledgers[0] ledger.scale(3) ledger[1].scale(2./3) ledger.center().to_edge(UP).shift(4*LEFT) plus = OldTex("+") plus.next_to(ledger, RIGHT) self.add(ledger, plus) self.ledger = ledger self.plus = plus def show_work(self): zeros = OldTex("0"*32) zeros.next_to(self.plus, RIGHT) brace = Brace(zeros, DOWN) words = brace.get_text("Computational work") self.add(brace, words) for n in range(2**12): binary = bin(n)[2:] for i, bit_str in enumerate(reversed(binary)): curr_bit = zeros.submobjects[-i-1] new_bit = OldTex(bit_str) new_bit.replace(curr_bit, dim_to_match = 1) if bit_str == "1": new_bit.set_color(YELLOW) zeros.submobjects[-i-1] = new_bit self.remove(curr_bit) self.add(zeros) self.wait(1./30) class TrustComputationalWorkSupplement(Scene): def construct(self): words = OldTexText( "Main tool: ", "Cryptographic hash functions" ) words[1].set_color(YELLOW) self.add(words[0]) self.play(Write(words[1])) self.wait() class FraudIsInfeasible(Scene): def construct(self): words = OldTexText( "Fraud", "$\\Leftrightarrow$", "Computationally infeasible" ) words.set_color_by_tex("Fraud", RED) words.to_edge(UP) self.play(FadeIn(words[0])) self.play(FadeIn(words[2])) self.play(Write(words[1])) self.wait() class ThisIsWellIntoTheWeeds(TeacherStudentsScene): def construct(self): idea = OldTexText("Proof of work") idea.move_to(self.teacher.get_corner(UP+LEFT)) idea.shift(MED_LARGE_BUFF*UP) idea.save_state() lightbulb = Lightbulb() lightbulb.next_to(idea, UP) idea.shift(DOWN) idea.set_fill(opacity = 0) self.teacher_says( "We're well into \\\\ the weeds now", target_mode = "sassy", added_anims = [ ApplyMethod(pi.change, mode) for pi, mode in zip(self.students, [ "hooray", "sad", "erm" ]) ], ) self.wait() self.play( idea.restore, RemovePiCreatureBubble( self.teacher, target_mode = "hooray", look_at = lightbulb ), ) self.play_student_changes( *["pondering"]*3, added_anims = [LaggedStartMap(FadeIn, lightbulb)] ) self.play(LaggedStartMap( ApplyMethod, lightbulb, lambda b : (b.set_color, YELLOW_A), rate_func = there_and_back )) self.wait(2) class IntroduceSHA256(Scene): def construct(self): self.introduce_evaluation() self.inverse_function_question() self.issue_challenge() self.shift_everything_down() self.guess_and_check() def introduce_evaluation(self): messages = [ "3Blue1Brown", "3Blue1Crown", "Mathologer", "Infinite Series", "Numberphile", "Welch Labs", "3Blue1Brown", ] groups = VGroup() for message in messages: lhs = OldTexText( "SHA256", "(``", message, "'') =", arg_separator = "" ) lhs.set_color_by_tex(message, BLUE) digest = sha256_tex_mob(message) digest.next_to(lhs, RIGHT) group = VGroup(lhs, digest) group.to_corner(UP+RIGHT) group.shift(MED_LARGE_BUFF*DOWN) groups.add(group) group = groups[0] lhs, digest = group sha, lp, message, lp = lhs sha_brace = Brace(sha, UP) message_brace = Brace(message, DOWN) digest_brace = Brace(digest, DOWN) sha_text = sha_brace.get_text("", "Hash function") sha_text.set_color(YELLOW) message_text = message_brace.get_text("Message/file") message_text.set_color(BLUE) digest_text = digest_brace.get_text("``Hash'' or ``Digest''") brace_text_pairs = [ (sha_brace, sha_text), (message_brace, message_text), (digest_brace, digest_text), ] looks_random = OldTexText("Looks random") looks_random.set_color(MAROON_B) looks_random.next_to(digest_text, DOWN) self.add(group) self.remove(digest) for brace, text in brace_text_pairs: if brace is digest_brace: self.play(LaggedStartMap( FadeIn, digest, run_time = 4, lag_ratio = 0.05 )) self.wait() self.play( GrowFromCenter(brace), Write(text, run_time = 2) ) self.wait() self.play(Write(looks_random)) self.wait(2) for mob in digest, message: self.play(LaggedStartMap( ApplyMethod, mob, lambda m : (m.set_color, YELLOW), rate_func = there_and_back, run_time = 1 )) self.wait() self.play(FadeOut(looks_random)) new_lhs, new_digest = groups[1] char = new_lhs[2][-5] arrow = Arrow(UP, ORIGIN, buff = 0) arrow.next_to(char, UP) arrow.set_color(RED) self.play(ShowCreation(arrow)) for new_group in groups[1:]: new_lhs, new_digest = new_group new_message = new_lhs[2] self.play( Transform(lhs, new_lhs), message_brace.stretch_to_fit_width, new_message.get_width(), message_brace.next_to, new_message, DOWN, MaintainPositionRelativeTo(message_text, message_brace), MaintainPositionRelativeTo(sha_brace, lhs[0]), MaintainPositionRelativeTo(sha_text, sha_brace) ) self.play(Transform( digest, new_digest, run_time = 2, lag_ratio = 0.5, path_arc = np.pi/2 )) if arrow in self.get_mobjects(): self.wait() self.play(FadeOut(arrow)) self.wait() new_sha_text = OldTexText( "Cryptographic", "hash function" ) new_sha_text.next_to(sha_brace, UP) new_sha_text.shift_onto_screen() new_sha_text.set_color(YELLOW) new_sha_text[0].set_color(GREEN) self.play(Transform(sha_text, new_sha_text)) self.wait() self.lhs = lhs self.message = message self.digest = digest self.digest_text = digest_text self.message_text = message_text def inverse_function_question(self): arrow = Arrow(3*RIGHT, 3*LEFT, buff = 0) arrow.set_stroke(width = 8) arrow.set_color(RED) everything = VGroup(*self.get_mobjects()) arrow.next_to(everything, DOWN) words = OldTexText("Inverse is infeasible") words.set_color(RED) words.next_to(arrow, DOWN) self.play(ShowCreation(arrow)) self.play(Write(words)) self.wait() def issue_challenge(self): desired_output_text = OldTexText("Desired output") desired_output_text.move_to(self.digest_text) desired_output_text.set_color(YELLOW) new_digest = sha256_tex_mob("Challenge") new_digest.replace(self.digest) q_marks = OldTexText("???") q_marks.move_to(self.message_text) q_marks.set_color(BLUE) self.play( Transform( self.digest, new_digest, run_time = 2, lag_ratio = 0.5, path_arc = np.pi/2 ), Transform(self.digest_text, desired_output_text) ) self.play( FadeOut(self.message), Transform(self.message_text, q_marks) ) self.wait() def shift_everything_down(self): everything = VGroup(*self.get_top_level_mobjects()) self.play( everything.scale, 0.85, everything.to_edge, DOWN ) def guess_and_check(self): groups = VGroup() for x in range(32): message = "Guess \\#%d"%x lhs = OldTexText( "SHA256(``", message, "'') = ", arg_separator = "" ) lhs.set_color_by_tex("Guess", BLUE) digest = sha256_tex_mob(message) digest.next_to(lhs, RIGHT) group = VGroup(lhs, digest) group.scale(0.85) group.next_to(self.digest, UP, aligned_edge = RIGHT) group.to_edge(UP) groups.add(group) group = groups[0] self.play(FadeIn(group)) for new_group in groups[1:]: self.play(Transform( group[0], new_group[0], run_time = 0.5, )) self.play(Transform( group[1], new_group[1], run_time = 1, lag_ratio = 0.5 )) class PonderScematic(Scene): def construct(self): randy = Randolph() randy.to_corner(DOWN+LEFT) self.play(randy.change, "confused", ORIGIN) for x in range(3): self.play(Blink(randy)) self.wait(2) class ViewingSLLCertificate(ExternallyAnimatedScene): pass class SHA256ToProofOfWork(TeacherStudentsScene): def construct(self): sha = OldTexText("SHA256") proof = OldTexText("Proof of work") arrow = Arrow(LEFT, RIGHT) group = VGroup(sha, arrow, proof) group.arrange(RIGHT) group.next_to(self.teacher, UP, buff = LARGE_BUFF) group.to_edge(RIGHT, buff = LARGE_BUFF) self.play( Write(sha, run_time = 1), self.teacher.change, "raise_right_hand" ) self.play(ShowCreation(arrow)) self.play(Write(proof, run_time = 1)) self.wait(3) class IntroduceNonceOnTrasactions(LedgerScene): CONFIG = { "denomination" : "LD", "ledger_width" : 5, "ledger_line_height" : 0.3, } def construct(self): self.add(self.get_ledger()) self.hash_with_nonce() self.write_probability() self.guess_and_check() self.name_proof_of_work() self.change_ledger() self.guess_and_check() def hash_with_nonce(self): ledger = self.ledger self.add(*[ self.add_payment_line_to_ledger(*payment) for payment in [ ("Alice", "Bob", 20), ("Alice", "You", 30), ("Charlie", "You", 100), ] ]) nonce = OldTex(str(2**30 + hash("Hey there")%(2**15))) nonce.next_to(ledger, RIGHT, LARGE_BUFF) nonce.set_color(GREEN_C) nonce_brace = Brace(nonce, DOWN) special_word = nonce_brace.get_text("Special number") arrow = Arrow(LEFT, RIGHT, buff = 0) arrow.next_to(ledger, RIGHT) arrow.shift(MED_LARGE_BUFF*DOWN) sha = OldTexText("SHA256") sha.next_to(arrow, UP) digest = sha256_tex_mob( """Man, you're reading this deeply into the code behind videos? I'm touched, really touched. Keeping loving math, my friend. """, n_forced_start_zeros = 30, ) digest.next_to(arrow, RIGHT) zeros = VGroup(*digest[:30]) zeros_brace = Brace(zeros, UP) zeros_words = zeros_brace.get_text("30 zeros") self.play(LaggedStartMap( FadeIn, VGroup(special_word, nonce_brace, nonce) )) self.wait() self.play( nonce.next_to, ledger.content, DOWN, MED_SMALL_BUFF, LEFT, FadeOut(special_word), FadeOut(nonce_brace) ) ledger.content.add(nonce) decomposed_ledger = VGroup(*[m for m in ledger.family_members_with_points() if not m.is_subpath]) self.play( ShowCreation(arrow), FadeIn(sha) ) self.play(LaggedStartMap( ApplyMethod, decomposed_ledger, lambda m : (m.set_color, YELLOW), rate_func = there_and_back )) point = VectorizedPoint(sha.get_center()) point.set_fill(opacity = 1) self.play(LaggedStartMap( Transform, decomposed_ledger.copy(), lambda m : (m, point), run_time = 1 )) bit_iter = iter(digest) self.play(LaggedStartMap( ReplacementTransform, VGroup(*[point.copy() for x in range(256)]), lambda m : (m, next(bit_iter)), )) self.remove(*self.get_mobjects_from_last_animation()) self.add(digest) self.play( GrowFromCenter(zeros_brace), Write(zeros_words, run_time = 1) ) self.play(LaggedStartMap( ApplyMethod, zeros, lambda m : (m.set_color, YELLOW) )) self.wait(2) self.nonce = nonce self.digest = digest self.zeros_brace = zeros_brace self.zeros_words = zeros_words def write_probability(self): probability = OldTexText( "Probability: $\\frac{1}{2^{30}}$", "$\\approx \\frac{1}{1{,}000{,}000{,}000}$", ) probability.next_to(self.zeros_words, UP, MED_LARGE_BUFF) self.play(FadeIn(probability[0])) self.wait() self.play(Write(probability[1], run_time = 2)) self.wait(2) def guess_and_check(self): q_mark = OldTex("?") q_mark.set_color(RED) q_mark.next_to(self.zeros_words, RIGHT, SMALL_BUFF) self.digest.save_state() self.nonce.save_state() self.play(FadeIn(q_mark)) for x in range(1, 13): nonce = OldTex(str(x)) nonce.move_to(self.nonce) nonce.set_color(GREEN_C) digest = sha256_tex_mob(str(x)) digest.replace(self.digest) self.play(Transform( self.nonce, nonce, run_time = 1 if x == 1 else 0.3 )) self.play(Transform( self.digest, digest, run_time = 1, lag_ratio = 0.5 )) self.wait() self.play(self.nonce.restore) self.play( self.digest.restore, lag_ratio = 0.5, run_time = 2 ) self.play(FadeOut(q_mark)) self.wait() def name_proof_of_work(self): words = OldTexText("``Proof of work''") words.next_to(self.nonce, DOWN, LARGE_BUFF) words.shift(MED_LARGE_BUFF*RIGHT) words.set_color(GREEN) arrow = Arrow( words.get_top(), self.nonce.get_bottom(), color = WHITE, tip_length = 0.15 ) self.play(Write(words, run_time = 2)) self.play(ShowCreation(arrow)) self.wait() def change_ledger(self): amount = self.ledger.content[2][-1] new_amount = OldTexText("300 LD") new_amount.set_height(amount.get_height()) new_amount.set_color(amount.get_color()) new_amount.move_to(amount, LEFT) new_digest = sha256_tex_mob("Ah shucks") new_digest.replace(self.digest) dot = Dot(amount.get_center()) dot.set_fill(opacity = 0.5) self.play(FocusOn(amount)) self.play(Transform(amount, new_amount)) self.play( dot.move_to, new_digest, dot.set_fill, None, 0 ) self.play(Transform( self.digest, new_digest, lag_ratio = 0.5, )) class ShowSomeBroadcasting(DistributedLedgerScene): def construct(self): self.add_large_network_and_distributed_ledger() lines = self.network.lines.copy() lines.add(*[ line.copy().rotate(np.pi) for line in lines ]) point = VectorizedPoint(self.pi_creatures.get_center()) last_pi = None for pi in self.pi_creatures: outgoing_lines = [] for line in lines: vect = line.get_start() - pi.get_center() dist = get_norm(vect) if dist < 2: outgoing_lines.append(line) dots = VGroup() for line in outgoing_lines: dot = Dot(line.get_start()) dot.set_color(YELLOW) dot.generate_target() dot.target.move_to(line.get_end()) for alt_pi in self.pi_creatures: vect = line.get_end() - alt_pi.get_center() dist = get_norm(vect) if dist < 2: dot.ledger = alt_pi.ledger dots.add(dot) self.play( Animation(point), Broadcast(pi), *[ Succession( FadeIn(dot), MoveToTarget(dot, run_time = 2), ) for dot in dots ] ) self.play(*it.chain(*[ [dot.move_to, dot.ledger, dot.set_fill, None, 0] for dot in dots ])) class IntroduceBlockChain(Scene): CONFIG = { "transaction_color" : YELLOW, "proof_of_work_color" : GREEN, "prev_hash_color" : BLUE, "block_width" : 3, "block_height" : 3.5, "n_transaction_lines" : 8, "payment_height_to_block_height" : 0.15, } def setup(self): ls = LedgerScene() self.names = [ name.capitalize() for name in ls.get_names() ] self.name_colors = [ ls.get_color_from_name(name) for name in self.names ] def construct(self): self.divide_ledger_into_blocks() self.show_proofs_of_work() self.chain_blocks_together() self.mess_with_early_block() self.propagate_hash_change() self.redo_proof_of_work() self.write_block_chain() def divide_ledger_into_blocks(self): blocks = VGroup(*[ self.get_block() for x in range(3) ]) blocks.arrange(RIGHT, buff = 1.5) blocks.to_edge(UP) all_payments = VGroup() all_proofs_of_work = VGroup() for block in blocks: block.remove(block.prev_hash) all_payments.add(*block.payments) all_proofs_of_work.add(block.proof_of_work) blocks_word = OldTexText("Blocks") blocks_word.scale(1.5) blocks_word.shift(2*DOWN) arrows = VGroup(*[ Arrow( blocks_word.get_top(), block.get_bottom(), buff = MED_LARGE_BUFF, color = WHITE ) for block in blocks ]) self.play(LaggedStartMap(FadeIn, blocks)) self.play( Write(blocks_word), LaggedStartMap( ShowCreation, arrows, run_time = 1, ) ) self.wait() for group in all_payments, all_proofs_of_work: self.play(LaggedStartMap( Indicate, group, rate_func = there_and_back, scale_factor = 1.1, )) self.play(*list(map(FadeOut, [blocks_word, arrows]))) self.blocks = blocks def show_proofs_of_work(self): random.seed(0) blocks = self.blocks proofs_of_work = VGroup() new_proofs_of_work = VGroup() digests = VGroup() arrows = VGroup() sha_words = VGroup() signatures = VGroup() for block in blocks: proofs_of_work.add(block.proof_of_work) num_str = str(random.randint(0, 10**12)) number = OldTex(num_str) number.set_color(self.proof_of_work_color) number.replace(block.proof_of_work, dim_to_match = 1) new_proofs_of_work.add(number) digest = sha256_tex_mob(num_str, 60) digest.scale(0.7) digest.move_to(block).to_edge(DOWN) VGroup(*digest[:60]).set_color(YELLOW) arrow = Arrow(block, digest) sha = OldTexText("SHA256") sha.scale(0.7) point = arrow.get_center() sha.next_to(point, UP, SMALL_BUFF) sha.rotate(-np.pi/2, about_point = point) sha.shift(SMALL_BUFF*(UP+RIGHT)) digests.add(digest) arrows.add(arrow) sha_words.add(sha) for payment in block.payments[:2]: signatures.add(payment[-1]) proofs_of_work.save_state() self.play(Transform( proofs_of_work, new_proofs_of_work, lag_ratio = 0.5 )) self.play( ShowCreation(arrows), Write(sha_words), run_time = 2 ) self.play(Write(digests)) self.wait() for group in signatures, proofs_of_work: self.play(LaggedStartMap( Indicate, group, run_time = 2, rate_func = there_and_back, )) self.wait() self.play( proofs_of_work.restore, FadeOut(sha_words) ) self.digests = digests self.sha_arrows = arrows def chain_blocks_together(self): blocks = self.blocks digests = self.digests sha_arrows = self.sha_arrows block_spacing = blocks[1].get_center() - blocks[0].get_center() prev_hashes = VGroup(*[ block.prev_hash for block in blocks ]) prev_hashes.add( prev_hashes[-1].copy().shift(block_spacing).fade(1) ) new_arrows = VGroup() for block in blocks: end = np.array([ block.get_left()[0] + block_spacing[0], block.prev_hash.get_center()[1], 0 ]) arrow = Arrow(end+LEFT, end, buff = SMALL_BUFF) arrow.get_points()[0] = block.get_right() arrow.get_points()[1] = block.get_right() + RIGHT arrow.get_points()[2] = end + LEFT + SMALL_BUFF*UP new_arrows.add(arrow) for i in range(3): self.play( ReplacementTransform(digests[i], prev_hashes[i+1]), Transform(sha_arrows[i], new_arrows[i]) ) arrow = new_arrows[0].copy().shift(-block_spacing) sha_arrows.add_to_back(arrow) self.play(*list(map(FadeIn, [arrow, prev_hashes[0]]))) self.wait(2) self.prev_hashes = prev_hashes def mess_with_early_block(self): blocks = self.blocks amount = blocks[0].payments[1][3] new_amount = OldTexText("400 LD") new_amount.set_height(amount.get_height()) new_amount.set_color(RED) new_amount.move_to(amount, LEFT) self.play(FocusOn(amount)) self.play(Transform(amount, new_amount)) self.wait() self.play(Swap(*blocks[:2])) self.wait() blocks.submobjects[:2] = blocks.submobjects[1::-1] def propagate_hash_change(self): prev_hashes = self.prev_hashes for block, prev_hash in zip(self.blocks, prev_hashes[1:]): rect = block.rect.copy() rect.set_stroke(RED, 8) rect.target = SurroundingRectangle(prev_hash) rect.target.set_stroke(rect.get_color(), 0) self.play(ShowCreation(rect)) self.play( MoveToTarget(rect), prev_hash.set_color, RED ) def redo_proof_of_work(self): proofs_of_work = VGroup(*[ block.proof_of_work for block in self.blocks ]) hashes = self.prev_hashes[1:] self.play(FadeOut(proofs_of_work)) for proof_of_work, prev_hash in zip(proofs_of_work, hashes): num_pow_group = VGroup(*[ Integer(random.randint(10**9, 10**10)) for x in range(50) ]) num_pow_group.set_color(proof_of_work.get_color()) num_pow_group.set_width(proof_of_work.get_width()) num_pow_group.move_to(proof_of_work) for num_pow in num_pow_group: self.add(num_pow) self.wait(1./20) prev_hash.set_color(random_bright_color()) self.remove(num_pow) self.add(num_pow) prev_hash.set_color(BLUE) def write_block_chain(self): ledger = OldTexText("Ledger") ledger.next_to(self.blocks, DOWN, LARGE_BUFF) cross = Cross(ledger) block_chain = OldTexText("``Block Chain''") block_chain.next_to(ledger, DOWN) self.play(FadeIn(ledger)) self.play( ShowCreation(cross), Write(block_chain) ) self.wait(2) ###### def get_block(self): block = VGroup() rect = Rectangle( color = WHITE, height = self.block_height, width = self.block_width, ) h_line1, h_line2 = [ Line( rect.get_left(), rect.get_right() ).shift(0.3*rect.get_height()*vect) for vect in (UP, DOWN) ] payments = VGroup() if not hasattr(self, "transaction_counter"): self.transaction_counter = 0 for x in range(2): hashes = [ hash("%d %d"%(seed, self.transaction_counter)) for seed in range(3) ] payment = OldTexText( self.names[hashes[0]%3], "pays", self.names[hashes[1]%4], "%d0 LD"%(hashes[2]%9 + 1), ) payment.set_color_by_tex("LD", YELLOW) for name, color in zip(self.names, self.name_colors): payment.set_color_by_tex(name, color) signature = OldTexText("$\\langle$ Signature $\\rangle$") signature.set_color(payment[0].get_color()) signature.next_to(payment, DOWN, SMALL_BUFF) payment.add(signature) factor = self.payment_height_to_block_height payment.set_height(factor*rect.get_height()) payments.add(payment) self.transaction_counter += 1 payments.add(OldTex("\\dots").scale(0.5)) payments.arrange(DOWN, buff = MED_SMALL_BUFF) payments.next_to(h_line1, DOWN) proof_of_work = OldTexText("Proof of work") proof_of_work.set_color(self.proof_of_work_color) proof_of_work.scale(0.8) proof_of_work.move_to( VGroup(h_line2, VectorizedPoint(rect.get_bottom())) ) prev_hash = OldTexText("Prev hash") prev_hash.scale(0.8) prev_hash.set_color(self.prev_hash_color) prev_hash.move_to( VGroup(h_line1, VectorizedPoint(rect.get_top())) ) block.rect = rect block.h_lines = VGroup(h_line1, h_line2) block.payments = payments block.proof_of_work = proof_of_work block.prev_hash = prev_hash block.digest_mobject_attrs() return block class DistributedBlockChainScene(DistributedLedgerScene): CONFIG = { "block_height" : 0.5, "block_width" : 0.5, "n_blocks" : 3, } def get_distributed_ledgers(self): ledgers = VGroup() point = self.pi_creatures.get_center() for pi in self.pi_creatures: vect = pi.get_center() - point vect[0] = 0 block_chain = self.get_block_chain() block_chain.next_to( VGroup(pi, pi.label), vect, SMALL_BUFF ) pi.block_chain = pi.ledger = block_chain ledgers.add(block_chain) self.ledgers = self.block_chains = ledgers return ledgers def get_block_chain(self): blocks = VGroup(*[ self.get_block() for x in range(self.n_blocks) ]) blocks.arrange(RIGHT, buff = MED_SMALL_BUFF) arrows = VGroup() for b1, b2 in zip(blocks, blocks[1:]): arrow = Arrow( LEFT, RIGHT, preserve_tip_size_when_scaling = False, tip_length = 0.15, ) arrow.set_width(b1.get_width()) target_point = interpolate( b2.get_left(), b2.get_corner(UP+LEFT), 0.8 ) arrow.next_to(target_point, LEFT, 0.5*SMALL_BUFF) arrow.get_points()[0] = b1.get_right() arrow.get_points()[1] = b2.get_left() arrow.get_points()[2] = b1.get_corner(UP+RIGHT) arrow.get_points()[2] += SMALL_BUFF*LEFT arrows.add(arrow) block_chain = VGroup(blocks, arrows) block_chain.blocks = blocks block_chain.arrows = arrows return block_chain def get_block(self): block = Rectangle( color = WHITE, height = self.block_height, width = self.block_width, ) for vect in UP, DOWN: line = Line(block.get_left(), block.get_right()) line.shift(0.3*block.get_height()*vect) block.add(line) return block def create_pi_creatures(self): creatures = DistributedLedgerScene.create_pi_creatures(self) VGroup( self.alice, self.alice.label, self.charlie, self.charlie.label, ).shift(LEFT) return creatures #Out of order class FromBankToDecentralizedSystem(DistributedBlockChainScene): CONFIG = { "n_blocks" : 5, "ledger_height" : 3, } def construct(self): self.remove_bank() self.show_block_chains() self.add_crypto_terms() self.set_aside_everything() def remove_bank(self): bank = SVGMobject( file_name = "bank_building", color = GREY_B, height = 3, ) cross = Cross(bank) cross.set_stroke(width = 10) group = VGroup(bank, cross) self.play(LaggedStartMap(DrawBorderThenFill, bank)) self.play(ShowCreation(cross)) self.wait() self.play( group.next_to, FRAME_X_RADIUS*RIGHT, RIGHT, rate_func = running_start, path_arc = -np.pi/6, ) self.wait() self.remove(group) def show_block_chains(self): creatures = self.pi_creatures creatures.center() VGroup(self.charlie, self.you).to_edge(DOWN) chains = self.get_distributed_ledgers() for pi, chain in zip(creatures, chains): pi.scale(1.5) pi.shift(0.5*pi.get_center()[0]*RIGHT) chain.next_to(pi, UP) center_chain = self.get_block_chain() center_chain.scale(2) center_chain.center() self.play(LaggedStartMap(FadeIn, creatures, run_time = 1)) self.play( LaggedStartMap(FadeIn, center_chain.blocks, run_time = 1), ShowCreation(center_chain.arrows), ) self.wait() self.play( ReplacementTransform(VGroup(center_chain), chains), *[ ApplyMethod(pi.change, "pondering", pi.ledger) for pi in creatures ] ) self.wait() def add_crypto_terms(self): terms = OldTexText( "Digital signatures \\\\", "Cryptographic hash functions", ) terms.set_color_by_tex("signature", BLUE) terms.set_color_by_tex("hash", YELLOW) for term in terms: self.play(Write(term, run_time = 1)) self.wait() self.digital_signature = terms[0] def set_aside_everything(self): digital_signature = self.digital_signature ledger = LedgerScene.get_ledger(self) LedgerScene.add_payment_line_to_ledger(self, "Alice", "Bob", "40", ) LedgerScene.add_payment_line_to_ledger(self, "Charlie", "Alice", "60", ) ledger.next_to(ORIGIN, LEFT) self.remove(digital_signature) everything = VGroup(*self.get_top_level_mobjects()) self.play( Animation(digital_signature), everything.scale, 0.1, everything.to_corner, DOWN+LEFT, ) self.play( Write(ledger), digital_signature.next_to, ORIGIN, RIGHT ) self.wait(2) class IntroduceBlockCreator(DistributedBlockChainScene): CONFIG = { "n_block_creators" : 3, "n_pow_guesses" : 60, } def construct(self): self.add_network() self.add_block_creators() self.broadcast_transactions() self.collect_transactions() self.find_proof_of_work() self.add_block_reward() self.comment_on_block_reward() self.write_miners() self.broadcast_block() def add_network(self): network = self.get_large_network() network.remove(network.lines) network.scale(0.7) ledgers = self.get_distributed_ledgers() self.add(network, ledgers) VGroup(network, ledgers).to_edge(RIGHT) def add_block_creators(self): block_creators = VGroup() labels = VGroup() everything = VGroup() for x in range(self.n_block_creators): block_creator = PiCreature(color = GREY) block_creator.set_height(self.alice.get_height()) label = OldTexText("Block creator %d"%(x+1)) label.scale(0.7) label.next_to(block_creator, DOWN, SMALL_BUFF) block_creator.label = label block_creators.add(block_creator) labels.add(label) everything.add(VGroup(block_creator, label)) everything.arrange(DOWN, buff = LARGE_BUFF) everything.to_edge(LEFT) self.play(LaggedStartMap(FadeIn, everything)) self.pi_creatures.add(*block_creators) self.wait() self.block_creators = block_creators self.block_creator_labels = labels def broadcast_transactions(self): payment_parts = [ ("Alice", "Bob", 20), ("Bob", "Charlie", 10), ("Charlie", "You", 50), ("You", "Alice", 30), ] payments = VGroup() payment_targets = VGroup() for from_name, to_name, amount in payment_parts: verb = "pay" if from_name == "You" else "pays" payment = OldTexText( from_name, verb, to_name, "%d LD"%amount ) payment.set_color_by_tex("LD", YELLOW) for name in self.get_names(): payment.set_color_by_tex( name.capitalize(), self.get_color_from_name(name) ) payment.scale(0.7) payment.generate_target() payment_targets.add(payment.target) pi = getattr(self, from_name.lower()) payment.scale(0.1) payment.set_fill(opacity = 0) payment.move_to(pi) payments.add(payment) payment_targets.arrange(DOWN, aligned_edge = LEFT) payment_targets.next_to( self.block_creator_labels, RIGHT, MED_LARGE_BUFF ) payment_targets.shift(UP) anims = [] alpha_range = np.linspace(0, 0.5, len(payments)) for pi, payment, alpha in zip(self.pi_creatures, payments, alpha_range): rf1 = squish_rate_func(smooth, alpha, alpha+0.5) rf2 = squish_rate_func(smooth, alpha, alpha+0.5) anims.append(Broadcast( pi, rate_func = rf1, big_radius = 3, )) anims.append(MoveToTarget(payment, rate_func = rf2)) self.play(*anims, run_time = 5) self.payments = payments def collect_transactions(self): creator = self.block_creators[0] block = self.get_block() block.stretch_to_fit_height(4) block.stretch_to_fit_width(3.5) block.next_to(creator.label, RIGHT, MED_LARGE_BUFF) block.to_edge(UP) payments = self.payments payments.generate_target() payments.target.set_height(1.5) payments.target.move_to(block) prev_hash = OldTexText("Prev hash") prev_hash.set_color(BLUE) prev_hash.set_height(0.3) prev_hash.next_to(block.get_top(), DOWN, MED_SMALL_BUFF) block.add(prev_hash) self.play( FadeIn(block), MoveToTarget(payments), creator.change, "raise_right_hand" ) self.wait() block.add(payments) self.block = block def find_proof_of_work(self): block = self.block arrow = Arrow(UP, ORIGIN, buff = 0) arrow.next_to(block, DOWN) sha = OldTexText("SHA256") sha.scale(0.7) sha.next_to(arrow, RIGHT) arrow.add(sha) self.add(arrow) for x in range(self.n_pow_guesses): guess = Integer(random.randint(10**11, 10**12)) guess.set_color(GREEN) guess.set_height(0.3) guess.next_to(block.get_bottom(), UP, MED_SMALL_BUFF) if x == self.n_pow_guesses - 1: digest = sha256_tex_mob(str(x), 60) VGroup(*digest[:60]).set_color(YELLOW) else: digest = sha256_tex_mob(str(x)) digest.set_width(block.get_width()) digest.next_to(arrow.get_end(), DOWN) self.add(guess, digest) self.wait(1./20) self.remove(guess, digest) proof_of_work = guess self.add(proof_of_work, digest) block.add(proof_of_work) self.wait() self.hash_group = VGroup(arrow, digest) def add_block_reward(self): payments = self.payments new_transaction = OldTexText( self.block_creator_labels[0].get_tex(), "gets", "10 LD" ) new_transaction[0].set_color(GREY_B) new_transaction.set_color_by_tex("LD", YELLOW) new_transaction.set_height(payments[0].get_height()) new_transaction.move_to(payments.get_top()) payments.generate_target() payments.target.next_to(new_transaction, DOWN, SMALL_BUFF, LEFT) new_transaction.shift(SMALL_BUFF*UP) self.play( MoveToTarget(payments), Write(new_transaction) ) payments.add_to_back(new_transaction) self.wait() def comment_on_block_reward(self): reward = self.payments[0] reward_rect = SurroundingRectangle(reward) big_rect = SurroundingRectangle(self.ledgers) big_rect.set_stroke(width = 0) big_rect.set_fill(BLACK, opacity = 1) comments = VGroup(*list(map(TexText, [ "- ``Block reward''", "- No sender/signature", "- Adds to total money supply", ]))) comments.arrange(DOWN, aligned_edge = LEFT) comments.move_to(big_rect, UP+LEFT) pi_creatures = self.pi_creatures self.pi_creatures = VGroup() self.play(ShowCreation(reward_rect)) self.play(FadeIn(big_rect)) for comment in comments: self.play(FadeIn(comment)) self.wait(2) self.play(*list(map(FadeOut, [big_rect, comments, reward_rect]))) self.pi_creatures = pi_creatures def write_miners(self): for label in self.block_creator_labels: tex = label.get_tex() new_label = OldTexText("Miner " + tex[-1]) new_label.set_color(label.get_color()) new_label.replace(label, dim_to_match = 1) self.play(Transform(label, new_label)) top_payment = self.payments[0] new_top_payment = OldTexText("Miner 1", "gets", "10 LD") new_top_payment[0].set_color(GREY_B) new_top_payment[-1].set_color(YELLOW) new_top_payment.set_height(top_payment.get_height()) new_top_payment.move_to(top_payment, LEFT) self.play(Transform(top_payment, new_top_payment)) self.wait() def broadcast_block(self): old_chains = self.block_chains self.n_blocks = 4 new_chains = self.get_distributed_ledgers() block_target_group = VGroup() anims = [] arrow_creations = [] for old_chain, new_chain in zip(old_chains, new_chains): for attr in "blocks", "arrows": pairs = list(zip( getattr(old_chain, attr), getattr(new_chain, attr), )) for m1, m2 in pairs: anims.append(Transform(m1, m2)) arrow_creations.append(ShowCreation(new_chain.arrows[-1])) block_target = self.block.copy() block_target.replace(new_chain.blocks[-1], stretch = True) block_target_group.add(block_target) anims.append(Transform( VGroup(self.block), block_target_group )) anims.append(Broadcast(self.block, n_circles = 4)) anims.append(FadeOut(self.hash_group)) anims.append(ApplyMethod( self.block_creators[0].change, "happy" )) self.play(*anims, run_time = 2) self.play(*it.chain( arrow_creations, [ ApplyMethod( pi.change, "hooray", pi.block_chain.get_right() ) for pi in self.pi_creatures ] )) self.wait(3) class MiningIsALottery(IntroduceBlockCreator): CONFIG = { "n_miners" : 3, "denomination" : "LD", "n_guesses" : 90, "n_nonce_digits" : 15, } def construct(self): self.add_blocks() self.add_arrows() self.make_guesses() def create_pi_creatures(self): IntroduceBlockCreator.create_pi_creatures(self) miners = VGroup(*[ PiCreature(color = GREY) for n in range(self.n_miners) ]) miners.scale(0.5) miners.arrange(DOWN, buff = LARGE_BUFF) miners.to_edge(LEFT) for x, miner in enumerate(miners): label = OldTexText("Miner %d"%(x+1)) label.scale(0.7) label.next_to(miner, DOWN, SMALL_BUFF) miner.label = label self.add(label) self.miners = miners return miners def add_blocks(self): self.add(self.miners) blocks = VGroup() for miner in self.miners: block = self.get_block() block.stretch_to_fit_height(2) block.stretch_to_fit_width(3) block.next_to(miner, RIGHT) payments = self.get_payments(miner) payments.set_height(1) payments.move_to(block) block.add(payments) prev_hash = OldTexText("Prev hash") prev_hash.set_color(BLUE) prev_hash.set_height(0.2) prev_hash.next_to(block.get_top(), DOWN, SMALL_BUFF) block.add(prev_hash) miner.block = block miner.change("pondering", block) blocks.add(block) self.blocks = blocks self.add(blocks) def add_arrows(self): self.arrows = VGroup() for block in self.blocks: arrow = Arrow(LEFT, RIGHT) arrow.next_to(block) label = OldTexText("SHA256") label.scale(0.7) label.next_to(arrow, UP, buff = SMALL_BUFF) self.add(arrow, label) block.arrow = arrow self.arrows.add(VGroup(arrow, label)) def make_guesses(self): for x in range(self.n_guesses): e = self.n_nonce_digits nonces = VGroup() digests = VGroup() for block in self.blocks: nonce = Integer(random.randint(10**e, 10**(e+1))) nonce.set_height(0.2) nonce.next_to(block.get_bottom(), UP, SMALL_BUFF) nonces.add(nonce) digest = sha256_tex_mob(str(x) + str(block)) digest.set_height(block.get_height()) digest.next_to(block.arrow, RIGHT) digests.add(digest) self.add(nonces, digests) self.wait(1./20) self.remove(nonces, digests) self.add(nonces, digests) winner_index = 1 winner = self.miners[winner_index] losers = VGroup(*[m for m in self.miners if m is not winner]) nonces[winner_index].set_color(GREEN) new_digest = sha256_tex_mob("Winner", 60) VGroup(*new_digest[:60]).set_color(YELLOW) old_digest = digests[winner_index] new_digest.replace(old_digest) Transform(old_digest, new_digest).update(1) self.play( winner.change, "hooray", *[ ApplyMethod(VGroup( self.blocks[i], self.arrows[i], nonces[i], digests[i] ).fade, 0.7) for i in range(len(self.blocks)) if i is not winner_index ] ) self.play(*[ ApplyMethod(loser.change, "angry", winner) for loser in losers ]) self.wait(2) ##### def get_payments(self, miner): if not hasattr(self, "ledger"): self.get_ledger() ##Unused self.ledger.content.remove(*self.ledger.content[1:]) lines = VGroup() miner_name = miner.label.get_tex() top_line = OldTexText(miner_name, "gets", "10 LD") top_line.set_color_by_tex(miner_name, GREY_B) top_line.set_color_by_tex("LD", YELLOW) lines.add(top_line) payments = [ ("Alice", "Bob", 20), ("Charlie", "You", 50), ] for payment in payments: lines.add(self.add_payment_line_to_ledger(*payment)) lines.add(OldTex("\\vdots")) for line in lines: line.set_height(0.5) lines.arrange( DOWN, buff = SMALL_BUFF, aligned_edge = LEFT ) lines[-1].next_to(lines[-2], DOWN, buff = SMALL_BUFF) return lines class TwoBlockChains(DistributedBlockChainScene): CONFIG = { "n_blocks" : 5, } def construct(self): self.listen_for_new_blocks() self.defer_to_longer() self.break_tie() def listen_for_new_blocks(self): randy = self.randy chain = self.get_block_chain() chain.scale(1.5) chain.next_to(randy, UP+RIGHT) chain.shift_onto_screen() randy.change("raise_right_hand", chain) corners = [ u1 * FRAME_X_RADIUS*RIGHT + u2 * FRAME_Y_RADIUS*UP for u1, u2 in it.product(*[[-1, 1]]*2) ] moving_blocks = chain.blocks[1:] self.add(randy, chain.blocks[0]) for corner, block, arrow in zip(corners, moving_blocks, chain.arrows): block.save_state() block.next_to(corner, corner) self.play( ApplyMethod( block.restore, rate_func = squish_rate_func(smooth, 0.3, 0.8), run_time = 3, ), Broadcast(corner, run_time = 3), ShowCreation( arrow, rate_func = squish_rate_func(smooth, 0.8, 1), run_time = 3, ), ) self.wait() self.block_chain = chain def defer_to_longer(self): randy = self.randy self.n_blocks -= 1 block_chains = VGroup( self.block_chain, self.get_block_chain().scale(1.5) ) block_chains[1].next_to(randy, UP+LEFT) block_chains[1].shift_onto_screen() conflicting = OldTexText("Conflicting") conflicting.to_edge(UP) conflicting.set_color(RED) arrows = VGroup(*[ Arrow( conflicting.get_bottom(), block_chain.get_top(), color = RED, buff = MED_LARGE_BUFF ) for block_chain in block_chains ]) longer_chain_rect = SurroundingRectangle(block_chains[0]) longer_chain_rect.set_stroke(GREEN, 8) checkmark = OldTex("\\checkmark") checkmark.set_color(GREEN) checkmark.next_to(longer_chain_rect, UP) checkmark.shift(RIGHT) chain = block_chains[1] chain.save_state() corner = FRAME_X_RADIUS*LEFT + FRAME_Y_RADIUS*UP chain.next_to(corner, UP+LEFT) self.play( randy.change, "confused", chain, Broadcast(corner), ApplyMethod( chain.restore, rate_func = squish_rate_func(smooth, 0.3, 0.7), run_time = 3 ) ) self.play( Write(conflicting), *list(map(ShowCreation, arrows)) ) self.wait() self.play(ShowCreation(longer_chain_rect)) self.play(Write(checkmark, run_time = 1)) self.play(randy.change, "thinking", checkmark) self.wait() self.to_fade = VGroup( conflicting, arrows, longer_chain_rect, checkmark ) self.block_chains = block_chains def break_tie(self): to_fade = self.to_fade block_chains = self.block_chains randy = self.randy arrow = block_chains[1].arrows[-1] block = block_chains[1].blocks[-1] arrow_block = VGroup(arrow, block).copy() block_chains.generate_target() block_chains.target.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) block_chains.target.next_to(randy, UP) block_chains.target.to_edge(LEFT) self.play( MoveToTarget(block_chains), FadeOut(to_fade), run_time = 1 ) arrow_block.next_to(block_chains[1], RIGHT, buff = 0) block_chains[1].add(arrow_block) self.play( randy.change, "confused", block_chains, FadeIn(arrow_block), ) self.wait() arrow_block = arrow_block.copy() arrow_block.next_to(FRAME_X_RADIUS*RIGHT, RIGHT) self.play( ApplyMethod( arrow_block.next_to, block_chains[0], RIGHT, 0, run_time = 3, rate_func = squish_rate_func(smooth, 0.3, 0.8) ), Broadcast(arrow_block), ) block_chains[0].add(arrow_block) rect = SurroundingRectangle(block_chains[0]) rect.set_stroke(GREEN, 8) checkmark = OldTex("\\checkmark") checkmark.next_to(rect, UP) checkmark.set_color(GREEN) self.play( ShowCreation(rect), Write(checkmark), randy.change, "happy", arrow_block ) self.wait(2) #### def create_pi_creatures(self): randy = Randolph() randy.to_edge(DOWN) self.randy = randy return VGroup(randy) class ReplaceCentralAuthorityWithWork(Scene): def construct(self): trust, central = words = OldTexText("Trust", "central authority") words.scale(1.5) cross = Cross(central) work = OldTexText("computational work") work.scale(1.5) work.move_to(central, LEFT) work.set_color(YELLOW) self.play(Write(words)) self.play(ShowCreation(cross)) central.add(cross) self.play( central.shift, DOWN, Write(work) ) self.wait() class AskAboutTrustingWork(TeacherStudentsScene): def construct(self): mode = "raise_left_hand" self.student_says( "Is trusting work \\\\ really enough?", target_mode = mode, ) self.play_student_changes("confused", mode, "erm") self.wait(3) self.teacher_says( "Well, let's try\\\\ fooling someone", target_mode = "speaking" ) self.wait(2) class DoubleSpendingAttack(DistributedBlockChainScene): CONFIG = { "fraud_block_height" : 3, } def construct(self): self.initialize_characters() self.show_fraudulent_block() self.send_to_bob() self.dont_send_to_rest_of_network() def initialize_characters(self): network = self.get_large_network() network.scale(0.7) block_chains = self.get_distributed_ledgers() self.add(network, block_chains) self.play(self.alice.change, "conniving") self.wait() def show_fraudulent_block(self): block = self.get_fraud_block() block.next_to(self.alice, LEFT, LARGE_BUFF) block.remove(block.content) self.play( ShowCreation(block), Write(block.content), self.alice.change, "raise_left_hand" ) block.add(block.content) self.wait() self.block = block def send_to_bob(self): block = self.block.copy() block.generate_target() block.target.replace( self.bob.block_chain.blocks[-1], stretch = True ) arrow = self.bob.block_chain.arrows[-1].copy() VGroup(arrow, block.target).next_to( self.bob.block_chain.blocks[-1], RIGHT, buff = 0 ) self.play( MoveToTarget(block), self.alice.change, "happy" ) self.play(ShowCreation(arrow)) self.wait() def dont_send_to_rest_of_network(self): bubble = ThoughtBubble() words = OldTexText("Alice", "never \\\\ paid", "Bob") for name in "Alice", "Bob": words.set_color_by_tex(name, self.get_color_from_name(name)) bubble.add_content(words) bubble.resize_to_content() bubble.add(*bubble.content) bubble.move_to(self.you.get_corner(UP+RIGHT), DOWN+LEFT) self.play( self.charlie.change, "shruggie", self.you.change, "shruggie", ) self.play(LaggedStartMap(FadeIn, bubble)) self.play(self.bob.change, "confused", words) self.wait(2) ### def get_fraud_block(self): block = self.get_block() block.set_height(self.fraud_block_height) content = VGroup() tuples = [ ("Prev hash", UP, BLUE), ("Proof of work", DOWN, GREEN), ] for word, vect, color in tuples: mob = OldTexText(word) mob.set_color(color) mob.set_height(0.07*block.get_height()) mob.next_to( block.get_edge_center(vect), -vect, buff = 0.06*block.get_height() ) content.add(mob) attr = word.lower().replace(" ", "_") setattr(block, attr, mob) payment = OldTexText("Alice", "pays", "Bob", "100 LD") for name in "Alice", "Bob": payment.set_color_by_tex(name, self.get_color_from_name(name)) payment.set_color_by_tex("LD", YELLOW) payments = VGroup( OldTex("\\vdots"), payment, OldTex("\\vdots") ) payments.arrange(DOWN) payments.set_width(0.9*block.get_width()) payments.move_to(block) content.add(payments) block.content = content block.add(content) return block class AliceRacesOtherMiners(DoubleSpendingAttack): CONFIG = { "n_frames_per_pow" : 3, "fraud_block_height" : 2, "n_miners" : 3, "n_proof_of_work_digits" : 11, "proof_of_work_update_counter" : 0, } def construct(self): self.initialize_characters() self.find_proof_of_work() self.receive_broadcast_from_other_miners() self.race_between_alice_and_miners() def initialize_characters(self): alice = self.alice bob = self.bob alice_l = VGroup(alice, alice.label) bob_l = VGroup(bob, bob.label) bob_l.move_to(ORIGIN) alice_l.to_corner(UP+LEFT) alice_l.shift(DOWN) self.add(bob_l, alice_l) chain = self.get_block_chain() chain.next_to(bob, UP) self.block_chain = chain self.add(chain) fraud_block = self.get_fraud_block() fraud_block.next_to(alice, RIGHT) fraud_block.to_edge(UP) proof_of_work = self.get_rand_int_mob() proof_of_work.replace(fraud_block.proof_of_work, dim_to_match = 1) fraud_block.content.remove(fraud_block.proof_of_work) fraud_block.content.add(proof_of_work) fraud_block.proof_of_work = proof_of_work self.fraud_block = fraud_block self.add(fraud_block) miners = VGroup(*[ PiCreature(color = GREY) for x in range(self.n_miners) ]) miners.set_height(alice.get_height()) miners.arrange(RIGHT, buff = LARGE_BUFF) miners.to_edge(DOWN+LEFT) miners.shift(0.5*UP) miners_word = OldTexText("Miners") miners_word.next_to(miners, DOWN) self.miners = miners self.add(miners_word, miners) miner_blocks = VGroup() self.proofs_of_work = VGroup() self.add_foreground_mobject(self.proofs_of_work) for miner in miners: block = self.get_block() block.set_width(1.5*miner.get_width()) block.next_to(miner, UP) transactions = self.get_block_filler(block) block.add(transactions) proof_of_work = self.get_rand_int_mob() prev_hash = OldTexText("Prev hash").set_color(BLUE) for mob, vect in (proof_of_work, DOWN), (prev_hash, UP): mob.set_height(0.1*block.get_height()) mob.next_to( block.get_edge_center(vect), -vect, buff = 0.05*block.get_height() ) block.add(mob) block.proof_of_work = proof_of_work block.prev_hash = prev_hash self.proofs_of_work.add(proof_of_work) miner.block = block miner_blocks.add(block) self.add(miner_blocks) def find_proof_of_work(self): fraud_block = self.fraud_block chain = self.block_chain self.proofs_of_work.add(self.fraud_block.proof_of_work) self.wait(3) self.proofs_of_work.remove(self.fraud_block.proof_of_work) fraud_block.proof_of_work.set_color(GREEN) self.play( Indicate(fraud_block.proof_of_work), self.alice.change, "hooray" ) self.wait() block = fraud_block.copy() block.generate_target() block.target.replace(chain.blocks[-1], stretch = True) arrow = chain.arrows[-1].copy() VGroup(arrow, block.target).next_to( chain.blocks[-1], RIGHT, buff = 0 ) self.remove(fraud_block) self.clean_fraud_block_content() self.fraud_fork_head = block self.fraud_fork_arrow = arrow self.play(MoveToTarget(block)) self.play(ShowCreation(arrow)) self.play(self.alice.change, "happy") self.wait() def receive_broadcast_from_other_miners(self): winner = self.miners[-1] proof_of_work = winner.block.proof_of_work self.proofs_of_work.remove(proof_of_work) proof_of_work.set_color(GREEN) self.play( Indicate(proof_of_work), winner.change, "hooray" ) block = winner.block.copy() proof_of_work.set_color(WHITE) self.remove(winner.block) ff_head = self.fraud_fork_head ff_arrow = self.fraud_fork_arrow arrow = ff_arrow.copy() movers = [ff_head, ff_arrow, block, arrow] for mover in movers: mover.generate_target() block.target.replace(ff_head, stretch = True) dist = 0.5*ff_head.get_height() + MED_SMALL_BUFF block.target.shift(dist*DOWN) ff_head.target.shift(dist*UP) arrow.target[1].shift(dist*DOWN) arrow.target.get_points()[-2:] += dist*DOWN ff_arrow.target[1].shift(dist*UP) ff_arrow.target.get_points()[-2:] += dist*UP self.play( Broadcast(block), *[ MoveToTarget( mover, run_time = 3, rate_func = squish_rate_func(smooth, 0.3, 0.8) ) for mover in movers ] ) self.play( FadeIn(winner.block), winner.change_mode, "plain", self.alice.change, "sassy", ) self.proofs_of_work.add(winner.block.proof_of_work) self.wait(2) self.play( self.alice.change, "pondering", FadeIn(self.fraud_block) ) self.proofs_of_work.add(self.fraud_block.proof_of_work) self.valid_fork_head = block def race_between_alice_and_miners(self): last_fraud_block = self.fraud_fork_head last_valid_block = self.valid_fork_head chain = self.block_chain winners = [ "Alice", "Alice", "Miners", "Miners", "Miners", "Alice", "Miners", "Miners", "Miners", "Alice", "Miners", "Miners" ] self.revert_to_original_skipping_status() for winner in winners: self.wait() if winner == "Alice": block = self.fraud_block prev_block = last_fraud_block else: block = random.choice(self.miners).block prev_block = last_valid_block block_copy = block.deepcopy() block_copy.proof_of_work.set_color(GREEN) block_copy.generate_target() block_copy.target.replace(chain.blocks[1], stretch = True) arrow = chain.arrows[0].copy() VGroup(arrow, block_copy.target).next_to( prev_block, RIGHT, buff = 0 ) anims = [ MoveToTarget(block_copy, run_time = 2), ShowCreation( arrow, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1), ), FadeIn(block), ] if winner == "Alice": last_fraud_block = block_copy else: last_valid_block = block_copy anims.append(Broadcast(block, run_time = 2)) self.proofs_of_work.remove(block.proof_of_work) self.play(*anims) self.proofs_of_work.add(block.proof_of_work) ##### def wait(self, time = 1): self.play( Animation(VGroup(*self.foreground_mobjects)), run_time = time ) def update_frame(self, *args, **kwargs): self.update_proofs_of_work() Scene.update_frame(self, *args, **kwargs) def update_proofs_of_work(self): self.proof_of_work_update_counter += 1 if self.proof_of_work_update_counter%self.n_frames_per_pow != 0: return for proof_of_work in self.proofs_of_work: new_pow = self.get_rand_int_mob() new_pow.replace(proof_of_work, dim_to_match = 1) Transform(proof_of_work, new_pow).update(1) def get_rand_int_mob(self): e = self.n_proof_of_work_digits return Integer(random.randint(10**e, 10**(e+1))) def clean_fraud_block_content(self): content = self.fraud_block.content payments = content[1] content.remove(payments) transactions = self.get_block_filler(self.fraud_block) content.add(transactions) def get_block_filler(self, block): result = OldTexText("$\\langle$Transactions$\\rangle$") result.set_width(0.8*block.get_width()) result.move_to(block) return result class WhenToTrustANewBlock(DistributedBlockChainScene): def construct(self): chain = self.block_chain = self.get_block_chain() chain.scale(2) chain.to_edge(LEFT) self.add(chain) words = list(map(TexText, [ "Don't trust yet", "Still don't trust", "...a little more...", "Maybe trust", "Probably safe", "Alright, you're good." ])) colors = [RED, RED, YELLOW, YELLOW, GREEN, GREEN] self.add_new_block() arrow = Arrow(UP, DOWN, color = RED) arrow.next_to(chain.blocks[-1], UP) for word, color in zip(words, colors): word.set_color(color) word.next_to(arrow, UP) word = words[0] self.play( FadeIn(word), ShowCreation(arrow) ) for new_word in words[1:]: kwargs = { "run_time" : 3, "rate_func" : squish_rate_func(smooth, 0.7, 1) } self.add_new_block( Transform(word, new_word, **kwargs), ApplyMethod( arrow.set_color, new_word.get_color(), **kwargs ) ) self.wait(2) def get_block(self): block = DistributedBlockChainScene.get_block(self) tuples = [ ("Prev hash", UP, BLUE), ("Proof of work", DOWN, GREEN), ] for word, vect, color in tuples: mob = OldTexText(word) mob.set_color(color) mob.set_height(0.07*block.get_height()) mob.next_to( block.get_edge_center(vect), -vect, buff = 0.06*block.get_height() ) block.add(mob) attr = word.lower().replace(" ", "_") setattr(block, attr, mob) transactions = OldTexText("$\\langle$Transactions$\\rangle$") transactions.set_width(0.8*block.get_width()) transactions.move_to(block) block.add(transactions) return block def add_new_block(self, *added_anims): blocks = self.block_chain.blocks arrows = self.block_chain.arrows block = blocks[-1].copy() arrow = arrows[-1].copy() VGroup(block, arrow).next_to(blocks[-1], RIGHT, buff = 0) corner = FRAME_X_RADIUS*RIGHT + FRAME_Y_RADIUS*UP block.save_state() block.next_to(corner, UP+RIGHT) self.play( Broadcast(block), ApplyMethod( block.restore, run_time = 3, rate_func = squish_rate_func(smooth, 0.3, 0.8), ), ShowCreation( arrow, run_time = 3, rate_func = squish_rate_func(smooth, 0.7, 1), ), *added_anims ) arrows.add(arrow) blocks.add(block) class MainIdeas(Scene): def construct(self): title = OldTexText("Main ideas") title.scale(1.5) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_X_RADIUS) h_line.next_to(title, DOWN) VGroup(title, h_line).to_corner(UP+LEFT) ideas = VGroup(*[ OldTexText("$\\cdot$ " + words) for words in [ "Digital signatures", "The ledger is the currency", "Decentralize", "Proof of work", "Block chain", ] ]) colors = BLUE, WHITE, RED, GREEN, YELLOW for idea, color in zip(ideas, colors): idea.set_color(color) ideas.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) ideas.next_to(h_line, DOWN) self.add(title, h_line) for idea in ideas: self.play(LaggedStartMap(FadeIn, idea)) self.wait() class VariableProofOfWork(WhenToTrustANewBlock): CONFIG = { "block_height" : 3, "block_width" : 3, "n_guesses" : 60, "n_proof_of_work_digits" : 11, "n_miners" : 6, } def construct(self): self.add_miner_and_hash() self.change_requirement() self.add_more_miners() def add_miner_and_hash(self): miner = PiCreature(color = GREY) miner.scale(0.7) miner.to_edge(LEFT) block = self.get_block() block.next_to(miner, RIGHT) old_proof_of_work = block.proof_of_work proof_of_work = self.get_rand_int_mob() proof_of_work.replace(old_proof_of_work, dim_to_match = 1) block.remove(old_proof_of_work) block.add(proof_of_work) block.proof_of_work = proof_of_work arrow = Arrow(LEFT, RIGHT) arrow.next_to(block) sha_tex = OldTexText("SHA256") sha_tex.scale(0.7) sha_tex.next_to(arrow, UP, SMALL_BUFF) sha_tex.set_color(YELLOW) arrow.add(sha_tex) digest = sha256_tex_mob("Random") digest.next_to(arrow.get_end(), RIGHT) miner.change("pondering", digest) self.add(miner, block, arrow, digest) for x in range(self.n_guesses): new_pow = self.get_rand_int_mob() new_pow.replace(proof_of_work, dim_to_match = 1) Transform(proof_of_work, new_pow).update(1) if x == self.n_guesses-1: n_zeros = 60 else: n_zeros = 0 new_digest = sha256_tex_mob(str(x+1), n_zeros) new_digest.replace(digest) Transform(digest, new_digest).update(1) self.wait(1./20) proof_of_work.set_color(GREEN) VGroup(*digest[:60]).set_color(YELLOW) self.miner = miner self.block = block self.arrow = arrow self.digest = digest def change_requirement(self): digest = self.digest requirement = OldTexText( "Must start with \\\\", "60", "zeros" ) requirement.next_to(digest, UP, MED_LARGE_BUFF) self.n_zeros_mob = requirement.get_part_by_tex("60") self.n_zeros_mob.set_color(YELLOW) self.play(Write(requirement, run_time = 2)) self.wait(2) for n_zeros in 30, 32, 35, 37, 42: self.change_challenge(n_zeros) self.wait() def add_more_miners(self): miner = self.miner block = self.block miner_block = VGroup(miner, block) target = miner_block.copy() target[1].scale( 0.5, about_point = miner.get_right() ) copies = VGroup(*[ target.copy() for x in range(self.n_miners - 1) ]) everyone = VGroup(target, *copies) everyone.arrange(DOWN) everyone.set_height(FRAME_HEIGHT - LARGE_BUFF) everyone.to_corner(UP+LEFT) self.play(Transform(miner_block, target)) self.play(LaggedStartMap(FadeIn, copies)) self.change_challenge(72) self.wait(2) ### def change_challenge(self, n_zeros): digest = self.digest proof_of_work = self.block.proof_of_work n_zeros_mob = self.n_zeros_mob new_digest = sha256_tex_mob(str(n_zeros), n_zeros) new_digest.move_to(digest) VGroup(*new_digest[:n_zeros]).set_color(YELLOW) new_n_zeros_mob = OldTex(str(n_zeros)) new_n_zeros_mob.move_to(n_zeros_mob) new_n_zeros_mob.set_color(n_zeros_mob.get_color()) new_pow = self.get_rand_int_mob() new_pow.replace(proof_of_work, dim_to_match = 1) new_pow.set_color(proof_of_work.get_color()) self.play( Transform(n_zeros_mob, new_n_zeros_mob), Transform( digest, new_digest, lag_ratio = 0.5 ), Transform(proof_of_work, new_pow), ) def get_rand_int_mob(self): e = self.n_proof_of_work_digits return Integer(random.randint(10**e, 10**(e+1))) class CompareBlockTimes(Scene): def construct(self): title = OldTexText("Average block time") title.scale(1.5) title.to_edge(UP) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_X_RADIUS) h_line.next_to(title, DOWN, SMALL_BUFF) examples = VGroup( OldTexText("BTC: ", "10 minutes"), OldTexText("ETH: ", "15 Seconds"), OldTexText("XRP: ", "3.5 Seconds"), OldTexText("LTC: ", "2.5 Minutes"), ) examples.arrange( DOWN, buff = LARGE_BUFF, aligned_edge = LEFT, ) examples.next_to(h_line, DOWN) logos = VGroup( BitcoinLogo(), EthereumLogo(), ImageMobject("ripple_logo"), LitecoinLogo(), ) colors = [BITCOIN_COLOR, GREEN, BLUE_B, GREY_B] for logo, example, color in zip(logos, examples, colors): logo.set_height(0.5) logo.next_to(example, LEFT) example[0].set_color(color) self.add(title, h_line) self.play( FadeIn(examples[0]), DrawBorderThenFill(logos[0]) ) self.wait() self.play(*[ LaggedStartMap(FadeIn, VGroup(*group[1:])) for group in (examples, logos) ]) self.wait(2) # def get_ethereum_logo(self): # logo = SVGMobject( # file_name = "ethereum_logo", # height = 1, # ) # logo.set_fill(GREEN, 1) # logo.set_stroke(WHITE, 3) # logo.set_color_by_gradient(GREEN_B, GREEN_D) # logo.set_width(1) # logo.center() # self.add(SurroundingRectangle(logo)) # return logo class BlockRewards(Scene): def construct(self): title = OldTexText("Block rewards") title.scale(1.5) logo = BitcoinLogo() logo.set_height(0.75) logo.next_to(title, LEFT) title.add(logo) title.to_edge(UP) h_line = Line(LEFT, RIGHT) h_line.set_width(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title, logo, h_line) rewards = VGroup( OldTexText("Jan 2009 - Nov 2012:", "50", "BTC"), OldTexText("Nov 2012 - Jul 2016:", "25", "BTC"), OldTexText("Jul 2016 - Feb 2020$^*$:", "12.5", "BTC"), OldTexText("Feb 2020$^*$ - Sep 2023$^*$:", "6.25", "BTC"), ) rewards.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) rewards.next_to(h_line, DOWN) for reward in rewards: reward[1].set_color(YELLOW) footnote = OldTexText( "$^*$ Extrapolating from the 25 BTC reward period" ) footnote.scale(0.5) footnote.to_corner(DOWN+RIGHT) self.play(LaggedStartMap( FadeIn, rewards, run_time = 4, lag_ratio = 0.5 )) self.play(FadeIn(footnote)) self.wait(3) class ShowFirstFewBlocks(ExternallyAnimatedScene): pass class ShowGeometricSum(Scene): def construct(self): equation = OldTex( "210{,}000", "(", "50", "+", "25", "+", "12.5", "+", "6.25", "+\\cdots", ")", "=", "21{,}000{,}000" ) numbers = ["50", "25", "12.5", "6.25"] colors = color_gradient([BLUE_D, BLUE_B], 4) for tex, color in zip(numbers, colors): equation.set_color_by_tex(tex, color) equation[-1].set_color(YELLOW) self.add(*equation[:2] + equation[-3:-1]) for i in range(2, 9, 2): self.play(FadeIn(VGroup(*equation[i:i+2]))) self.wait() self.play(Write(equation[-1])) self.wait(2) class TransactionFeeExample(PiCreatureScene): def construct(self): alice = self.pi_creature payment = OldTexText( "Alice", "pays", "Bob", "0.42 BTC", ) payment.set_color_by_tex("Alice", BLUE_C) payment.set_color_by_tex("Bob", MAROON) payment.set_color_by_tex("BTC", YELLOW) payment.move_to(2.5*UP) fee = OldTexText("And leaves", "0.001 BTC", "to the miner") fee.set_color_by_tex("BTC", YELLOW) fee.next_to(payment, DOWN) signature = OldTexText( "$\\langle$Alice's digital signature$\\rangle$" ) signature.set_color(BLUE_C) signature.next_to(fee, DOWN) group = VGroup(payment, fee, signature) rect = SurroundingRectangle(group, color = BLUE_B) incentive_words = OldTexText( "Incentivizes miner \\\\ to include" ) incentive_words.next_to(rect, DOWN, buff = 1.5) incentive_words.shift(2*RIGHT) arrow = Arrow( incentive_words.get_top(), rect.get_bottom(), buff = MED_LARGE_BUFF ) fee.save_state() fee.shift(DOWN) fee.set_fill(opacity = 0) self.play(Write(payment)) self.wait() self.play( alice.change, "raise_right_hand", payment, fee.restore, ) self.play(Write(signature)) self.play( ShowCreation(rect), alice.change_mode, "happy" ) self.wait() self.play( Write(incentive_words), ShowCreation(arrow), alice.change, "pondering" ) self.wait(2) def create_pi_creature(self): alice = PiCreature(color = BLUE_C) alice.to_edge(DOWN) alice.shift(FRAME_X_RADIUS*LEFT/2) return alice class ShowBitcoinBlockSize(LedgerScene): CONFIG = { "denomination" : "BTC" } def construct(self): block = VGroup() ledger = self.get_ledger() payments = VGroup(*[ self.add_payment_line_to_ledger(*args) for args in [ ("Alice", "Bob", "0.42"), ("You", "Charlie", "3.14"), ("Bob", "You", "2.72"), ("Alice", "Charlie", "4.67"), ] ]) dots = OldTex("\\vdots") dots.next_to(payments, DOWN) payments.add(dots) payments.to_edge(LEFT) payments.shift(DOWN+0.5*RIGHT) payments_rect = SurroundingRectangle( payments, color = WHITE, buff = MED_LARGE_BUFF ) block.add(payments_rect, payments) tuples = [ ("Prev hash", UP, BLUE_C), ("Proof of work", DOWN, GREEN), ] for word, vect, color in tuples: mob = OldTexText(word) mob.set_color(color) rect = SurroundingRectangle( mob, color = WHITE, buff = MED_SMALL_BUFF ) VGroup(mob, rect).next_to(payments_rect, vect, 0) rect.stretch_to_fit_width(payments_rect.get_width()) block.add(mob, rect) title = VGroup( BitcoinLogo(height = 0.75), OldTexText("Block").scale(1.5) ) title.arrange(RIGHT, SMALL_BUFF) title.next_to(block, UP) brace = Brace(payments_rect, RIGHT) limit = brace.get_text( "Limited to\\\\", "$\\sim 2{,}400$", "transactions" ) limit.set_color_by_tex("2{,}400", RED) self.add(title, block) self.remove(payments) self.play( GrowFromCenter(brace), Write(limit) ) self.play(LaggedStartMap(FadeIn, payments)) self.wait() ####Visa visa_logo = SVGMobject( file_name = "visa_logo", height = 0.5, stroke_width = 0, fill_color = BLUE_D, fill_opacity = 1, ) visa_logo[-1].set_color("#faa61a") visa_logo.sort() avg_rate = OldTexText("Avg: $1{,}700$/second") max_rate = OldTexText("Max: $>24{,}000$/second") rates = VGroup(avg_rate, max_rate) rates.scale(0.8) rates.arrange(DOWN, aligned_edge = LEFT) rates.next_to(visa_logo, RIGHT, buff = MED_SMALL_BUFF) visa = VGroup(visa_logo, rates) visa.to_corner(UP+RIGHT) self.play(LaggedStartMap(DrawBorderThenFill, visa_logo)) self.play(LaggedStartMap(FadeIn, avg_rate)) self.wait() self.play(LaggedStartMap(FadeIn, max_rate)) self.wait(2) class CurrentAverageFees(Scene): def construct(self): fees = OldTexText( "Current average fees: ", "$\\sim 0.0013$ BTC", "$\\approx$", "\\$3.39" ) fees.set_color_by_tex("BTC", YELLOW) fees.set_color_by_tex("\\$", GREEN) fees.to_edge(UP) self.play(Write(fees)) self.wait() class HighlightingAFewFees(ExternallyAnimatedScene): pass class TopicsNotCovered(TeacherStudentsScene): def construct(self): title = OldTexText("Topics not covered:") title.to_corner(UP+LEFT) title.set_color(YELLOW) title.save_state() title.shift(DOWN) title.set_fill(opacity = 0) topics = VGroup(*list(map(TexText, [ "Merkle trees", "Alternatives to proof of work", "Scripting", "$\\vdots$", "(See links in description)", ]))) topics.arrange(DOWN, aligned_edge = LEFT) topics[-2].next_to(topics[-3], DOWN) topics.next_to(title, RIGHT) topics.to_edge(UP) self.play( title.restore, self.teacher.change_mode, "raise_right_hand" ) for topic in topics: self.play_student_changes( "confused", "thinking","pondering", look_at = topic, added_anims = [LaggedStartMap(FadeIn, topic)] ) self.wait() class Exchange(Animation): CONFIG = { "rate_func" : None, } def __init__(self, exchange, **kwargs): self.swap = Swap( exchange.left, exchange.right, ) self.changed_symbols_yet = False Animation.__init__(self, exchange, **kwargs) def interpolate_mobject(self, alpha): exchange = self.mobject if alpha < 1./3: self.swap.update(3*alpha) elif alpha < 2./3: sub_alpha = alpha*3 - 1 group = VGroup(exchange.left, exchange.right) group.set_fill(opacity = 1-smooth(sub_alpha)) else: if not self.changed_symbols_yet: new_left = random.choice( exchange.cryptocurrencies ).copy() new_left.move_to(exchange.right) new_right = random.choice( exchange.currencies ).copy() new_right.move_to(exchange.left) Transform(exchange.left, new_left).update(1) Transform(exchange.right, new_right).update(1) self.changed_symbols_yet = True sub_alpha = 3*alpha - 2 group = VGroup(exchange.left, exchange.right) group.set_fill(opacity = smooth(sub_alpha)) class ShowManyExchanges(Scene): CONFIG = { "n_rows" : 2, "n_cols" : 8, "shift_radius" : 0.5, "run_time" : 30, } def construct(self): cryptocurrencies = self.get_cryptocurrencies() currencies = self.get_currencies() for currency in it.chain(currencies, cryptocurrencies): currency.set_height(0.5) currency.align_data_and_family(EthereumLogo()) exchange = VGroup(*[ Arrow( p1, p2, path_arc = np.pi, buff = MED_LARGE_BUFF ) for p1, p2 in [(LEFT, RIGHT), (RIGHT, LEFT)] ]).set_color(WHITE) exchanges = VGroup(*[ VGroup(*[ exchange.copy() for x in range(3) ]).arrange(RIGHT, buff = 2*LARGE_BUFF) for y in range(3) ]).arrange(DOWN, buff = MED_LARGE_BUFF) exchanges = VGroup(*it.chain(*exchanges)) self.add(exchanges) start_times = list(np.linspace(0, 2, len(exchanges))) random.shuffle(start_times) for exchange, start_time in zip(exchanges, start_times): left = random.choice(cryptocurrencies).copy() right = random.choice(currencies).copy() left.move_to(exchange.get_left()) right.move_to(exchange.get_right()) exchange.left = left exchange.right = right exchange.start_time = start_time exchange.add(left, right) exchange.currencies = currencies exchange.cryptocurrencies = cryptocurrencies exchange.animation = Exchange(exchange) times = np.arange(0, self.run_time, self.frame_duration) from scene.scene import ProgressDisplay for t in ProgressDisplay(times): for exchange in exchanges: sub_t = t - exchange.start_time if sub_t < 0: continue elif sub_t > 3: exchange.start_time = t sub_t = 0 exchange.animation = Exchange(exchange) exchange.animation.update(sub_t/3.0) self.update_frame( self.extract_mobject_family_members(exchanges) ) self.add_frames(self.get_frame()) def get_cryptocurrencies(self): return [ BitcoinLogo(), BitcoinLogo(), BitcoinLogo(), EthereumLogo(), LitecoinLogo() ] def get_currencies(self): return [ OldTex("\\$").set_color(GREEN), OldTex("\\$").set_color(GREEN), OldTex("\\$").set_color(GREEN), SVGMobject( file_name = "euro_symbol", stroke_width = 0, fill_opacity = 1, fill_color = BLUE, ), SVGMobject( file_name = "yen_symbol", stroke_width = 0, fill_opacity = 1, fill_color = RED, ) ] class ShowLDAndOtherCurrencyExchanges(ShowManyExchanges): CONFIG = { "run_time" : 15, } def get_cryptocurrencies(self): euro = SVGMobject( file_name = "euro_symbol", stroke_width = 0, fill_opacity = 1, fill_color = BLUE, ) return [ OldTexText("LD").set_color(YELLOW), OldTexText("LD").set_color(YELLOW), euro, euro.copy(), SVGMobject( file_name = "yen_symbol", stroke_width = 0, fill_opacity = 1, fill_color = RED, ), BitcoinLogo(), ] def get_currencies(self): return [Tex("\\$").set_color(GREEN)] class CryptoPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Desmos", "Burt Humburg", "CrypticSwarm", "Juan Benet", "Samantha D. Suplee", "James Park", "Erik Sundell", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Ed Kellett", "Joseph John Cox", "Dan Buchoff", "Luc Ritchie", "Andrew Busey", "Michael McGuffin", "John Haley", "Mourits de Beer", "Ankalagon", "Eric Lavault", "Tomohiro Furusawa", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class ProtocolLabs(PiCreatureScene): def construct(self): morty = self.pi_creature logo = self.get_logo() logo.next_to(morty, UP) logo.shift_onto_screen() screen_rect = ScreenRectangle() screen_rect.set_height(5) screen_rect.to_edge(LEFT) self.play( DrawBorderThenFill(logo[0]), LaggedStartMap(FadeIn, logo[1]), morty.change, "raise_right_hand", ) self.wait() self.play( logo.scale, 0.5, logo.to_corner, UP+LEFT, ShowCreation(screen_rect) ) modes = ["pondering", "happy", "happy"] for mode in modes: for x in range(2): self.play(Blink(morty)) self.wait(3) self.play(morty.change, mode, screen_rect) def get_logo(self): logo = SVGMobject( file_name = "protocol_labs_logo", height = 1.5, fill_color = WHITE, ) name = SVGMobject( file_name = "protocol_labs_name", height = 0.5*logo.get_height(), fill_color = GREY_B, ) for mob in logo, name: for submob in mob: submob.is_subpath = False name.next_to(logo, RIGHT) return VGroup(logo, name) class Thumbnail(DistributedBlockChainScene): CONFIG = { "n_blocks" : 4, } def construct(self): title = OldTexText("Crypto", "currencies", arg_separator = "") title.scale(2.5) title.to_edge(UP) title[0].set_color(YELLOW) title[0].set_stroke(RED, 2) self.add(title) # logos = VGroup( # BitcoinLogo(), EthereumLogo(), LitecoinLogo() # ) # for logo in logos: # logo.set_height(1) # logos.add(OldTex("\\dots").scale(2)) # logos.arrange(RIGHT) # logos.next_to(title, RIGHT, LARGE_BUFF) # self.add(logos) block_chain = self.get_block_chain() block_chain.arrows.set_color(RED) block_chain.blocks.set_color_by_gradient(BLUE, GREEN) block_chain.set_width(FRAME_WIDTH-1) block_chain.set_stroke(width = 12) self.add(block_chain)
videos_3b1b/_2017/fractal_dimension.py
from manim_imports_ext import * from functools import reduce def break_up(mobject, factor = 1.3): mobject.scale(factor) for submob in mobject: submob.scale(1./factor) return mobject class Britain(SVGMobject): CONFIG = { "file_name" : "Britain.svg", "stroke_width" : 0, "fill_color" : BLUE_D, "fill_opacity" : 1, "height" : 5, "mark_paths_closed" : True, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.set_points(self[0].get_points()) self.submobjects = [] self.set_height(self.height) self.center() class Norway(Britain): CONFIG = { "file_name" : "Norway", "mark_paths_closed" : False } class KochTest(Scene): def construct(self): koch = KochCurve(order = 5, stroke_width = 2) self.play(ShowCreation(koch, run_time = 3)) self.play( koch.scale, 3, koch.get_left(), koch.set_stroke, None, 4 ) self.wait() class SierpinskiTest(Scene): def construct(self): sierp = Sierpinski( order = 5, ) self.play(FadeIn( sierp, run_time = 5, lag_ratio = 0.5, )) self.wait() # self.play(sierp.scale, 2, sierp.get_top()) # self.wait(3) ################################### class ZoomInOnFractal(PiCreatureScene): CONFIG = { "fractal_order" : 6, "num_zooms" : 5, "fractal_class" : DiamondFractal, "index_to_replace" : 0, } def construct(self): morty = self.pi_creature fractal = self.fractal_class(order = self.fractal_order) fractal.show() fractal = self.introduce_fractal() self.change_mode("thinking") self.blink() self.zoom_in(fractal) def introduce_fractal(self): fractal = self.fractal_class(order = 0) self.play(FadeIn(fractal)) for order in range(1, self.fractal_order+1): new_fractal = self.fractal_class(order = order) self.play( Transform(fractal, new_fractal, run_time = 2), self.pi_creature.change_mode, "hooray" ) return fractal def zoom_in(self, fractal): grower = fractal[self.index_to_replace] grower_target = fractal.copy() for x in range(self.num_zooms): self.tweak_fractal_subpart(grower_target) grower_family = grower.family_members_with_points() everything = VGroup(*[ submob for submob in fractal.family_members_with_points() if not submob.is_off_screen() if submob not in grower_family ]) everything.generate_target() everything.target.shift( grower_target.get_center()-grower.get_center() ) everything.target.scale( grower_target.get_height()/grower.get_height() ) self.play( Transform(grower, grower_target), MoveToTarget(everything), self.pi_creature.change_mode, "thinking", run_time = 2 ) self.wait() grower_target = grower.copy() grower = grower[self.index_to_replace] def tweak_fractal_subpart(self, subpart): subpart.rotate(np.pi/4) class WhatAreFractals(TeacherStudentsScene): def construct(self): self.student_says( "But what \\emph{is} a fractal?", index = 2, width = 6 ) self.play_student_changes("thinking", "pondering", None) self.wait() name = OldTexText("Benoit Mandelbrot") name.to_corner(UP+LEFT) # picture = Rectangle(height = 4, width = 3) picture = ImageMobject("Mandelbrot") picture.set_height(4) picture.next_to(name, DOWN) self.play( Write(name, run_time = 2), FadeIn(picture), *[ ApplyMethod(pi.look_at, name) for pi in self.get_pi_creatures() ] ) self.wait(2) question = OldTexText("Aren't they", "self-similar", "shapes?") question.set_color_by_tex("self-similar", YELLOW) self.student_says(question) self.play(self.get_teacher().change_mode, "happy") self.wait(2) class IntroduceVonKochCurve(Scene): CONFIG = { "order" : 5, "stroke_width" : 3, } def construct(self): snowflake = self.get_snowflake() name = OldTexText("Von Koch Snowflake") name.to_edge(UP) self.play(ShowCreation(snowflake, run_time = 3)) self.play(Write(name, run_time = 2)) curve = self.isolate_one_curve(snowflake) self.wait() self.zoom_in_on(curve) self.zoom_in_on(curve) self.zoom_in_on(curve) def get_snowflake(self): triangle = RegularPolygon(n = 3, start_angle = np.pi/2) triangle.set_height(4) curves = VGroup(*[ KochCurve( order = self.order, stroke_width = self.stroke_width ) for x in range(3) ]) for index, curve in enumerate(curves): width = curve.get_width() curve.move_to( (np.sqrt(3)/6)*width*UP, DOWN ) curve.rotate(-index*2*np.pi/3) curves.set_color_by_gradient(BLUE, WHITE, BLUE) return curves def isolate_one_curve(self, snowflake): self.play(*[ ApplyMethod(curve.shift, curve.get_center()/2) for curve in snowflake ]) self.wait() self.play( snowflake.scale, 2.1, snowflake.next_to, UP, DOWN ) self.remove(*snowflake[1:]) return snowflake[0] def zoom_in_on(self, curve): larger_curve = KochCurve( order = self.order+1, stroke_width = self.stroke_width ) larger_curve.replace(curve) larger_curve.scale(3, about_point = curve.get_corner(DOWN+LEFT)) larger_curve.set_color_by_gradient( curve[0].get_color(), curve[-1].get_color(), ) self.play(Transform(curve, larger_curve, run_time = 2)) n_parts = len(curve.split()) sub_portion = VGroup(*curve[:n_parts/4]) self.play( sub_portion.set_color, YELLOW, rate_func = there_and_back ) self.wait() class IntroduceSierpinskiTriangle(PiCreatureScene): CONFIG = { "order" : 7, } def construct(self): sierp = Sierpinski(order = self.order) sierp.save_state() self.play(FadeIn( sierp, run_time = 2, lag_ratio = 0.5 )) self.wait() self.play( self.pi_creature.change_mode, "pondering", *[ ApplyMethod(submob.shift, submob.get_center()) for submob in sierp ] ) self.wait() for submob in sierp: self.play(sierp.shift, -submob.get_center()) self.wait() self.play(sierp.restore) self.change_mode("happy") self.wait() class SelfSimilarFractalsAsSubset(Scene): CONFIG = { "fractal_width" : 1.5 } def construct(self): self.add_self_similar_fractals() self.add_general_fractals() def add_self_similar_fractals(self): fractals = VGroup( DiamondFractal(order = 5), KochSnowFlake(order = 3), Sierpinski(order = 5), ) for submob in fractals: submob.set_width(self.fractal_width) fractals.arrange(RIGHT) fractals[-1].next_to(VGroup(*fractals[:-1]), DOWN) title = OldTexText("Self-similar fractals") title.next_to(fractals, UP) small_rect = Rectangle() small_rect.replace(VGroup(fractals, title), stretch = True) small_rect.scale(1.2) self.small_rect = small_rect group = VGroup(fractals, title, small_rect) group.to_corner(UP+LEFT, buff = MED_LARGE_BUFF) self.play( Write(title), ShowCreation(fractals), run_time = 3 ) self.play(ShowCreation(small_rect)) self.wait() def add_general_fractals(self): big_rectangle = Rectangle( width = FRAME_WIDTH - MED_LARGE_BUFF, height = FRAME_HEIGHT - MED_LARGE_BUFF, ) title = OldTexText("Fractals") title.scale(1.5) title.next_to(ORIGIN, RIGHT, buff = LARGE_BUFF) title.to_edge(UP, buff = MED_LARGE_BUFF) britain = Britain( fill_opacity = 0, stroke_width = 2, stroke_color = WHITE, ) britain.next_to(self.small_rect, RIGHT) britain.shift(2*DOWN) randy = Randolph().flip().scale(1.4) randy.next_to(britain, buff = SMALL_BUFF) randy.generate_target() randy.target.change_mode("pleading") fractalify(randy.target, order = 2) self.play( ShowCreation(big_rectangle), Write(title), ) self.play(ShowCreation(britain), run_time = 5) self.play( britain.set_fill, BLUE, 1, britain.set_stroke, None, 0, run_time = 2 ) self.play(FadeIn(randy)) self.play(MoveToTarget(randy, run_time = 2)) self.wait(2) class ConstrastSmoothAndFractal(Scene): CONFIG = { "britain_zoom_point_proportion" : 0.45, "scale_factor" : 50, "fractalification_order" : 2, "fractal_dimension" : 1.21, } def construct(self): v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) smooth = OldTexText("Smooth") smooth.shift(FRAME_X_RADIUS*LEFT/2) fractal = OldTexText("Fractal") fractal.shift(FRAME_X_RADIUS*RIGHT/2) VGroup(smooth, fractal).to_edge(UP) background_rectangle = Rectangle( height = FRAME_HEIGHT, width = FRAME_X_RADIUS, ) background_rectangle.to_edge(RIGHT, buff = 0) background_rectangle.set_fill(BLACK, 1) background_rectangle.set_stroke(width = 0) self.add(v_line, background_rectangle, smooth, fractal) britain = Britain( fill_opacity = 0, stroke_width = 2, stroke_color = WHITE, )[0] anchors = britain.get_anchors() smooth_britain = VMobject() smooth_britain.set_points_smoothly(anchors[::10]) smooth_britain.center().shift(FRAME_X_RADIUS*LEFT/2) index = np.argmax(smooth_britain.get_anchors()[:,0]) smooth_britain.zoom_point = smooth_britain.point_from_proportion( self.britain_zoom_point_proportion ) britain.shift(FRAME_X_RADIUS*RIGHT/2) britain.zoom_point = britain.point_from_proportion( self.britain_zoom_point_proportion ) fractalify( britain, order = self.fractalification_order, dimension = self.fractal_dimension, ) britains = VGroup(britain, smooth_britain) self.play(*[ ShowCreation(mob, run_time = 3) for mob in britains ]) self.play( britains.set_fill, BLUE, 1, britains.set_stroke, None, 0, ) self.wait() self.play( ApplyMethod( smooth_britain.scale, self.scale_factor, smooth_britain.zoom_point ), Animation(v_line), Animation(background_rectangle), ApplyMethod( britain.scale, self.scale_factor, britain.zoom_point ), Animation(smooth), Animation(fractal), run_time = 10, ) self.wait(2) class InfiniteKochZoom(Scene): CONFIG = { "order" : 6, "left_point" : 3*LEFT, } def construct(self): small_curve = self.get_curve(self.order) larger_curve = self.get_curve(self.order + 1) larger_curve.scale(3, about_point = small_curve.get_points()[0]) self.play(Transform(small_curve, larger_curve, run_time = 2)) self.repeat_frames(5) def get_curve(self, order): koch_curve = KochCurve( monochromatic = True, order = order, color = BLUE, stroke_width = 2, ) koch_curve.set_width(18) koch_curve.shift( self.left_point - koch_curve.get_points()[0] ) return koch_curve class ShowIdealizations(Scene): def construct(self): arrow = DoubleArrow(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) arrow.shift(DOWN) left_words = OldTexText("Idealization \\\\ as smooth") middle_words = OldTexText("Nature") right_words = OldTexText(""" Idealization as perfectly self-similar """) for words in left_words, middle_words, right_words: words.scale(0.8) words.next_to(arrow, DOWN) left_words.to_edge(LEFT) right_words.to_edge(RIGHT) self.add(arrow, left_words, middle_words, right_words) britain = Britain()[0] britain.set_height(4) britain.next_to(arrow, UP) anchors = britain.get_anchors() smooth_britain = VMobject() smooth_britain.set_points_smoothly(anchors[::10]) smooth_britain.set_stroke(width = 0) smooth_britain.set_fill(BLUE_D, opacity = 1) smooth_britain.next_to(arrow, UP) smooth_britain.to_edge(LEFT) koch_snowflake = KochSnowFlake(order = 5, monochromatic = True) koch_snowflake.set_stroke(width = 0) koch_snowflake.set_fill(BLUE_D, opacity = 1) koch_snowflake.set_height(3) koch_snowflake.rotate(2*np.pi/3) koch_snowflake.next_to(arrow, UP) koch_snowflake.to_edge(RIGHT) VGroup(smooth_britain, britain, koch_snowflake).set_color_by_gradient( BLUE_B, BLUE_D ) self.play(FadeIn(britain)) self.wait() self.play(Transform(britain.copy(), smooth_britain)) self.wait() self.play(Transform(britain.copy(), koch_snowflake)) self.wait() self.wait(2) class SayFractalDimension(TeacherStudentsScene): def construct(self): self.teacher_says("Fractal dimension") self.play_student_changes("confused", "hesitant", "pondering") self.wait(3) class ExamplesOfDimension(Scene): def construct(self): labels = VGroup(*[ OldTexText("%s-dimensional"%s) for s in ("1.585", "1.262", "1.21") ]) fractals = VGroup(*[ Sierpinski(order = 7), KochSnowFlake(order = 5), Britain(stroke_width = 2, fill_opacity = 0) ]) for fractal, vect in zip(fractals, [LEFT, ORIGIN, RIGHT]): fractal.to_edge(vect) fractals[2].shift(0.5*UP) fractals[1].shift(0.5*RIGHT) for fractal, label, vect in zip(fractals, labels, [DOWN, UP, DOWN]): label.next_to(fractal, vect) label.shift_onto_screen() self.play( ShowCreation(fractal), Write(label), run_time = 3 ) self.wait() self.wait() class FractalDimensionIsNonsense(Scene): def construct(self): morty = Mortimer().shift(DOWN+3*RIGHT) mathy = Mathematician().shift(DOWN+3*LEFT) morty.make_eye_contact(mathy) self.add(morty, mathy) self.play( PiCreatureSays( mathy, "It's 1.585-dimensional!", target_mode = "hooray" ), morty.change_mode, "hesitant" ) self.play(Blink(morty)) self.play( PiCreatureSays(morty, "Nonsense!", target_mode = "angry"), FadeOut(mathy.bubble), FadeOut(mathy.bubble.content), mathy.change_mode, "guilty" ) self.play(Blink(mathy)) self.wait() class DimensionForNaturalNumbers(Scene): def construct(self): labels = VGroup(*[ OldTexText("%d-dimensional"%d) for d in (1, 2, 3) ]) for label, vect in zip(labels, [LEFT, ORIGIN, RIGHT]): label.to_edge(vect) labels.shift(2*DOWN) line = Line(DOWN+LEFT, 3*UP+RIGHT, color = BLUE) line.next_to(labels[0], UP) self.play( Write(labels[0]), ShowCreation(line) ) self.wait() for label in labels[1:]: self.play(Write(label)) self.wait() class Show2DPlanein3D(Scene): def construct(self): pass class ShowCubeIn3D(Scene): def construct(self): pass class OfCourseItsMadeUp(TeacherStudentsScene): def construct(self): self.teacher_says(""" Fractal dimension \\emph{is} a made up concept... """) self.play_student_changes(*["hesitant"]*3) self.wait(2) self.teacher_says( """But it's useful!""", target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.wait(3) class FourSelfSimilarShapes(Scene): CONFIG = { "shape_width" : 2, "sierpinski_order" : 6, } def construct(self): titles = self.get_titles() shapes = self.get_shapes(titles) self.introduce_shapes(titles, shapes) self.show_self_similarity(shapes) self.mention_measurements() def get_titles(self): titles = VGroup(*list(map(TexText, [ "Line", "Square", "Cube", "Sierpinski" ]))) for title, x in zip(titles, np.linspace(-0.75, 0.75, 4)): title.shift(x*FRAME_X_RADIUS*RIGHT) titles.to_edge(UP) return titles def get_shapes(self, titles): line = VGroup( Line(LEFT, ORIGIN), Line(ORIGIN, RIGHT) ) line.set_color(BLUE_C) square = VGroup(*[ Square().next_to(ORIGIN, vect, buff = 0) for vect in compass_directions(start_vect = DOWN+LEFT) ]) square.set_stroke(width = 0) square.set_fill(BLUE, 0.7) cube = OldTexText("TODO") cube.set_fill(opacity = 0) sierpinski = Sierpinski(order = self.sierpinski_order) shapes = VGroup(line, square, cube, sierpinski) for shape, title in zip(shapes, titles): shape.set_width(self.shape_width) shape.next_to(title, DOWN, buff = MED_SMALL_BUFF) line.shift(DOWN) return shapes def introduce_shapes(self, titles, shapes): line, square, cube, sierpinski = shapes brace = Brace(VGroup(*shapes[:3]), DOWN) brace_text = brace.get_text("Not fractals") self.play(ShowCreation(line)) self.play(GrowFromCenter(square)) self.play(FadeIn(cube)) self.play(ShowCreation(sierpinski)) self.wait() self.play( GrowFromCenter(brace), FadeIn(brace_text) ) self.wait() self.play(*list(map(FadeOut, [brace, brace_text]))) self.wait() for title in titles: self.play(Write(title, run_time = 1)) self.wait(2) def show_self_similarity(self, shapes): shapes_copy = shapes.copy() self.shapes_copy = shapes_copy line, square, cube, sierpinski = shapes_copy self.play(line.shift, 3*DOWN) self.play(ApplyFunction(break_up, line)) self.wait() brace = Brace(line[0], DOWN) brace_text = brace.get_text("1/2") self.play( GrowFromCenter(brace), Write(brace_text) ) brace.add(brace_text) self.wait() self.play(square.next_to, square, DOWN, LARGE_BUFF) self.play(ApplyFunction(break_up, square)) subsquare = square[0] subsquare.save_state() self.play(subsquare.replace, shapes[1]) self.wait() self.play(subsquare.restore) self.play(brace.next_to, subsquare, DOWN) self.wait() self.wait(5)#Handle cube self.play(sierpinski.next_to, sierpinski, DOWN, LARGE_BUFF) self.play(ApplyFunction(break_up, sierpinski)) self.wait() self.play(brace.next_to, sierpinski[0], DOWN) self.wait(2) self.play(FadeOut(brace)) def mention_measurements(self): line, square, cube, sierpinski = self.shapes_copy labels = list(map(TexText, [ "$1/2$ length", "$1/4$ area", "$1/8$ volume", "You'll see...", ])) for label, shape in zip(labels, self.shapes_copy): label.next_to(shape, DOWN) label.to_edge(DOWN, buff = MED_LARGE_BUFF) if label is labels[-1]: label.shift(0.1*UP) #Dumb self.play( Write(label, run_time = 1), shape[0].set_color, YELLOW ) self.wait() class BreakUpCubeIn3D(Scene): def construct(self): pass class BrokenUpCubeIn3D(Scene): def construct(self): pass class GeneralWordForMeasurement(Scene): def construct(self): measure = OldTexText("``Measure''") measure.to_edge(UP) mass = OldTexText("Mass") mass.move_to(measure) words = VGroup(*list(map(TexText, [ "Length", "Area", "Volume" ]))) words.arrange(RIGHT, buff = 2*LARGE_BUFF) words.next_to(measure, DOWN, buff = 2*LARGE_BUFF) colors = color_gradient([BLUE_B, BLUE_D], len(words)) for word, color in zip(words, colors): word.set_color(color) lines = VGroup(*[ Line( measure.get_bottom(), word.get_top(), color = word.get_color(), buff = MED_SMALL_BUFF ) for word in words ]) for word in words: self.play(FadeIn(word)) self.play(ShowCreation(lines, run_time = 2)) self.wait() self.play(Write(measure)) self.wait(2) self.play(Transform(measure, mass)) self.wait(2) class ImagineShapesAsMetal(FourSelfSimilarShapes): def construct(self): titles = VGroup(*list(map(VGroup, self.get_titles()))) shapes = self.get_shapes(titles) shapes.shift(DOWN) descriptions = VGroup(*[ OldTexText(*words, arg_separator = "\\\\") for shape, words in zip(shapes, [ ["Thin", "wire"], ["Flat", "sheet"], ["Solid", "cube"], ["Sierpinski", "mesh"] ]) ]) for title, description in zip(titles, descriptions): description.move_to(title, UP) title.target = description self.add(titles, shapes) for shape in shapes: shape.generate_target() shape.target.set_color(GREY_B) shapes[-1].target.set_color_by_gradient(GREY, WHITE) for shape, title in zip(shapes, titles): self.play( MoveToTarget(title), MoveToTarget(shape) ) self.wait() self.wait() for shape in shapes: self.play( shape.scale, 0.5, shape.get_top(), run_time = 3, rate_func = there_and_back ) self.wait() class ScaledLineMass(Scene): CONFIG = { "title" : "Line", "mass_scaling_factor" : "\\frac{1}{2}", "shape_width" : 2, "break_up_factor" : 1.3, "vert_distance" : 2, "brace_direction" : DOWN, "shape_to_shape_buff" : 2*LARGE_BUFF, } def construct(self): title = OldTexText(self.title) title.to_edge(UP) scaling_factor_label = OldTexText( "Scaling factor:", "$\\frac{1}{2}$" ) scaling_factor_label[1].set_color(YELLOW) scaling_factor_label.to_edge(LEFT).shift(UP) mass_scaling_label = OldTexText( "Mass scaling factor:", "$%s$"%self.mass_scaling_factor ) mass_scaling_label[1].set_color(GREEN) mass_scaling_label.next_to( scaling_factor_label, DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ) shape = self.get_shape() shape.set_width(self.shape_width) shape.center() shape.shift(FRAME_X_RADIUS*RIGHT/2 + self.vert_distance*UP) big_brace = Brace(shape, self.brace_direction) big_brace_text = big_brace.get_text("$1$") shape_copy = shape.copy() shape_copy.next_to(shape, DOWN, buff = self.shape_to_shape_buff) shape_copy.scale(self.break_up_factor) for submob in shape_copy: submob.scale(1./self.break_up_factor) little_brace = Brace(shape_copy[0], self.brace_direction) little_brace_text = little_brace.get_text("$\\frac{1}{2}$") self.add(title, scaling_factor_label, mass_scaling_label[0]) self.play(GrowFromCenter(shape)) self.play( GrowFromCenter(big_brace), Write(big_brace_text) ) self.wait() self.play( shape.copy().replace, shape_copy[0] ) self.remove(*self.get_mobjects_from_last_animation()) self.add(shape_copy[0]) self.play( GrowFromCenter(little_brace), Write(little_brace_text) ) self.wait() self.play(Write(mass_scaling_label[1], run_time = 1)) self.wait() self.play(FadeIn( VGroup(*shape_copy[1:]), lag_ratio = 0.5 )) self.wait() self.play(Transform( shape_copy.copy(), shape )) self.wait() def get_shape(self): return VGroup( Line(LEFT, ORIGIN), Line(ORIGIN, RIGHT) ).set_color(BLUE) class ScaledSquareMass(ScaledLineMass): CONFIG = { "title" : "Square", "mass_scaling_factor" : "\\frac{1}{4} = \\left( \\frac{1}{2} \\right)^2", "brace_direction" : LEFT, } def get_shape(self): return VGroup(*[ Square( stroke_width = 0, fill_color = BLUE, fill_opacity = 0.7 ).shift(vect) for vect in compass_directions(start_vect = DOWN+LEFT) ]) class ScaledCubeMass(ScaledLineMass): CONFIG = { "title" : "Cube", "mass_scaling_factor" : "\\frac{1}{8} = \\left( \\frac{1}{2} \\right)^3", } def get_shape(self): return VectorizedPoint() class FormCubeFromSubcubesIn3D(Scene): def construct(self): pass class ScaledSierpinskiMass(ScaledLineMass): CONFIG = { "title" : "Sierpinski", "mass_scaling_factor" : "\\frac{1}{3}", "vert_distance" : 2.5, "shape_to_shape_buff" : 1.5*LARGE_BUFF, } def get_shape(self): return Sierpinski(order = 6) class DefineTwoDimensional(PiCreatureScene): CONFIG = { "dimension" : "2", "length_color" : GREEN, "dimension_color" : YELLOW, "shape_width" : 2, "scale_factor" : 0.5, "bottom_shape_buff" : MED_SMALL_BUFF, "scalar" : "s", } def construct(self): self.add_title() self.add_h_line() self.add_shape() self.add_width_mass_labels() self.show_top_length() self.change_mode("thinking") self.perform_scaling() self.show_dimension() def add_title(self): title = OldTexText( self.dimension, "-dimensional", arg_separator = "" ) self.dimension_in_title = title[0] self.dimension_in_title.set_color(self.dimension_color) title.to_edge(UP) self.add(title) self.title = title def add_h_line(self): self.h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) self.add(self.h_line) def add_shape(self): shape = self.get_shape() shape.set_width(self.shape_width) shape.next_to(self.title, DOWN, buff = MED_LARGE_BUFF) # self.shape.shift(FRAME_Y_RADIUS*UP/2) self.mass_color = shape.get_color() self.add(shape) self.shape = shape def add_width_mass_labels(self): top_length = OldTexText("Length:", "$L$") top_mass = OldTexText("Mass:", "$M$") bottom_length = OldTexText( "Length: ", "$%s$"%self.scalar, "$L$", arg_separator = "" ) bottom_mass = OldTexText( "Mass: ", "$%s^%s$"%(self.scalar, self.dimension), "$M$", arg_separator = "" ) self.dimension_in_exp = VGroup( *bottom_mass[1][-len(self.dimension):] ) self.dimension_in_exp.set_color(self.dimension_color) top_group = VGroup(top_length, top_mass) bottom_group = VGroup(bottom_length, bottom_mass) for group in top_group, bottom_group: group.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) group[0][-1].set_color(self.length_color) group[1][-1].set_color(self.mass_color) top_group.next_to(self.h_line, UP, buff = LARGE_BUFF) bottom_group.next_to(self.h_line, DOWN, buff = LARGE_BUFF) for group in top_group, bottom_group: group.to_edge(LEFT) self.add(top_group, bottom_group) self.top_L = top_length[-1] self.bottom_L = VGroup(*bottom_length[-2:]) self.bottom_mass = bottom_mass def show_top_length(self): brace = Brace(self.shape, LEFT) top_L = self.top_L.copy() self.play(GrowFromCenter(brace)) self.play(top_L.next_to, brace, LEFT) self.wait() self.brace = brace def perform_scaling(self): group = VGroup(self.shape, self.brace).copy() self.play( group.shift, (group.get_top()[1]+self.bottom_shape_buff)*DOWN ) shape, brace = group bottom_L = self.bottom_L.copy() shape.generate_target() shape.target.scale( self.scale_factor, ) brace.target = Brace(shape.target, LEFT) self.play(*list(map(MoveToTarget, group))) self.play(bottom_L.next_to, brace, LEFT) self.wait() def show_dimension(self): top_dimension = self.dimension_in_title.copy() self.play(self.pi_creature.look_at, top_dimension) self.play(Transform( top_dimension, self.dimension_in_exp, run_time = 2, )) self.wait(3) def get_shape(self): return Square( stroke_width = 0, fill_color = BLUE, fill_opacity = 0.7, ) class DefineThreeDimensional(DefineTwoDimensional): CONFIG = { "dimension" : "3", } def get_shape(self): return Square( stroke_width = 0, fill_opacity = 0 ) class DefineSierpinskiDimension(DefineTwoDimensional): CONFIG = { "dimension" : "D", "scalar" : "\\left( \\frac{1}{2} \\right)", "sierpinski_order" : 6, "equation_scale_factor" : 1.3, } def construct(self): DefineTwoDimensional.construct(self) self.change_mode("confused") self.wait() self.add_one_third() self.isolate_equation() def add_one_third(self): equation = OldTexText( "$= \\left(\\frac{1}{3}\\right)$", "$M$", arg_separator = "" ) equation.set_color_by_tex("$M$", self.mass_color) equation.next_to(self.bottom_mass) self.play(Write(equation)) self.change_mode("pondering") self.wait() self.equation = VGroup(self.bottom_mass, equation) self.distilled_equation = VGroup( self.bottom_mass[1], equation[0] ).copy() def isolate_equation(self): # everything = VGroup(*self.get_mobjects()) keepers = [self.pi_creature, self.equation] for mob in keepers: mob.save_state() keepers_copies = [mob.copy() for mob in keepers] self.play( *[ ApplyMethod(mob.fade, 0.5) for mob in self.get_mobjects() ] + [ Animation(mob) for mob in keepers_copies ] ) self.remove(*keepers_copies) for mob in keepers: ApplyMethod(mob.restore).update(1) self.add(*keepers) self.play( self.pi_creature.change_mode, "confused", self.pi_creature.look_at, self.equation ) self.wait() equation = self.distilled_equation self.play( equation.arrange, RIGHT, equation.scale, self.equation_scale_factor, equation.to_corner, UP+RIGHT, run_time = 2 ) self.wait(2) simpler_equation = OldTex("2^D = 3") simpler_equation[1].set_color(self.dimension_color) simpler_equation.scale(self.equation_scale_factor) simpler_equation.next_to(equation, DOWN, buff = MED_LARGE_BUFF) log_expression = OldTex("\\log_2(3) \\approx", "1.585") log_expression[-1].set_color(self.dimension_color) log_expression.scale(self.equation_scale_factor) log_expression.next_to(simpler_equation, DOWN, buff = MED_LARGE_BUFF) log_expression.shift_onto_screen() self.play(Write(simpler_equation)) self.change_mode("pondering") self.wait(2) self.play(Write(log_expression)) self.play( self.pi_creature.change_mode, "hooray", self.pi_creature.look_at, log_expression ) self.wait(2) def get_shape(self): return Sierpinski( order = self.sierpinski_order, color = RED, ) class ShowSierpinskiCurve(Scene): CONFIG = { "max_order" : 8, } def construct(self): curve = self.get_curve(2) self.play(ShowCreation(curve, run_time = 2)) for order in range(3, self.max_order + 1): self.play(Transform( curve, self.get_curve(order), run_time = 2 )) self.wait() def get_curve(self, order): curve = SierpinskiCurve(order = order, monochromatic = True) curve.set_color(RED) return curve class LengthAndAreaOfSierpinski(ShowSierpinskiCurve): CONFIG = { "curve_start_order" : 5, "sierpinski_start_order" : 4, "n_iterations" : 3, } def construct(self): length = OldTexText("Length = $\\infty$") length.shift(FRAME_X_RADIUS*LEFT/2).to_edge(UP) area = OldTexText("Area = $0$") area.shift(FRAME_X_RADIUS*RIGHT/2).to_edge(UP) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) self.add(length, area, v_line) curve = self.get_curve(order = self.curve_start_order) sierp = self.get_sierpinski(order = self.sierpinski_start_order) self.add(curve, sierp) self.wait() for x in range(self.n_iterations): new_curve = self.get_curve(order = self.curve_start_order+x+1) alpha = (x+1.0)/self.n_iterations stroke_width = interpolate(3, 1, alpha) new_curve.set_stroke(width = stroke_width) new_sierp = self.get_sierpinski( order = self.sierpinski_start_order+x+1 ) self.play( Transform(curve, new_curve), Transform(sierp, new_sierp), run_time = 2 ) self.play(sierp.set_fill, None, 0) self.wait() def get_curve(self, order): # curve = ShowSierpinskiCurve.get_curve(self, order) curve = SierpinskiCurve(order = order) curve.set_height(4).center() curve.shift(FRAME_X_RADIUS*LEFT/2) return curve def get_sierpinski(self, order): result = Sierpinski(order = order) result.shift(FRAME_X_RADIUS*RIGHT/2) return result class FractionalAnalogOfLengthAndArea(Scene): def construct(self): last_sc = LengthAndAreaOfSierpinski(skip_animations = True) self.add(*last_sc.get_mobjects()) morty = Mortimer() morty.to_corner(DOWN+RIGHT) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, """ Better described with a 1.585-dimensional measure. """ )) self.play(Blink(morty)) self.wait() class DimensionOfKoch(Scene): CONFIG = { "scaling_factor_color" : YELLOW, "mass_scaling_color" : BLUE, "dimension_color" : GREEN_A, "curve_class" : KochCurve, "scaling_factor" : 3, "mass_scaling_factor" : 4, "num_subparts" : 4, "koch_curve_order" : 5, "koch_curve_width" : 5, "break_up_factor" : 1.5, "down_shift" : 3*DOWN, "dimension_rhs" : "\\approx 1.262", } def construct(self): self.add_labels() self.add_curve() self.break_up_curve() self.compare_sizes() self.show_dimension() def add_labels(self): scaling_factor = OldTexText( "Scaling factor:", "$\\frac{1}{%d}$"%self.scaling_factor, ) scaling_factor.next_to(ORIGIN, UP) scaling_factor.to_edge(LEFT) scaling_factor[1].set_color(self.scaling_factor_color) self.add(scaling_factor[0]) mass_scaling = OldTexText( "Mass scaling factor:", "$\\frac{1}{%d}$"%self.mass_scaling_factor ) mass_scaling.next_to(ORIGIN, DOWN) mass_scaling.to_edge(LEFT) mass_scaling[1].set_color(self.mass_scaling_color) self.add(mass_scaling[0]) self.scaling_factor_mob = scaling_factor[1] self.mass_scaling_factor_mob = mass_scaling[1] def add_curve(self): curve = self.curve_class(order = self.koch_curve_order) curve.set_width(self.koch_curve_width) curve.to_corner(UP+RIGHT, LARGE_BUFF) self.play(ShowCreation(curve, run_time = 2)) self.wait() self.curve = curve def break_up_curve(self): curve_copy = self.curve.copy() length = len(curve_copy) n_parts = self.num_subparts broken_curve = VGroup(*[ VGroup(*curve_copy[i*length/n_parts:(i+1)*length/n_parts]) for i in range(n_parts) ]) self.play(broken_curve.shift, self.down_shift) broken_curve.generate_target() break_up(broken_curve.target, self.break_up_factor) broken_curve.target.shift_onto_screen self.play(MoveToTarget(broken_curve)) self.wait() self.add(broken_curve) self.broken_curve = broken_curve def compare_sizes(self): big_brace = Brace(self.curve, DOWN) one = big_brace.get_text("$1$") little_brace = Brace(self.broken_curve[0], DOWN) one_third = little_brace.get_text("1/%d"%self.scaling_factor) one_third.set_color(self.scaling_factor_color) self.play( GrowFromCenter(big_brace), GrowFromCenter(little_brace), Write(one), Write(one_third), ) self.wait() self.play(Write(self.scaling_factor_mob)) self.wait() self.play(Write(self.mass_scaling_factor_mob)) self.wait() def show_dimension(self): raw_formula = OldTex(""" \\left( \\frac{1}{%s} \\right)^D = \\left( \\frac{1}{%s} \\right) """%(self.scaling_factor, self.mass_scaling_factor)) formula = VGroup( VGroup(*raw_formula[:5]), VGroup(raw_formula[5]), VGroup(raw_formula[6]), VGroup(*raw_formula[7:]), ) formula.to_corner(UP+LEFT) simpler_formula = OldTex( str(self.scaling_factor), "^D", "=", str(self.mass_scaling_factor) ) simpler_formula.move_to(formula, UP) for mob in formula, simpler_formula: mob[0].set_color(self.scaling_factor_color) mob[1].set_color(self.dimension_color) mob[3].set_color(self.mass_scaling_color) log_expression = OldTex( "D = \\log_%d(%d) %s"%( self.scaling_factor, self.mass_scaling_factor, self.dimension_rhs ) ) log_expression[0].set_color(self.dimension_color) log_expression[5].set_color(self.scaling_factor_color) log_expression[7].set_color(self.mass_scaling_color) log_expression.next_to( simpler_formula, DOWN, aligned_edge = LEFT, buff = MED_LARGE_BUFF ) third = self.scaling_factor_mob.copy() fourth = self.mass_scaling_factor_mob.copy() for mob in third, fourth: mob.add(VectorizedPoint(mob.get_right())) mob.add_to_back(VectorizedPoint(mob.get_left())) self.play( Transform(third, formula[0]), Transform(fourth, formula[-1]), ) self.play(*list(map(FadeIn, formula[1:-1]))) self.remove(third, fourth) self.add(formula) self.wait(2) self.play(Transform(formula, simpler_formula)) self.wait(2) self.play(Write(log_expression)) self.wait(2) class DimensionOfQuadraticKoch(DimensionOfKoch): CONFIG = { "curve_class" : QuadraticKoch, "scaling_factor" : 4, "mass_scaling_factor" : 8, "num_subparts" : 8, "koch_curve_order" : 4, "koch_curve_width" : 4, "break_up_factor" : 1.7, "down_shift" : 4*DOWN, "dimension_rhs" : "= \\frac{3}{2} = 1.5", } def construct(self): self.add_labels() self.add_curve() self.set_color_curve_subparts() self.show_dimension() def get_curve(self, order): curve = self.curve_class( order = order, monochromatic = True ) curve.set_width(self.koch_curve_width) alpha = float(order) / self.koch_curve_order stroke_width = interpolate(3, 1, alpha) curve.set_stroke(width = stroke_width) return curve def add_curve(self): seed_label = OldTexText("Seed") seed_label.shift(FRAME_X_RADIUS*RIGHT/2).to_edge(UP) seed = self.get_curve(order = 1) seed.next_to(seed_label, DOWN) curve = seed.copy() resulting_fractal = OldTexText("Resulting fractal") resulting_fractal.shift(FRAME_X_RADIUS*RIGHT/2) self.add(seed_label, seed) self.wait() self.play( curve.next_to, resulting_fractal, DOWN, MED_LARGE_BUFF, Write(resulting_fractal, run_time = 1) ) for order in range(2, self.koch_curve_order+1): new_curve = self.get_curve(order) new_curve.move_to(curve) n_curve_parts = curve.get_num_curves() curve.insert_n_curves(6 * n_curve_parts) curve.make_jagged() self.play(Transform(curve, new_curve, run_time = 2)) self.wait() self.curve = curve def set_color_curve_subparts(self): n_parts = self.num_subparts colored_curve = self.curve_class( order = self.koch_curve_order, stroke_width = 1 ) colored_curve.replace(self.curve) length = len(colored_curve) broken_curve = VGroup(*[ VGroup(*colored_curve[i*length/n_parts:(i+1)*length/n_parts]) for i in range(n_parts) ]) colors = it.cycle([WHITE, RED]) for subpart, color in zip(broken_curve, colors): subpart.set_color(color) self.play( FadeOut(self.curve), FadeIn(colored_curve) ) self.play( ApplyFunction( lambda m : break_up(m, self.break_up_factor), broken_curve, rate_func = there_and_back, run_time = 2 ) ) self.wait() self.play(Write(self.scaling_factor_mob)) self.play(Write(self.mass_scaling_factor_mob)) self.wait(2) class ThisIsSelfSimilarityDimension(TeacherStudentsScene): def construct(self): self.teacher_says(""" This is called ``self-similarity dimension'' """) self.play_student_changes(*["pondering"]*3) self.wait(2) class ShowSeveralSelfSimilarityDimensions(Scene): def construct(self): vects = [ 4*LEFT, ORIGIN, 4*RIGHT, ] fractal_classes = [ PentagonalFractal, QuadraticKoch, DiamondFractal, ] max_orders = [ 4, 4, 5, ] dimensions = [ 1.668, 1.500, 1.843, ] title = OldTexText("``Self-similarity dimension''") title.to_edge(UP) title.set_color(YELLOW) self.add(title) def get_curves(order): curves = VGroup() for Class, vect in zip(fractal_classes, vects): curve = Class(order = order) curve.set_width(2), curve.shift(vect) curves.add(curve) return curves curves = get_curves(1) self.add(curves) for curve, dimension, u in zip(curves, dimensions, [1, -1, 1]): label = OldTexText("%.3f-dimensional"%dimension) label.scale(0.85) label.next_to(curve, u*UP, buff = LARGE_BUFF) self.add(label) self.wait() for order in range(2, max(max_orders)+1): anims = [] for curve, max_order in zip(curves, max_orders): if order <= max_order: new_curve = curve.__class__(order = order) new_curve.replace(curve) anims.append(Transform(curve, new_curve)) self.play(*anims, run_time = 2) self.wait() self.curves = curves class SeparateFractals(Scene): def construct(self): last_sc = ShowSeveralSelfSimilarityDimensions(skip_animations = True) self.add(*last_sc.get_mobjects()) quad_koch = last_sc.curves[1] length = len(quad_koch) new_quad_koch = VGroup(*[ VGroup(*quad_koch[i*length/8:(i+1)*length/8]) for i in range(8) ]) curves = list(last_sc.curves) curves[1] = new_quad_koch curves = VGroup(*curves) curves.save_state() self.play(*[ ApplyFunction( lambda m : break_up(m, 2), curve ) for curve in curves ]) self.wait(2) self.play(curves.restore) self.wait() class ShowDiskScaling(Scene): def construct(self): self.show_non_self_similar_shapes() self.isolate_disk() self.scale_disk() self.write_mass_scaling_factor() self.try_fitting_small_disks() def show_non_self_similar_shapes(self): title = OldTexText( "Most shapes are not self-similar" ) title.to_edge(UP) self.add(title) hexagon = RegularPolygon(n = 6) disk = Circle() blob = VMobject().set_points_smoothly([ RIGHT, RIGHT+UP, ORIGIN, RIGHT+DOWN, LEFT, UP, RIGHT ]) britain = Britain() shapes = VGroup(hexagon, blob, disk, britain) for shape in shapes: shape.set_width(1.5) shape.set_stroke(width = 0) shape.set_fill(opacity = 1) shapes.set_color_by_gradient(BLUE_B, BLUE_E) shapes.arrange(RIGHT, buff = LARGE_BUFF) shapes.next_to(title, DOWN) for shape in shapes: self.play(FadeIn(shape)) self.wait(2) self.disk = disk self.to_fade = VGroup( title, hexagon, blob, britain ) def isolate_disk(self): disk = self.disk self.play( FadeOut(self.to_fade), disk.set_width, 2, disk.next_to, ORIGIN, LEFT, 2, disk.set_fill, BLUE_D, 0.7 ) radius = Line( disk.get_center(), disk.get_right(), color = YELLOW ) one = OldTex("1").next_to(radius, DOWN, SMALL_BUFF) self.play(ShowCreation(radius)) self.play(Write(one)) self.wait() self.disk.add(radius, one) def scale_disk(self): scaled_disk = self.disk.copy() scaled_disk.generate_target() scaled_disk.target.scale(2) scaled_disk.target.next_to(ORIGIN, RIGHT) one = scaled_disk.target[-1] two = OldTex("2") two.move_to(one, UP) scaled_disk.target.submobjects[-1] = two self.play(MoveToTarget(scaled_disk)) self.wait() self.scaled_disk = scaled_disk def write_mass_scaling_factor(self): mass_scaling = OldTexText( "Mass scaling factor: $2^2 = 4$" ) mass_scaling.next_to(self.scaled_disk, UP) mass_scaling.to_edge(UP) self.play(Write(mass_scaling)) self.wait() def try_fitting_small_disks(self): disk = self.disk.copy() disk.submobjects = [] disk.set_fill(opacity = 0.5) foursome = VGroup(*[ disk.copy().next_to(ORIGIN, vect, buff = 0) for vect in compass_directions(start_vect = UP+RIGHT) ]) foursome.move_to(self.scaled_disk) self.play(Transform(disk, foursome)) self.remove(*self.get_mobjects_from_last_animation()) self.add(foursome) self.wait() self.play(ApplyFunction( lambda m : break_up(m, 0.2), foursome, rate_func = there_and_back, run_time = 4, )) self.wait() self.play(FadeOut(foursome)) self.wait() class WhatDoYouMeanByMass(TeacherStudentsScene): def construct(self): self.student_says( "What do you mean \\\\ by mass?", target_mode = "sassy" ) self.play_student_changes("pondering", "sassy", "confused") self.wait() self.play(self.get_teacher().change_mode, "thinking") self.wait(2) self.teacher_thinks("") self.zoom_in_on_thought_bubble() class BoxCountingScene(Scene): CONFIG = { "box_width" : 0.25, "box_color" : YELLOW, "box_opacity" : 0.5, "num_boundary_check_points" : 200, "corner_rect_left_extension" : 0, } def setup(self): self.num_rows = 2*int(FRAME_Y_RADIUS/self.box_width)+1 self.num_cols = 2*int(FRAME_X_RADIUS/self.box_width)+1 def get_grid(self): v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_lines = VGroup(*[ v_line.copy().shift(u*x*self.box_width*RIGHT) for x in range(self.num_cols/2+1) for u in [-1, 1] ]) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_lines = VGroup(*[ h_line.copy().shift(u*y*self.box_width*UP) for y in range(self.num_rows/2+1) for u in [-1, 1] ]) grid = VGroup(v_lines, h_lines) if self.box_width > 0.2: grid.set_stroke(width = 1) else: grid.set_stroke(width = 0.5) return grid def get_highlighted_boxes(self, vmobject): points = [] if vmobject.stroke_width > 0: for submob in vmobject.family_members_with_points(): alphas = np.linspace(0, 1, self.num_boundary_check_points) points += [ submob.point_from_proportion(alpha) for alpha in alphas ] if vmobject.fill_opacity > 0: camera = Camera(**LOW_QUALITY_CAMERA_CONFIG) camera.capture_mobject(vmobject) box_centers = self.get_box_centers() pixel_coords = camera.points_to_pixel_coords(box_centers) for index, (x, y) in enumerate(pixel_coords): try: rgb = camera.pixel_array[y, x] if not np.all(rgb == np.zeros(3)): points.append(box_centers[index]) except: pass return self.get_boxes(points) def get_box_centers(self): bottom_left = reduce(op.add, [ self.box_width*(self.num_cols/2)*LEFT, self.box_width*(self.num_rows/2)*DOWN, self.box_width*RIGHT/2, self.box_width*UP/2, ]) return np.array([ bottom_left + (x*RIGHT+y*UP)*self.box_width for x in range(self.num_cols) for y in range(self.num_rows) ]) def get_boxes(self, points): points = np.array(points) rounded_points = np.floor(points/self.box_width)*self.box_width unique_rounded_points = np.vstack({ tuple(row) for row in rounded_points }) return VGroup(*[ Square( side_length = self.box_width, stroke_width = 0, fill_color = self.box_color, fill_opacity = self.box_opacity, ).move_to(point, DOWN+LEFT) for point in unique_rounded_points ]) def get_corner_rect(self): rect = Rectangle( height = FRAME_Y_RADIUS/2, width = FRAME_X_RADIUS+self.corner_rect_left_extension, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.8 ) rect.to_corner(UP+RIGHT, buff = 0) return rect def get_counting_label(self): label = OldTexText("Boxes touched:") label.next_to(ORIGIN, RIGHT) label.to_edge(UP) label.shift(self.corner_rect_left_extension*LEFT) self.counting_num_reference = label[-1] rect = BackgroundRectangle(label) rect.stretch(1.3, 0) rect.move_to(label, LEFT) label.add_to_back(rect) return label def count_boxes(self, boxes): num = DecimalNumber(len(boxes), num_decimal_places = 0) num.next_to(boxes, RIGHT) num.add_to_back(BackgroundRectangle(num)) self.play(ShowCreation(boxes, run_time = 3)) self.play(Write(num)) self.play( num.next_to, self.counting_num_reference, RIGHT, MED_SMALL_BUFF, DOWN, num.set_color, YELLOW ) return num class BoxCountingWithDisk(BoxCountingScene): CONFIG = { "box_width" : 0.25, "num_boundary_check_points" : 200, "corner_rect_left_extension" : 2, "disk_opacity" : 0.5, "disk_stroke_width" : 0.5, "decimal_string" : "= %.2f", } def construct(self): disk = Circle(radius = 1) disk.set_fill(BLUE, opacity = self.disk_opacity) disk.set_stroke(BLUE, width = self.disk_stroke_width) disk.shift(0.1*np.sqrt(2)*(UP+RIGHT)) radius = Line(disk.get_center(), disk.get_right()) disk.add(radius) one = OldTex("1").next_to(radius, DOWN, SMALL_BUFF) boxes = self.get_highlighted_boxes(disk) small_box_num = len(boxes) grid = self.get_grid() corner_rect = self.get_corner_rect() counting_label = self.get_counting_label() prop_words = OldTexText("Proportional to", "$\\pi r^2$") prop_words[1].set_color(BLUE) prop_words.next_to(counting_label, DOWN, aligned_edge = LEFT) self.add(disk, one) self.play( ShowCreation(grid), Animation(disk), ) self.wait() self.play( FadeIn(corner_rect), FadeIn(counting_label) ) counting_mob = self.count_boxes(boxes) self.wait() self.play(Write(prop_words, run_time = 2)) self.wait(2) self.play(FadeOut(prop_words)) disk.generate_target() disk.target.scale(2, about_point = disk.get_top()) two = OldTex("2").next_to(disk.target[1], DOWN, SMALL_BUFF) self.play( MoveToTarget(disk), Transform(one, two), FadeOut(boxes), ) self.play(counting_mob.next_to, counting_mob, DOWN) boxes = self.get_highlighted_boxes(disk) large_box_count = len(boxes) new_counting_mob = self.count_boxes(boxes) self.wait() frac_line = OldTex("-") frac_line.set_color(YELLOW) frac_line.stretch_to_fit_width(new_counting_mob.get_width()) frac_line.next_to(new_counting_mob, DOWN, buff = SMALL_BUFF) decimal = OldTex(self.decimal_string%(float(large_box_count)/small_box_num)) decimal.next_to(frac_line, RIGHT) approx = OldTex("\\approx 2^2") approx.next_to(decimal, RIGHT, aligned_edge = DOWN) approx.shift_onto_screen() self.play(*list(map(Write, [frac_line, decimal]))) self.play(Write(approx)) self.wait() randy = Randolph().shift(3*RIGHT).to_edge(DOWN) self.play(FadeIn(randy)) self.play(PiCreatureSays( randy, "Is it?", target_mode = "sassy", bubble_config = {"direction" : LEFT} )) self.play(Blink(randy)) self.wait() class FinerBoxCountingWithDisk(BoxCountingWithDisk): CONFIG = { "box_width" : 0.03, "num_boundary_check_points" : 1000, "disk_stroke_width" : 0.5, "decimal_string" : "= %.2f", } class PlotDiskBoxCounting(GraphScene): CONFIG = { "x_axis_label" : "Scaling factor", "y_axis_label" : "Number of boxes \\\\ touched", "x_labeled_nums" : [], "y_labeled_nums" : [], "x_min" : 0, "y_min" : 0, "y_max" : 30, "func" : lambda x : 0.5*x**2, "func_label" : "f(x) = cx^2", } def construct(self): self.plot_points() self.describe_better_fit() def plot_points(self): self.setup_axes() self.graph_function(self.func) self.remove(self.graph) data_points = [ self.input_to_graph_point(x) + ((random.random()-0.5)/x)*UP for x in np.arange(2, 10, 0.5) ] data_dots = VGroup(*[ Dot(point, radius = 0.05, color = YELLOW) for point in data_points ]) self.play(ShowCreation(data_dots)) self.wait() self.play(ShowCreation(self.graph)) self.label_graph( self.graph, self.func_label, direction = RIGHT+DOWN, buff = SMALL_BUFF, color = WHITE, ) self.wait() def describe_better_fit(self): words = OldTexText("Better fit at \\\\ higher inputs") arrow = Arrow(2*LEFT, 2*RIGHT) arrow.next_to(self.x_axis_label_mob, UP) arrow.shift(2*LEFT) words.next_to(arrow, UP) self.play(ShowCreation(arrow)) self.play(Write(words)) self.wait(2) class FineGridSameAsLargeScaling(BoxCountingScene): CONFIG = { "box_width" : 0.25/6, "scale_factor" : 6 } def construct(self): disk = Circle(radius = 1) disk.set_fill(BLUE, opacity = 0.5) disk.set_stroke(BLUE, width = 1) grid = self.get_grid() grid.scale(self.scale_factor) self.add(grid, disk) self.wait() self.play(disk.scale, self.scale_factor) self.wait() self.play( grid.scale, 1./self.scale_factor, disk.scale, 1./self.scale_factor, disk.set_stroke, None, 0.5, ) self.wait() boxes = self.get_highlighted_boxes(disk) self.play(ShowCreation(boxes, run_time = 3)) self.wait(2) class BoxCountingSierpinski(BoxCountingScene): CONFIG = { "box_width" : 0.1, "sierpinski_order" : 7, "sierpinski_width" : 3, "num_boundary_check_points" : 6, "corner_rect_left_extension" : 2, } def construct(self): self.add(self.get_grid()) sierp = Sierpinski(order = self.sierpinski_order) sierp.set_fill(opacity = 0) sierp.move_to(3*DOWN, DOWN+RIGHT) sierp.set_width(self.sierpinski_width) boxes = self.get_highlighted_boxes(sierp) corner_rect = self.get_corner_rect() counting_label = self.get_counting_label() self.play(ShowCreation(sierp)) self.play(*list(map(FadeIn, [corner_rect, counting_label]))) self.wait() counting_mob = self.count_boxes(boxes) self.wait() self.play( FadeOut(boxes), sierp.scale, 2, sierp.get_corner(DOWN+RIGHT), ) self.play(counting_mob.next_to, counting_mob, DOWN) boxes = self.get_highlighted_boxes(sierp) new_counting_mob = self.count_boxes(boxes) self.wait() frac_line = OldTex("-") frac_line.set_color(YELLOW) frac_line.stretch_to_fit_width(new_counting_mob.get_width()) frac_line.next_to(new_counting_mob, DOWN, buff = SMALL_BUFF) approx_three = OldTex("\\approx 3") approx_three.next_to(frac_line, RIGHT) equals_exp = OldTex("= 2^{1.585...}") equals_exp.next_to(approx_three, RIGHT, aligned_edge = DOWN) equals_exp.shift_onto_screen() self.play(*list(map(Write, [frac_line, approx_three]))) self.wait() self.play(Write(equals_exp)) self.wait() class PlotSierpinskiBoxCounting(PlotDiskBoxCounting): CONFIG = { "func" : lambda x : 0.5*x**1.585, "func_label" : "f(x) = cx^{1.585}", } def construct(self): self.plot_points() class BoxCountingWithBritain(BoxCountingScene): CONFIG = { "box_width" : 0.1, "num_boundary_check_points" : 5000, "corner_rect_left_extension" : 1, } def construct(self): self.show_box_counting() self.show_formula() def show_box_counting(self): self.add(self.get_grid()) britain = Britain( stroke_width = 2, fill_opacity = 0 ) britain = fractalify(britain, order = 1, dimension = 1.21) britain.shift(DOWN+LEFT) boxes = self.get_highlighted_boxes(britain) self.play(ShowCreation(britain, run_time = 3)) self.wait() self.play(ShowCreation(boxes, run_time = 3)) self.wait() self.play(FadeOut(boxes)) self.play(britain.scale, 2.5, britain.get_corner(DOWN+RIGHT)) boxes = self.get_highlighted_boxes(britain) self.play(ShowCreation(boxes, run_time = 2)) self.wait() def show_formula(self): corner_rect = self.get_corner_rect() equation = OldTexText(""" Number of boxes $\\approx$ \\quad $c(\\text{scaling factor})^{1.21}$ """) equation.next_to( corner_rect.get_corner(UP+LEFT), DOWN+RIGHT ) N = equation[0].copy() word_len = len("Numberofboxes") approx = equation[word_len].copy() c = equation[word_len+1].copy() s = equation[word_len+3].copy() dim = VGroup(*equation[-len("1.21"):]).copy() N.set_color(YELLOW) s.set_color(BLUE) dim.set_color(GREEN) simpler_eq = VGroup(N, approx, c, s, dim) simpler_eq.generate_target() simpler_eq.target.arrange(buff = SMALL_BUFF) simpler_eq.target.move_to(N, LEFT) simpler_eq.target[-1].next_to( simpler_eq.target[-2].get_corner(UP+RIGHT), RIGHT, buff = SMALL_BUFF ) self.play( FadeIn(corner_rect), Write(equation) ) self.wait(2) self.play(FadeIn(simpler_eq)) self.wait() self.play( FadeOut(equation), Animation(simpler_eq) ) self.play(MoveToTarget(simpler_eq)) self.wait(2) log_expression1 = OldTex( "\\log(", "N", ")", "=", "\\log(", "c", "s", "^{1.21}", ")" ) log_expression2 = OldTex( "\\log(", "N", ")", "=", "\\log(", "c", ")", "+", "1.21", "\\log(", "s", ")" ) for log_expression in log_expression1, log_expression2: log_expression.next_to(simpler_eq, DOWN, aligned_edge = LEFT) log_expression.set_color_by_tex("N", N.get_color()) log_expression.set_color_by_tex("s", s.get_color()) log_expression.set_color_by_tex("^{1.21}", dim.get_color()) log_expression.set_color_by_tex("1.21", dim.get_color()) rewired_log_expression1 = VGroup(*[ log_expression1[index].copy() for index in [ 0, 1, 2, 3, #match with log_expression2 4, 5, 8, 8, 7, 4, 6, 8 ] ]) self.play(Write(log_expression1)) self.remove(log_expression1) self.add(rewired_log_expression1) self.wait() self.play(Transform( rewired_log_expression1, log_expression2, run_time = 2 )) self.wait(2) self.final_expression = VGroup( simpler_eq, rewired_log_expression1 ) class GiveShapeAndPonder(Scene): def construct(self): morty = Mortimer() randy = Randolph() morty.next_to(ORIGIN, DOWN).shift(3*RIGHT) randy.next_to(ORIGIN, DOWN).shift(3*LEFT) norway = Norway(fill_opacity = 0, stroke_width = 1) norway.set_width(2) norway.next_to(morty, UP+LEFT, buff = -MED_SMALL_BUFF) self.play( morty.change_mode, "raise_right_hand", morty.look_at, norway, randy.look_at, norway, ShowCreation(norway) ) self.play(Blink(morty)) self.play(randy.change_mode, "pondering") self.play(Blink(randy)) self.wait() class CheapBoxCountingWithBritain(BoxCountingWithBritain): CONFIG = { "skip_animations" : True, } def construct(self): self.show_formula() class ConfusedAtParabolicData(PlotDiskBoxCounting): CONFIG = { "func" : lambda x : 0.5*x**1.6, "func_label" : "f(x) = cx^{1.21}", } def construct(self): self.plot_points() randy = Randolph() randy.to_corner(DOWN+LEFT) randy.shift(RIGHT) self.play(FadeIn(randy)) self.play(randy.change_mode, "confused") self.play(randy.look_at, self.x_axis_label_mob) self.play(Blink(randy)) self.wait(2) class IntroduceLogLogPlot(GraphScene): CONFIG = { "x_axis_label" : "\\log(s)", "y_axis_label" : "\\log(N)", "x_labeled_nums" : [], "y_labeled_nums" : [], "graph_origin" : 2.5*DOWN+6*LEFT, "dimension" : 1.21, "y_intercept" : 2, "x_max" : 16, } def construct(self): last_scene = CheapBoxCountingWithBritain() expression = last_scene.final_expression box = Rectangle( stroke_color = WHITE, fill_color = BLACK, fill_opacity = 0.7, ) box.replace(expression, stretch = True) box.scale(1.2) expression.add_to_back(box) self.add(expression) self.setup_axes(animate = False) self.x_axis_label_mob[-2].set_color(BLUE) self.y_axis_label_mob[-2].set_color(YELLOW) graph = self.graph_function( lambda x : self.y_intercept+self.dimension*x ) self.remove(graph) p1 = self.input_to_graph_point(2) p2 = self.input_to_graph_point(3) interim_point = p2[0]*RIGHT + p1[1]*UP h_line = Line(p1, interim_point) v_line = Line(interim_point, p2) slope_lines = VGroup(h_line, v_line) slope_lines.set_color(GREEN) slope = OldTexText("Slope = ", "$%.2f$"%self.dimension) slope[-1].set_color(GREEN) slope.next_to(slope_lines, RIGHT) self.wait() data_points = [ self.input_to_graph_point(x) + ((random.random()-0.5)/x)*UP for x in np.arange(1, 8, 0.7) ] data_dots = VGroup(*[ Dot(point, radius = 0.05, color = YELLOW) for point in data_points ]) self.play(ShowCreation(data_dots, run_time = 3)) self.wait() self.play( ShowCreation(graph), Animation(expression) ) self.wait() self.play(ShowCreation(slope_lines)) self.play(Write(slope)) self.wait() class ManyBritainCounts(BoxCountingWithBritain): CONFIG = { "box_width" : 0.1, "num_boundary_check_points" : 10000, "corner_rect_left_extension" : 1, } def construct(self): britain = Britain( stroke_width = 2, fill_opacity = 0 ) britain = fractalify(britain, order = 1, dimension = 1.21) britain.next_to(ORIGIN, LEFT) self.add(self.get_grid()) self.add(britain) for x in range(5): self.play(britain.scale, 2, britain.point_from_proportion(0.8)) boxes = self.get_highlighted_boxes(britain) self.play(ShowCreation(boxes)) self.wait() self.play(FadeOut(boxes)) class ReadyForRealDefinition(TeacherStudentsScene): def construct(self): self.teacher_says(""" Now for what fractals really are. """) self.play_student_changes(*["hooray"]*3) self.wait(2) class DefineFractal(TeacherStudentsScene): def construct(self): self.teacher_says(""" Fractals are shapes with a non-integer dimension. """) self.play_student_changes("thinking", "happy", "erm") self.wait(3) self.teacher_says( "Kind of...", target_mode = "sassy" ) self.play_student_changes(*["pondering"]*3) self.play(*[ ApplyMethod(pi.look, DOWN) for pi in self.get_pi_creatures() ]) self.wait(3) class RoughnessAndFractionalDimension(Scene): def construct(self): title = OldTexText( "Non-integer dimension $\\Leftrightarrow$ Roughness" ) title.to_edge(UP) self.add(title) randy = Randolph().scale(2) randy.to_corner(DOWN+RIGHT) self.add(randy) target = randy.copy() target.change_mode("hooray") ponder_target = randy.copy() ponder_target.change_mode("pondering") for mob in target, ponder_target: fractalify(mob, order = 2) dimension_label = OldTexText("Boundary dimension = ", "1") dimension_label.to_edge(LEFT) one = dimension_label[1] one.set_color(BLUE) new_dim = OldTex("1.2") new_dim.move_to(one, DOWN+LEFT) new_dim.set_color(one.get_color()) self.add(dimension_label) self.play(Blink(randy)) self.play( Transform(randy, target, run_time = 2), Transform(one, new_dim) ) self.wait() self.play(Blink(randy)) self.play(randy.look, DOWN+RIGHT) self.wait() self.play(randy.look, DOWN+LEFT) self.play(Blink(randy)) self.wait() self.play(Transform(randy, ponder_target)) self.wait() class DifferentSlopesAtDifferentScales(IntroduceLogLogPlot): def construct(self): self.setup_axes(animate = False) self.x_axis_label_mob[-2].set_color(BLUE) self.y_axis_label_mob[-2].set_color(YELLOW) self.graph_function( lambda x : 0.01*(x-5)**3 + 0.3*x + 3 ) self.remove(self.graph) words = OldTexText(""" Different slopes at different scales """) words.to_edge(RIGHT) arrows = VGroup(*[ Arrow(words.get_left(), self.input_to_graph_point(x)) for x in (1, 7, 12) ]) data_points = [ self.input_to_graph_point(x) + (0.3*(random.random()-0.5))*UP for x in np.arange(1, self.x_max, 0.7) ] data_dots = VGroup(*[ Dot(point, radius = 0.05, color = YELLOW) for point in data_points ]) self.play(ShowCreation(data_dots, run_time = 2)) self.play(ShowCreation(self.graph)) self.wait() self.play( Write(words), ShowCreation(arrows) ) self.wait() class HoldUpCoilExample(TeacherStudentsScene): def construct(self): point = UP+RIGHT self.play( self.get_teacher().change_mode, "raise_right_hand", self.get_teacher().look_at, point ) self.play(*[ ApplyMethod(pi.look_at, point) for pi in self.get_students() ]) self.wait(5) self.play_student_changes(*["thinking"]*3) self.play(*[ ApplyMethod(pi.look_at, point) for pi in self.get_students() ]) self.wait(5) class SmoothHilbertZoom(Scene): def construct(self): hilbert = HilbertCurve( order = 7, color = MAROON_B, monochromatic = True ) hilbert.make_smooth() self.add(hilbert) two_d_title = OldTexText("2D at a distance...") one_d_title = OldTexText("1D up close") for title in two_d_title, one_d_title: title.to_edge(UP) self.add(two_d_title) self.wait() self.play( ApplyMethod( hilbert.scale, 100, hilbert.point_from_proportion(0.3), ), Transform( two_d_title, one_d_title, rate_func = squish_rate_func(smooth) ), run_time = 3 ) self.wait() class ListDimensionTypes(PiCreatureScene): CONFIG = { "use_morty" : False, } def construct(self): types = VGroup(*list(map(TexText, [ "Box counting dimension", "Information dimension", "Hausdorff dimension", "Packing dimension" ]))) types.arrange(DOWN, aligned_edge = LEFT) for text in types: self.play( Write(text, run_time = 1), self.pi_creature.change_mode, "pondering" ) self.wait(3) class ZoomInOnBritain(Scene): CONFIG = { "zoom_factor" : 1000 } def construct(self): britain = Britain() fractalify(britain, order = 3, dimension = 1.21) anchors = britain.get_anchors() key_value = int(0.3*len(anchors)) point = anchors[key_value] thinning_factor = 100 num_neighbors_kept = 1000 britain.set_points_as_corners(reduce( lambda a1, a2 : np.append(a1, a2, axis = 0), [ anchors[:key_value-num_neighbors_kept:thinning_factor,:], anchors[key_value-num_neighbors_kept:key_value+num_neighbors_kept,:], anchors[key_value+num_neighbors_kept::thinning_factor,:], ] )) self.add(britain) self.wait() self.play( britain.scale, self.zoom_factor, point, run_time = 10 ) self.wait() class NoteTheConstantSlope(Scene): def construct(self): words = OldTexText("Note the \\\\ constant slope") words.set_color(YELLOW) self.play(Write(words)) self.wait(2) class FromHandwavyToQuantitative(Scene): def construct(self): randy = Randolph() morty = Mortimer() for pi in randy, morty: pi.next_to(ORIGIN, DOWN) randy.shift(2*LEFT) morty.shift(2*RIGHT) randy.make_eye_contact(morty) self.add(randy, morty) self.play(PiCreatureSays( randy, "Fractals are rough", target_mode = "shruggie" )) self.play(morty.change_mode, "sassy") self.play(Blink(morty)) self.play( PiCreatureSays( morty, "We can make \\\\ that quantitative!", target_mode = "hooray" ), FadeOut(randy.bubble), FadeOut(randy.bubble.content), randy.change_mode, "happy" ) self.play(Blink(randy)) self.wait() class WhatSlopeDoesLogLogPlotApproach(IntroduceLogLogPlot): CONFIG = { "words" : "What slope does \\\\ this approach?", "x_max" : 20, "y_max" : 15, } def construct(self): self.setup_axes(animate = False) self.x_axis_label_mob[-2].set_color(BLUE) self.y_axis_label_mob[-2].set_color(YELLOW) spacing = 0.5 x_range = np.arange(1, self.x_max, spacing) randomness = [ 0.5*np.exp(-x/2)+spacing*(0.8 + random.random()/(x**(0.5))) for x in x_range ] cum_sums = np.cumsum(randomness) data_points = [ self.coords_to_point(x, cum_sum) for x, cum_sum in zip(x_range, cum_sums) ] data_dots = VGroup(*[ Dot(point, radius = 0.025, color = YELLOW) for point in data_points ]) words = OldTexText(self.words) p1, p2 = [ data_dots[int(alpha*len(data_dots))].get_center() for alpha in (0.3, 0.5) ] words.rotate(Line(p1, p2).get_angle()) words.next_to(p1, RIGHT, aligned_edge = DOWN, buff = 1.5) morty = Mortimer() morty.to_corner(DOWN+RIGHT) self.add(morty) self.play(ShowCreation(data_dots, run_time = 7)) self.play( Write(words), morty.change_mode, "speaking" ) self.play(Blink(morty)) self.wait() class BritainBoxCountHighZoom(BoxCountingWithBritain): def construct(self): britain = Britain( stroke_width = 2, fill_opacity = 0 ) britain = fractalify(britain, order = 2, dimension = 1.21) self.add(self.get_grid()) self.add(britain) for x in range(2): self.play( britain.scale, 10, britain.point_from_proportion(0.3), run_time = 2 ) if x == 0: a, b = 0.2, 0.5 else: a, b = 0.25, 0.35 britain.pointwise_become_partial(britain, a, b) self.count_britain(britain) self.wait() def count_britain(self, britain): boxes = self.get_highlighted_boxes(britain) self.play(ShowCreation(boxes)) self.wait() self.play(FadeOut(boxes)) class IfBritainWasEventuallySmooth(Scene): def construct(self): britain = Britain() britain.make_smooth() point = britain.point_from_proportion(0.3) self.add(britain) self.wait() self.play( britain.scale, 200, point, run_time = 10 ) self.wait() class SmoothBritainLogLogPlot(IntroduceLogLogPlot): CONFIG = { } def construct(self): self.setup_axes() self.graph_function( lambda x : (1 + np.exp(-x/5.0))*x ) self.remove(self.graph) p1, p2, p3, p4 = [ self.input_to_graph_point(x) for x in (1, 2, 7, 8) ] interim_point1 = p2[0]*RIGHT + p1[1]*UP interim_point2 = p4[0]*RIGHT + p3[1]*UP print(self.func(2)) slope_lines1, slope_lines2 = VMobject(), VMobject() slope_lines1.set_points_as_corners( [p1, interim_point1, p2] ) slope_lines2.set_points_as_corners( [p3, interim_point2, p4] ) slope_lines_group = VGroup(slope_lines1, slope_lines2) slope_lines_group.set_color(GREEN) slope_label1 = OldTexText("Slope $> 1$") slope_label2 = OldTexText("Slope $= 1$") slope_label1.next_to(slope_lines1) slope_label2.next_to(slope_lines2) data_points = [ self.input_to_graph_point(x) + ((random.random()-0.5)/x)*UP for x in np.arange(1, 12, 0.7) ] data_dots = VGroup(*[ Dot(point, radius = 0.05, color = YELLOW) for point in data_points ]) self.play(ShowCreation(data_dots, run_time = 3)) self.play(ShowCreation(self.graph)) self.wait() self.play( ShowCreation(slope_lines1), Write(slope_label1) ) self.wait() self.play( ShowCreation(slope_lines2), Write(slope_label2) ) self.wait() class SlopeAlwaysAboveOne(WhatSlopeDoesLogLogPlotApproach): CONFIG = { "words" : "Slope always $> 1$", "x_max" : 20, } class ChangeWorldview(TeacherStudentsScene): def construct(self): self.teacher_says(""" This changes how you see the world. """) self.play_student_changes(*["thinking"]*3) self.wait(3) class CompareBritainAndNorway(Scene): def construct(self): norway = Norway( fill_opacity = 0, stroke_width = 2, ) norway.to_corner(UP+RIGHT, buff = 0) fractalify(norway, order = 1, dimension = 1.5) anchors = list(norway.get_anchors()) anchors.append(FRAME_X_RADIUS*RIGHT+FRAME_Y_RADIUS*UP) norway.set_points_as_corners(anchors) britain = Britain( fill_opacity = 0, stroke_width = 2 ) britain.shift(FRAME_X_RADIUS*LEFT/2) britain.to_edge(UP) fractalify(britain, order = 1, dimension = 1.21) britain_label = OldTexText(""" Britain coast: 1.21-dimensional """) norway_label = OldTexText(""" Norway coast: 1.52-dimensional """) britain_label.next_to(britain, DOWN) norway_label.next_to(britain_label, RIGHT, aligned_edge = DOWN) norway_label.to_edge(RIGHT) self.add(britain_label, norway_label) self.play( *list(map(ShowCreation, [norway, britain])), run_time = 3 ) self.wait() self.play(*it.chain(*[ [ mob.set_stroke, None, 0, mob.set_fill, BLUE, 1 ] for mob in (britain, norway) ])) self.wait(2) class CompareOceansLabels(Scene): def construct(self): label1 = OldTexText("Dimension $\\approx 2.05$") label2 = OldTexText("Dimension $\\approx 2.3$") label1.shift(FRAME_X_RADIUS*LEFT/2).to_edge(UP) label2.shift(FRAME_X_RADIUS*RIGHT/2).to_edge(UP) self.play(Write(label1)) self.wait() self.play(Write(label2)) self.wait() class CompareOceans(Scene): def construct(self): pass class FractalNonFractalFlowChart(Scene): def construct(self): is_fractal = OldTexText("Is it a \\\\ fractal?") nature = OldTexText("Probably from \\\\ nature") man_made = OldTexText("Probably \\\\ man-made") is_fractal.to_edge(UP) nature.shift(FRAME_X_RADIUS*LEFT/2) man_made.shift(FRAME_X_RADIUS*RIGHT/2) yes_arrow = Arrow( is_fractal.get_bottom(), nature.get_top() ) no_arrow = Arrow( is_fractal.get_bottom(), man_made.get_top() ) yes = OldTexText("Yes") no = OldTexText("No") yes.set_color(GREEN) no.set_color(RED) for word, arrow in (yes, yes_arrow), (no, no_arrow): word.next_to(ORIGIN, UP) word.rotate(arrow.get_angle()) if word is yes: word.rotate(np.pi) word.shift(arrow.get_center()) britain = Britain() britain.set_height(3) britain.to_corner(UP+LEFT) self.add(britain) randy = Randolph() randy.set_height(3) randy.to_corner(UP+RIGHT) self.add(randy) self.add(is_fractal) self.wait() for word, arrow, answer in (yes, yes_arrow, nature), (no, no_arrow, man_made): self.play( ShowCreation(arrow), Write(word, run_time = 1) ) self.play(Write(answer, run_time = 1)) if word is yes: self.wait() else: self.play(Blink(randy)) class ShowPiCreatureFractalCreation(FractalCreation): CONFIG = { "fractal_class" : PentagonalPiCreatureFractal, "max_order" : 4, } class FractalPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Meshal Alshammari", "Ali Yahya", "CrypticSwarm ", "Yu Jun", "Shelby Doolittle", "Dave Nicponski", "Damion Kistler", "Juan Batiz-Benet", "Othman Alikhan", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Jerry Ling", "Mark Govea", "Guido Gambardella", "Vecht ", "Jonathan Eppele", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } class AffirmLogo(SVGMobject): CONFIG = { "fill_color" : "#0FA0EA", "fill_opacity" : 1, "stroke_color" : "#0FA0EA", "stroke_width" : 0, "file_name" : "affirm_logo", "width" : 3, } def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.set_width(self.width) class MortyLookingAtRectangle(Scene): def construct(self): morty = Mortimer() morty.to_corner(DOWN+RIGHT) url = OldTexText("affirmjobs.3b1b.co") url.to_corner(UP+LEFT) rect = Rectangle(height = 9, width = 16) rect.set_height(5) rect.next_to(url, DOWN) rect.shift_onto_screen() url.save_state() url.next_to(morty.get_corner(UP+LEFT), UP) affirm_logo = AffirmLogo()[0] affirm_logo.to_corner(UP+RIGHT, buff = MED_LARGE_BUFF) affirm_logo.shift(0.5*DOWN) self.add(morty) affirm_logo.save_state() affirm_logo.shift(DOWN) affirm_logo.set_fill(opacity = 0) self.play( ApplyMethod(affirm_logo.restore, run_time = 2), morty.look_at, affirm_logo, ) self.play( morty.change_mode, "raise_right_hand", morty.look_at, url, ) self.play(Write(url)) self.play(Blink(morty)) self.wait() self.play( url.restore, morty.change_mode, "happy" ) self.play(ShowCreation(rect)) self.wait() self.play(Blink(morty)) for mode in ["wave_2", "hooray", "happy", "pondering", "happy"]: self.play(morty.change_mode, mode) self.wait(2) self.play(Blink(morty)) self.wait(2) class Thumbnail(Scene): def construct(self): title = OldTexText("1.5-dimensional") title.scale(2) title.to_edge(UP) koch_curve = QuadraticKoch(order = 6, monochromatic = True) koch_curve.set_stroke(width = 0) koch_curve.set_fill(BLUE) koch_curve.set_height(1.5*FRAME_Y_RADIUS) koch_curve.to_edge(DOWN, buff = SMALL_BUFF) self.add(koch_curve, title)
videos_3b1b/_2017/bell.py
from manim_imports_ext import * from tqdm import tqdm as ProgressDisplay from .waves import * from functools import reduce #force_skipping #revert_to_original_skipping_status class PhotonPassesCompletelyOrNotAtAll(DirectionOfPolarizationScene): CONFIG = { "pol_filter_configs" : [{ "include_arrow_label" : False, "label_tex" : "\\text{Filter}", }], "EMWave_config" : { "wave_number" : 0, "A_vect" : [0, 1, 1], "start_point" : FRAME_X_RADIUS*LEFT + DOWN + 1.5*OUT, }, "start_theta" : -0.9*np.pi, "target_theta" : -0.6*np.pi, "apply_filter" : True, "lower_portion_shift" : 3*IN, "show_M_vects" : True, } def setup(self): DirectionOfPolarizationScene.setup(self) if not self.show_M_vects: for M_vect in self.em_wave.M_vects: M_vect.set_fill(opacity = 0) self.update_mobjects() for vect in it.chain(self.em_wave.E_vects, self.em_wave.M_vects): vect.reset_normal_vector() self.remove(self.em_wave) def construct(self): pol_filter = self.pol_filter pol_filter.shift(0.5*OUT) lower_filter = pol_filter.copy() lower_filter.save_state() pol_filter.remove(pol_filter.label) passing_words = OldTexText("Photon", "passes through\\\\", "entirely") passing_words.set_color(GREEN) filtered_words = OldTexText("Photon", "is blocked\\\\", "entirely") filtered_words.set_color(RED) for words in passing_words, filtered_words: words.next_to(ORIGIN, UP+LEFT) words.shift(2*UP) words.add_background_rectangle() words.rotate(np.pi/2, RIGHT) filtered_words.shift(self.lower_portion_shift) passing_photon = WavePacket( run_time = 2, get_filtered = False, em_wave = self.em_wave.copy() ) lower_em_wave = self.em_wave.copy() lower_em_wave.mobject.shift(self.lower_portion_shift) lower_em_wave.start_point += self.lower_portion_shift filtered_photon = WavePacket( run_time = 2, get_filtered = True, em_wave = lower_em_wave.copy() ) green_flash = ApplyMethod( pol_filter.set_fill, GREEN, rate_func = squish_rate_func(there_and_back, 0.4, 0.6), run_time = passing_photon.run_time ) self.play( DrawBorderThenFill(pol_filter), Write(pol_filter.label, run_time = 2), ) self.move_camera(theta = self.target_theta) self.play( FadeIn(passing_words), passing_photon, green_flash, ) self.play( lower_filter.restore, lower_filter.shift, self.lower_portion_shift, FadeIn(filtered_words) ) red_flash = ApplyMethod( lower_filter.set_fill, RED, rate_func = squish_rate_func(there_and_back, 0.4, 0.6), run_time = filtered_photon.run_time ) for x in range(4): self.play( passing_photon, filtered_photon, green_flash, red_flash, ) self.wait() class PhotonPassesCompletelyOrNotAtAllForWavesVideo(PhotonPassesCompletelyOrNotAtAll): CONFIG = { "show_M_vects" : False, } class DirectionOfPolarization(DirectionOfPolarizationScene): def construct(self): self.remove(self.pol_filter) self.axes.z_axis.rotate(np.pi/2, OUT) words = OldTexText("Polarization direction") words.next_to(ORIGIN, UP+RIGHT, LARGE_BUFF) words.shift(2*UP) words.rotate(np.pi/2, RIGHT) words.rotate(-np.pi/2, OUT) em_wave = self.em_wave self.add(em_wave) self.wait(2) self.move_camera( phi = self.target_phi, theta = self.target_theta ) self.play(Write(words, run_time = 1)) for angle in 2*np.pi/3, -np.pi/3, np.pi/4: self.change_polarization_direction(angle) self.wait() self.wait(2) class PhotonsThroughPerpendicularFilters(PhotonPassesCompletelyOrNotAtAll): CONFIG = { "filter_x_coordinates" : [-2, 2], "pol_filter_configs" : [ {"filter_angle" : 0}, {"filter_angle" : np.pi/2}, ], "start_theta" : -0.9*np.pi, "target_theta" : -0.6*np.pi, "EMWave_config" : { "A_vect" : [0, 0, 1], "start_point" : FRAME_X_RADIUS*LEFT + DOWN + OUT, }, "apply_filter" : False, } def construct(self): photons = self.get_photons() prob_text = self.get_probability_text() self.pol_filters = VGroup(*reversed(self.pol_filters)) ninety_filter, zero_filter = self.pol_filters self.remove(*self.pol_filters) self.play(DrawBorderThenFill(zero_filter), run_time = 1) self.add_foreground_mobject(zero_filter) self.move_camera( theta = self.target_theta, added_anims = [ApplyFunction( self.reposition_filter_label, zero_filter )] ) self.reposition_filter_label(ninety_filter) self.play(self.get_photons()[2]) self.play(FadeIn(ninety_filter)) self.add_foreground_mobject(ninety_filter) self.shoot_photon() self.shoot_photon() self.play(FadeIn(prob_text)) for x in range(6): self.shoot_photon() def reposition_filter_label(self, pf): pf.arrow_label.rotate(np.pi/2, OUT) pf.arrow_label.next_to(pf.arrow, RIGHT) return pf def shoot_photon(self, *added_anims): photon = self.get_photons()[1] pol_filter = self.pol_filters[0] absorption = self.get_filter_absorption_animation(pol_filter, photon) self.play(photon, absorption) def get_photons(self): self.reference_line.rotate(np.pi/4) self.update_mobjects() return [ WavePacket( filter_distance = FRAME_X_RADIUS + x, get_filtered = True, em_wave = self.em_wave.copy(), run_time = 1, ) for x in (-2, 2, 10) ] def get_probability_text(self, prob = 0): prob_text = OldTex( "P(", "\\substack", "{\\text{photons that make it} \\\\ ", " \\text{here } ", "\\text{make it}", " \\text{ here} }", ")", "=", str(int(prob*100)), "\\%", arg_separator = "" ) here1, here2 = prob_text.get_parts_by_tex("here") here1.set_color(GREEN) here2.set_color(RED) prob_text.add_background_rectangle() prob_text.next_to(ORIGIN, UP+RIGHT) prob_text.shift(2.5*UP+LEFT) prob_text.rotate(np.pi/2, RIGHT) arrows = [ Arrow( here.get_edge_center(IN), DOWN+OUT + x*RIGHT, color = here.get_color(), normal_vector = DOWN+OUT, ) for here, x in ((here1, 0), (here2, 4)) ] prob_text.add(*arrows) return prob_text class MoreFiltersMoreLight(FilterScene): CONFIG = { "filter_x_coordinates" : list(range(-2, 3)), "pol_filter_configs" : [ { "include_arrow_label" : False, "filter_angle" : angle } for angle in np.linspace(0, np.pi/2, 5) ], "ambient_rotation_rate" : 0, "arrow_rgb" : (0, 0, 0), "background_rgb" : (245, 245, 245), } def construct(self): self.remove(self.axes) pfs = VGroup(*reversed(self.pol_filters)) self.color_filters(pfs) self.remove(pfs) self.build_color_map(pfs) self.add(pfs[0], pfs[2], pfs[4]) pfs.center().scale(1.5) self.move_camera( phi = 0.9*np.pi/2, theta = -0.95*np.pi, ) self.play( Animation(pfs[0]), pfs[2].shift, 3*OUT, Animation(pfs[4]), ) self.wait() self.play( Animation(pfs[0]), pfs[2].shift, 3*IN, Animation(pfs[4]), ) pfs[1].shift(8*OUT) self.play( Animation(pfs[0]), pfs[1].shift, 8*IN, Animation(VGroup(pfs[2], pfs[4])), run_time = 2 ) self.wait() pfs[3].shift(8*OUT) self.play( Animation(VGroup(*pfs[:3])), pfs[3].shift, 8*IN, Animation(VGroup(*pfs[4:])), run_time = 2 ) self.wait() def color_filters(self, pfs): colors = [RED, GREEN, BLUE, MAROON_B, PURPLE_C] for pf, color in zip(pfs, colors): pf.set_fill(color, 0.5) pf.arrow.set_fill(WHITE, 1) turn_off_3d_shading(pfs) def build_color_map(self, pfs): phi, theta = self.camera.get_phi(), self.camera.get_theta() self.set_camera_orientation(np.pi/2, -np.pi) self.original_rgbas = [(255, 255, 255)] self.new_rgbas = [self.arrow_rgb] for bool_array in it.product(*5*[[True, False]]): pfs_to_use = VGroup(*[ pf for pf, b in zip(pfs, bool_array) if b ]) self.camera.capture_mobject(pfs_to_use) frame = self.camera.get_image() h, w, three = frame.shape rgb = frame[3*h/8, 7*w/12] self.original_rgbas.append(rgb) angles = [pf.filter_angle for pf in pfs_to_use] p = 0.5 for a1, a2 in zip(angles, angles[1:]): p *= np.cos(a2 - a1)**2 new_rgb = (255*p*np.ones(3)).astype(int) if not any(bool_array): new_rgb = self.background_rgb self.new_rgbas.append(new_rgb) self.camera.reset() self.set_camera_orientation(phi, theta) def update_frame(self, mobjects = None, image = None): FilterScene.update_frame(self, mobjects) def get_frame(self): frame = FilterScene.get_frame(self) bool_arrays = [ (frame[:,:,0] == r) & (frame[:,:,1] == g) & (frame[:,:,2] == b) for (r, g, b) in self.original_rgbas ] for ba, new_rgb in zip(bool_arrays, self.new_rgbas): frame[ba] = new_rgb covered = reduce( lambda b1, b2 : b1 | b2, bool_arrays ) frame[~covered] = [65, 65, 65] return frame class MoreFiltersMoreLightBlackBackground(MoreFiltersMoreLight): CONFIG = { "arrow_rgb" : (255, 255, 255), "background_rgb" : (0, 0, 0), } class ConfusedPiCreature(Scene): def construct(self): randy = Randolph() self.play( randy.change, "confused", 3*(UP+RIGHT), ) self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) self.wait(2) class AngryPiCreature(PiCreatureScene): def construct(self): self.pi_creature_says( "No, \\emph{locality} \\\\ must be wrong!", target_mode = "angry", look_at = 2*RIGHT, run_time = 1 ) self.wait(3) def create_pi_creature(self): return Randolph().shift(DOWN+3*LEFT) class ShowALittleMath(TeacherStudentsScene): def construct(self): exp1 = OldTex( "|", "\\psi", "\\rangle = ", "\\alpha", "|\\uparrow\\rangle", "+", "\\beta", "|\\rightarrow\\rangle" ) exp2 = OldTex( "|| \\langle", "\\psi", "|", "\\psi", "\\rangle ||^2", "= ", "\\alpha", "^2", "+", "\\beta", "^2" ) color_map = { "alpha" : GREEN, "beta" : RED, "psi" : BLUE } for exp in exp1, exp2: exp.set_color_by_tex_to_color_map(color_map) exp1.next_to(self.teacher.get_corner(UP+LEFT), UP, LARGE_BUFF) exp2.move_to(exp1) self.play( Write(exp1, run_time = 2), self.teacher.change, "raise_right_hand" ) self.play(exp1.shift, UP) self.play(*[ ReplacementTransform( exp1.get_parts_by_tex(tex).copy(), exp2.get_parts_by_tex(tex).copy(), ) for tex in list(color_map.keys()) ] + [Write(exp2, run_time = 2)]) self.play_student_changes( *["pondering"]*3, look_at = exp2 ) self.wait(2) class SecondVideoWrapper(Scene): def construct(self): title = OldTexText("Some light quantum mechanics") title.to_edge(UP) self.add(title) screen_rect = ScreenRectangle(height = 6) screen_rect.next_to(title, DOWN) self.play(ShowCreation(screen_rect)) self.wait(3) class BasicsOfPolarization(DirectionOfPolarizationScene): CONFIG = { "apply_filter" : True, } def construct(self): self.setup_rectangles() self.show_continual_wave() self.show_photons() def show_continual_wave(self): em_wave = self.em_wave title = OldTexText("Waves in the ``electromagnetic field''") title.to_edge(UP) subtitle = OldTexText("Polarization = Direction of", "wiggling") subtitle.set_color_by_tex("wiggling", BLUE) subtitle.next_to(title, DOWN) for words in title, subtitle: words.add_background_rectangle() words.rotate(np.pi/2, RIGHT) self.play(Write(title)) self.wait(2) self.play( Write(subtitle, run_time = 2), FadeIn(self.rectangles) ) self.change_polarization_direction(np.pi/2, run_time = 3) self.wait() self.change_polarization_direction(-np.pi/12, run_time = 2) self.move_camera(theta = -0.95*np.pi) self.change_polarization_direction(-np.pi/6, run_time = 2) self.change_polarization_direction(np.pi/6, run_time = 2) self.move_camera(theta = -0.6*np.pi) self.change_polarization_direction(-np.pi/6, run_time = 2) self.change_polarization_direction(np.pi/6, run_time = 2) self.change_polarization_direction(-5*np.pi/12, run_time = 2) self.play( FadeOut(em_wave.mobject), FadeOut(self.rectangles), ) self.remove(em_wave) self.reference_line.put_start_and_end_on(ORIGIN, RIGHT) def show_photons(self): quantum_left_words = OldTexText( "Quantum", "$\\Rightarrow$", ) quantum_left_words.next_to(ORIGIN, UP+RIGHT) quantum_left_words.shift(UP) quantum_right_words = OldTexText( "Completely through", "or \\\\", "Completely blocked", ) quantum_right_words.scale(0.8) quantum_right_words.next_to(quantum_left_words, buff = 0) quantum_right_words.set_color_by_tex("through", GREEN) quantum_right_words.set_color_by_tex("blocked", RED) quantum_words = VGroup(quantum_left_words, quantum_right_words) quantum_words.rotate(np.pi/2, RIGHT) prob_eq = OldTex( "&P(", "\\text{Pass}", ")", "=", "p\\\\", "&P(", "\\text{Blocked}", ")", "=", "1-p", ) prob_eq.set_color_by_tex_to_color_map({ "Pass" : GREEN, "Blocked" : RED, }) prob_eq.next_to(ORIGIN, DOWN+RIGHT) prob_eq.shift(RIGHT) prob_eq.rotate(np.pi/2, RIGHT) config = dict(self.EMWave_config) config.update({ "wave_number" : 0, "A_vect" : [0, 1, -1], }) self.em_wave = EMWave(**config) self.update_mobjects() passing_photon = WavePacket( em_wave = self.em_wave.copy(), run_time = 1.5, ) filtered_photon = WavePacket( em_wave = self.em_wave.copy(), get_filtered = True, run_time = 1.5, ) self.play(FadeIn( quantum_words, run_time = 2, lag_ratio = 0.5 )) anim_sets = [ [passing_photon], [ filtered_photon, self.get_filter_absorption_animation( self.pol_filter, filtered_photon ) ], ] for index in 0, 1: self.play(*anim_sets[index]) self.play( # FadeIn(prob_eq, lag_ratio = 0.5), passing_photon ) for index in 1, 0, 0, 1: self.play(*anim_sets[index]) class AngleToProbabilityChart(Scene): def construct(self): left_title = OldTexText("Angle between \\\\ filters") left_title.to_corner(UP+LEFT) right_title = OldTexText( "Probability that photons passing \\\\", "through the first pass through the second" ) right_title.next_to(left_title, RIGHT, LARGE_BUFF) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.to_edge(UP, buff = 2) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.next_to(left_title, RIGHT, MED_LARGE_BUFF) v_line.to_edge(UP, buff = 0) VGroup(h_line, v_line).set_color(BLUE) self.add(left_title, right_title, h_line, v_line) angles = [0, 22.5, 45, 67.5, 90] angle_mobs = VGroup(*[ OldTex(str(angle) + "^\\circ") for angle in angles ]) angle_mobs.arrange(DOWN, buff = MED_LARGE_BUFF) angle_mobs.next_to(left_title, DOWN, LARGE_BUFF) probs = [ np.cos(angle*np.pi/180.0)**2 for angle in angles ] prob_mobs = VGroup(*[ OldTex("%.1f"%(100*prob) + "\\%") for prob in probs ]) prob_mobs.set_color(YELLOW) angle_prob_pairs = list(zip(angle_mobs, prob_mobs)) for angle_mob, prob_mob in angle_prob_pairs: prob_mob.next_to(angle_mob, RIGHT, buff = 3) for prob_mob in prob_mobs[1:]: prob_mob.align_to(prob_mobs[0], LEFT) for i in [0, 4, 2, 1, 3]: self.play(FadeIn(angle_mobs[i])) self.play(ReplacementTransform( angle_mobs[i].copy(), prob_mobs[i] )) explanation = OldTexText("Based on $\\cos(\\theta)^2$") explanation.next_to(prob_mobs, RIGHT, LARGE_BUFF) self.play(Write(explanation, run_time = 2)) self.wait() class ShowVariousFilterPairsWithPhotonsOverTime(PhotonsThroughPerpendicularFilters): CONFIG = { "filter_x_coordinates" : [-2, 2, 2, 2, 2], "pol_filter_configs" : [ {"filter_angle" : angle} for angle in (0, 0, np.pi/2, np.pi/4, np.pi/8) ], "apply_filter" : False, } def setup(self): PhotonsThroughPerpendicularFilters.setup(self) self.new_filters = self.pol_filters[2:] self.remove(*self.new_filters) self.pol_filters = self.pol_filters[:2] def construct(self): self.photons = self.get_photons() self.add_filters() self.add_probability_text() self.show_photons() for pol_filter in self.new_filters: self.change_to_new_filter(pol_filter) self.show_photons() def add_filters(self): self.remove(*self.pol_filters[1:]) self.wait() self.play(ReplacementTransform( self.pol_filters[0].copy().set_fill(BLACK, 1), self.pol_filters[1] )) self.move_camera( theta = -0.65*np.pi, added_anims = list(it.chain(*[ [ pf.arrow_label.rotate, np.pi/2, OUT, pf.arrow_label.next_to, pf.arrow, RIGHT ] for pf in self.pol_filters[:2] ])) ) for pf in self.new_filters: pf.arrow_label.rotate(np.pi/2, OUT) pf.arrow_label.next_to(pf.arrow, RIGHT) self.second_filter = self.pol_filters[1] self.add_foreground_mobject(self.second_filter) def add_probability_text(self): prob_text = self.get_probability_text(self.get_prob()) self.play(FadeIn(prob_text)) self.prob_text = prob_text def show_photons(self, n_photons = 5): p = self.get_prob() blocked_photon = copy.deepcopy(self.photons[0]) blocked_photon.rate_func = squish_rate_func( lambda x : x, 0, 0.5, ) first_absorption = self.get_filter_absorption_animation( self.pol_filters[0], blocked_photon ) first_absorption.rate_func = squish_rate_func( first_absorption.rate_func, 0, 0.5, ) photons = [ copy.deepcopy(self.photons[2 if q <= p else 1]) for q in np.arange(0, 1, 1./n_photons) ] random.shuffle(photons) for photon in photons: photon.rate_func = squish_rate_func( lambda x : x, 0.5, 1 ) added_anims = [] if photon.filter_distance == FRAME_X_RADIUS + 2: absorption = self.get_filter_absorption_animation( self.second_filter, photon ) absorption.rate_func = squish_rate_func( absorption.rate_func, 0.5, 1 ) added_anims.append(absorption) self.play( blocked_photon, first_absorption, photon, *added_anims ) self.wait() def change_to_new_filter(self, pol_filter, added_anims = None): if added_anims is None: added_anims = [] self.play( Transform(self.second_filter, pol_filter), *added_anims ) self.second_filter.filter_angle = pol_filter.filter_angle new_prob_text = self.get_probability_text(self.get_prob()) new_prob_text[1][-2].set_color(YELLOW) self.play(Transform(self.prob_text, new_prob_text)) #### def get_prob(self, pol_filter = None): if pol_filter is None: pol_filter = self.second_filter return np.cos(pol_filter.filter_angle)**2 class ShowVariousFilterPairs(ShowVariousFilterPairsWithPhotonsOverTime): CONFIG = { "filter_x_coordinates" : [], "filter_z_coordinates" : [2.5, 0, -2.5], "angles" : [0, np.pi/4, np.pi/2], "n_lines" : 20, "new_group_shift_val" : 2.5*IN, "prev_group_shift_val" : 1.75*IN, "ambient_rotation_rate" : 0.015, "line_start_length" : 16, "line_end_length" : 16, "lines_depth" : 1.2, "lines_shift_vect" : SMALL_BUFF*OUT, } def setup(self): ShowVariousFilterPairsWithPhotonsOverTime.setup(self) self.remove(*self.pol_filters) self.prev_groups = VGroup() self.remove(self.axes) self.setup_filters() self.stop_ambient_camera_rotation() self.prob_texts = VGroup() def setup_filters(self): self.filter_pairs = [] zs = self.filter_z_coordinates for non_zero_angle, z in zip(self.angles, zs): filter_pair = VGroup() for angle, x in (0, -3), (non_zero_angle, 3): pf = PolarizingFilter(filter_angle = angle) pf.scale(0.7) pf.rotate(np.pi/2, RIGHT) pf.rotate(np.pi/2, IN) pf.shift(x*RIGHT + z*OUT) pf.arrow_label.rotate(np.pi/2, OUT) pf.arrow_label.next_to(pf.arrow, RIGHT, SMALL_BUFF) filter_pair.add(pf) self.filter_pairs.append(filter_pair) def construct(self): self.add_top_filters() self.show_light(self.filter_pairs[0]) self.turn_one_filter_pair_into_another(0, 2) self.show_light(self.filter_pairs[2]) self.turn_one_filter_pair_into_another(2, 1) self.show_light(self.filter_pairs[1]) def add_top_filters(self): pf1, pf2 = pair = self.filter_pairs[0] for pf in pair: pf.save_state() pf.arrow_label.rotate(np.pi/2, IN) pf.arrow_label.next_to(pf.arrow, UP, SMALL_BUFF) pf.shift(2*IN) self.add(pf1) self.play( ReplacementTransform(pf1.copy().fade(1), pf2), Animation(pf1) ) self.move_camera( 0.9*np.pi/2, -0.6*np.pi, added_anims = [ pf.restore for pf in pair ] ) def show_light(self, filter_pair): pf1, pf2 = filter_pair lines_to_pf1 = self.get_lines(None, pf1) vect = lines_to_pf1[1].get_center() - lines_to_pf1[0].get_center() lines_to_pf1.add(*lines_to_pf1.copy().shift(vect/2)) lines_to_pf2 = self.get_lines(pf1, pf2) lines_from_pf2 = self.get_lines(pf2) prob = self.get_prob(pf2) n_black = int(prob*len(lines_from_pf2)) VGroup(*lines_from_pf2[n_black:]).set_stroke(BLACK, 0) kwargs = { "rate_func" : None, "lag_ratio" : 0, } self.play(ShowCreation(lines_to_pf1, run_time = 2./3, **kwargs)) self.play( ShowCreation(lines_to_pf2, **kwargs), Animation(VGroup(pf1, lines_to_pf1)), run_time = 1./6, ) self.play( ShowCreation(lines_from_pf2, **kwargs), Animation(VGroup(pf2, lines_to_pf2, pf1, lines_to_pf1)), run_time = 2./3, ) group = VGroup( lines_from_pf2, pf2, lines_to_pf2, pf1, lines_to_pf2 ) #Write probability prob_text = self.get_probability_text(pf2) self.play(Write(prob_text, run_time = 1)) self.wait() self.prob_texts.add(prob_text) def turn_one_filter_pair_into_another(self, i1, i2): mover = self.filter_pairs[i1].copy() mover.set_stroke(width = 0) mover.set_fill(opacity = 0) target = self.filter_pairs[i2] self.play(ReplacementTransform(mover, target)) def get_probability_text(self, pol_filter = None): if pol_filter is None: pol_filter = self.second_filter prob = self.get_prob(pol_filter) prob_mob = OldTexText(str(int(prob*100)) + "\\%", " pass") prob_mob.scale(0.7) prob_mob.rotate(np.pi/2, RIGHT) prob_mob.next_to(pol_filter.arrow_label, RIGHT) prob_mob.set_color( list(Color(RED).range_to(GREEN, 11))[int(prob*10)] ) return prob_mob ##### def get_lines( self, filter1 = None, filter2 = None, ratio = 1.0, remove_from_bottom = False, ): # n = int(ratio*self.n_lines) n = self.n_lines start, end = [ (f.point_from_proportion(0.75) if f is not None else None) for f in (filter1, filter2) ] if start is None: start = end + self.line_start_length*LEFT if end is None: end = start + self.line_end_length*RIGHT nudge = (float(self.lines_depth)/self.n_lines)*OUT lines = VGroup(*[ Line(start, end).shift(z*nudge) for z in range(n) ]) lines.set_stroke(YELLOW, 2) lines.move_to(start, IN+LEFT) lines.shift(self.lines_shift_vect) n_to_block = int((1-ratio)*self.n_lines) if remove_from_bottom: to_block = lines[:n_to_block] else: to_block = lines[len(lines)-n_to_block:] VGroup(*to_block).set_stroke(width = 0) return lines class ShowVariousFilterPairsFrom0To45(ShowVariousFilterPairs): CONFIG = { "angles" : [0, np.pi/8, np.pi/4] } def construct(self): ShowVariousFilterPairs.construct(self) self.mention_probabilities() def mention_probabilities(self): rects = VGroup() for prob_text in self.prob_texts: prob_text.rotate(np.pi/2, LEFT) rect = SurroundingRectangle(prob_text, color = BLUE) VGroup(prob_text, rect).rotate(np.pi/2, RIGHT) rects.add(rect) cosines = VGroup(*[ OldTex("\\cos^2(%s^\\circ)"%str(x)) for x in (45, 22.5) ]) cosines.scale(0.8) # cosines.set_color(BLUE) cosines.rotate(np.pi/2, RIGHT) for cos, rect in zip(cosines, rects[1:]): cos.next_to(rect, OUT, SMALL_BUFF) self.play(LaggedStartMap(ShowCreation, rects)) self.wait() self.play(*list(map(Write, cosines)), run_time = 2) self.wait() class ForgetPreviousActions(ShowVariousFilterPairs): CONFIG = { "filter_x_coordinates" : [-6, -2, 2, 2, 2], "pol_filter_configs" : [ {"filter_angle" : angle} for angle in (np.pi/4, 0, np.pi/4, np.pi/3, np.pi/6) ], "start_theta" : -0.6*np.pi, "EMWave_config" : { "wave_number" : 0, "start_point" : FRAME_X_RADIUS*LEFT + DOWN, }, "apply_filter" : False, } def setup(self): PhotonsThroughPerpendicularFilters.setup(self) self.remove(self.axes) VGroup(*self.pol_filters).shift(IN) for pf in self.pol_filters: pf.arrow_label.rotate(np.pi/2, OUT) pf.arrow_label.next_to(pf.arrow, RIGHT) self.stop_ambient_camera_rotation() def construct(self): front_filter = self.pol_filters[0] first_filter = self.pol_filters[1] possible_second_filters = self.pol_filters[2:] for pf in possible_second_filters: prob_text = self.get_probability_text(pf) prob_text.scale(1.3, about_point = prob_text.get_left()) pf.add(prob_text) second_filter = possible_second_filters[0].copy() self.second_filter = second_filter self.pol_filters = VGroup( first_filter, second_filter ) self.remove(front_filter) self.remove(*possible_second_filters) self.add(second_filter) self.apply_filter = True self.update_mobjects() self.photons = self.get_photons()[1:] group = VGroup(*self.pol_filters) rect1 = SurroundingRectangle(group) rect1.rotate(np.pi/2, RIGHT) rect1.rescale_to_fit(group.get_depth()+MED_SMALL_BUFF, 2, True) rect1.stretch_in_place(1.2, 0) prob_words = OldTexText( "Probabilities depend only\\\\", "on this angle difference" ) prob_words.add_background_rectangle() prob_words.rotate(np.pi/2, RIGHT) prob_words.next_to(rect1, OUT) self.add(rect1) self.play(FadeIn(prob_words)) for index in 1, 2: self.shoot_photon() self.play(Transform( second_filter, possible_second_filters[index] )) rect2 = SurroundingRectangle(front_filter, color = RED) rect2.rotate(np.pi/2, RIGHT) rect2.rescale_to_fit(front_filter.get_depth()+MED_SMALL_BUFF, 2, True) rect2.stretch_in_place(1.5, 0) ignore_words = OldTexText("Photon \\\\", "``forgets'' this") ignore_words.add_background_rectangle() ignore_words.rotate(np.pi/2, RIGHT) ignore_words.next_to(rect2, OUT) self.play( ShowCreation(rect2), Write(ignore_words, run_time = 1), FadeIn(front_filter), run_time = 1.5, ) self.shoot_photon() for index in 0, 1, 2: self.play(Transform( second_filter, possible_second_filters[index] )) self.shoot_photon() def shoot_photon(self): photon = random.choice(self.photons) added_anims = [] if photon.filter_distance == FRAME_X_RADIUS + 2: added_anims.append( ApplyMethod( self.second_filter.set_color, RED, rate_func = squish_rate_func(there_and_back, 0.5, 0.7) ) ) self.play(photon, *added_anims, run_time = 1.5) class IntroduceLabeledFilters(ShowVariousFilterPairs): CONFIG = { "filter_x_coordinates" : [-5, -2, 1], "pol_filter_configs" : [ {"filter_angle" : angle} for angle in [0, np.pi/8, np.pi/4] ], "start_phi" : 0.9*np.pi/2, "start_theta" : -0.85*np.pi, "target_theta" : -0.65*np.pi, "lines_depth" : 1.7, "lines_shift_vect" : MED_SMALL_BUFF*OUT, "line_start_length" : 3, "line_end_length" : 9, "ambient_rotation_rate" : 0.005, } def setup(self): PhotonsThroughPerpendicularFilters.setup(self) self.remove(self.axes) def construct(self): self.add_letters_to_labels() self.introduce_filters() self.reposition_camera() self.separate_cases() self.show_bottom_lines() self.comment_on_half_blocked_by_C() self.show_top_lines() self.comment_on_those_blocked_by_B() self.show_sum() def add_letters_to_labels(self): for char, pf, color in zip("ABC", self.pol_filters, [RED, GREEN, BLUE]): label = OldTexText(char) label.scale(0.9) label.add_background_rectangle() label.set_color(color) label.rotate(np.pi/2, RIGHT) label.rotate(np.pi/2, IN) label.next_to(pf.arrow_label, UP) pf.arrow_label.add(label) pf.arrow_label.next_to(pf.arrow, OUT, SMALL_BUFF) self.remove(*self.pol_filters) def introduce_filters(self): self.A_filter, self.B_filter, self.C_filter = self.pol_filters for pf in self.pol_filters: pf.save_state() pf.shift(4*OUT) pf.fade(1) self.play(pf.restore) self.wait() def reposition_camera(self): self.move_camera( theta = self.target_theta, added_anims = list(it.chain(*[ [ pf.arrow_label.rotate, np.pi/2, OUT, pf.arrow_label.next_to, pf.arrow, RIGHT ] for pf in self.pol_filters ])) ) def separate_cases(self): self.lower_pol_filters = VGroup( self.A_filter.deepcopy(), self.C_filter.deepcopy(), ) self.lower_pol_filters.save_state() self.lower_pol_filters.fade(1) self.play( self.lower_pol_filters.restore, self.lower_pol_filters.shift, 3*IN, self.pol_filters.shift, 1.5*OUT, ) self.wait() def show_bottom_lines(self): A, C = self.lower_pol_filters lines_to_A = self.get_lines(None, A) vect = lines_to_A[1].get_center() - lines_to_A[0].get_center() lines_to_A.add(*lines_to_A.copy().shift(vect/2)) lines_to_C = self.get_lines(A, C) lines_from_C = self.get_lines(C, ratio = 0.5) kwargs = { "rate_func" : None, "lag_ratio" : 0, "run_time" : 1./3, } self.play( ShowCreation(lines_to_A), **kwargs ) self.play( ShowCreation(lines_to_C), Animation(VGroup(A, lines_to_A)), **kwargs ) kwargs["run_time"] = 3*kwargs["run_time"] self.play( ShowCreation(lines_from_C), Animation(VGroup(C, lines_to_C, A, lines_to_A)), **kwargs ) line_group = VGroup(lines_from_C, C, lines_to_C, A, lines_to_A) self.remove(*line_group) self.add_foreground_mobject(line_group) self.bottom_lines_group = line_group def comment_on_half_blocked_by_C(self): arrow = Arrow( ORIGIN, 3.5*RIGHT, path_arc = -0.9*np.pi, color = BLUE, stroke_width = 5, ) words = OldTexText("50\\% blocked") words.set_color(BLUE) words.next_to(arrow, RIGHT, buff = 0) group = VGroup(arrow, words) group.rotate(np.pi/2, RIGHT) group.shift(1.7*IN + 0.5*RIGHT) self.play( Write(words, run_time = 2), ShowCreation(arrow) ) self.wait(2) self.blocked_at_C_words = words self.blocked_at_C_label_group = VGroup(arrow, words) def show_top_lines(self): A, B, C = self.pol_filters lines_to_A = self.get_lines(None, A) vect = lines_to_A[1].get_center() - lines_to_A[0].get_center() lines_to_A.add(*lines_to_A.copy().shift(vect/2)) lines_to_B = self.get_lines(A, B) lines_to_C = self.get_lines(B, C, ratio = 0.85, remove_from_bottom = True) lines_from_C = self.get_lines(C, ratio = 0.85**2, remove_from_bottom = True) kwargs = { "rate_func" : None, "lag_ratio" : 0, "run_time" : 1./5, } self.play( ShowCreation(lines_to_A), **kwargs ) self.play( ShowCreation(lines_to_B), Animation(VGroup(A, lines_to_A)), **kwargs ) self.play( ShowCreation(lines_to_C), Animation(VGroup(B, lines_to_B, A, lines_to_A)), **kwargs ) kwargs["run_time"] = 3*kwargs["run_time"] self.play( ShowCreation(lines_from_C), Animation(VGroup(C, lines_to_C, B, lines_to_B, A, lines_to_A)), **kwargs ) line_group = VGroup( lines_from_C, C, lines_to_C, B, lines_to_B, A, lines_to_A ) self.remove(*line_group) self.add_foreground_mobject(line_group) self.top_lines_group = line_group def comment_on_those_blocked_by_B(self): arrow0 = Arrow( 2*LEFT, 0.5*(UP+RIGHT), path_arc = 0.8*np.pi, color = WHITE, stroke_width = 5, buff = 0 ) arrow1 = Arrow( 2*LEFT, ORIGIN, path_arc = 0.8*np.pi, color = GREEN, stroke_width = 5, buff = 0 ) arrow2 = arrow1.copy() arrow2.next_to(arrow1, RIGHT, buff = LARGE_BUFF) words1 = OldTexText("15\\%", "blocked") words1.set_color(GREEN) words2 = words1.copy() words1.next_to(arrow1, DOWN, buff = SMALL_BUFF) words2.next_to(arrow2, DOWN, buff = SMALL_BUFF) words2.shift(MED_LARGE_BUFF*RIGHT) words0 = OldTexText("85\\%", "pass") words0.move_to(words1) group = VGroup(arrow0, arrow1, arrow2, words0, words1, words2) group.rotate(np.pi/2, RIGHT) group.shift(0.8*LEFT+1.5*OUT) self.play( ShowCreation(arrow0), Write(words0, run_time = 1) ) self.wait() self.play( ReplacementTransform(words0, words1), ReplacementTransform(arrow0, arrow1), ) self.wait() self.play( ShowCreation(arrow2), Write(words2) ) self.wait(2) self.fifteens = VGroup(words1, words2) self.blocked_at_B_label_group = VGroup( words1, words2, arrow1, arrow2 ) def show_sum(self): fifteen1, fifteen2 = self.fifteens fifty = self.blocked_at_C_words plus = OldTex("+").rotate(np.pi/2, RIGHT) plus.move_to(Line(fifteen1.get_right(), fifteen2.get_left())) equals = OldTex("=").rotate(np.pi/2, RIGHT) equals.next_to(fifteen2, RIGHT, 2*SMALL_BUFF) q_mark = OldTex("?").rotate(np.pi/2, RIGHT) q_mark.next_to(equals, OUT, SMALL_BUFF) q_mark.set_color(RED) randy = Randolph(mode = "confused").flip() randy.scale(0.7) randy.rotate(np.pi/2, RIGHT) randy.move_to(fifty) randy.shift(0.5*RIGHT) randy.look_at(equals) blinked = randy.copy() blinked.rotate(np.pi/2, LEFT) blinked.blink() blinked.rotate(np.pi/2, RIGHT) self.play( fifteen1.set_color, YELLOW, Write(plus) ) self.play( fifteen2.set_color, YELLOW, Write(equals) ) self.play( fifty.next_to, equals, RIGHT, 2*SMALL_BUFF, Write(q_mark), FadeIn(randy) ) self.play(Transform( randy, blinked, rate_func = squish_rate_func(there_and_back) )) self.wait(3) class IntroduceLabeledFiltersNoRotation(IntroduceLabeledFilters): CONFIG = { "ambient_rotation_rate" : 0, "target_theta" : -0.55*np.pi, } class RemoveBFromLabeledFilters(IntroduceLabeledFiltersNoRotation): def construct(self): self.force_skipping() IntroduceLabeledFiltersNoRotation.construct(self) self.revert_to_original_skipping_status() self.setup_start() self.show_filter_B_removal() self.fade_in_labels() def show_sum(self): pass def setup_start(self): self.remove(self.blocked_at_C_label_group) self.remove(self.blocked_at_B_label_group) self.remove(self.bottom_lines_group) self.top_lines_group.save_state() self.top_lines_group.shift(2*IN) def show_filter_B_removal(self): top_lines_group = self.top_lines_group bottom_lines_group = self.bottom_lines_group mover = top_lines_group.copy() mover.save_state() mover.fade(1) sl1, sC, sl2, sB, sl3, sA, sl4 = mover tl1, tC, tl2, tA, tl3 = bottom_lines_group for line in tl2: line.scale(0.5, about_point = line.get_end()) kwargs = { "lag_ratio" : 0, "rate_func" : None, } self.play( top_lines_group.shift, 2*OUT, mover.restore, mover.shift, 2.5*IN, ) self.wait() self.play( ApplyMethod(sB.shift, 4*IN, rate_func = running_start), FadeOut(sl1), Animation(sC), FadeOut(sl2), ) self.play(ShowCreation(tl2, run_time = 0.25, **kwargs)) self.play( ShowCreation(tl1, run_time = 0.5, **kwargs), Animation(sC), Animation(tl2), ) self.wait() def fade_in_labels(self): self.play(*list(map(FadeIn, [ self.blocked_at_B_label_group, self.blocked_at_C_label_group, ]))) self.wait() class NumbersSuggestHiddenVariablesAreImpossible(TeacherStudentsScene): def construct(self): self.teacher_says( "These numbers suggest\\\\", "no hidden variables" ) self.play_student_changes("erm", "sassy", "confused") self.wait(3) class VennDiagramProofByContradiction(Scene): CONFIG = { "circle_colors" : [RED, GREEN, BLUE] } def construct(self): self.setup_venn_diagram_sections() self.draw_venn_diagram() self.show_100_photons() self.show_one_photon_answering_questions() self.put_all_photons_in_A() self.separate_by_B() self.separate_by_C() self.show_two_relevant_subsets() def draw_venn_diagram(self, send_to_corner = True): A, B, C = venn_diagram = VGroup(*[ Circle( radius = 3, stroke_width = 3, stroke_color = c, fill_opacity = 0.2, fill_color = c, ).shift(vect) for c, vect in zip( self.circle_colors, compass_directions(3, UP) ) ]) self.A_to_B_vect = B.get_center() - A.get_center() self.A_to_C_vect = C.get_center() - A.get_center() venn_diagram.center() labels = VGroup() alt_labels = VGroup() props = [1./12, 0.5, 0] angles = [0, np.pi/8, np.pi/4] for circle, char, prop, angle in zip(venn_diagram, "ABC", props, angles): label, alt_label = [ OldTexText( "%s \\\\"%start, "through", char + "$\\! \\uparrow$" ).set_color_by_tex(char, circle.get_color()) for start in ("Would pass", "Pass") ] for mob in label, alt_label: mob[-1][-1].rotate(-angle) mob[-1][-1].shift(0.5*SMALL_BUFF*UP) center = circle.get_center() label.move_to(center) label.generate_target() point = circle.point_from_proportion(prop) alt_label.scale(2) for mob in label.target, alt_label: mob.next_to(point, point-center, SMALL_BUFF) circle.label = label circle.alt_label = alt_label labels.add(label) alt_labels.add(alt_label) last_circle = None for circle in venn_diagram: added_anims = [] if last_circle: added_anims.append(MoveToTarget(last_circle.label)) self.play( DrawBorderThenFill(circle, run_time = 2), Write(circle.label, run_time = 2), *added_anims ) last_circle = circle self.play(MoveToTarget(last_circle.label)) self.wait() if hasattr(self, "A_segments"): A.add(self.A_segments) if send_to_corner: group = VGroup(venn_diagram, labels) target = VGroup(venn_diagram.copy(), alt_labels) target.scale(0.25) target.to_corner(UP+RIGHT) self.play(Transform(group, target)) self.remove(group) for circle in venn_diagram: circle.label = circle.alt_label self.add(circle) for circle in venn_diagram: self.add(circle.label) self.venn_diagram = venn_diagram def show_100_photons(self): photon = FunctionGraph( lambda x : -np.cos(3*np.pi*x)*np.exp(-x*x), x_min = -2, x_max = 2, color = YELLOW, stroke_width = 2, ) photon.shift(LEFT + 2*UP) eyes = Eyes(photon) photon.eyes = eyes hundred, photon_word, s = words = OldTexText( "100 ", "Photon", "s", arg_separator = "" ) words.next_to(eyes, UP) self.play( ShowCreation(photon), FadeIn(photon.eyes), Write(photon_word, run_time = 1.5) ) photon.add(photon.eyes) #Split to hundred photons = VGroup(*[photon.deepcopy() for x in range(100)]) self.arrange_photons_in_circle(photons) photons.set_height(6) photons.next_to(words, DOWN) photons.to_edge(LEFT) self.play( Write(hundred), Write(s), ReplacementTransform( VGroup(photon), photons, lag_ratio = 0.5 ) ) self.photons = photons self.photon_words = words def show_one_photon_answering_questions(self): photon = self.photons[89] photon.save_state() photon.generate_target() answers = OldTexText( "Pass through A?", "Yes\\\\", "Pass through B?", "No\\\\", "Pass through C?", "No\\\\", ) answers.set_color_by_tex_to_color_map({ "Yes" : GREEN, "No" : RED, }) bubble = ThoughtBubble() bubble.add_content(answers) bubble.resize_to_content() answers.shift(SMALL_BUFF*(RIGHT+UP)) bubble_group = VGroup(bubble, answers) bubble_group.scale(0.25) bubble_group.next_to(photon, UP+RIGHT, buff = 0) group = VGroup(photon, bubble_group) group.save_state() bubble_group.set_fill(opacity = 0) bubble_group.set_stroke(width = 0) self.play( group.restore, group.scale, 4, group.to_corner, DOWN + RIGHT, ) self.play(photon.eyes.blink_anim()) self.wait() self.play( FadeOut(bubble_group), photon.restore, ) def put_all_photons_in_A(self): A, B, C = circles = self.venn_diagram[:3] A_group, B_group, C_group = [ VGroup(circle, circle.label) for circle in circles ] B_group.save_state() C_group.save_state() A.generate_target() A.target.scale(4) A.target.shift( (FRAME_Y_RADIUS-MED_LARGE_BUFF)*UP - \ A.target.get_top() ) A.label.generate_target() A.label.target.scale(2) A.label.target.next_to( A.target.point_from_proportion(0.1), UP+RIGHT, SMALL_BUFF ) self.play( B_group.fade, 1, C_group.fade, 1, MoveToTarget(A), MoveToTarget(A.label), FadeOut(self.photon_words), self.photons.set_height, 0.85*A.target.get_height(), self.photons.space_out_submobjects, 0.8, self.photons.move_to, A.target, ) self.wait() self.A_group = A_group self.B_group = B_group self.C_group = C_group def separate_by_B(self): A_group = self.A_group B_group = self.B_group photons = self.photons B = B_group[0] B.target, B.label.target = B_group.saved_state B.target.scale(4) B.target.move_to(A_group[0]) B.target.shift(self.A_to_B_vect) B.label.target.scale(2) B.label.target.next_to( B.target.point_from_proportion(0.55), LEFT, SMALL_BUFF ) B_center = B.target.get_center() photons.sort( lambda p : get_norm(p-B_center) ) in_B = VGroup(*photons[:85]) out_of_B = VGroup(*photons[85:]) out_of_B.sort(lambda p : np.dot(p, 2*UP+LEFT)) self.play( MoveToTarget(B), MoveToTarget(B.label), in_B.shift, 0.5*DOWN+0.2*LEFT, out_of_B.scale, 1./0.8, out_of_B.shift, 0.15*(UP+RIGHT), ) words1 = OldTexText("85 also \\\\", "pass ", "B") words1.set_color_by_tex("B", GREEN) words1.scale(0.8) words1.next_to(A_group, LEFT, LARGE_BUFF).shift(UP) arrow1 = Arrow( words1.get_right(), in_B.get_corner(UP+LEFT) + MED_LARGE_BUFF*(DOWN+RIGHT) ) arrow1.set_color(GREEN) words2 = OldTexText("15 blocked \\\\", "by ", "B") words2.set_color_by_tex("B", GREEN) words2.scale(0.8) words2.next_to(A_group, LEFT, MED_LARGE_BUFF, UP) arrow2 = Arrow(words2.get_right(), out_of_B[-1]) arrow2.set_color(RED) self.play( Write(words1, run_time = 1), ShowCreation(arrow1), self.in_A_in_B.set_fill, GREEN, 0.5, Animation(in_B), ) self.wait() self.play( ReplacementTransform(words1, words2), ReplacementTransform(arrow1, arrow2), self.in_A_in_B.set_fill, None, 0, Animation(in_B), self.in_A_out_B.set_fill, RED, 0.5, Animation(out_of_B) ) self.wait() self.play(ApplyMethod( VGroup(self.in_A_out_B, out_of_B).shift, MED_LARGE_BUFF*UP, rate_func = wiggle, run_time = 1.5, )) self.wait(0.5) self.in_B = in_B self.out_of_B = out_of_B self.out_of_B_words = words2 self.out_of_B_arrow = arrow2 def separate_by_C(self): A_group = self.A_group B_group = self.B_group C_group = self.C_group in_B = self.in_B A, B, C = self.venn_diagram C.target, C.label.target = C_group.saved_state C.target.scale(4) C.target.move_to(A) C.target.shift(self.A_to_C_vect) C_center = C.target.get_center() C.label.target.scale(2) C.label.target.next_to( C.target.point_from_proportion(0), DOWN+RIGHT, buff = SMALL_BUFF ) in_B.sort( lambda p : get_norm(p - C_center) ) in_C = VGroup(*in_B[:-11]) out_of_C = VGroup(*in_B[-11:]) in_C_out_B = VGroup(*self.out_of_B[:6]) words = OldTexText( "$15\\%$", "passing", "B \\\\", "get blocked by ", "C", ) words.scale(0.8) words.set_color_by_tex_to_color_map({ "B" : GREEN, "C" : BLUE, }) words.next_to(self.out_of_B_words, DOWN, LARGE_BUFF) words.to_edge(LEFT) percent = words[0] pound = OldTex("\\#") pound.move_to(percent, RIGHT) less_than_15 = OldTex("<15") less_than_15.next_to(words, DOWN) arrow = Arrow(words.get_right(), out_of_C) arrow.set_color(GREEN) C_copy = C.copy() C_copy.set_fill(BLACK, opacity = 1) self.play( self.in_A_in_B.set_fill, GREEN, 0.5, rate_func = there_and_back, ) self.play( MoveToTarget(C), MoveToTarget(C.label), in_C.shift, 0.2*DOWN+0.15*RIGHT, out_of_C.shift, SMALL_BUFF*(UP+LEFT), in_C_out_B.shift, 0.3*DOWN ) self.play( self.in_A_in_B_out_C.set_fill, GREEN, 0.5, Write(words, run_time = 1), ShowCreation(arrow), Animation(out_of_C), ) self.play(ApplyMethod( VGroup(self.in_A_in_B_out_C, out_of_C).shift, MED_LARGE_BUFF*UP, rate_func = wiggle )) self.wait() C.save_state() self.play(C.set_fill, BLACK, 1) self.wait() self.play(C.restore) self.wait(2) self.play(Transform(percent, pound)) self.play(Write(less_than_15, run_time = 1)) self.wait() self.in_C = in_C self.out_of_C = out_of_C words.add(less_than_15) self.out_of_C_words = words self.out_of_C_arrow = arrow def show_two_relevant_subsets(self): A, B, C = self.venn_diagram all_out_of_C = VGroup(*it.chain( self.out_of_B[6:], self.out_of_C, )) everything = VGroup(*self.get_top_level_mobjects()) photon_groups = [all_out_of_C, self.out_of_C, self.out_of_B] regions = [self.in_A_out_C, self.in_A_in_B_out_C, self.in_A_out_B] self.play(*[ ApplyMethod( m.scale, 0.7, method_kwargs = { "about_point" : FRAME_Y_RADIUS*DOWN } ) for m in everything ]) terms = VGroup( OldTex("N(", "A", "\\checkmark", ",", "C", ")", "\\le"), OldTex( "N(", "A", "\\checkmark", ",", "B", "\\checkmark", ",", "C", ")" ), OldTex("+\\, N(", "A", "\\checkmark", ",", "B", ")"), ) terms.arrange(RIGHT) terms.to_edge(UP) for term, index, group in zip(terms, [-3, -2, -2], photon_groups): term.set_color_by_tex("checkmark", "#00ff00") cross = Cross(term[index]) cross.set_color("#ff0000") cross.set_stroke(width = 8) term[index].add(cross) less_than = terms[0][-1] terms[0].remove(less_than) plus = terms[2][0][0] terms[2][0].remove(plus) rects = list(map(SurroundingRectangle, terms)) terms[2][0].add_to_back(plus) last_rects = VGroup(*rects[1:]) should_be_50 = OldTexText("Should be 50 \\\\", "...somehow") should_be_50.scale(0.8) should_be_50.next_to(rects[0], DOWN) lt_fifteen = VGroup(self.out_of_C_words[-1]).copy() something_lt_15 = OldTexText("(Something", "$<15$", ")") something_lt_15.scale(0.8) something_lt_15.next_to(rects[1], DOWN) lt_fifteen.target = something_lt_15 fifteen = VGroup(*self.out_of_B_words[0][:2]).copy() fifteen.generate_target() fifteen.target.scale(1.5) fifteen.target.next_to(rects[2], DOWN) nums = [should_be_50, lt_fifteen, fifteen] cross = Cross(less_than) cross.set_color("#ff0000") cross.set_stroke(width = 8) tweaser_group = VGroup( self.in_A_in_B_out_C.copy(), self.in_A_out_B.copy(), ) tweaser_group.set_fill(TEAL, 1) tweaser_group.set_stroke(TEAL, 5) #Fade out B circle faders = VGroup( B, B.label, self.out_of_B_words, self.out_of_C_words, self.out_of_B_arrow, self.out_of_C_arrow, *regions[1:] ) faders.save_state() self.play(faders.fade, 1) self.play(Write(terms[0]), run_time = 1) self.wait() self.photon_thinks_in_A_out_C() regions[0].set_stroke(YELLOW, width = 8) regions[0].set_fill(YELLOW, opacity = 0.25) self.play( VGroup(regions[0], all_out_of_C).shift, 0.5*UP, run_time = 1.5, rate_func = wiggle, ) self.wait(2) #Photons jump self.photons.save_state() self.play(Write(should_be_50[0], run_time = 1)) self.photons_jump_to_A_not_C_region() self.wait() self.play( faders.restore, self.photons.restore, ) self.play( faders.restore, regions[0].set_fill, None, 0, Animation(self.photons) ) #Funny business everything_copy = everything.copy().scale(1./3) braces = VGroup( Brace(everything_copy, LEFT), Brace(everything_copy, RIGHT), ).scale(3) funny_business = OldTexText("Funny business") funny_business.scale(1.5) funny_business.to_edge(UP) funny_business.shift(RIGHT) self.play( FadeIn(funny_business), *list(map(Write, braces)), run_time = 1 ) self.wait() self.play( FadeIn(less_than), *list(map(FadeOut, [funny_business, braces])) ) for term, group, region, num in zip(terms, photon_groups, regions, nums)[1:]: group.set_stroke(WHITE) self.play(Write(term, run_time = 1)) self.wait() self.play( ApplyMethod( VGroup(region, group).shift, 0.5*UP, rate_func = wiggle, run_time = 1.5, ), ) self.play(MoveToTarget(num)) self.wait() self.wait() self.play(ShowCreation(rects[0])) self.play( VGroup(regions[0], all_out_of_C).shift, 0.5*UP, run_time = 1.5, rate_func = wiggle, ) self.wait() self.play(Transform(rects[0], last_rects)) self.in_A_out_B.save_state() self.in_A_in_B_out_C.save_state() self.play( self.in_A_out_B.set_fill, YELLOW, 0.5, self.in_A_in_B_out_C.set_fill, YELLOW, 0.5, Animation(self.photons) ) self.wait() self.play( FadeOut(rects[0]), self.in_A_out_B.restore, self.in_A_in_B_out_C.restore, Animation(self.in_A_out_C), Animation(self.photons) ) self.wait() self.play( FadeIn(should_be_50[1]), ShowCreation(cross) ) morty = Mortimer() morty.to_corner(DOWN+RIGHT) contradiction = OldTexText("Contradiction!") contradiction.next_to(morty, UP, aligned_edge = RIGHT) contradiction.set_color(RED) self.play(FadeIn(morty)) self.play( morty.change, "confused", should_be_50, Write(contradiction, run_time = 1) ) self.play(Blink(morty)) self.wait() def photons_jump_to_A_not_C_region(self): in_C = self.in_C in_C.sort(lambda p : np.dot(p, DOWN+RIGHT)) movers = VGroup(*self.in_C[:30]) for mover in movers: mover.generate_target() mover.target.shift(1.2*UP + 0.6*LEFT) mover.target.set_stroke(WHITE) self.play(LaggedStartMap( MoveToTarget, movers, path_arc = np.pi, lag_ratio = 0.3 )) def photon_thinks_in_A_out_C(self): photon = self.photons[-1] photon.save_state() photon.generate_target() photon.target.scale(4) photon.target.center().to_edge(LEFT).shift(DOWN) bubble = ThoughtBubble() content = OldTex("A", "\\checkmark", ",", "C") content.set_color_by_tex("checkmark", "#00ff00") cross = Cross(content[-1]) cross.set_color("#ff0000") content.add(cross) bubble.add_content(content) bubble.resize_to_content() bubble.add(bubble.content) bubble.pin_to(photon.target).shift(SMALL_BUFF*RIGHT) bubble.save_state() bubble.scale(0.25) bubble.move_to(photon.get_corner(UP+RIGHT), DOWN+LEFT) bubble.fade() self.play( MoveToTarget(photon), bubble.restore, ) self.play(photon.eyes.blink_anim()) self.play( photon.restore, FadeOut(bubble) ) ####### def setup_venn_diagram_sections(self): in_A_out_B, in_A_in_B_out_C, in_A_out_C, in_A_in_B = segments = VGroup(*[ SVGMobject( file_name = "VennDiagram_" + s, stroke_width = 0, fill_opacity = 0.5, fill_color = YELLOW, ) for s in ("in_A_out_B", "in_A_in_B_out_C", "in_A_out_C", "in_A_in_B") ]) in_A_out_B.scale(2.59) in_A_out_B.move_to(3.74*UP + 2.97*RIGHT, UP+RIGHT) in_A_in_B_out_C.scale(1.84) in_A_in_B_out_C.move_to(2.23*UP, UP+RIGHT) in_A_out_C.scale(2.56) in_A_out_C.move_to(3*LEFT + (3.69)*UP, UP+LEFT) in_A_in_B.scale(2.24) in_A_in_B.move_to(2.23*UP + 3*LEFT, UP+LEFT) segments.set_fill(BLACK, opacity = 0) self.in_A_out_B = in_A_out_B self.in_A_in_B_out_C = in_A_in_B_out_C self.in_A_out_C = in_A_out_C self.in_A_in_B = in_A_in_B self.A_segments = segments def arrange_photons_in_circle(self, photons): R = np.sqrt(len(photons) / np.pi) pairs = [] rejected = [] for x, y in it.product(*[list(range(-int(R)-1, int(R)+2))]*2): if x**2 + y**2 < R**2: pairs.append((x, y)) else: rejected.append((x, y)) rejected.sort( kay=lambda x, y: (x**2 + y**2) ) for i in range(len(photons) - len(pairs)): pairs.append(rejected.pop()) for photon, (x, y) in zip(photons, pairs): photon.set_width(0.7) photon.move_to(x*RIGHT + y*UP) return photons class PonderingPiCreature(Scene): def construct(self): randy = Randolph() randy.to_edge(DOWN).shift(3*LEFT) self.play(randy.change, "pondering", UP+RIGHT) self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) self.wait(2) class ReEmphasizeVennDiagram(VennDiagramProofByContradiction): def construct(self): self.draw_venn_diagram(send_to_corner = False) self.rescale_diagram() self.setup_faded_circles() self.shift_B_circle() self.shift_C_circle() self.show_A_not_C_region() self.shorten_labels() self.show_inequality_with_circle() # self.emphasize_containment() self.write_50_percent() self.write_assumption() self.adjust_circles() def rescale_diagram(self): group = VGroup(self.venn_diagram, *[ c.label for c in self.venn_diagram ]) self.play( group.scale, 0.7, group.to_edge, DOWN, MED_SMALL_BUFF, ) self.clear() self.add_foreground_mobjects(*group) def setup_faded_circles(self): self.circles = self.venn_diagram[:3] self.black_circles = VGroup(*[ circ.copy().set_stroke(width = 0).set_fill(BLACK, 1) for circ in self.circles ]) self.filled_circles = VGroup(*[ circ.copy().set_stroke(width = 0).set_fill(circ.get_color(), 1) for circ in self.circles ]) def shift_B_circle(self): A, B, C = self.circles A0, B0, C0 = self.black_circles A1, B1, C1 = self.filled_circles words = OldTexText("Should be 15\\% \\\\ of circle ", "A") words.scale(0.7) words.set_color_by_tex("A", RED) words.next_to(A, UP, LARGE_BUFF) words.shift(RIGHT) arrow = Arrow( words.get_bottom(), A.get_top() + MED_SMALL_BUFF*RIGHT, color = RED ) self.play(FadeIn(A1)) self.play(FadeIn(B0)) self.play( FadeIn(words, lag_ratio = 0.5), ShowCreation(arrow) ) self.wait() vect = 0.6*(A.get_center() - B.get_center()) self.play( B0.shift, vect, B.shift, vect, B.label.shift, vect, run_time = 2, rate_func = running_start, ) B1.shift(vect) self.wait() self.in_A_out_B_words = words self.in_A_out_B_arrow = arrow for mob in words, arrow: mob.save_state() def shift_C_circle(self): A, B, C = self.circles A0, B0, C0 = self.black_circles A1, B1, C1 = self.filled_circles words = OldTexText("Should be 15\\% \\\\ of circle ", "B") words.scale(0.7) words.set_color_by_tex("B", GREEN) words.next_to(B, LEFT) words.shift(2.5*UP) arrow = Arrow( words.get_bottom(), B.point_from_proportion(0.4), color = GREEN ) self.play( FadeOut(A1), FadeOut(B0), self.in_A_out_B_words.fade, 1, self.in_A_out_B_arrow.fade, 1, FadeIn(B1), FadeIn(words, lag_ratio = 0.5), ShowCreation(arrow) ) self.play(FadeIn(C0)) self.wait(2) vect = 0.5*(B.get_center() - C.get_center()) self.play( C0.shift, vect, C.shift, vect, C.label.shift, vect, run_time = 2, rate_func = running_start, ) C1.shift(vect) self.wait() for mob in words, arrow: mob.save_state() self.in_B_out_C_words = words self.in_B_out_C_arrow = arrow def show_A_not_C_region(self): A, B, C = self.circles A0, B0, C0 = self.black_circles A1, B1, C1 = self.filled_circles A1_yellow_copy = A1.copy().set_fill(YELLOW) self.play( FadeOut(B1), FadeOut(C0), self.in_B_out_C_words.fade, 1, self.in_B_out_C_arrow.fade, 1, FadeIn(A1_yellow_copy) ) self.play(FadeIn(C0)) self.wait() self.A1_yellow_copy = A1_yellow_copy def shorten_labels(self): A, B, C = self.circles A0, B0, C0 = self.black_circles A1, B1, C1 = self.filled_circles for circle in A, B, C: circle.pre_label = VGroup(*circle.label[:-1]) circle.letter = circle.label[-1] self.play( A.pre_label.fade, 1, A.letter.scale, 2, A.letter.move_to, A.pre_label, LEFT, B.pre_label.fade, 1, B.letter.scale, 2, B.letter.get_right(), C.pre_label.fade, 1, C.letter.scale, 2, C.letter.move_to, C.pre_label, LEFT, C.letter.shift, DOWN+0.5*LEFT, ) for circle in A, B, C: circle.remove(circle.label) self.remove(circle.label) circle.add(circle.letter) self.add(circle.letter) def show_inequality_with_circle(self): A, B, C = self.circles A0, B0, C0 = self.black_circles A1, B1, C1 = self.filled_circles A1_yellow_copy = self.A1_yellow_copy inequality = VGroup( OldTex("N(", "A", "\\checkmark", ",", "C", ")"), OldTex("N(", "B", "\\checkmark", ",", "C", ")"), OldTex("N(", "A", "\\checkmark", ",", "B", ")"), ) inequality.arrange(RIGHT) for tex in inequality: tex.set_color_by_tex("checkmark", "#00ff00") if len(tex) > 1: cross = Cross(tex[-2], color = "#ff0000") cross.set_stroke(width = 8) tex[-2].add(cross) inequality.space_out_submobjects(2.1) big_le = OldTex("\\le").scale(2) big_plus = OldTex("+").scale(2) big_le.move_to(2.75*LEFT) big_plus.move_to(2.25*RIGHT) groups = VGroup(*[ VGroup( m2.copy(), m1.copy(), VGroup(*self.circles).copy() ) for m1, m2 in [(C0, A1_yellow_copy), (C0, B1), (B0, A1)] ]) for group, vect in zip(groups[1:], [UP, 5*RIGHT+UP]): group.scale(0.5) group.shift(vect) group.save_state() group.shift(-vect[0]*RIGHT + 5*LEFT) inequality.shift(2.25*DOWN + 0.25*LEFT) self.in_B_out_C_words.restore() self.in_B_out_C_words.move_to(2*UP) self.in_A_out_B_words.restore() self.in_A_out_B_words.move_to(5*RIGHT+2*UP) self.clear() self.play( groups[0].scale, 0.5, groups[0].shift, 5*LEFT + UP, Write(inequality[0], run_time = 1), FadeIn(big_le), ) self.wait() self.play(FadeIn(groups[1])) self.play( groups[1].restore, FadeIn(inequality[1]), FadeIn(self.in_B_out_C_words), FadeIn(big_plus), ) self.play(FadeIn(groups[2])) self.play( groups[2].restore, FadeIn(inequality[2]), FadeIn(self.in_A_out_B_words), ) self.wait(2) self.groups = groups self.inequality = inequality def emphasize_containment(self): groups = self.groups c1, c2 = [VGroup(*group[:2]).copy() for group in groups[1:]] foreground = VGroup(groups[0][-1], *groups[1:]) rect = SurroundingRectangle(groups[0]) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play( ApplyMethod( c1.shift, 4*LEFT, path_arc = -np.pi/2, ), Animation(foreground) ) self.play( ApplyMethod( c2.shift, 8*LEFT, path_arc = -np.pi/2, ), Animation(c1), Animation(foreground), run_time = 1.5 ) self.play( FadeOut(c2), FadeOut(c1), Animation(foreground), run_time = 2 ) self.wait() def write_50_percent(self): words = OldTexText( "Should be 50\\% \\\\ of circle ", "A", "...somehow" ) words.scale(0.7) words.set_color_by_tex("A", RED) words.move_to(5*LEFT + 2*UP) self.play(Write(words)) self.wait() def write_assumption(self): words = OldTexText("Assume circles have the same size$^*$") words.scale(0.8) words.to_edge(UP) footnote = OldTexText(""" *If you prefer, you can avoid the need for that assumption by swapping the roles of A and C here and writing a second inequality for added constraint. """) footnote.scale(0.5) footnote.to_corner(DOWN+RIGHT) footnote.add(words[-1]) words.remove(words[-1]) self.footnote = footnote self.play(FadeIn(words)) def adjust_circles(self): groups = self.groups A_group = VGroup( groups[0][0], groups[2][0], groups[0][2][0], groups[1][2][0], groups[2][2][0], ) B_group = VGroup( groups[1][0], groups[2][1], groups[0][2][1], groups[1][2][1], groups[2][2][1], ) C_group = VGroup( groups[0][1], groups[1][1], groups[0][2][2], groups[1][2][2], groups[2][2][2], ) def center_of_mass(mob): return np.apply_along_axis(np.mean, 0, mob.get_points()) movers = [A_group, B_group, C_group] A_ref, B_ref, C_ref = [g[4] for g in movers] B_center = center_of_mass(B_ref) B_to_A = center_of_mass(A_ref) - B_center B_to_C = center_of_mass(C_ref) - B_center A_freq = 1 C_freq = -0.7 self.time = 0 dt = 1 / self.camera.frame_rate def move_around(total_time): self.time t_range = list(range(int(total_time/dt))) for x in ProgressDisplay(t_range): self.time += dt new_B_to_A = rotate_vector(B_to_A, self.time*A_freq) new_B_to_C = rotate_vector(B_to_C, self.time*C_freq) A_group.shift(B_center + new_B_to_A - center_of_mass(A_ref)) C_group.shift(B_center + new_B_to_C - center_of_mass(C_ref)) self.wait(dt) move_around(3) self.add(self.footnote) move_around(1) self.remove(self.footnote) move_around(15) class NoFirstMeasurementPreferenceBasedOnDirection(ShowVariousFilterPairs): CONFIG = { "filter_x_coordinates" : [0, 0, 0], "pol_filter_configs" : [ {"filter_angle" : angle} for angle in (0, np.pi/8, np.pi/4) ], "lines_depth" : 1.2, "lines_shift_vect" : SMALL_BUFF*OUT, "n_lines" : 30, } def setup(self): DirectionOfPolarization.setup(self) self.remove(self.axes, self.em_wave) zs = [2.5, 0, -2.5] chars = "ABC" colors = [RED, GREEN, BLUE] for z, char, color, pf in zip(zs, chars, colors, self.pol_filters): pf.scale(0.7) pf.move_to(z*OUT) label = OldTexText(char) label.add_background_rectangle() label.set_color(color) label.scale(0.7) label.rotate(np.pi/2, RIGHT) label.rotate(-np.pi/2, OUT) label.next_to(pf.arrow_label, UP, SMALL_BUFF) pf.arrow_label.add(label) self.add_foreground_mobject(pf) def construct(self): self.reposition_camera() self.show_lines() def reposition_camera(self): words = OldTexText("No statistical preference") words.to_corner(UP+LEFT) words.rotate(np.pi/2, RIGHT) self.move_camera( theta = -0.6*np.pi, added_anims = list(it.chain(*[ [ pf.arrow_label.rotate, np.pi/2, OUT, pf.arrow_label.next_to, pf.arrow, OUT+RIGHT, SMALL_BUFF ] for pf in self.pol_filters ] + [[FadeIn(words)]])) ) def show_lines(self): all_pre_lines = VGroup() all_post_lines = VGroup() for pf in self.pol_filters: pre_lines = self.get_lines(None, pf) post_lines = self.get_lines(pf, None) VGroup( *random.sample(post_lines, self.n_lines/2) ).set_stroke(BLACK, 0) all_pre_lines.add(*pre_lines) all_post_lines.add(*post_lines) kwargs = { "rate_func" : None, "lag_ratio" : 0 } self.play(ShowCreation(all_pre_lines, **kwargs)) self.play( ShowCreation(all_post_lines, **kwargs), Animation(self.pol_filters), Animation(all_pre_lines), ) self.add_foreground_mobject(all_pre_lines) self.wait(7)
videos_3b1b/_2017/256.py
from manim_imports_ext import * from _2017.crypto import sha256_tex_mob, bit_string_to_mobject, BitcoinLogo def get_google_logo(): result = SVGMobject( file_name = "google_logo", height = 0.75 ) blue, red, yellow, green = [ "#4885ed", "#db3236", "#f4c20d", "#3cba54" ] colors = [red, yellow, blue, green, red, blue] result.set_color_by_gradient(*colors) return result class LastVideo(Scene): def construct(self): title = OldTexText("Crypto", "currencies", arg_separator = "") title[0].set_color(YELLOW) title.scale(1.5) title.to_edge(UP) screen_rect = ScreenRectangle(height = 6) screen_rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(screen_rect)) self.wait() class BreakUp2To256(PiCreatureScene): def construct(self): self.initialize_bits() self.add_number() self.break_up_as_powers_of_two() self.break_up_as_four_billions() self.reorganize_four_billions() def initialize_bits(self): bits = bit_string_to_mobject("") bits.to_corner(UP+LEFT) one = OldTex("1")[0] one.replace(bits[0], dim_to_match = 1) self.add(bits) self.add_foreground_mobject(VGroup(*bits[-15:])) self.number = 0 self.bits = bits self.one = one self.zero = bits[0].copy() def add_number(self): brace = Brace(self.bits, RIGHT) number, possibilities = expression = OldTexText( "$2^{256}$", "possibilities" ) number.set_color(YELLOW) expression.next_to(brace, RIGHT) words = OldTexText("Seems big...I guess...") words.next_to(self.pi_creature.get_corner(UP+LEFT), UP) self.play( self.pi_creature.change, "raise_right_hand", GrowFromCenter(brace), Write(expression, run_time = 1) ) self.wait() self.play( self.pi_creature.change, "maybe", Write(words) ) self.wait(2) self.play( self.pi_creature.change, "happy", FadeOut(words) ) self.wait() self.expression = expression self.bits_brace = brace def break_up_as_powers_of_two(self): bits = self.bits bits.generate_target() subgroups = [ VGroup(*bits.target[32*i:32*(i+1)]) for i in range(8) ] subexpressions = VGroup() for i, subgroup in enumerate(subgroups): subgroup.shift(i*MED_LARGE_BUFF*DOWN) subexpression = OldTexText( "$2^{32}$", "possibilities" ) subexpression[0].set_color(GREEN) subexpression.next_to(subgroup, RIGHT) subexpressions.add(subexpression) self.play( FadeOut(self.bits_brace), ReplacementTransform( VGroup(self.expression), subexpressions ), MoveToTarget(bits) ) self.play(self.pi_creature.change, "pondering") self.wait() self.subexpressions = subexpressions def break_up_as_four_billions(self): new_subexpressions = VGroup() for subexpression in self.subexpressions: new_subexpression = OldTexText( "4 Billion", "possibilities" ) new_subexpression[0].set_color(YELLOW) new_subexpression.move_to(subexpression, LEFT) new_subexpressions.add(new_subexpression) self.play( Transform( self.subexpressions, new_subexpressions, run_time = 2, lag_ratio = 0.5, ), FadeOut(self.pi_creature) ) self.wait(3) def reorganize_four_billions(self): target = VGroup(*[ OldTexText( "$\\big($", "4 Billion", "$\\big)$", arg_separator = "" ) for x in range(8) ]) target.arrange(RIGHT, buff = SMALL_BUFF) target.to_edge(UP) target.set_width(FRAME_WIDTH - LARGE_BUFF) parens = VGroup(*it.chain(*[ [t[0], t[2]] for t in target ])) target_four_billions = VGroup(*[t[1] for t in target]) target_four_billions.set_color(YELLOW) four_billions, to_fade = [ VGroup(*[se[i] for se in self.subexpressions]) for i in range(2) ] self.play( self.bits.to_corner, DOWN+LEFT, Transform(four_billions, target_four_billions), LaggedStartMap(FadeIn, parens), FadeOut(to_fade) ) self.wait() ###### def wait(self, time = 1): self.play(Animation(self.bits, run_time = time)) def update_frame(self, *args, **kwargs): self.number += 1 new_bit_string = bin(self.number)[2:] for i, bit in enumerate(reversed(new_bit_string)): index = -i-1 bit_mob = self.bits[index] if bit == "0": new_mob = self.zero.copy() else: new_mob = self.one.copy() new_mob.replace(bit_mob, dim_to_match = 1) Transform(bit_mob, new_mob).update(1) Scene.update_frame(self, *args, **kwargs) class ShowTwoTo32(Scene): def construct(self): mob = OldTex("2^{32} = 4{,}294{,}967{,}296") mob.scale(1.5) self.add(mob) self.wait() class MainBreakdown(Scene): CONFIG = { "n_group_rows" : 8, "n_group_cols" : 8, } def construct(self): self.add_four_billions() self.gpu_packed_computer() self.kilo_google() self.half_all_people_on_earth() self.four_billion_earths() self.four_billion_galxies() self.show_time_scale() self.show_probability() def add_four_billions(self): top_line = VGroup() four_billions = VGroup() for x in range(8): mob = OldTexText( "$\\big($", "4 Billion", "$\\big)$", arg_separator = "" ) top_line.add(mob) four_billions.add(mob[1]) top_line.arrange(RIGHT, buff = SMALL_BUFF) top_line.set_width(FRAME_WIDTH - LARGE_BUFF) top_line.to_edge(UP) four_billions.set_color(YELLOW) self.add(top_line) self.top_line = top_line self.four_billions = four_billions def gpu_packed_computer(self): self.show_gpu() self.cram_computer_with_gpus() def show_gpu(self): gpu = SVGMobject( file_name = "gpu", height = 1, fill_color = GREY_B, ) name = OldTexText("Graphics", "Processing", "Unit") for word in name: word[0].set_color(BLUE) name.to_edge(LEFT) gpu.next_to(name, UP) hash_names = VGroup(*[ OldTexText("hash") for x in range(10) ]) hash_names.arrange(DOWN, buff = MED_SMALL_BUFF) hash_names.next_to(name, RIGHT, buff = 2) paths = VGroup() for hash_name in hash_names: hash_name.add_background_rectangle(opacity = 0.5) path = VMobject() start_point = name.get_right() + SMALL_BUFF*RIGHT end_point = start_point + (4+hash_name.get_width())*RIGHT path.set_points([ start_point, start_point+RIGHT, hash_name.get_left()+LEFT, hash_name.get_left(), hash_name.get_left(), hash_name.get_right(), hash_name.get_right(), hash_name.get_right() + RIGHT, end_point + LEFT, end_point, ]) paths.add(path) paths.set_stroke(width = 3) paths.set_color_by_gradient(BLUE, GREEN) def get_passing_flash(): return ShowPassingFlash( paths, lag_ratio = 0, time_width = 0.7, run_time = 2, ) rate_words = OldTexText( "$<$ 1 Billion", "Hashes/sec" ) rate_words.next_to(name, DOWN) self.play(FadeIn(name)) self.play(DrawBorderThenFill(gpu)) self.play( get_passing_flash(), FadeIn(hash_names) ) for x in range(2): self.play( get_passing_flash(), Animation(hash_names) ) self.play( Write(rate_words, run_time = 2), get_passing_flash(), Animation(hash_names) ) self.play(get_passing_flash(), Animation(hash_names)) self.play(*list(map(FadeOut, [name, hash_names]))) self.gpu = gpu self.rate_words = rate_words def cram_computer_with_gpus(self): gpu = self.gpu gpus = VGroup(gpu, *[gpu.copy() for x in range(5)]) rate_words = self.rate_words four_billion = self.four_billions[0] laptop = Laptop() laptop.next_to(rate_words, RIGHT) laptop.to_edge(RIGHT) new_rate_words = OldTexText("4 Billion", "Hashes/sec") new_rate_words.move_to(rate_words) new_rate_words[0].set_color(BLUE) hps, h_line, target_laptop = self.get_fraction( 0, OldTexText("H/s"), Laptop() ) hps.scale(0.7) self.play(FadeIn(laptop)) self.play( gpus.arrange, RIGHT, SMALL_BUFF, gpus.next_to, rate_words, UP, gpus.to_edge, LEFT ) self.play( Transform( four_billion.copy(), new_rate_words[0], remover = True, ), Transform(rate_words, new_rate_words) ) self.wait() self.play( LaggedStartMap( ApplyFunction, gpus, lambda g : ( lambda m : m.scale(0.01).move_to(laptop), g ), remover = True ) ) self.wait() self.play( Transform( rate_words[0], four_billion.copy().set_color(BLUE), remover = True, ), four_billion.set_color, BLUE, Transform(rate_words[1], hps), ) self.play( Transform(laptop, target_laptop), ShowCreation(h_line), ) self.wait() def kilo_google(self): self.create_four_billion_copies(1, Laptop()) google = self.get_google_logo() google.next_to( self.group_of_four_billion_things, UP, buff = LARGE_BUFF, aligned_edge = LEFT ) google.shift(RIGHT) millions = OldTexText("$\\sim$ Millions of servers") millions.next_to(google, RIGHT) plus_plus = OldTex("++") plus_plus.next_to(google, RIGHT, SMALL_BUFF) plus_plus.set_stroke(width = 2) kilo = OldTexText("Kilo") kilo.scale(1.5) kilo.next_to(google[-1], LEFT, SMALL_BUFF, DOWN) kilogoogle = VGroup(kilo, google, plus_plus) four_billion = self.four_billions[1] laptop, h_line, target_kilogoogle = self.get_fraction( 1, Laptop(), self.get_kilogoogle() ) self.revert_to_original_skipping_status() self.play(DrawBorderThenFill(google)) self.wait(2) self.play(Write(millions)) self.wait(2) self.play(LaggedStartMap( Indicate, self.group_of_four_billion_things, run_time = 4, rate_func = there_and_back, lag_ratio = 0.25, )) self.play(FadeOut(millions), FadeIn(plus_plus)) self.play(Write(kilo)) self.wait() self.play( four_billion.restore, FadeOut(self.group_of_four_billion_things) ) self.play( Transform(kilogoogle, target_kilogoogle), FadeIn(laptop), FadeIn(h_line), ) self.wait() def half_all_people_on_earth(self): earth = self.get_earth() people = OldTexText("7.3 Billion people") people.next_to(earth, RIGHT) group = VGroup(earth, people) group.next_to(self.four_billions, DOWN, MED_LARGE_BUFF) group.shift(RIGHT) kg, h_line, target_earth = self.get_fraction( 2, self.get_kilogoogle(), self.get_earth(), ) self.play( GrowFromCenter(earth), Write(people) ) self.wait() self.create_four_billion_copies(2, self.get_kilogoogle()) self.wait() self.play( self.four_billions[2].restore, Transform(earth, target_earth), FadeIn(h_line), FadeIn(kg), FadeOut(self.group_of_four_billion_things), FadeOut(people) ) self.wait() def four_billion_earths(self): self.create_four_billion_copies( 3, self.get_earth() ) milky_way = ImageMobject("milky_way") milky_way.set_height(3) milky_way.to_edge(LEFT, buff = 0) milky_way.shift(DOWN) n_stars_estimate = OldTexText("100 to 400 \\\\ billion stars") n_stars_estimate.next_to(milky_way, RIGHT) n_stars_estimate.shift(UP) earth, h_line, denom = self.get_fraction( 3, self.get_earth(), self.get_galaxy() ) self.revert_to_original_skipping_status() self.play(FadeIn(milky_way)) self.play(Write(n_stars_estimate)) self.wait() self.play(LaggedStartMap( Indicate, self.group_of_four_billion_things, rate_func = there_and_back, lag_ratio = 0.2, run_time = 3, )) self.wait() self.play( ReplacementTransform( self.group_of_four_billion_things, VGroup(earth) ), ShowCreation(h_line), FadeIn(denom), self.four_billions[3].restore, FadeOut(milky_way), FadeOut(n_stars_estimate), ) self.wait() def four_billion_galxies(self): self.create_four_billion_copies(4, self.get_galaxy()) num, h_line, denom = fraction = self.get_fraction( 4, self.get_galaxy(), OldTexText("GGSC").set_color(BLUE) ) name = OldTexText( "Giga", "Galactic \\\\", " Super", " Computer", arg_separator = "" ) for word in name: word[0].set_color(BLUE) name.next_to(self.group_of_four_billion_things, UP) self.play(Write(name)) self.wait() self.play( self.four_billions[4].restore, ReplacementTransform( self.group_of_four_billion_things, VGroup(num), run_time = 2, lag_ratio = 0.5 ), ShowCreation(h_line), ReplacementTransform( name, denom ), ) self.wait() def show_time_scale(self): fb1, fb2 = self.four_billions[5:7] seconds_to_years = OldTexText("seconds $\\approx$ 126.8 years") seconds_to_years.shift(LEFT) years_to_eons = OldTexText( "$\\times$ 126.8 years", "$\\approx$ 507 Billion years", ) years_to_eons.next_to( seconds_to_years, DOWN, aligned_edge = LEFT, ) universe_lifetimes = OldTexText("$\\approx 37 \\times$ Age of universe") universe_lifetimes.next_to( years_to_eons[1], DOWN, aligned_edge = LEFT ) for fb, words in (fb1, seconds_to_years), (fb2, years_to_eons): self.play( fb.scale, 1.3, fb.next_to, words, LEFT, fb.set_color, BLUE, Write(words) ) self.wait() self.play(Write(universe_lifetimes)) self.wait() def show_probability(self): four_billion = self.four_billions[7] words = OldTexText( "1 in ", "4 Billion\\\\", "chance of success" ) words.next_to(four_billion, DOWN, buff = MED_LARGE_BUFF) words.to_edge(RIGHT) words[1].set_color(BLUE) self.play( Write(VGroup(*words[::2])), Transform(four_billion, words[1]) ) self.wait() ############ def create_four_billion_copies(self, index, mobject): four_billion = self.four_billions[index] four_billion.set_color(BLUE) four_billion.save_state() group = VGroup(*[ VGroup(*[ mobject.copy().set_height(0.25) for x in range(self.n_group_rows) ]).arrange(DOWN, buff = SMALL_BUFF) for y in range(self.n_group_cols-1) ]) dots = OldTex("\\dots") group.add(dots) group.add(*[group[0].copy() for x in range(2)]) group.arrange(RIGHT, buff = SMALL_BUFF) group.set_height(FRAME_Y_RADIUS) max_width = 1.25*FRAME_X_RADIUS if group.get_width() > max_width: group.set_width(max_width) group.to_corner(DOWN+RIGHT) group = VGroup(*it.chain(*group)) brace = Brace(group, LEFT) self.play( four_billion.scale, 2, four_billion.next_to, brace, LEFT, GrowFromCenter(brace), LaggedStartMap( FadeIn, group, run_time = 3, lag_ratio = 0.2 ) ) self.wait() group.add_to_back(brace) self.group_of_four_billion_things = group def get_fraction(self, index, numerator, denominator): four_billion = self.four_billions[index] if hasattr(four_billion, "saved_state"): four_billion = four_billion.saved_state space = LARGE_BUFF h_line = Line(LEFT, RIGHT) h_line.set_width(four_billion.get_width()) h_line.next_to(four_billion, DOWN, space) for mob in numerator, denominator: mob.set_height(0.75*space) max_width = h_line.get_width() if mob.get_width() > max_width: mob.set_width(max_width) numerator.next_to(h_line, UP, SMALL_BUFF) denominator.next_to(h_line, DOWN, SMALL_BUFF) fraction = VGroup(numerator, h_line, denominator) return fraction def get_google_logo(self): return get_google_logo() def get_kilogoogle(self): G = self.get_google_logo()[-1] kilo = OldTexText("K") kilo.scale(1.5) kilo.next_to(G[-1], LEFT, SMALL_BUFF, DOWN) plus_plus = OldTex("++") plus_plus.set_stroke(width = 1) plus_plus.next_to(G, RIGHT, SMALL_BUFF) return VGroup(kilo, G, plus_plus) def get_earth(self): earth = SVGMobject( file_name = "earth", height = 1.5, fill_color = BLACK, ) circle = Circle( stroke_width = 3, stroke_color = GREEN, fill_opacity = 1, fill_color = BLUE_C, ) circle.replace(earth) earth.add_to_back(circle) return earth def get_galaxy(self): return SVGMobject( file_name = "galaxy", fill_opacity = 0, stroke_width = 3, stroke_color = WHITE, height = 1, ) class WriteTWoTo160(Scene): def construct(self): mob = OldTexText("$2^{160}$ ", "Hashes/sec") mob[0].set_color(BLUE) mob.scale(2) self.play(Write(mob)) self.wait() class StateOfBitcoin(TeacherStudentsScene): def construct(self): title = OldTexText("Total", "B", "mining") title.to_edge(UP) bitcoin_logo = BitcoinLogo() bitcoin_logo.set_height(0.5) bitcoin_logo.move_to(title[1]) title.remove(title[1]) rate = OldTexText( "5 Billion Billion", "$\\frac{\\text{Hashes}}{\\text{Second}}$" ) rate.next_to(title, DOWN, MED_LARGE_BUFF) google = get_google_logo() kilo = OldTexText("Kilo") kilo.scale(1.5) kilo.next_to(google[-1], LEFT, SMALL_BUFF, DOWN) third = OldTex("1 \\over 3") third.next_to(kilo, LEFT) kilogoogle = VGroup(*it.chain(third, kilo, google)) kilogoogle.sort() kilogoogle.next_to(rate, DOWN, MED_LARGE_BUFF) rate.save_state() rate.shift(DOWN) rate.set_fill(opacity = 0) all_text = VGroup(title, bitcoin_logo, rate, kilogoogle) gpu = SVGMobject( file_name = "gpu", height = 1, fill_color = GREY_B, ) gpu.shift(0.5*FRAME_X_RADIUS*RIGHT) gpu_name = OldTexText("GPU") gpu_name.set_color(BLUE) gpu_name.next_to(gpu, UP) gpu_group = VGroup(gpu, gpu_name) gpu_group.to_edge(UP) cross = Cross(gpu_group) gpu_group.add(cross) asic = OldTexText( "Application", "Specific\\\\", "Integrated", "Circuit" ) for word in asic: word[0].set_color(YELLOW) asic.move_to(gpu) asic.to_edge(UP) asic.shift(LEFT) circuit = SVGMobject( file_name = "circuit", height = asic.get_height(), fill_color = WHITE, ) random.shuffle(circuit.submobjects) circuit.set_color_by_gradient(WHITE, GREY) circuit.next_to(asic, RIGHT) asic_rate = OldTexText("Trillion hashes/sec") asic_rate.next_to(asic, DOWN, MED_LARGE_BUFF) asic_rate.set_color(GREEN) self.play( Write(title), DrawBorderThenFill(bitcoin_logo) ) self.play( self.teacher.change, "raise_right_hand", rate.restore, ) self.play_student_changes(*["pondering"]*3) self.play(LaggedStartMap(FadeIn, kilogoogle)) self.play_student_changes(*["surprised"]*3) self.wait() self.play_student_changes( *["plain"]*3, added_anims = [ all_text.to_edge, LEFT, self.teacher.change_mode, "happy" ], look_at = gpu ) self.play( Write(gpu_name), DrawBorderThenFill(gpu) ) self.play(ShowCreation(cross)) self.wait() self.play( Write(asic), gpu_group.to_edge, DOWN, self.teacher.change, "raise_right_hand", ) self.play_student_changes( *["pondering"]*3, added_anims = [Write(asic_rate)] ) self.play(LaggedStartMap( FadeIn, circuit, run_time = 3, lag_ratio = 0.2, )) self.wait() class QAndA(PiCreatureScene): def construct(self): self.pi_creature.center().to_edge(DOWN) self.show_powers_of_two() num_subscriber_words = OldTex( "> 2^{18} = 262{,}144", "\\text{ subscribers}" ) num_subscriber_words.to_edge(UP) num_subscriber_words.shift(RIGHT) num_subscriber_words.set_color_by_tex("subscribers", RED) q_and_a = OldTexText("Q\\&A") q_and_a.next_to(self.pi_creature.get_corner(UP+LEFT), UP) q_and_a.save_state() q_and_a.shift(DOWN) q_and_a.set_fill(opacity = 0) reddit = OldTexText("reddit.com/r/3blue1brown") reddit.next_to(num_subscriber_words, DOWN, LARGE_BUFF) twitter = OldTexText("@3blue1brown") twitter.set_color(BLUE_C) twitter.next_to(reddit, DOWN) self.play(Write(num_subscriber_words)) self.play(self.pi_creature.change, "gracious", num_subscriber_words) self.wait() self.play( q_and_a.restore, self.pi_creature.change, "raise_right_hand", ) self.wait() self.play(Write(reddit)) self.wait() self.play( FadeIn(twitter), self.pi_creature.change_mode, "shruggie" ) self.wait(2) def show_powers_of_two(self): rows = 16 cols = 64 dots = VGroup(*[ VGroup(*[ Dot() for x in range(rows) ]).arrange(DOWN, buff = SMALL_BUFF) for y in range(cols) ]).arrange(RIGHT, buff = SMALL_BUFF) dots.set_width(FRAME_WIDTH - 2*LARGE_BUFF) dots.next_to(self.pi_creature, UP) dots = VGroup(*it.chain(*dots)) top = dots.get_top() dots.sort( lambda p : get_norm(p-top) ) powers_of_two = VGroup(*[ Integer(2**i) for i in range(int(np.log2(rows*cols))+1) ]) curr_power = powers_of_two[0] curr_power.to_edge(UP) self.play( Write(curr_power), FadeIn(dots[0]) ) for i, power_of_two in enumerate(powers_of_two): if i == 0: continue power_of_two.to_edge(UP) self.play( FadeIn(VGroup(*dots[2**(i-1) : 2**i])), Transform( curr_power, power_of_two, rate_func = squish_rate_func(smooth, 0, 0.5) ) ) self.wait() self.play( FadeOut(dots), FadeOut(powers_of_two) ) class Thumbnail(Scene): def construct(self): num = OldTex("2^{256}") num.set_height(2) num.set_color(BLUE_C) num.set_stroke(BLUE_B, 3) num.shift(MED_SMALL_BUFF*UP) num.add_background_rectangle(opacity = 1) num.background_rectangle.scale(1.5) self.add(num) background_num_str = "115792089237316195423570985008687907853269984665640564039457584007913129639936" n_chars = len(background_num_str) new_str = "" for i, char in enumerate(background_num_str): new_str += char # if i%3 == 1: # new_str += "{,}" if i%(n_chars/4) == 0: new_str += " \\\\ " background_num = OldTex(new_str) background_num.set_width(FRAME_WIDTH - LARGE_BUFF) background_num.set_fill(opacity = 0.2) secure = OldTexText("Secure?") secure.scale(4) secure.shift(FRAME_Y_RADIUS*DOWN/2) secure.set_color(RED) secure.set_stroke(RED_A, 3) lock = SVGMobject( file_name = "shield_locked", fill_color = WHITE, ) lock.set_height(6) self.add(background_num, num)
videos_3b1b/_2017/mug.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from manim_imports_ext import * # from _2017.efvgt import ConfettiSpiril #revert_to_original_skipping_status class HappyHolidays(TeacherStudentsScene): def construct(self): hats = VGroup(*list(map( self.get_hat, self.pi_creatures ))) self.add(self.get_snowflakes()) self.play_student_changes( *["hooray"]*3, look_at = FRAME_Y_RADIUS*UP, added_anims = [self.teacher.change, "hooray"] ) self.play(LaggedStartMap( DrawBorderThenFill, hats ), Animation(self.pi_creatures)) self.play_student_changes( "happy", "wave_2", "wave_1", look_at = FRAME_Y_RADIUS*UP, ) self.look_at(self.teacher.get_corner(UP+LEFT)) self.wait(2) self.play(self.teacher.change, "happy") self.wait(2) def get_hat(self, pi): hat = SVGMobject( file_name = "santa_hat", height = 0.5*pi.get_height() ) hat.rotate(-np.pi/12) vect = RIGHT if not pi.is_flipped(): hat.flip() vect = LEFT hat.set_fill(RED_D) hat.set_stroke(width=0) hat[0].set_points(hat[0].get_points()[8 * 4:]) hat[0].set_fill("#DDDDDD") hat[2].set_fill(WHITE) hat.add(hat[0]) hat.next_to(pi.body, UP, buff = SMALL_BUFF) hat.shift(SMALL_BUFF*vect) return hat def get_snowflakes(self, n_flakes = 50): snowflakes = VGroup(*[ SVGMobject( file_name = "snowflake", height = 0.5, stroke_width = 0, fill_opacity = 0.75, fill_color = WHITE, ).rotate(np.pi/12, RIGHT) for x in range(n_flakes) ]) def random_confetti_spiral(mob, **kwargs): return ConfettiSpiril( mob, x_start = 2*random.random()*FRAME_X_RADIUS - FRAME_X_RADIUS, **kwargs ) snowflake_spirils = LaggedStartMap( random_confetti_spiral, snowflakes, run_time = 10, rate_func = lambda x : x, ) return turn_animation_into_updater(snowflake_spirils) class UtilitiesPuzzleScene(Scene): CONFIG = { "object_height" : 0.75, "h_distance" : 2, "v_distance" : 2, "line_width" : 4, } def setup_configuration(self): houses = VGroup() for x in range(3): house = SVGMobject(file_name = "house") house.set_stroke(BLACK, 5, background=True) house.set_height(self.object_height) house.set_fill(GREY_B) house.move_to(x*self.h_distance*RIGHT) houses.add(house) houses.move_to(self.v_distance*UP/2) utilities = VGroup(*[ self.get_utility(u, c).move_to(x*self.h_distance*RIGHT) for x, u, c in zip( it.count(), ["fire", "electricity", "water"], [RED_D, YELLOW_C, BLUE_D] ) ]) utilities.move_to(self.v_distance*DOWN/2) objects = VGroup(houses, utilities) bounding_box = SurroundingRectangle( objects, buff = MED_LARGE_BUFF, stroke_width = 0 ) objects.add(bounding_box) self.add(objects) self.houses = houses self.utilities = utilities self.objects = objects self.bounding_box = bounding_box def get_utility(self, name, color): circle = Circle( fill_color = color, fill_opacity = 1, stroke_width = 0, ) utility = SVGMobject( file_name = name, height = 0.65*circle.get_height(), fill_color = WHITE, ) utility.insert_n_curves(100) utility.set_stroke(width=0) if color == YELLOW: utility.set_fill(GREY_D) utility.move_to(circle) circle.add(utility) circle.set_height(self.object_height) return circle def get_line( self, utility_index, house_index, *midpoints, **kwargs ): prop = kwargs.pop("prop", 1.0) utility = self.utilities[utility_index] points = [utility.get_center()] points += list(midpoints) points += [self.houses[house_index].get_center()] line = Line( points[0], points[-1], color = utility[0].get_color(), stroke_width = self.line_width ) line.set_points_smoothly(points) line.pointwise_become_partial(line, 0, prop) return line def get_almost_solution_lines(self): bb = self.bounding_box return VGroup( VGroup( self.get_line(0, 0), self.get_line(0, 1), self.get_line(0, 2, bb.get_top()), ), VGroup( self.get_line(1, 0, bb.get_corner(DOWN+LEFT)), self.get_line(1, 1), self.get_line(1, 2, bb.get_corner(DOWN+RIGHT)), ), VGroup( self.get_line(2, 0, bb.get_top()), self.get_line(2, 1), self.get_line(2, 2), ), ) def get_straight_lines(self): return VGroup(*[ VGroup(*[self.get_line(i, j) for j in range(3)]) for i in range(3) ]) def get_no_crossing_words(self): arrow = Vector(DOWN) arrow.next_to(self.bounding_box.get_top(), UP, SMALL_BUFF) words = OldTexText("No crossing!") words.next_to(arrow, UP, buff = SMALL_BUFF) result = VGroup(words, arrow) result.set_color("RED") return result def get_region(self, *bounding_edges): region = VMobject(mark_paths_closed = True) for i, edge in enumerate(bounding_edges): new_edge = edge.copy() if i%2 == 1: new_edge.set_points(new_edge.get_points()[::-1]) region.append_vectorized_mobject(new_edge) region.set_stroke(width = 0) region.set_fill(WHITE, opacity = 1) return region def convert_objects_to_dots(self, run_time = 2): group = VGroup(*it.chain(self.houses, self.utilities)) for mob in group: mob.target = Dot(color = mob.get_color()) mob.target.scale(2) mob.target.move_to(mob) self.play(LaggedStartMap(MoveToTarget, group, run_time = run_time)) class PauseIt(PiCreatureScene): def construct(self): morty = self.pi_creatures morty.center().to_edge(DOWN) self.pi_creature_says( "Pause it!", target_mode = "surprised" ) self.wait(2) class AboutToyPuzzles(UtilitiesPuzzleScene, TeacherStudentsScene, ThreeDScene): def construct(self): self.remove(self.pi_creatures) self.lay_out_puzzle() self.point_to_abstractions() self.show_this_video() def lay_out_puzzle(self): self.setup_configuration() houses, utilities = self.houses, self.utilities lines = VGroup(*it.chain(*self.get_almost_solution_lines())) no_crossing_words = self.get_no_crossing_words() self.remove(self.objects) self.play( ReplacementTransform( VGroup(houses[1], houses[1]).copy().fade(1), VGroup(houses[0], houses[2]), rate_func = squish_rate_func(smooth, 0.35, 1), run_time = 2, ), FadeIn(houses[1]), LaggedStartMap(DrawBorderThenFill, utilities, run_time = 2) ) self.play( LaggedStartMap( ShowCreation, lines, run_time = 3 ), Animation(self.objects) ) self.play( Write(no_crossing_words[0]), GrowArrow(no_crossing_words[1]), ) self.wait() self.objects.add_to_back(lines, no_crossing_words) def point_to_abstractions(self): objects = self.objects objects.generate_target() objects.target.scale(0.5) objects.target.move_to( (FRAME_Y_RADIUS*DOWN + FRAME_X_RADIUS*LEFT)/2 ) eulers = OldTex(*"V-E+F=2") eulers.set_color_by_tex_to_color_map({ "V" : RED, "E" : GREEN, "F" : BLUE, }) eulers.to_edge(UP, buff = 2) cube = Cube() cube.set_stroke(WHITE, 2) cube.set_height(0.75) cube.pose_at_angle() cube.next_to(eulers, UP) tda = OldTexText("Topological \\\\ Data Analysis") tda.move_to(DOWN + 4*RIGHT) arrow_from_eulers = Arrow( eulers.get_bottom(), tda.get_corner(UP+LEFT), color = WHITE ) self.play( objects.scale, 0.5, objects.move_to, DOWN + 4*LEFT, ) arrow_to_eulers = Arrow( self.houses[2].get_corner(UP+LEFT), eulers.get_bottom(), color = WHITE ) always_rotate(cube, axis=UP) self.play( GrowArrow(arrow_to_eulers), Write(eulers), FadeIn(cube) ) self.wait(5) self.play( GrowArrow(arrow_from_eulers), Write(tda) ) self.wait(2) self.set_variables_as_attrs( eulers, cube, tda, arrows = VGroup(arrow_to_eulers, arrow_from_eulers), ) def show_this_video(self): screen_rect = FullScreenFadeRectangle( stroke_color = WHITE, stroke_width = 2, fill_opacity = 0, ) everything = VGroup( self.objects, self.arrows, self.eulers, self.cube, self.tda, screen_rect, ) self.teacher.save_state() self.teacher.fade(1) self.play( everything.scale, 0.5, everything.next_to, self.teacher, UP+LEFT, self.teacher.restore, self.teacher.change, "raise_right_hand", UP+LEFT, LaggedStartMap(FadeIn, self.students) ) self.play_student_changes( *["pondering"]*3, look_at = everything ) self.wait(5) class ThisPuzzleIsHard(UtilitiesPuzzleScene, PiCreatureScene): def construct(self): self.introduce_components() self.failed_attempts() self.ask_meta_puzzle() def introduce_components(self): randy = self.pi_creature try_it = OldTexText("Try it yourself!") try_it.to_edge(UP) self.setup_configuration() houses, utilities = self.houses, self.utilities self.remove(self.objects) house = houses[0] puzzle_words = OldTexText(""" Puzzle: Connect each house to \\\\ each utility without crossing lines. """) # puzzle_words.next_to(self.objects, UP) puzzle_words.to_edge(UP) self.add(try_it) self.play(Animation(try_it)) self.play( LaggedStartMap(DrawBorderThenFill, houses), LaggedStartMap(GrowFromCenter, utilities), try_it.set_width, house.get_width(), try_it.fade, 1, try_it.move_to, house, self.pi_creature.change, "happy", ) self.play(LaggedStartMap(FadeIn, puzzle_words)) self.add_foreground_mobjects(self.objects) self.set_variables_as_attrs(puzzle_words) def failed_attempts(self): bb = self.bounding_box utilities = self.utilities houses = self.houses randy = self.pi_creature line_sets = [ [ self.get_line(0, 0), self.get_line(1, 1), self.get_line(2, 2), self.get_line(0, 1), self.get_line(2, 1), self.get_line(0, 2, bb.get_corner(UP+LEFT)), self.get_line( 2, 0, bb.get_corner(DOWN+LEFT), prop = 0.85, ), self.get_line( 2, 0, bb.get_corner(UP+RIGHT), bb.get_top(), prop = 0.73, ), ], [ self.get_line(0, 0), self.get_line(1, 1), self.get_line(2, 2), self.get_line(0, 1), self.get_line(1, 2), self.get_line( 2, 0, bb.get_bottom(), bb.get_corner(DOWN+LEFT) ), self.get_line(0, 2, bb.get_top()), self.get_line( 2, 1, utilities[1].get_bottom() + MED_SMALL_BUFF*DOWN, utilities[1].get_left() + MED_SMALL_BUFF*LEFT, ), self.get_line( 1, 0, houses[2].get_corner(UP+LEFT) + MED_LARGE_BUFF*LEFT, prop = 0.49, ), self.get_line( 1, 2, bb.get_right(), prop = 0.25, ), ], [ self.get_line(0, 0), self.get_line(0, 1), self.get_line(0, 2, bb.get_top()), self.get_line(1, 0, bb.get_corner(DOWN+LEFT)), self.get_line(1, 1), self.get_line(1, 2, bb.get_corner(DOWN+RIGHT)), self.get_line(2, 1), self.get_line(2, 2), self.get_line(2, 0, bb.get_top(), prop = 0.45), self.get_line(2, 0, prop = 0.45), ], ] modes = ["confused", "sassy", "angry"] for line_set, mode in zip(line_sets, modes): good_lines = VGroup(*line_set[:-2]) bad_lines = line_set[-2:] self.play(LaggedStartMap(ShowCreation, good_lines)) for bl in bad_lines: self.play( ShowCreation( bl, rate_func = bezier([0, 0, 0, 1, 1, 1, 1, 1, 0.3, 1, 1]), run_time = 1.5 ), randy.change, mode, ) self.play(ShowCreation( bl, rate_func = lambda t : smooth(1-t), )) self.remove(bl) self.play(LaggedStartMap(FadeOut, good_lines)) def ask_meta_puzzle(self): randy = self.pi_creature group = VGroup( self.puzzle_words, self.objects, ) rect = SurroundingRectangle(group, color = BLUE, buff = MED_LARGE_BUFF) group.add(rect) group.generate_target() group.target.scale(0.75) group.target.shift(DOWN) group[-1].set_stroke(width = 0) meta_puzzle_words = OldTexText(""" Meta-puzzle: Prove that this\\\\ is impossible. """) meta_puzzle_words.next_to(group.target, UP) meta_puzzle_words.set_color(BLUE) self.play( MoveToTarget(group), randy.change, "pondering" ) self.play(Write(meta_puzzle_words)) self.play(randy.change, "confused") straight_lines = self.get_straight_lines() almost_solution_lines = self.get_almost_solution_lines() self.play(LaggedStartMap( ShowCreation, straight_lines, run_time = 2, lag_ratio = 0.8 ), Blink(randy)) self.play(Transform( straight_lines, almost_solution_lines, run_time = 3, lag_ratio = 0.5 )) self.wait() ###### def create_pi_creature(self): return Randolph().to_corner(DOWN+LEFT) class IntroduceGraph(PiCreatureScene): def construct(self): pi_creatures = self.pi_creatures dots = VGroup(*[ Dot(color = pi.get_color()).scale(2).move_to(pi) for pi in pi_creatures ]) lines = VGroup(*[ Line(pi1.get_center(), pi2.get_center()) for pi1, pi2 in it.combinations(pi_creatures, 2) ]) graph_word = OldTexText("``", "", "Graph", "''", arg_separator = "") graph_word.to_edge(UP) planar_graph_word = OldTexText("``", "Planar", " graph", "''", arg_separator = "") planar_graph_word.move_to(graph_word) vertices_word = OldTexText("Vertices") vertices_word.to_edge(RIGHT, buff = LARGE_BUFF) vertices_word.set_color(YELLOW) vertex_arrows = VGroup(*[ Arrow(vertices_word.get_left(), dot) for dot in dots[-2:] ]) edge_word = OldTexText("Edge") edge_word.next_to(lines, LEFT, LARGE_BUFF) edge_arrow = Arrow( edge_word, lines, buff = SMALL_BUFF, color = WHITE ) self.play(LaggedStartMap(GrowFromCenter, pi_creatures)) self.play( LaggedStartMap(ShowCreation, lines), LaggedStartMap( ApplyMethod, pi_creatures, lambda pi : (pi.change, "pondering", lines) ) ) self.play(Write(graph_word)) self.play(ReplacementTransform( pi_creatures, dots, run_time = 2, lag_ratio = 0.5 )) self.add_foreground_mobjects(dots) self.play( FadeIn(vertex_arrows), FadeIn(vertices_word), ) self.wait() self.play(LaggedStartMap( ApplyMethod, lines, lambda l : (l.rotate, np.pi/12), rate_func = wiggle )) self.play( FadeIn(edge_word), GrowArrow(edge_arrow), ) self.wait(2) line = lines[2] self.play( line.set_points_smoothly, [ line.get_start(), dots.get_left() + MED_SMALL_BUFF*LEFT, dots.get_corner(DOWN+LEFT) + MED_SMALL_BUFF*(DOWN+LEFT), dots.get_bottom() + MED_SMALL_BUFF*DOWN, line.get_end(), ], VGroup(edge_word, edge_arrow).shift, MED_LARGE_BUFF*LEFT, ) self.wait() self.play(ReplacementTransform(graph_word, planar_graph_word)) self.wait(2) ### def create_pi_creatures(self): pis = VGroup( PiCreature(color = BLUE_D), PiCreature(color = GREY_BROWN), PiCreature(color = BLUE_C).flip(), PiCreature(color = BLUE_E).flip(), ) pis.scale(0.5) pis.arrange_in_grid(buff = 2) return pis class IsK33Planar(UtilitiesPuzzleScene): def construct(self): self.setup_configuration() self.objects.shift(MED_LARGE_BUFF*DOWN) straight_lines = self.get_straight_lines() almost_solution_lines = self.get_almost_solution_lines() question = OldTexText("Is", "this graph", "planar?") question.set_color_by_tex("this graph", YELLOW) question.to_edge(UP) brace = Brace(question.get_part_by_tex("graph"), DOWN, buff = SMALL_BUFF) fancy_name = brace.get_text( "``Complete bipartite graph $K_{3, 3}$''", buff = SMALL_BUFF ) fancy_name.set_color(YELLOW) self.add(question) self.convert_objects_to_dots() self.play(LaggedStartMap(ShowCreation, straight_lines)) self.play( GrowFromCenter(brace), LaggedStartMap(FadeIn, fancy_name), ) self.play(ReplacementTransform( straight_lines, almost_solution_lines, run_time = 3, lag_ratio = 0.5 )) self.wait(2) class TwoKindsOfViewers(PiCreatureScene, UtilitiesPuzzleScene): def construct(self): self.setup_configuration() objects = self.objects objects.remove(self.bounding_box) lines = self.get_straight_lines() objects.add_to_back(lines) objects.scale(0.75) objects.next_to(ORIGIN, RIGHT, LARGE_BUFF) self.remove(objects) pi1, pi2 = self.pi_creatures words = OldTexText( "$(V-E+F)$", "kinds of viewers" ) words.to_edge(UP) eulers = words.get_part_by_tex("V-E+F") eulers.set_color(GREEN) non_eulers = VGroup(*[m for m in words if m is not eulers]) self.add(words) self.wait() self.play( pi1.shift, 2*LEFT, pi2.shift, 2*RIGHT, ) know_eulers = OldTexText("Know about \\\\ Euler's formula") know_eulers.next_to(pi1, DOWN) know_eulers.set_color(GREEN) dont = OldTexText("Don't") dont.next_to(pi2, DOWN) dont.set_color(RED) self.play( FadeIn(know_eulers), pi1.change, "hooray", ) self.play( FadeIn(dont), pi2.change, "maybe", eulers, ) self.wait() self.pi_creature_thinks( pi1, "", bubble_config = {"width" : 3, "height" : 2}, target_mode = "thinking" ) self.play(pi2.change, "confused", eulers) self.wait() ### Out of thin air self.play(*list(map(FadeOut, [ non_eulers, pi1, pi2, pi1.bubble, know_eulers, dont ]))) self.play(eulers.next_to, ORIGIN, LEFT, LARGE_BUFF) arrow = Arrow(eulers, objects, color = WHITE) self.play( GrowArrow(arrow), LaggedStartMap(DrawBorderThenFill, VGroup(*it.chain(*objects))) ) self.wait() self.play( objects.move_to, eulers, RIGHT, eulers.move_to, objects, LEFT, path_arc = np.pi, run_time = 1.5, ) self.wait(2) ### def create_pi_creatures(self): group = VGroup(Randolph(color = BLUE_C), Randolph()) group.scale(0.7) group.shift(MED_LARGE_BUFF*DOWN) return group class IntroduceRegions(UtilitiesPuzzleScene): def construct(self): self.setup_configuration() houses, utilities = self.houses, self.utilities objects = self.objects lines, line_groups, regions = self.get_lines_line_groups_and_regions() back_region = regions[0] front_regions = VGroup(*regions[1:]) self.convert_objects_to_dots(run_time = 0) self.play(LaggedStartMap( ShowCreation, lines, run_time = 3, )) self.add_foreground_mobjects(lines, objects) self.wait() for region in front_regions: self.play(FadeIn(region)) self.play( FadeIn(back_region), Animation(front_regions), ) self.wait() self.play(FadeOut(regions)) ##Paint bucket paint_bucket = SVGMobject( file_name = "paint_bucket", height = 0.5, ) paint_bucket.flip() paint_bucket.move_to(8*LEFT + 5*UP) def click(region): self.play( UpdateFromAlphaFunc( region, lambda m, a : m.set_fill(opacity = int(2*a)), ), ApplyMethod( paint_bucket.scale, 0.5, rate_func = there_and_back, ), run_time = 0.25, ) self.play( paint_bucket.next_to, utilities, DOWN+LEFT, SMALL_BUFF ) click(regions[1]) self.play(paint_bucket.next_to, utilities[1], UP+RIGHT, SMALL_BUFF) click(regions[2]) self.play(paint_bucket.next_to, houses[1], RIGHT) click(regions[3]) self.play(paint_bucket.move_to, 4*LEFT + 2*UP) self.add_foreground_mobjects(front_regions, lines, objects) click(back_region) self.remove_foreground_mobjects(front_regions) self.wait() self.play( FadeOut(back_region), FadeOut(front_regions[0]), FadeOut(paint_bucket), *list(map(Animation, front_regions[1:])) ) #Line tries to escape point_sets = [ [ VGroup(*houses[1:]).get_center(), houses[2].get_top() + MED_SMALL_BUFF*UP, ], [ houses[1].get_top() + SMALL_BUFF*UP, utilities[0].get_center(), ], [VGroup(houses[1], utilities[1]).get_center()], [ utilities[2].get_center() + 0.75*(DOWN+RIGHT) ], ] escape_lines = VGroup(*[ Line(LEFT, RIGHT).set_points_smoothly( [utilities[2].get_center()] + point_set ) for point_set in point_sets ]) self.wait() for line in escape_lines: self.play(ShowCreation(line, rate_func = lambda t : 0.8*smooth(t) )) self.play(ShowCreation(line, rate_func = lambda t : smooth(1 - t) )) def get_lines_line_groups_and_regions(self): lines = self.get_almost_solution_lines() flat_lines = VGroup(*it.chain(*lines)) flat_lines.remove(lines[2][0]) line_groups = [ VGroup(*[lines[i][j] for i, j in ij_set]) for ij_set in [ [(0, 0), (1, 0), (1, 1), (0, 1)], [(1, 1), (2, 1), (2, 2), (1, 2)], [(0, 2), (2, 2), (2, 1), (0, 1)], [(0, 0), (1, 0), (1, 2), (0, 2)], ] ] regions = VGroup(*[ self.get_region(*line_group) for line_group in line_groups ]) back_region = FullScreenFadeRectangle(fill_opacity = 1 ) regions.submobjects.pop() regions.submobjects.insert(0, back_region) front_regions = VGroup(*regions[1:]) back_region.set_color(BLUE_E) front_regions.set_color_by_gradient(GREEN_E, MAROON_E) return flat_lines, line_groups, regions class FromLastVideo(Scene): def construct(self): title = OldTexText("From last video") title.to_edge(UP) rect = ScreenRectangle(height = 6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait(2) class AskAboutRegions(IntroduceRegions): def construct(self): self.setup_configuration() houses, utilities = self.houses, self.utilities self.convert_objects_to_dots(run_time = 0) objects = self.objects lines, line_groups, regions = self.get_lines_line_groups_and_regions() back_region = regions[0] front_regions = VGroup(*regions[1:]) missing_lines = VGroup( self.get_line(2, 0, self.objects.get_top()), self.get_line( 2, 0, self.objects.get_bottom() + DOWN, self.objects.get_corner(DOWN+LEFT) + DOWN+LEFT, ) ) missing_lines.set_stroke(width = 5) front_regions.save_state() front_regions.generate_target() front_regions.target.scale(0.5) front_regions.target.arrange(RIGHT, buff = LARGE_BUFF) front_regions.target.to_edge(UP) self.add(front_regions) self.add_foreground_mobjects(lines, objects) self.wait() self.play(MoveToTarget(front_regions)) self.play(LaggedStartMap( ApplyMethod, front_regions, lambda m : (m.rotate, np.pi/12), rate_func = wiggle, lag_ratio = 0.75, run_time = 1 )) self.play(front_regions.restore) self.wait() #Show missing lines for line in missing_lines: self.play(ShowCreation( line, rate_func = there_and_back, run_time = 2, )) #Count regions count = OldTex("1") count.scale(1.5) count.to_edge(UP) self.play( FadeIn(back_region), FadeIn(count), Animation(front_regions) ) last_region = None for n, region in zip(it.count(2), front_regions): new_count = OldTex(str(n)) new_count.replace(count, dim_to_match = 1) self.remove(count) self.add(new_count) count = new_count region.save_state() anims = [ApplyMethod(region.set_color, YELLOW)] if last_region: anims.append(ApplyMethod(last_region.restore)) anims.append(Animation(front_regions)) self.play(*anims, run_time = 0.25) self.wait(0.5) last_region = region self.play(last_region.restore) self.wait() self.play(FadeOut(count)) #Count edges per region fade_rect = FullScreenFadeRectangle(opacity = 0.8) line_group = line_groups[0].copy() region = front_regions[0].copy() self.foreground_mobjects = [] def show_lines(line_group): lg_copy = line_group.copy() lg_copy.set_stroke(WHITE, 6) self.play(LaggedStartMap( FadeIn, lg_copy, run_time = 3, rate_func = there_and_back, lag_ratio = 0.4, remover = True, )) self.play( FadeIn(fade_rect), Animation(region), Animation(line_group), ) show_lines(line_group) last_line_group = line_group last_region = region for i in range(1, 3): line_group = line_groups[i].copy() region = front_regions[i].copy() self.play( FadeOut(last_region), FadeOut(last_line_group), FadeIn(region), FadeIn(line_group), ) show_lines(line_group) last_line_group = line_group last_region = region self.play( FadeOut(fade_rect), FadeOut(last_region), FadeOut(last_line_group), ) self.wait() class NewRegionClosedOnlyForNodesWithEdges(UtilitiesPuzzleScene): def construct(self): self.setup_configuration() self.convert_objects_to_dots(run_time = 0) objects = self.objects houses, utilities = self.houses, self.utilities bb = self.bounding_box lines = VGroup( self.get_line(2, 1), self.get_line(0, 1), self.get_line(0, 2, bb.get_corner(UP+LEFT), bb.get_top() + MED_LARGE_BUFF*UP, ), self.get_line(2, 2), ) lit_line = lines[2].copy() lit_line.set_points(lit_line.get_points()[::-1]) lit_line.set_stroke(WHITE, 5) region = self.get_region(*lines) region.set_fill(MAROON_E) arrow = Vector(DOWN+LEFT, color = WHITE) arrow.next_to(houses[2], UP+RIGHT, buff = SMALL_BUFF) words = OldTexText("Already has \\\\ an edge") words.next_to(arrow.get_start(), UP, SMALL_BUFF) for line in lines[:-1]: self.play(ShowCreation(line)) lines[-1].pointwise_become_partial(lines[-1], 0, 0.92) lines[-1].save_state() self.wait() self.play(ShowCreation(lines[-1])) self.add(region, lines, objects) self.wait() self.remove(region) self.play(ShowCreation(lines[-1], rate_func = lambda t : smooth(1-2*t*(1-t)) )) self.add(region, lines, objects) self.wait() self.remove(region) self.play( ShowCreation(lines[-1], rate_func = lambda t : smooth(1-0.5*t) ), FadeIn(words), GrowArrow(arrow), ) for x in range(2): self.play(ShowCreationThenDestruction(lit_line)) self.play(lines[-1].restore) self.add(region, lines, objects) self.wait(2) class LightUpNodes(IntroduceRegions): CONFIG = { "vertices_word" : "Lit vertices", } def construct(self): self.setup_configuration() self.setup_regions() self.setup_counters() self.describe_one_as_lit() self.show_rule_for_lighting() def setup_configuration(self): IntroduceRegions.setup_configuration(self) self.convert_objects_to_dots(run_time = 0) self.objects.shift(DOWN) def setup_regions(self): lines, line_groups, regions = self.get_lines_line_groups_and_regions() back_region = regions[0] front_regions = VGroup(*regions[1:]) self.set_variables_as_attrs( lines, line_groups, regions, back_region, front_regions, ) def setup_counters(self): titles = [ OldTexText("\\# %s"%self.vertices_word), OldTexText("\\# Edges"), OldTexText("\\# Regions"), ] for title, vect in zip(titles, [LEFT, ORIGIN, RIGHT]): title.shift(FRAME_X_RADIUS*vect/2) title.to_edge(UP) underline = Line(LEFT, RIGHT) underline.stretch_to_fit_width(title.get_width()) underline.next_to(title, DOWN, SMALL_BUFF) title.add(underline) self.add(title) self.count_titles = titles self.v_count, self.e_count, self.f_count = self.counts = list(map( Integer, [1, 0, 1] )) for count, title in zip(self.counts, titles): count.next_to(title, DOWN) self.add(count) def describe_one_as_lit(self): houses, utilities = self.houses, self.utilities vertices = VGroup(*it.chain(houses, utilities)) dim_arrows = VGroup() for vertex in vertices: arrow = Vector(0.5*(DOWN+LEFT), color = WHITE) arrow.next_to(vertex, UP+RIGHT, SMALL_BUFF) vertex.arrow = arrow dim_arrows.add(arrow) lit_vertex = utilities[0] lit_arrow = lit_vertex.arrow lit_arrow.rotate(np.pi/2, about_point = lit_vertex.get_center()) dim_arrows.remove(lit_arrow) lit_word = OldTexText("Lit up") lit_word.next_to(lit_arrow.get_start(), UP, SMALL_BUFF) dim_word = OldTexText("Dim") dim_word.next_to(dim_arrows[1].get_start(), UP, MED_LARGE_BUFF) dot = Dot().move_to(self.v_count) self.play( vertices.set_fill, None, 0, vertices.set_stroke, None, 1, ) self.play(ReplacementTransform(dot, lit_vertex)) self.play( FadeIn(lit_word), GrowArrow(lit_arrow) ) self.play(*self.get_lit_vertex_animations(lit_vertex)) self.play( FadeIn(dim_word), LaggedStartMap(GrowArrow, dim_arrows) ) self.wait() self.play(*list(map(FadeOut, [ lit_word, lit_arrow, dim_word, dim_arrows ]))) def show_rule_for_lighting(self): lines = self.lines regions = self.regions line_groups = self.line_groups objects = self.objects houses, utilities = self.houses, self.utilities #First region, lines 0, 1, 4, 3 lines[4].rotate(np.pi) region = regions[1] self.play(ShowCreation(lines[0])) self.play(*self.get_count_change_animations(0, 1, 0)) self.play(*it.chain( self.get_lit_vertex_animations(houses[0]), self.get_count_change_animations(1, 0, 0) )) self.wait() for line, vertex in (lines[1], houses[1]), (lines[4], utilities[1]): self.play( ShowCreation(line), *self.get_count_change_animations(0, 1, 0) ) self.play(*it.chain( self.get_lit_vertex_animations(vertex), self.get_count_change_animations(1, 0, 0), )) self.wait() self.play( ShowCreation(lines[3], run_time = 2), *self.get_count_change_animations(0, 1, 0) ) self.add_foreground_mobjects(line_groups[0]) self.add_foreground_mobjects(objects) self.play( FadeIn(region), *self.get_count_change_animations(0, 0, 1) ) self.wait() #Next region, lines 2, 7, 8 region = regions[3] lines[6].rotate(np.pi) for line, vertex in (lines[2], houses[2]), (lines[6], utilities[2]): self.play(ShowCreation(line), *it.chain( self.get_lit_vertex_animations( vertex, run_time = 2, squish_range = (0.5, 1), ), self.get_count_change_animations(1, 1, 0) )) self.wait() self.play( ShowCreation(lines[7]), *self.get_count_change_animations(0, 1, 1) ) self.add_foreground_mobjects(line_groups[2]) self.add_foreground_mobjects(objects) self.play(FadeIn(region)) self.wait() #### def get_count_change_animations(self, *changes): anims = [] for change, count in zip(changes, self.counts): if change == 0: continue new_count = Integer(count.number + 1) new_count.move_to(count) anims.append(Transform( count, new_count, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1) )) count.number += 1 anims.append(self.get_plus_one_anim(count)) return anims def get_plus_one_anim(self, count): plus_one = OldTex("+1") plus_one.set_color(YELLOW) plus_one.move_to(count) plus_one.next_to(count, DOWN) plus_one.generate_target() plus_one.target.move_to(count) plus_one.target.set_fill(opacity = 0) move = MoveToTarget(plus_one, remover = True) grow = GrowFromCenter(plus_one) return UpdateFromAlphaFunc( plus_one, lambda m, a : ( (grow if a < 0.5 else move).update(2*a%1) ), remover = True, rate_func = double_smooth, run_time = 2 ) def get_lit_vertex_animations(self, vertex, run_time = 1, squish_range = (0, 1)): line = Line( LEFT, RIGHT, stroke_width = 0, stroke_color = BLACK, ) line.set_width(0.5*vertex.get_width()) line.next_to(ORIGIN, buff = 0.75*vertex.get_width()) lines = VGroup(*[ line.copy().rotate(angle) for angle in np.arange(0, 2*np.pi, np.pi/4) ]) lines.move_to(vertex) random.shuffle(lines.submobjects) return [ LaggedStartMap( ApplyMethod, lines, lambda l : (l.set_stroke, YELLOW, 4), rate_func = squish_rate_func(there_and_back, *squish_range), lag_ratio = 0.75, remover = True, run_time = run_time ), ApplyMethod( vertex.set_fill, None, 1, run_time = run_time, rate_func = squish_rate_func(smooth, *squish_range) ), ] class ShowRule(TeacherStudentsScene): def construct(self): new_edge = OldTexText("New edge") new_vertex = OldTexText("New (lit) vertex") new_vertex.next_to(new_edge, UP+RIGHT, MED_LARGE_BUFF) new_region = OldTexText("New region") new_region.next_to(new_edge, DOWN+RIGHT, MED_LARGE_BUFF) VGroup(new_vertex, new_region).shift(RIGHT) arrows = VGroup(*[ Arrow( new_edge.get_right(), mob.get_left(), color = WHITE, buff = SMALL_BUFF ) for mob in (new_vertex, new_region) ]) for word, arrow in zip(["Either", "or"], arrows): word_mob = OldTexText(word) word_mob.scale(0.65) word_mob.next_to(ORIGIN, UP, SMALL_BUFF) word_mob.rotate(arrow.get_angle()) word_mob.shift(arrow.get_center()) word_mob.set_color(GREEN) arrow.add(word_mob) new_vertex.set_color(YELLOW) new_edge.set_color(BLUE) new_region.set_color(RED) rule = VGroup(new_edge, arrows, new_vertex, new_region) rule.center().to_edge(UP) nine_total = OldTexText("(9 total)") nine_total.next_to(new_edge, DOWN) self.play( Animation(rule), self.teacher.change, "raise_right_hand" ) self.play_student_changes( *["confused"]*3, look_at = rule ) self.wait(2) self.play( Write(nine_total), self.teacher.change, "happy", ) self.play_student_changes( *["thinking"]*3, look_at = rule ) self.wait(3) class ConcludeFiveRegions(LightUpNodes): def construct(self): self.setup_configuration() self.setup_regions() self.setup_counters() self.describe_start_setup() self.show_nine_lines_to_start() self.show_five_to_lit_up_nodes() self.relate_four_lines_to_regions() self.conclude_about_five_regions() def describe_start_setup(self): to_dim = VGroup(*it.chain(self.houses, self.utilities[1:])) to_dim.set_stroke(width = 1) to_dim.set_fill(opacity = 0) full_screen_rect = FullScreenFadeRectangle( fill_color = GREY_B, fill_opacity = 0.25, ) self.play( Indicate(self.v_count), *self.get_lit_vertex_animations(self.utilities[0]) ) self.play( FadeIn( full_screen_rect, rate_func = there_and_back, remover = True, ), Indicate(self.f_count), *list(map(Animation, self.mobjects)) ) self.wait() def show_nine_lines_to_start(self): line_sets = self.get_straight_lines() line_sets.target = VGroup() for lines in line_sets: lines.generate_target() for line in lines.target: line.rotate(-line.get_angle()) line.set_width(1.5) lines.target.arrange(DOWN) line_sets.target.add(lines.target) line_sets.target.arrange(DOWN) line_sets.target.center() line_sets.target.to_edge(RIGHT) for lines in line_sets: self.play(LaggedStartMap(ShowCreation, lines, run_time = 1)) self.play(MoveToTarget(lines)) self.wait() ghost_lines = line_sets.copy() ghost_lines.fade(0.9) self.add(ghost_lines, line_sets) self.side_lines = VGroup(*it.chain(*line_sets)) def show_five_to_lit_up_nodes(self): side_lines = self.side_lines lines = self.lines vertices = VGroup(*it.chain(self.houses, self.utilities)) line_indices = [0, 1, 4, 6, 7] vertex_indices = [0, 1, 4, 5, 2] for li, vi in zip(line_indices, vertex_indices): side_line = side_lines[li] line = lines[li] vertex = vertices[vi] self.play(ReplacementTransform(side_line, line)) self.play(*it.chain( self.get_count_change_animations(1, 1, 0), self.get_lit_vertex_animations(vertex), )) def relate_four_lines_to_regions(self): f_rect = SurroundingRectangle( VGroup(self.count_titles[-1], self.f_count) ) on_screen_side_lines = VGroup(*[m for m in self.side_lines if m in self.mobjects]) side_lines_rect = SurroundingRectangle(on_screen_side_lines) side_lines_rect.set_color(WHITE) self.play(ShowCreation(side_lines_rect)) self.wait() self.play(ReplacementTransform(side_lines_rect, f_rect)) self.play(FadeOut(f_rect)) self.wait() def conclude_about_five_regions(self): lines = self.lines side_lines = self.side_lines regions = self.regions[1:] line_groups = self.line_groups line_indices = [3, 5, 2] objects = self.objects for region, line_group, li in zip(regions, line_groups, line_indices): self.play(ReplacementTransform( side_lines[li], lines[li] )) self.play( FadeIn(region), Animation(line_group), Animation(objects), *self.get_count_change_animations(0, 1, 1) ) self.wait() #Conclude words = OldTexText("Last line must \\\\ introduce 5th region") words.scale(0.8) words.set_color(BLUE) rect = SurroundingRectangle(self.f_count) rect.set_color(BLUE) words.next_to(rect, DOWN) randy = Randolph().flip() randy.scale(0.5) randy.next_to(words, RIGHT, SMALL_BUFF, DOWN) self.play(ShowCreation(rect), Write(words)) self.play(FadeIn(randy)) self.play(randy.change, "pondering") self.play(Blink(randy)) self.wait(2) class WhatsWrongWithFive(TeacherStudentsScene): def construct(self): self.student_says( "What's wrong with \\\\ 5 regions?", target_mode = "maybe" ) self.wait(2) class CyclesHaveAtLeastFour(UtilitiesPuzzleScene): def construct(self): self.setup_configuration() houses, utilities = self.houses, self.utilities vertices = VGroup( houses[0], utilities[0], houses[1], utilities[1], houses[0], ) lines = [ VectorizedPoint(), self.get_line(0, 0), self.get_line(0, 1), self.get_line(1, 1), self.get_line(1, 0, self.objects.get_corner(DOWN+LEFT)), ] for line in lines[1::2]: line.set_points(line.get_points()[::-1]) arrows = VGroup() for vertex in vertices: vect = vertices.get_center() - vertex.get_center() arrow = Vector(vect, color = WHITE) arrow.next_to(vertex, -vect, buff = 0) vertex.arrow = arrow arrows.add(arrow) word_strings = [ "Start at a house", "Go to a utility", "Go to another house", "Go to another utility", "Back to the start", ] words = VGroup() for word_string, arrow in zip(word_strings, arrows): vect = arrow.get_vector()[1]*UP word = OldTexText(word_string) word.next_to(arrow.get_start(), -vect) words.add(word) count = Integer(-1) count.fade(1) count.to_edge(UP) last_word = None last_arrow = None for line, word, arrow in zip(lines, words, arrows): anims = [] for mob in last_word, last_arrow: if mob: anims.append(FadeOut(mob)) new_count = Integer(count.number + 1) new_count.move_to(count) anims += [ FadeIn(word), GrowArrow(arrow), ShowCreation(line), FadeOut(count), FadeIn(new_count), ] self.play(*anims) self.wait() last_word = word last_arrow = arrow count = new_count self.wait(2) class FiveRegionsFourEdgesEachGraph(Scene): CONFIG = { "v_color" : WHITE, "e_color" : YELLOW, "f_colors" : (BLUE, RED_E, BLUE_E), "n_edge_double_count_examples" : 6, "random_seed" : 1, } def construct(self): self.draw_squares() self.transition_to_graph() self.count_edges_per_region() self.each_edges_has_two_regions() self.ten_total_edges() def draw_squares(self): words = VGroup( OldTexText("5", "regions"), OldTexText("4", "edges each"), ) words.arrange(DOWN) words.to_edge(UP) words[0][0].set_color(self.f_colors[0]) words[1][0].set_color(self.e_color) squares = VGroup(*[Square() for x in range(5)]) squares.scale(0.5) squares.set_stroke(width = 0) squares.set_fill(opacity = 1) squares.set_color_by_gradient(*self.f_colors) squares.arrange(RIGHT, buff = MED_LARGE_BUFF) squares.next_to(words, DOWN, LARGE_BUFF) all_edges = VGroup() all_vertices = VGroup() for square in squares: corners = square.get_anchors()[:4] square.edges = VGroup(*[ Line(c1, c2, color = self.e_color) for c1, c2 in adjacent_pairs(corners) ]) square.vertices = VGroup(*[ Dot(color = self.v_color).move_to(c) for c in corners ]) all_edges.add(*square.edges) all_vertices.add(*square.vertices) self.play( FadeIn(words[0]), LaggedStartMap(FadeIn, squares, run_time = 1.5) ) self.play( FadeIn(words[1]), LaggedStartMap(ShowCreation, all_edges), LaggedStartMap(GrowFromCenter, all_vertices), ) self.wait() self.add_foreground_mobjects(words) self.set_variables_as_attrs(words, squares) def transition_to_graph(self): squares = self.squares words = self.words points = np.array([ UP+LEFT, UP+RIGHT, DOWN+RIGHT, DOWN+LEFT, 3*(UP+RIGHT), 3*(DOWN+LEFT), 3*(DOWN+RIGHT), ]) points *= 0.75 regions = VGroup(*[ Square().set_points_as_corners(points[indices]) for indices in [ [0, 1, 2, 3], [0, 4, 2, 1], [5, 0, 3, 2], [5, 2, 4, 6], [6, 4, 0, 5], ] ]) regions.set_stroke(width = 0) regions.set_fill(opacity = 1) regions.set_color_by_gradient(*self.f_colors) all_edges = VGroup() all_movers = VGroup() for region, square in zip(regions, squares): corners = region.get_anchors()[:4] region.edges = VGroup(*[ Line(c1, c2, color = self.e_color) for c1, c2 in adjacent_pairs(corners) ]) all_edges.add(*region.edges) region.vertices = VGroup(*[ Dot(color = self.v_color).move_to(c) for c in corners ]) mover = VGroup( square, square.edges, square.vertices, ) mover.target = VGroup( region, region.edges, region.vertices ) all_movers.add(mover) back_region = FullScreenFadeRectangle() back_region.set_fill(regions[-1].get_color(), 0.5) regions[-1].set_fill(opacity = 0) back_region.add(regions[-1].copy().set_fill(BLACK, 1)) back_region.edges = regions[-1].edges self.play( FadeIn( back_region, rate_func = squish_rate_func(smooth, 0.7, 1), run_time = 3, ), LaggedStartMap( MoveToTarget, all_movers, run_time = 3, replace_mobject_with_target_in_scene = True, ), ) self.wait(2) self.set_variables_as_attrs( regions, all_edges, back_region, graph = VGroup(*[m.target for m in all_movers]) ) def count_edges_per_region(self): all_edges = self.all_edges back_region = self.back_region regions = self.regions graph = self.graph all_vertices = VGroup(*[r.vertices for r in regions]) ghost_edges = all_edges.copy() ghost_edges.set_stroke(GREY_B, 1) count = Integer(0) count.scale(2) count.next_to(graph, RIGHT, buff = 2) count.set_fill(YELLOW, opacity = 0) last_region = VGroup(back_region, *regions[1:]) last_region.add(all_edges) for region in list(regions[:-1]) + [back_region]: self.play( FadeIn(region), Animation(ghost_edges), FadeOut(last_region), Animation(count), Animation(all_vertices), ) for edge in region.edges: new_count = Integer(count.number + 1) new_count.replace(count, dim_to_match = 1) new_count.set_color(count.get_color()) self.play( ShowCreation(edge), FadeOut(count), FadeIn(new_count), run_time = 0.5 ) count = new_count last_region = VGroup(region, region.edges) self.wait() self.add_foreground_mobjects(count) self.play( FadeOut(last_region), Animation(ghost_edges), Animation(all_vertices), ) self.set_variables_as_attrs(count, ghost_edges, all_vertices) def each_edges_has_two_regions(self): regions = list(self.regions[:-1]) + [self.back_region] back_region = self.back_region self.add_foreground_mobjects(self.ghost_edges, self.all_vertices) edge_region_pair_groups = [] for r1, r2 in it.combinations(regions, 2): for e1 in r1.edges: for e2 in r2.edges: diff = e1.get_center()-e2.get_center() if get_norm(diff) < 0.01: edge_region_pair_groups.append(VGroup( e1, r1, r2 )) for x in range(self.n_edge_double_count_examples): edge, r1, r2 = random.choice(edge_region_pair_groups) if r2 is back_region: #Flip again, maybe you're still unlucky, maybe not edge, r1, r2 = random.choice(edge_region_pair_groups) self.play(ShowCreation(edge)) self.add_foreground_mobjects(edge) self.play(FadeIn(r1), run_time = 0.5) self.play(FadeIn(r2), Animation(r1), run_time = 0.5) self.wait(0.5) self.play(*list(map(FadeOut, [r2, r1, edge])), run_time = 0.5) self.remove_foreground_mobjects(edge) def ten_total_edges(self): double_count = self.count brace = Brace(double_count, UP) words = brace.get_text("Double-counts \\\\ edges") regions = self.regions edges = VGroup(*it.chain( regions[0].edges, regions[-1].edges, [regions[1].edges[1]], [regions[2].edges[3]], )) count = Integer(0) count.scale(2) count.set_fill(WHITE, 0) count.next_to(self.graph, LEFT, LARGE_BUFF) self.play( GrowFromCenter(brace), Write(words) ) self.wait() for edge in edges: new_count = Integer(count.number + 1) new_count.replace(count, dim_to_match = 1) self.play( ShowCreation(edge), FadeOut(count), FadeIn(new_count), run_time = 0.5 ) count = new_count self.wait() class EulersFormulaForGeneralPlanarGraph(LightUpNodes, ThreeDScene): CONFIG = { "vertices_word" : "Vertices" } def construct(self): self.setup_counters() self.show_creation_of_graph() self.show_formula() self.transform_into_cube() def show_creation_of_graph(self): points = np.array([ UP+LEFT, UP+RIGHT, DOWN+RIGHT, DOWN+LEFT, 3*(UP+LEFT), 3*(UP+RIGHT), 3*(DOWN+RIGHT), 3*(DOWN+LEFT), ]) points *= 0.75 points += DOWN vertices = VGroup(*list(map(Dot, points))) vertices.set_color(YELLOW) edges = VGroup(*[ VGroup(*[ Line(p1, p2, color = WHITE) for p2 in points ]) for p1 in points ]) regions = self.get_cube_faces(points) regions.set_stroke(width = 0) regions.set_fill(opacity = 1) regions.set_color_by_gradient(GREEN, RED, BLUE_E) regions[-1].set_fill(opacity = 0) pairs = [ (edges[0][1], vertices[1]), (edges[1][2], vertices[2]), (edges[2][6], vertices[6]), (edges[6][5], vertices[5]), (edges[5][1], regions[2]), (edges[0][4], vertices[4]), (edges[4][5], regions[1]), (edges[0][3], vertices[3]), (edges[3][2], regions[0]), (edges[4][7], vertices[7]), (edges[7][3], regions[4]), (edges[7][6], regions[3]), ] self.add_foreground_mobjects(vertices[0]) self.wait() for edge, obj in pairs: anims = [ShowCreation(edge)] if obj in vertices: obj.save_state() obj.move_to(edge.get_start()) anims.append(ApplyMethod(obj.restore)) anims += self.get_count_change_animations(1, 1, 0) self.add_foreground_mobjects(obj) else: anims = [FadeIn(obj)] + anims anims += self.get_count_change_animations(0, 1, 1) self.play(*anims) self.add_foreground_mobjects(edge) self.wait() self.set_variables_as_attrs(edges, vertices, regions) def show_formula(self): counts = VGroup(*self.counts) count_titles = VGroup(*self.count_titles) groups = [count_titles, counts] for group in groups: group.symbols = VGroup(*list(map(Tex, ["-", "+", "="]))) group.generate_target() line = VGroup(*it.chain(*list(zip(group.target, group.symbols)))) line.arrange(RIGHT) line.to_edge(UP, buff = MED_SMALL_BUFF) VGroup(counts.target, counts.symbols).shift(0.75*DOWN) for mob in count_titles.target: mob[-1].fade(1) count_titles.symbols.shift(0.5*SMALL_BUFF*UP) twos = VGroup(*[ OldTex("2").next_to(group.symbols, RIGHT) for group in groups ]) twos.shift(0.5*SMALL_BUFF*UP) words = OldTexText("``Euler's characteristic formula''") words.next_to(counts.target, DOWN) words.shift(MED_LARGE_BUFF*RIGHT) words.set_color(YELLOW) for group in groups: self.play( MoveToTarget(group), Write(group.symbols) ) self.wait() self.play(Write(twos)) self.wait() self.play(Write(words)) self.wait() self.top_formula = VGroup(count_titles, count_titles.symbols, twos[0]) self.bottom_formula = VGroup(counts, counts.symbols, twos[1]) def transform_into_cube(self): regions = self.regions points = np.array([ UP+LEFT, UP+RIGHT, DOWN+RIGHT, DOWN+LEFT, UP+LEFT+2*IN, UP+RIGHT+2*IN, DOWN+RIGHT+2*IN, DOWN+LEFT+2*IN, ]) cube = self.get_cube_faces(points) cube.shift(OUT) cube.rotate(np.pi/12, RIGHT) cube.rotate(np.pi/6, UP) cube.shift(MED_LARGE_BUFF*DOWN) shade_in_3d(cube) for face, region in zip(cube, regions): face.set_fill(region.get_color(), opacity = 0.8) self.remove(self.edges) regions.set_stroke(WHITE, 3) cube.set_stroke(WHITE, 3) new_formula = OldTex("V - E + F = 2") new_formula.to_edge(UP, buff = MED_SMALL_BUFF) new_formula.align_to(self.bottom_formula, RIGHT) self.play(FadeOut(self.vertices)) self.play(ReplacementTransform(regions, cube, run_time = 2)) cube.sort(lambda p : -p[2]) always_rotate(cube, axis=UP, about_point=ORIGIN) self.add(cube) self.wait(3) self.play( FadeOut(self.top_formula), FadeIn(new_formula) ) self.wait(10) ### def get_cube_faces(self, eight_points): return VGroup(*[ Square().set_points_as_corners(eight_points[indices]) for indices in [ [0, 1, 2, 3], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], [4, 5, 6, 7], ] ]) class YouGaveFriendsAnImpossiblePuzzle(TeacherStudentsScene): def construct(self): self.student_says( "You gave friends \\\\ an impossible puzzle?", target_mode = "sassy", ) self.play_student_changes( "angry", "sassy", "angry", added_anims = [self.teacher.change, "happy"] ) self.wait(2) class FunnyStory(TeacherStudentsScene): def construct(self): self.teacher_says("Funny story", target_mode = "hooray") self.wait() self.play_student_changes( *["happy"]*3, added_anims = [RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand" )], look_at = UP+2*RIGHT ) self.wait(5) class QuestionWrapper(Scene): def construct(self): question = OldTexText( "Where", "\\emph{specifically}", "does\\\\", "this proof break down?", ) question.to_edge(UP) question.set_color_by_tex("specifically", YELLOW) screen_rect = ScreenRectangle(height = 5.5) screen_rect.next_to(question, DOWN) self.play(ShowCreation(screen_rect)) self.wait() for word in question: self.play(LaggedStartMap( FadeIn, word, run_time = 0.05*len(word) )) self.wait(0.05) self.wait() class Homework(TeacherStudentsScene): def construct(self): self.teacher_says("Consider this \\\\ homework") self.play_student_changes(*["pondering"]*3) self.wait(2) self.student_says( "$V-E+F=0$ on \\\\ a torus!", target_mode = "hooray" ) self.wait() self.teacher_says("Not good enough!", target_mode = "surprised") self.play_student_changes(*["confused"]*3) self.wait(2) class WantToLearnMore(Scene): def construct(self): text = OldTexText("Want to learn more?") self.play(Write(text)) self.wait() class PatreonThanks(PatreonEndScreen): CONFIG = { "specific_patrons" : [ "Randall Hunt", "Desmos", "Burt Humburg", "CrypticSwarm", "Juan Benet", "David Kedmey", "Ali Yahya", "Mayank M. Mehrotra", "Lukas Biewald", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Jordan Scales", "Markus Persson", "Egor Gumenuk", "Yoni Nazarathy", "Ryan Atallah", "Joseph John Cox", "Luc Ritchie", "Onuralp Soylemez", "John Bjorn Nelson", "Yaw Etse", "David Barbetta", "Julio Cesar Campo Neto", "Waleed Hamied", "Oliver Steele", "George Chiesa", "supershabam", "James Park", "Samantha D. Suplee", "Delton Ding", "Thomas Tarler", "Jonathan Eppele", "Isak Hietala", "1stViewMaths", "Jacob Magnuson", "Mark Govea", "Dagan Harrington", "Clark Gaebel", "Eric Chow", "Mathias Jansson", "David Clark", "Michael Gardner", "Mads Elvheim", "Erik Sundell", "Awoo", "Dr. David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class NewMugThumbnail(Scene): def construct(self): title = OldTex( "V - E + F = 0", tex_to_color_map={"0": YELLOW}, ) title.scale(3) title.to_edge(UP) image = ImageMobject("sci_youtubers_thumbnail") image.set_height(5.5) image.next_to(title, DOWN) self.add(title, image) class Thumbnail3(UtilitiesPuzzleScene): def construct(self): self.setup_configuration() lines = self.get_almost_solution_lines() lines.set_stroke(WHITE, 5, opacity=0.9) group = VGroup(lines, self.objects) group.set_height(5.5) group.to_edge(DOWN, buff=0.1) self.add(*group) words = OldTexText("No crossing\\\\allowed!", font_size=72) words.to_corner(UL) # words.shift(3 * RIGHT) arrow = Arrow( words.get_corner(UR) + 0.1 * DOWN, group.get_top() + 0.35 * DOWN + 0.15 * RIGHT, path_arc=-75 * DEGREES, thickness=0.1, ) arrow.set_fill(RED) self.add(words, arrow)
videos_3b1b/_2017/eoc/chapter6.py
from manim_imports_ext import * SPACE_UNIT_TO_PLANE_UNIT = 0.75 class Chapter6OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "Do not ask whether a ", "statement is true until", "you know what it means." ], "author" : "Errett Bishop" } class ThisWasConfusing(TeacherStudentsScene): def construct(self): words = OldTexText("Implicit differentiation") words.move_to(self.get_teacher().get_corner(UP+LEFT), DOWN+RIGHT) words.set_fill(opacity = 0) self.play( self.get_teacher().change_mode, "raise_right_hand", words.set_fill, None, 1, words.shift, 0.5*UP ) self.play_student_changes( *["confused"]*3, look_at = words, added_anims = [Animation(self.get_teacher())] ) self.wait() self.play( self.get_teacher().change_mode, "confused", self.get_teacher().look_at, words, ) self.wait(3) class SlopeOfCircleExample(ZoomedScene): CONFIG = { "plane_kwargs" : { "x_radius" : FRAME_X_RADIUS/SPACE_UNIT_TO_PLANE_UNIT, "y_radius" : FRAME_Y_RADIUS/SPACE_UNIT_TO_PLANE_UNIT, "space_unit_to_x_unit" : SPACE_UNIT_TO_PLANE_UNIT, "space_unit_to_y_unit" : SPACE_UNIT_TO_PLANE_UNIT, }, "example_point" : (3, 4), "circle_radius" : 5, "circle_color" : YELLOW, "example_color" : MAROON_B, "zoom_factor" : 20, "zoomed_canvas_corner" : UP+LEFT, "zoomed_canvas_corner_buff" : MED_SMALL_BUFF, } def construct(self): self.setup_plane() self.introduce_circle() self.talk_through_pythagorean_theorem() self.draw_example_slope() self.show_perpendicular_radius() self.show_dx_and_dy() self.write_slope_as_dy_dx() self.point_out_this_is_not_a_graph() self.perform_implicit_derivative() self.show_final_slope() def setup_plane(self): self.plane = NumberPlane(**self.plane_kwargs) self.planes.fade() self.plane.add(self.plane.get_axis_labels()) self.plane.add_coordinates() self.add(self.plane) def introduce_circle(self): circle = Circle( radius = self.circle_radius*SPACE_UNIT_TO_PLANE_UNIT, color = self.circle_color, ) equation = OldTex("x^2 + y^2 = 5^2") equation.add_background_rectangle() equation.next_to( circle.point_from_proportion(1./8), UP+RIGHT ) equation.to_edge(RIGHT) self.play(ShowCreation(circle, run_time = 2)) self.play(Write(equation)) self.wait() self.circle = circle self.circle_equation = equation def talk_through_pythagorean_theorem(self): point = self.plane.num_pair_to_point(self.example_point) x_axis_point = point[0]*RIGHT dot = Dot(point, color = self.example_color) x_line = Line(ORIGIN, x_axis_point, color = GREEN) y_line = Line(x_axis_point, point, color = RED) radial_line = Line(ORIGIN, point, color = self.example_color) lines = VGroup(radial_line, x_line, y_line) labels = VGroup() self.play(ShowCreation(dot)) for line, tex in zip(lines, "5xy"): label = OldTex(tex) label.set_color(line.get_color()) label.add_background_rectangle() label.next_to( line.get_center(), rotate_vector(UP, line.get_angle()), buff = SMALL_BUFF ) self.play( ShowCreation(line), Write(label) ) labels.add(label) full_group = VGroup(dot, lines, labels) start_angle = angle_of_vector(point) end_angle = np.pi/12 spatial_radius = get_norm(point) def update_full_group(group, alpha): dot, lines, labels = group angle = interpolate(start_angle, end_angle, alpha) new_point = spatial_radius*rotate_vector(RIGHT, angle) new_x_axis_point = new_point[0]*RIGHT dot.move_to(new_point) radial_line, x_line, y_line = lines x_line.put_start_and_end_on(ORIGIN, new_x_axis_point) y_line.put_start_and_end_on(new_x_axis_point, new_point) radial_line.put_start_and_end_on(ORIGIN, new_point) for line, label in zip(lines, labels): label.next_to( line.get_center(), rotate_vector(UP, line.get_angle()), buff = SMALL_BUFF ) return group self.play(UpdateFromAlphaFunc( full_group, update_full_group, rate_func = there_and_back, run_time = 5, )) self.wait(2) #Move labels to equation movers = labels.copy() pairs = list(zip( [movers[1], movers[2], movers[0]], self.circle_equation[1][0:-1:3] )) self.play(*[ ApplyMethod(m1.replace, m2) for m1, m2 in pairs ]) self.wait() self.play(*list(map(FadeOut, [lines, labels, movers]))) self.remove(full_group) self.add(dot) self.wait() self.example_point_dot = dot def draw_example_slope(self): point = self.example_point_dot.get_center() line = Line(ORIGIN, point) line.set_color(self.example_color) line.rotate(np.pi/2) line.scale(2) line.move_to(point) word = OldTexText("Slope?") word.next_to(line.get_start(), UP, aligned_edge = LEFT) word.add_background_rectangle() coords = OldTex("(%d, %d)"%self.example_point) coords.add_background_rectangle() coords.scale(0.7) coords.next_to(point, LEFT) coords.shift(SMALL_BUFF*DOWN) coords.set_color(self.example_color) self.play(GrowFromCenter(line)) self.play(Write(word)) self.wait() self.play(Write(coords)) self.wait() self.tangent_line = line self.slope_word = word self.example_point_coords_mob = coords def show_perpendicular_radius(self): point = self.example_point_dot.get_center() radial_line = Line(ORIGIN, point, color = RED) perp_mark = VGroup( Line(UP, UP+RIGHT), Line(UP+RIGHT, RIGHT), ) perp_mark.scale(0.2) perp_mark.set_stroke(width = 2) perp_mark.rotate(radial_line.get_angle()+np.pi) perp_mark.shift(point) self.play(ShowCreation(radial_line)) self.play(ShowCreation(perp_mark)) self.wait() self.play(Indicate(perp_mark)) self.wait() morty = Mortimer().flip().to_corner(DOWN+LEFT) self.play(FadeIn(morty)) self.play(PiCreatureBubbleIntroduction( morty, "Suppose you \\\\ don't know this.", )) to_fade =self.get_mobjects_from_last_animation() self.play(Blink(morty)) self.wait() self.play(*list(map(FadeOut, to_fade))) self.play(*list(map(FadeOut, [radial_line, perp_mark]))) self.wait() def show_dx_and_dy(self): dot = self.example_point_dot point = dot.get_center() step_vect = rotate_vector(point, np.pi/2) step_length = 1./self.zoom_factor step_vect *= step_length/get_norm(step_vect) step_line = Line(ORIGIN, LEFT) step_line.set_color(WHITE) brace = Brace(step_line, DOWN) step_text = brace.get_text("Step", buff = SMALL_BUFF) step_group = VGroup(step_line, brace, step_text) step_group.rotate(angle_of_vector(point) - np.pi/2) step_group.scale(1./self.zoom_factor) step_group.shift(point) interim_point = step_line.get_corner(UP+RIGHT) dy_line = Line(point, interim_point) dx_line = Line(interim_point, point+step_vect) dy_line.set_color(RED) dx_line.set_color(GREEN) for line, tex in (dx_line, "dx"), (dy_line, "dy"): label = OldTex(tex) label.scale(1./self.zoom_factor) next_to_vect = np.round( rotate_vector(DOWN, line.get_angle()) ) label.next_to( line, next_to_vect, buff = MED_SMALL_BUFF/self.zoom_factor ) label.set_color(line.get_color()) line.label = label self.activate_zooming() self.little_rectangle.move_to(step_line.get_center()) self.little_rectangle.save_state() self.little_rectangle.scale(self.zoom_factor) self.wait() self.play( self.little_rectangle.restore, dot.scale, 1./self.zoom_factor, run_time = 2 ) self.wait() self.play(ShowCreation(step_line)) self.play(GrowFromCenter(brace)) self.play(Write(step_text)) self.wait() for line in dy_line, dx_line: self.play(ShowCreation(line)) self.play(Write(line.label)) self.wait() self.wait() self.step_group = step_group self.dx_line = dx_line self.dy_line = dy_line def write_slope_as_dy_dx(self): slope_word = self.slope_word new_slope_word = OldTexText("Slope =") new_slope_word.add_background_rectangle() new_slope_word.next_to(ORIGIN, RIGHT) new_slope_word.shift(slope_word.get_center()[1]*UP) dy_dx = OldTex("\\frac{dy}{dx}") VGroup(*dy_dx[:2]).set_color(RED) VGroup(*dy_dx[-2:]).set_color(GREEN) dy_dx.next_to(new_slope_word, RIGHT) dy_dx.add_background_rectangle() self.play(Transform(slope_word, new_slope_word)) self.play(Write(dy_dx)) self.wait() self.dy_dx = dy_dx def point_out_this_is_not_a_graph(self): equation = self.circle_equation x = equation[1][0] y = equation[1][3] brace = Brace(equation, DOWN) brace_text = brace.get_text( "Not $y = f(x)$", buff = SMALL_BUFF ) brace_text.set_color(RED) alt_brace_text = brace.get_text("Implicit curve") for text in brace_text, alt_brace_text: text.add_background_rectangle() text.to_edge(RIGHT, buff = MED_SMALL_BUFF) new_circle = self.circle.copy() new_circle.set_color(BLUE) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play(Indicate(x)) self.wait() self.play(Indicate(y)) self.wait() self.play(Transform(brace_text, alt_brace_text)) self.wait() self.play( ShowCreation(new_circle, run_time = 2), Animation(brace_text) ) self.play(new_circle.set_stroke, None, 0) self.wait() self.play(*list(map(FadeOut, [brace, brace_text]))) self.wait() def perform_implicit_derivative(self): equation = self.circle_equation morty = Mortimer() morty.flip() morty.next_to(ORIGIN, LEFT) morty.to_edge(DOWN, buff = SMALL_BUFF) q_marks = OldTex("???") q_marks.next_to(morty, UP) rect = Rectangle( width = FRAME_X_RADIUS - SMALL_BUFF, height = FRAME_Y_RADIUS - SMALL_BUFF, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.8, ) rect.to_corner(DOWN+RIGHT, buff = 0) derivative = OldTex("2x\\,dx + 2y\\,dy = 0") dx = VGroup(*derivative[2:4]) dy = VGroup(*derivative[7:9]) dx.set_color(GREEN) dy.set_color(RED) self.play( FadeIn(rect), FadeIn(morty), equation.next_to, ORIGIN, DOWN, MED_LARGE_BUFF, equation.shift, FRAME_X_RADIUS*RIGHT/2, ) self.play( morty.change_mode, "confused", morty.look_at, equation ) self.play(Blink(morty)) derivative.next_to(equation, DOWN) derivative.shift( equation[1][-3].get_center()[0]*RIGHT - \ derivative[-2].get_center()[0]*RIGHT ) #Differentiate self.play( morty.look_at, derivative[0], *[ ReplacementTransform( equation[1][i].copy(), derivative[j], ) for i, j in ((1, 0), (0, 1)) ] ) self.play(Write(dx, run_time = 1)) self.wait() self.play(*[ ReplacementTransform( equation[1][i].copy(), derivative[j], ) for i, j in ((2, 4), (3, 6), (4, 5)) ]) self.play(Write(dy, run_time = 1)) self.play(Blink(morty)) self.play(*[ ReplacementTransform( equation[1][i].copy(), derivative[j], ) for i, j in ((-3, -2), (-2, -1), (-1, -1)) ]) self.wait() #React self.play(morty.change_mode, "erm") self.play(Blink(morty)) self.play(Write(q_marks)) self.wait() self.play(Indicate(dx), morty.look_at, dx) self.play(Indicate(dy), morty.look_at, dy) self.wait() self.play( morty.change_mode, "shruggie", FadeOut(q_marks) ) self.play(Blink(morty)) self.play( morty.change_mode, "pondering", morty.look_at, derivative, ) #Rearrange x, y, eq = np.array(derivative)[[1, 6, 9]] final_form = OldTex( "\\frac{dy}{dx} = \\frac{-x}{y}" ) new_dy = VGroup(*final_form[:2]) new_dx = VGroup(*final_form[3:5]) new_dy.set_color(dy.get_color()) new_dx.set_color(dx.get_color()) new_dy.add(final_form[2]) new_x = VGroup(*final_form[6:8]) new_y = VGroup(*final_form[8:10]) new_eq = final_form[5] final_form.next_to(derivative, DOWN) final_form.shift((eq.get_center()[0]-new_eq.get_center()[0])*RIGHT) self.play(*[ ReplacementTransform( mover.copy(), target, run_time = 2, path_arc = np.pi/2, ) for mover, target in [ (dy, new_dy), (dx, new_dx), (eq, new_eq), (x, new_x), (y, new_y) ] ] + [ morty.look_at, final_form ]) self.wait(2) self.morty = morty self.neg_x_over_y = VGroup(*final_form[6:]) def show_final_slope(self): morty = self.morty dy_dx = self.dy_dx coords = self.example_point_coords_mob x, y = coords[1][1].copy(), coords[1][3].copy() frac = self.neg_x_over_y.copy() frac.generate_target() eq = OldTex("=") eq.add_background_rectangle() eq.next_to(dy_dx, RIGHT) frac.target.next_to(eq, RIGHT) frac.target.shift(SMALL_BUFF*DOWN) rect = BackgroundRectangle(frac.target) self.play( FadeIn(rect), MoveToTarget(frac), Write(eq), morty.look_at, rect, run_time = 2, ) self.wait() self.play(FocusOn(coords), morty.look_at, coords) self.play(Indicate(coords)) scale_factor = 1.4 self.play( x.scale, scale_factor, x.set_color, GREEN, x.move_to, frac[1], FadeOut(frac[1]), y.scale, scale_factor, y.set_color, RED, y.move_to, frac[3], DOWN, y.shift, SMALL_BUFF*UP, FadeOut(frac[3]), morty.look_at, frac, run_time = 2 ) self.wait() self.play(Blink(morty)) class NameImplicitDifferentation(TeacherStudentsScene): def construct(self): title = OldTexText("``Implicit differentiation''") equation = OldTex("x^2", "+", "y^2", "=", "5^2") derivative = OldTex( "2x\\,dx", "+", "2y\\,dy", "=", "0" ) VGroup(*derivative[0][2:]).set_color(GREEN) VGroup(*derivative[2][2:]).set_color(RED) arrow = Arrow(ORIGIN, DOWN, buff = SMALL_BUFF) group = VGroup(title, equation, arrow, derivative) group.arrange(DOWN) group.to_edge(UP) self.add(title, equation) self.play( self.get_teacher().change_mode, "raise_right_hand", ShowCreation(arrow) ) self.play_student_changes( *["confused"]*3, look_at = derivative, added_anims = [ReplacementTransform(equation.copy(), derivative)] ) self.wait(2) self.teacher_says( "Don't worry...", added_anims = [ group.scale, 0.7, group.to_corner, UP+LEFT, ] ) self.play_student_changes(*["happy"]*3) self.wait(3) class Ladder(VMobject): CONFIG = { "height" : 4, "width" : 1, "n_rungs" : 7, } def init_points(self): left_line, right_line = [ Line(ORIGIN, self.height*UP).shift(self.width*vect/2.0) for vect in (LEFT, RIGHT) ] rungs = [ Line( left_line.point_from_proportion(a), right_line.point_from_proportion(a), ) for a in np.linspace(0, 1, 2*self.n_rungs+1)[1:-1:2] ] self.add(left_line, right_line, *rungs) self.center() class RelatedRatesExample(ThreeDScene): CONFIG = { "start_x" : 3.0, "start_y" : 4.0, "wall_dimensions" : [0.3, 5, 5], "wall_color" : color_gradient([GREY_BROWN, BLACK], 4)[1], "wall_center" : 1.5*LEFT+0.5*UP, } def construct(self): self.introduce_ladder() self.write_related_rates() self.measure_ladder() self.slide_ladder() self.ponder_question() self.write_equation() self.isolate_x_of_t() self.discuss_lhs_as_function() self.let_dt_pass() self.take_derivative_of_rhs() self.take_derivative_of_lhs() self.bring_back_velocity_arrows() self.replace_terms_in_final_form() self.write_final_solution() def introduce_ladder(self): ladder = Ladder(height = self.get_ladder_length()) wall = Prism( dimensions = self.wall_dimensions, fill_color = self.wall_color, fill_opacity = 1, ) wall.rotate(np.pi/12, UP) wall.shift(self.wall_center) ladder.generate_target() ladder.fallen = ladder.copy() ladder.target.rotate(self.get_ladder_angle(), LEFT) ladder.fallen.rotate(np.pi/2, LEFT) for ladder_copy in ladder.target, ladder.fallen: ladder_copy.rotate(-5*np.pi/12, UP) ladder_copy.next_to(wall, LEFT, 0, DOWN) ladder_copy.shift(0.8*RIGHT) ##BAD! self.play( ShowCreation(ladder, run_time = 2) ) self.wait() self.play( DrawBorderThenFill(wall), MoveToTarget(ladder), run_time = 2 ) self.wait() self.ladder = ladder def write_related_rates(self): words = OldTexText("Related rates") words.to_corner(UP+RIGHT) self.play(Write(words)) self.wait() self.related_rates_words = words def measure_ladder(self): ladder = self.ladder ladder_brace = self.get_ladder_brace(ladder) x_and_y_lines = self.get_x_and_y_lines(ladder) x_line, y_line = x_and_y_lines y_label = OldTex("%dm"%int(self.start_y)) y_label.next_to(y_line, LEFT, buff = SMALL_BUFF) y_label.set_color(y_line.get_color()) x_label = OldTex("%dm"%int(self.start_x)) x_label.next_to(x_line, UP) x_label.set_color(x_line.get_color()) self.play(Write(ladder_brace)) self.wait() self.play(ShowCreation(y_line), Write(y_label)) self.wait() self.play(ShowCreation(x_line), Write(x_label)) self.wait(2) self.play(*list(map(FadeOut, [x_label, y_label]))) self.ladder_brace = ladder_brace self.x_and_y_lines = x_and_y_lines self.numerical_x_and_y_labels = VGroup(x_label, y_label) def slide_ladder(self): ladder = self.ladder brace = self.ladder_brace x_and_y_lines = self.x_and_y_lines x_line, y_line = x_and_y_lines down_arrow, left_arrow = [ Arrow(ORIGIN, vect, color = YELLOW, buff = 0) for vect in (DOWN, LEFT) ] down_arrow.shift(y_line.get_start()+MED_SMALL_BUFF*RIGHT) left_arrow.shift(x_line.get_start()+SMALL_BUFF*DOWN) # speed_label = OldTex("1 \\text{m}/\\text{s}") speed_label = OldTex("1 \\frac{\\text{m}}{\\text{s}}") speed_label.next_to(down_arrow, RIGHT, buff = SMALL_BUFF) q_marks = OldTex("???") q_marks.next_to(left_arrow, DOWN, buff = SMALL_BUFF) added_anims = [ UpdateFromFunc(brace, self.update_brace), UpdateFromFunc(x_and_y_lines, self.update_x_and_y_lines), Animation(down_arrow), ] self.play(ShowCreation(down_arrow)) self.play(Write(speed_label)) self.let_ladder_fall(ladder, *added_anims) self.wait() self.reset_ladder(ladder, *added_anims) self.play(ShowCreation(left_arrow)) self.play(Write(q_marks)) self.wait() self.let_ladder_fall(ladder, *added_anims) self.wait() self.reset_ladder(ladder, *added_anims) self.wait() self.dy_arrow = down_arrow self.dy_label = speed_label self.dx_arrow = left_arrow self.dx_label = q_marks def ponder_question(self): randy = Randolph(mode = "pondering") randy.flip() randy.to_corner(DOWN+RIGHT) self.play(FadeIn(randy)) self.play(Blink(randy)) self.wait() self.play( randy.change_mode, "confused", randy.look_at, self.ladder.get_top() ) self.play(randy.look_at, self.ladder.get_bottom()) self.play(randy.look_at, self.ladder.get_top()) self.play(Blink(randy)) self.wait() self.play(PiCreatureSays( randy, "Give names" )) self.play(Blink(randy)) self.play(*list(map(FadeOut, [ randy, randy.bubble, randy.bubble.content ]))) def write_equation(self): self.x_and_y_labels = self.get_x_and_y_labels() x_label, y_label = self.x_and_y_labels equation = OldTex( "x(t)", "^2", "+", "y(t)", "^2", "=", "5^2" ) equation[0].set_color(GREEN) equation[3].set_color(RED) equation.next_to(self.related_rates_words, DOWN, buff = MED_LARGE_BUFF) equation.to_edge(RIGHT, buff = LARGE_BUFF) self.play(Write(y_label)) self.wait() self.let_ladder_fall( self.ladder, y_label.shift, self.start_y*DOWN/2, *self.get_added_anims_for_ladder_fall()[:-1], rate_func = lambda t : 0.2*there_and_back(t), run_time = 3 ) self.play(FocusOn(x_label)) self.play(Write(x_label)) self.wait(2) self.play( ReplacementTransform(x_label.copy(), equation[0]), ReplacementTransform(y_label.copy(), equation[3]), Write(VGroup(*np.array(equation)[[1, 2, 4, 5, 6]])) ) self.wait(2) self.let_ladder_fall( self.ladder, *self.get_added_anims_for_ladder_fall(), rate_func = there_and_back, run_time = 6 ) self.wait() self.equation = equation def isolate_x_of_t(self): alt_equation = OldTex( "x(t)", "=", "\\big(5^2", "-", "y(t)", "^2 \\big)", "^{1/2}", ) alt_equation[0].set_color(GREEN) alt_equation[4].set_color(RED) alt_equation.next_to(self.equation, DOWN, buff = MED_LARGE_BUFF) alt_equation.to_edge(RIGHT) randy = Randolph() randy.next_to( alt_equation, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT, ) randy.look_at(alt_equation) find_dx_dt = OldTex("\\text{Find } \\,", "\\frac{dx}{dt}") find_dx_dt.next_to(randy, RIGHT, aligned_edge = UP) find_dx_dt[1].set_color(GREEN) self.play(FadeIn(randy)) self.play( randy.change_mode, "raise_right_hand", randy.look_at, alt_equation, *[ ReplacementTransform( self.equation[i].copy(), alt_equation[j], path_arc = np.pi/2, run_time = 3, rate_func = squish_rate_func( smooth, j/12.0, (j+6)/12.0 ) ) for i, j in enumerate([0, 6, 3, 4, 5, 1, 2]) ] ) self.play(Blink(randy)) self.wait() self.play( Write(find_dx_dt), randy.change_mode, "pondering", randy.look_at, find_dx_dt, ) self.let_ladder_fall( self.ladder, *self.get_added_anims_for_ladder_fall(), run_time = 8, rate_func = there_and_back ) self.play(*list(map(FadeOut, [ randy, find_dx_dt, alt_equation ]))) self.wait() def discuss_lhs_as_function(self): equation = self.equation lhs = VGroup(*equation[:5]) brace = Brace(lhs, DOWN) function_of_time = brace.get_text( "Function of time" ) constant_words = OldTexText( """that happens to be constant""" ) constant_words.set_color(YELLOW) constant_words.next_to(function_of_time, DOWN) derivative = OldTex( "\\frac{d\\left(x(t)^2 + y(t)^2 \\right)}{dt}" ) derivative.next_to(equation, DOWN, buff = MED_LARGE_BUFF) derivative.shift( ##Align x terms equation[0][0].get_center()[0]*RIGHT-\ derivative[2].get_center()[0]*RIGHT ) derivative_interior = lhs.copy() derivative_interior.move_to(VGroup(*derivative[2:13])) derivative_scaffold = VGroup( *list(derivative[:2])+list(derivative[13:]) ) self.play( GrowFromCenter(brace), Write(function_of_time) ) self.wait() self.play(Write(constant_words)) self.let_ladder_fall( self.ladder, *self.get_added_anims_for_ladder_fall(), run_time = 6, rate_func = lambda t : 0.5*there_and_back(t) ) self.wait() self.play(*list(map(FadeOut, [ brace, constant_words, function_of_time ]))) self.play( ReplacementTransform(lhs.copy(), derivative_interior), Write(derivative_scaffold), ) self.wait() self.derivative = VGroup( derivative_scaffold, derivative_interior ) def let_dt_pass(self): dt_words = OldTexText("After", "$dt$", "seconds...") dt_words.to_corner(UP+LEFT) dt = dt_words[1] dt.set_color(YELLOW) dt_brace = Brace(dt, buff = SMALL_BUFF) dt_brace_text = dt_brace.get_text("Think 0.01", buff = SMALL_BUFF) dt_brace_text.set_color(dt.get_color()) shadow_ladder = self.ladder.copy() shadow_ladder.fade(0.5) x_line, y_line = self.x_and_y_lines y_top = y_line.get_start() x_left = x_line.get_start() self.play(Write(dt_words, run_time = 2)) self.play( GrowFromCenter(dt_brace), Write(dt_brace_text, run_time = 2) ) self.play(*list(map(FadeOut, [ self.dy_arrow, self.dy_label, self.dx_arrow, self.dx_label, ]))) self.add(shadow_ladder) self.let_ladder_fall( self.ladder, *self.get_added_anims_for_ladder_fall(), rate_func = lambda t : 0.1*smooth(t), run_time = 1 ) new_y_top = y_line.get_start() new_x_left = x_line.get_start() dy_line = Line(y_top, new_y_top) dy_brace = Brace(dy_line, RIGHT, buff = SMALL_BUFF) dy_label = dy_brace.get_text("$dy$", buff = SMALL_BUFF) dy_label.set_color(RED) dx_line = Line(x_left, new_x_left) dx_brace = Brace(dx_line, DOWN, buff = SMALL_BUFF) dx_label = dx_brace.get_text("$dx$") dx_label.set_color(GREEN) VGroup(dy_line, dx_line).set_color(YELLOW) for line, brace, label in (dy_line, dy_brace, dy_label), (dx_line, dx_brace, dx_label): self.play( ShowCreation(line), GrowFromCenter(brace), Write(label), run_time = 1 ) self.wait() self.play(Indicate(self.derivative[1])) self.wait() self.dy_group = VGroup(dy_line, dy_brace, dy_label) self.dx_group = VGroup(dx_line, dx_brace, dx_label) self.shadow_ladder = shadow_ladder def take_derivative_of_rhs(self): derivative = self.derivative equals_zero = OldTex("= 0") equals_zero.next_to(derivative) rhs = self.equation[-1] self.play(Write(equals_zero)) self.wait() self.play(FocusOn(rhs)) self.play(Indicate(rhs)) self.wait() self.reset_ladder( self.ladder, *self.get_added_anims_for_ladder_fall()+[ Animation(self.dy_group), Animation(self.dx_group), ], rate_func = there_and_back, run_time = 3 ) self.wait() self.equals_zero = equals_zero def take_derivative_of_lhs(self): derivative_scaffold, equation = self.derivative equals_zero_copy = self.equals_zero.copy() lhs_derivative = OldTex( "2", "x(t)", "\\frac{dx}{dt}", "+", "2", "y(t)", "\\frac{dy}{dt}", ) lhs_derivative[1].set_color(GREEN) VGroup(*lhs_derivative[2][:2]).set_color(GREEN) lhs_derivative[5].set_color(RED) VGroup(*lhs_derivative[6][:2]).set_color(RED) lhs_derivative.next_to( derivative_scaffold, DOWN, aligned_edge = RIGHT, buff = MED_LARGE_BUFF ) equals_zero_copy.next_to(lhs_derivative, RIGHT) pairs = [ (0, 1), (1, 0), #x^2 -> 2x (2, 3), (3, 5), (4, 4), #+y^2 -> +2y ] def perform_replacement(index_pairs): self.play(*[ ReplacementTransform( equation[i].copy(), lhs_derivative[j], path_arc = np.pi/2, run_time = 2 ) for i, j in index_pairs ]) perform_replacement(pairs[:2]) self.play(Write(lhs_derivative[2])) self.wait() self.play(Indicate( VGroup( *list(lhs_derivative[:2])+\ list(lhs_derivative[2][:2]) ), run_time = 2 )) self.play(Indicate(VGroup(*lhs_derivative[2][3:]))) self.wait(2) perform_replacement(pairs[2:]) self.play(Write(lhs_derivative[6])) self.wait() self.play(FocusOn(self.equals_zero)) self.play(ReplacementTransform( self.equals_zero.copy(), equals_zero_copy )) self.wait(2) lhs_derivative.add(equals_zero_copy) self.lhs_derivative = lhs_derivative def bring_back_velocity_arrows(self): dx_dy_group = VGroup(self.dx_group, self.dy_group) arrow_group = VGroup( self.dy_arrow, self.dy_label, self.dx_arrow, self.dx_label, ) ladder_fall_args = [self.ladder] + self.get_added_anims_for_ladder_fall() self.reset_ladder(*ladder_fall_args + [ FadeOut(dx_dy_group), FadeOut(self.derivative), FadeOut(self.equals_zero), self.lhs_derivative.shift, 2*UP, ]) self.remove(self.shadow_ladder) self.play(FadeIn(arrow_group)) self.let_ladder_fall(*ladder_fall_args) self.wait() self.reset_ladder(*ladder_fall_args) self.wait() def replace_terms_in_final_form(self): x_label, y_label = self.x_and_y_labels num_x_label, num_y_label = self.numerical_x_and_y_labels new_lhs_derivative = OldTex( "2", "(%d)"%int(self.start_x), "\\frac{dx}{dt}", "+", "2", "(%d)"%int(self.start_y), "(-1)", "= 0" ) new_lhs_derivative[1].set_color(GREEN) VGroup(*new_lhs_derivative[2][:2]).set_color(GREEN) new_lhs_derivative[5].set_color(RED) new_lhs_derivative.next_to( self.lhs_derivative, DOWN, buff = MED_LARGE_BUFF, aligned_edge = RIGHT ) def fill_in_equation_part(*indices): self.play(*[ ReplacementTransform( self.lhs_derivative[i].copy(), new_lhs_derivative[i], run_time = 2 ) for i in indices ]) self.play(FadeOut(y_label), FadeIn(num_y_label)) fill_in_equation_part(3, 4, 5) self.play(FadeOut(x_label), FadeIn(num_x_label)) for indices in [(0, 1), (6,), (2, 7)]: fill_in_equation_part(*indices) self.wait() self.wait() self.new_lhs_derivative = new_lhs_derivative def write_final_solution(self): solution = OldTex( "\\frac{dx}{dt} = \\frac{4}{3}" ) for i in 0, 1, -1: solution[i].set_color(GREEN) solution[-3].set_color(RED) solution.next_to( self.new_lhs_derivative, DOWN, buff = MED_LARGE_BUFF, aligned_edge = RIGHT ) box = Rectangle(color = YELLOW) box.replace(solution) box.scale(1.5) self.play(Write(solution)) self.wait() self.play(ShowCreation(box)) self.wait() ######### def get_added_anims_for_ladder_fall(self): return [ UpdateFromFunc(self.ladder_brace, self.update_brace), UpdateFromFunc(self.x_and_y_lines, self.update_x_and_y_lines), UpdateFromFunc(self.x_and_y_labels, self.update_x_and_y_labels), ] def let_ladder_fall(self, ladder, *added_anims, **kwargs): kwargs["run_time"] = kwargs.get("run_time", self.start_y) kwargs["rate_func"] = kwargs.get("rate_func", None) self.play( Transform(ladder, ladder.fallen), *added_anims, **kwargs ) def reset_ladder(self, ladder, *added_anims, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 2) self.play( Transform(ladder, ladder.target), *added_anims, **kwargs ) def update_brace(self, brace): Transform( brace, self.get_ladder_brace(self.ladder) ).update(1) return brace def update_x_and_y_lines(self, x_and_y_lines): Transform( x_and_y_lines, self.get_x_and_y_lines(self.ladder) ).update(1) return x_and_y_lines def update_x_and_y_labels(self, x_and_y_labels): Transform( x_and_y_labels, self.get_x_and_y_labels() ).update(1) return x_and_y_labels def get_ladder_brace(self, ladder): vect = rotate_vector(LEFT, -self.get_ladder_angle()) brace = Brace(ladder, vect) length_string = "%dm"%int(self.get_ladder_length()) length_label = brace.get_text( length_string, use_next_to = False ) brace.add(length_label) brace.length_label = length_label return brace def get_x_and_y_labels(self): x_line, y_line = self.x_and_y_lines x_label = OldTex("x(t)") x_label.set_color(x_line.get_color()) x_label.next_to(x_line, DOWN, buff = SMALL_BUFF) y_label = OldTex("y(t)") y_label.set_color(y_line.get_color()) y_label.next_to(y_line, LEFT, buff = SMALL_BUFF) return VGroup(x_label, y_label) def get_x_and_y_lines(self, ladder): bottom_point, top_point = np.array(ladder[1].get_start_and_end()) interim_point = top_point[0]*RIGHT + bottom_point[1]*UP interim_point += SMALL_BUFF*DOWN y_line = Line(top_point, interim_point) y_line.set_color(RED) x_line = Line(bottom_point, interim_point) x_line.set_color(GREEN) return VGroup(x_line, y_line) def get_ladder_angle(self): if hasattr(self, "ladder"): c1 = self.ladder.get_corner(UP+RIGHT) c2 = self.ladder.get_corner(DOWN+LEFT) vect = c1-c2 return np.pi/2 - angle_of_vector(vect) else: return np.arctan(self.start_x/self.start_y) def get_ladder_length(self): return get_norm([self.start_x, self.start_y]) class LightweightLadderScene(RelatedRatesExample): CONFIG = { "skip_animations" : True } def construct(self): self.introduce_ladder() self.measure_ladder() self.add(self.numerical_x_and_y_labels) class LightweightCircleExample(SlopeOfCircleExample): CONFIG = { "skip_animations" : True, "plane_kwargs" : { "x_radius" : 5, "y_radius" : 5, "space_unit_to_x_unit" : SPACE_UNIT_TO_PLANE_UNIT, "space_unit_to_y_unit" : SPACE_UNIT_TO_PLANE_UNIT, }, } def construct(self): self.setup_plane() self.introduce_circle() self.talk_through_pythagorean_theorem() self.draw_example_slope() self.remove(self.circle_equation) self.remove(self.slope_word) self.example_point_coords_mob.scale( 1.5, about_point = self.example_point_coords_mob.get_corner(UP+RIGHT) ) self.plane.axis_labels[0].shift(3*LEFT) class CompareLadderAndCircle(PiCreatureScene, ThreeDScene): def construct(self): self.introduce_both_scenes() self.show_derivatives() self.comment_on_ladder_derivative() self.comment_on_circle_derivative() def introduce_both_scenes(self): ladder_scene = LightweightLadderScene() ladder_mobs = VGroup(*ladder_scene.get_top_level_mobjects()) circle_scene = LightweightCircleExample() circle_mobs = VGroup(*circle_scene.get_top_level_mobjects()) for mobs, vect in (ladder_mobs, LEFT), (circle_mobs, RIGHT): mobs.set_height(FRAME_Y_RADIUS-MED_LARGE_BUFF) mobs.next_to( self.pi_creature.get_corner(UP+vect), UP, buff = SMALL_BUFF, aligned_edge = -vect ) ladder_mobs.save_state() ladder_mobs.fade(1) ladder_mobs.rotate(np.pi/3, UP) self.play( self.pi_creature.change_mode, "raise_right_hand", self.pi_creature.look_at, ladder_mobs, ApplyMethod(ladder_mobs.restore, run_time = 2) ) self.play( self.pi_creature.change_mode, "raise_left_hand", self.pi_creature.look_at, circle_mobs, Write(circle_mobs, run_time = 2) ) self.wait(2) self.play( circle_mobs.to_edge, RIGHT, ladder_mobs.to_edge, LEFT, ) def show_derivatives(self): equation = OldTex( "x", "^2", "+", "y", "^2", "= 5^2" ) derivative = OldTex( "2", "x", "dx", "+", "2", "y", "dy", "=0" ) self.color_equations(equation, derivative) equation.to_edge(UP) equation.shift(MED_LARGE_BUFF*LEFT) derivative.next_to(equation, DOWN, buff = MED_LARGE_BUFF) self.play( Write(equation), self.pi_creature.change_mode, "plain", self.pi_creature.look_at, equation ) self.wait() self.play(*[ ReplacementTransform( equation[i].copy(), derivative[j], path_arc = np.pi/2 ) for i, j in enumerate([1, 0, 3, 5, 4, 7]) ]+[ Write(derivative[j]) for j in (2, 6) ]) self.play( self.pi_creature.change_mode, "pondering", self.pi_creature.look_at, derivative ) self.wait() self.equation = equation self.derivative = derivative def comment_on_ladder_derivative(self): equation = self.equation derivative = self.derivative time_equation = OldTex( "x(t)", "^2", "+", "y(t)", "^2", "= 5^2" ) time_derivative = OldTex( "2", "x(t)", "\\frac{dx}{dt}", "+", "2", "y(t)", "\\frac{dy}{dt}", "=0" ) self.color_equations(time_equation, time_derivative) time_equation.move_to(equation) time_derivative.move_to(derivative, UP) brace = Brace(time_derivative) brace_text = brace.get_text("A rate") equation.save_state() derivative.save_state() self.play(Transform(equation, time_equation)) self.wait() self.play(Transform(derivative, time_derivative)) self.wait() self.play(GrowFromCenter(brace)) self.play(Write(brace_text)) self.change_mode("hooray") self.wait(2) self.play( equation.restore, derivative.restore, FadeOut(brace), FadeOut(brace_text), self.pi_creature.change_mode, "confused" ) self.wait() def comment_on_circle_derivative(self): derivative = self.derivative dx = derivative.get_part_by_tex("dx") dy = derivative.get_part_by_tex("dy") for mob in dx, dy: brace = Brace(mob) brace.next_to(mob[0], DOWN, buff = SMALL_BUFF, aligned_edge = LEFT) text = brace.get_text("No $dt$", buff = SMALL_BUFF) text.set_color(YELLOW) self.play( GrowFromCenter(brace), Write(text) ) self.wait() self.play( self.pi_creature.change_mode, "pondering", self.pi_creature.look, DOWN+LEFT ) self.wait(2) ####### def create_pi_creature(self): self.pi_creature = Mortimer().to_edge(DOWN) return self.pi_creature def color_equations(self, equation, derivative): for mob in equation[0], derivative[1]: mob.set_color(GREEN) for mob in equation[3], derivative[5]: mob.set_color(RED) class TwoVariableFunctionAndDerivative(SlopeOfCircleExample): CONFIG = { "zoomed_canvas_corner" : DOWN+RIGHT, "zoomed_canvas_frame_shape" : (3, 4), } def construct(self): self.setup_plane() self.write_equation() self.show_example_point() self.shift_example_point((4, 4)) self.shift_example_point((3, 3)) self.shift_example_point(self.example_point) self.take_derivative_symbolically() self.show_dx_dy_step() self.plug_in_example_values() self.ask_about_equalling_zero() self.show_tangent_step() self.point_out_equalling_zero() self.show_tangent_line() def write_equation(self): equation = OldTex("x", "^2", "+", "y", "^2") equation.add_background_rectangle() brace = Brace(equation, UP, buff = SMALL_BUFF) s_expression = self.get_s_expression("x", "y") s_rect, s_of_xy = s_expression s, xy = s_of_xy s_expression.next_to(brace, UP, buff = SMALL_BUFF) group = VGroup(equation, s_expression, brace) group.shift(FRAME_WIDTH*LEFT/3) group.to_edge(UP, buff = MED_SMALL_BUFF) s.save_state() s.next_to(brace, UP) self.play(Write(equation)) self.play(GrowFromCenter(brace)) self.play(Write(s)) self.wait() self.play( FadeIn(s_rect), s.restore, GrowFromCenter(xy) ) self.wait() self.equation = equation self.s_expression = s_expression def show_example_point(self): point = self.plane.num_pair_to_point(self.example_point) dot = Dot(point, color = self.example_color) new_s_expression = self.get_s_expression(*self.example_point) new_s_expression.next_to(dot, UP+RIGHT, buff = 0) new_s_expression.set_color(self.example_color) equals_25 = OldTex("=%d"%int(get_norm(self.example_point)**2)) equals_25.set_color(YELLOW) equals_25.next_to(new_s_expression, RIGHT, align_using_submobjects = True) equals_25.add_background_rectangle() circle = Circle( radius = self.circle_radius*self.plane.space_unit_to_x_unit, color = self.circle_color, ) self.play( ReplacementTransform( self.s_expression.copy(), new_s_expression ), ShowCreation(dot) ) self.play(ShowCreation(circle), Animation(dot)) self.play(Write(equals_25)) self.wait() self.example_point_dot = dot self.example_point_label = VGroup( new_s_expression, equals_25 ) def shift_example_point(self, coords): point = self.plane.num_pair_to_point(coords) s_expression = self.get_s_expression(*coords) s_expression.next_to(point, UP+RIGHT, buff = SMALL_BUFF) s_expression.set_color(self.example_color) result = coords[0]**2 + coords[1]**2 rhs = OldTex("=%d"%int(result)) rhs.add_background_rectangle() rhs.set_color(YELLOW) rhs.next_to(s_expression, RIGHT, align_using_submobjects = True) point_label = VGroup(s_expression, rhs) self.play( self.example_point_dot.move_to, point, Transform(self.example_point_label, point_label) ) self.wait(2) def take_derivative_symbolically(self): equation = self.equation derivative = OldTex( "dS =", "2", "x", "\\,dx", "+", "2", "y", "\\,dy", ) derivative[2].set_color(GREEN) derivative[6].set_color(RED) derivative.next_to(equation, DOWN, buff = MED_LARGE_BUFF) derivative.add_background_rectangle() derivative.to_edge(LEFT) self.play(*[ FadeIn(derivative[0]) ]+[ ReplacementTransform( self.s_expression[1][0].copy(), derivative[1][0], ) ]+[ Write(derivative[1][j]) for j in (3, 7) ]) self.play(*[ ReplacementTransform( equation[1][i].copy(), derivative[1][j], path_arc = np.pi/2, run_time = 2, rate_func = squish_rate_func(smooth, (j-1)/12., (j+6)/12.) ) for i, j in enumerate([2, 1, 4, 6, 5]) ]) self.wait(2) self.derivative = derivative def show_dx_dy_step(self): dot = self.example_point_dot s_label = self.example_point_label rhs = s_label[-1] s_label.remove(rhs) point = dot.get_center() vect = 2*LEFT + DOWN new_point = point + vect*0.6/self.zoom_factor interim_point = new_point[0]*RIGHT + point[1]*UP dx_line = Line(point, interim_point, color = GREEN) dy_line = Line(interim_point, new_point, color = RED) for line, tex, vect in (dx_line, "dx", UP), (dy_line, "dy", LEFT): label = OldTex(tex) label.set_color(line.get_color()) label.next_to(line, vect, buff = SMALL_BUFF) label.add_background_rectangle() label.scale( 1./self.zoom_factor, about_point = line.get_center() ) line.label = label self.activate_zooming() lil_rect = self.little_rectangle lil_rect.move_to(dot) lil_rect.shift(0.05*lil_rect.get_width()*LEFT) lil_rect.shift(0.2*lil_rect.get_height()*DOWN) lil_rect.save_state() lil_rect.set_height(FRAME_Y_RADIUS - MED_LARGE_BUFF) lil_rect.move_to(s_label, UP) lil_rect.shift(MED_SMALL_BUFF*UP) self.wait() self.play( FadeOut(rhs), dot.scale, 1./self.zoom_factor, point, s_label.scale, 1./self.zoom_factor, point, lil_rect.restore, run_time = 2 ) self.wait() for line in dx_line, dy_line: self.play(ShowCreation(line)) self.play(Write(line.label, run_time = 1)) self.wait() new_dot = Dot(color = dot.get_color()) new_s_label = self.get_s_expression( "%d + dx"%int(self.example_point[0]), "%d + dy"%int(self.example_point[1]), ) new_dot.set_height(dot.get_height()) new_dot.move_to(new_point) new_s_label.set_height(s_label.get_height()) new_s_label.scale(0.8) new_s_label.next_to( new_dot, DOWN, buff = SMALL_BUFF/self.zoom_factor, aligned_edge = LEFT ) new_s_label.shift(MED_LARGE_BUFF*LEFT/self.zoom_factor) new_s_label.set_color(self.example_color) VGroup(*new_s_label[1][1][3:5]).set_color(GREEN) VGroup(*new_s_label[1][1][-3:-1]).set_color(RED) self.play(ShowCreation(new_dot)) self.play(Write(new_s_label)) self.wait() ds = self.derivative[1][0] self.play(FocusOn(ds)) self.play(Indicate(ds)) self.wait() self.tiny_step_group = VGroup( dx_line, dx_line.label, dy_line, dy_line.label, s_label, new_s_label, new_dot ) def plug_in_example_values(self): deriv_example = OldTex( "dS =", "2", "(3)", "\\,(-0.02)", "+", "2", "(4)", "\\,(-0.01)", ) deriv_example[2].set_color(GREEN) deriv_example[6].set_color(RED) deriv_example.add_background_rectangle() deriv_example.scale(0.8) deriv_example.next_to(ORIGIN, UP, buff = SMALL_BUFF) deriv_example.to_edge(LEFT, buff = MED_SMALL_BUFF) def add_example_parts(*indices): self.play(*[ ReplacementTransform( self.derivative[1][i].copy(), deriv_example[1][i], run_time = 2 ) for i in indices ]) self.play(FadeIn(deriv_example[0])) add_example_parts(0) self.wait() add_example_parts(1, 2, 4, 5, 6) self.wait(2) add_example_parts(3) self.wait() add_example_parts(7) self.wait() #React randy = Randolph() randy.next_to(ORIGIN, LEFT) randy.to_edge(DOWN) self.play(FadeIn(randy)) self.play( randy.change_mode, "pondering", randy.look_at, deriv_example.get_left() ) self.play(Blink(randy)) self.play(randy.look_at, deriv_example.get_right()) self.wait() self.play( Indicate(self.equation), randy.look_at, self.equation ) self.play(Blink(randy)) self.play( randy.change_mode, "thinking", randy.look_at, self.big_rectangle ) self.wait(2) self.play(PiCreatureSays( randy, "Approximately", target_mode = "sassy" )) self.wait() self.play(RemovePiCreatureBubble(randy)) self.play(randy.look_at, deriv_example) self.play(FadeOut(deriv_example)) self.wait() self.randy = randy def ask_about_equalling_zero(self): dot = self.example_point_dot randy = self.randy equals_zero = OldTex("=0") equals_zero.set_color(YELLOW) equals_zero.add_background_rectangle() equals_zero.next_to(self.derivative, RIGHT) self.play( Write(equals_zero), randy.change_mode, "confused", randy.look_at, equals_zero ) self.wait() self.play(Blink(randy)) self.play( randy.change_mode, "plain", randy.look_at, self.big_rectangle, ) self.play( FadeOut(self.tiny_step_group), self.little_rectangle.move_to, dot, ) self.wait() self.equals_zero = equals_zero def show_tangent_step(self): dot = self.example_point_dot randy = self.randy point = dot.get_center() step_vect = rotate_vector(point, np.pi/2)/get_norm(point) new_point = point + step_vect/self.zoom_factor interim_point = point[0]*RIGHT + new_point[1]*UP new_dot = dot.copy().move_to(new_point) step_line = Line(point, new_point, color = WHITE) dy_line = Line(point, interim_point, color = RED) dx_line = Line(interim_point, new_point, color = GREEN) s_label = OldTex("S = 25") s_label.set_color(self.example_color) s_label.next_to( point, DOWN, buff = MED_LARGE_BUFF, aligned_edge = RIGHT ) s_label.scale(1./self.zoom_factor, about_point = point) arrow1, arrow2 = [ Arrow( s_label.get_top(), mob, preserve_tip_size_when_scaling = False, color = self.example_color, buff = SMALL_BUFF/self.zoom_factor, tip_length = 0.15/self.zoom_factor ) for mob in (dot, new_dot) ] for line, tex, vect in (dy_line, "dy", RIGHT), (dx_line, "dx", UP): label = OldTex(tex) label.set_color(line.get_color()) label.next_to(line, vect) label.scale( 1./self.zoom_factor, about_point = line.get_center() ) line.label = label self.play(ShowCreation(line)) self.play(Write(label)) self.play(ShowCreation(new_dot)) self.play( randy.change_mode, "pondering", randy.look_at, self.big_rectangle ) self.play(Blink(randy)) self.wait() self.play(Write(s_label)) self.play(ShowCreation(arrow1)) self.wait() self.play(ReplacementTransform(arrow1.copy(), arrow2)) self.wait(2) def point_out_equalling_zero(self): derivative = self.derivative equals_zero = self.equals_zero randy = self.randy self.play( FocusOn(equals_zero), self.randy.look_at, equals_zero ) self.play(Indicate(equals_zero, color = RED)) self.play(Blink(randy)) self.play(randy.change_mode, "happy") self.play(randy.look_at, self.big_rectangle) self.wait(2) def show_tangent_line(self): randy = self.randy point = self.example_point_dot.get_center() line = Line(ORIGIN, 5*RIGHT) line.rotate(angle_of_vector(point)+np.pi/2) line.move_to(point) self.play(PiCreatureSays( randy, "Approximately...", )) self.play(Blink(randy)) self.play(RemovePiCreatureBubble(randy)) self.play( GrowFromCenter(line), randy.look_at, line ) self.wait(2) self.play( self.little_rectangle.scale, self.zoom_factor/2, run_time = 4, rate_func = there_and_back ) self.wait(2) ############ def get_s_expression(self, x, y): result = OldTex("S", "(%s, %s)"%(str(x), str(y))) result.add_background_rectangle() return result class TryOtherExamples(TeacherStudentsScene): def construct(self): formula = OldTex("\\sin(x)y^2 = x") formula.next_to( self.get_teacher().get_corner(UP+LEFT), UP, buff = MED_LARGE_BUFF, aligned_edge = RIGHT ) self.teacher_says( """Nothing special about $x^2 + y^2 = 25$""" ) self.wait() self.play(RemovePiCreatureBubble( self.get_teacher(), target_mode = "raise_right_hand" )) self.play(Write(formula, run_time = 1)) self.play_student_changes(*["pondering"]*3) self.wait(2) self.play(formula.to_corner, UP+LEFT) self.wait() class AlternateExample(ZoomedScene): CONFIG = { "example_color" : MAROON_B, "zoom_factor" : 10, "zoomed_canvas_corner" : DOWN+RIGHT, "zoomed_canvas_frame_shape" : (3, 4), } def construct(self): self.add_plane() self.draw_graph() self.emphasize_meaning_of_points() self.zoom_in() self.show_tiny_step() self.ask_about_derivatives() self.differentiate_lhs() self.differentiate_rhs() self.put_step_on_curve() self.emphasize_equality() self.manipulate_to_find_dy_dx() def add_plane(self): formula = OldTex("\\sin(x)y^2 = x") formula.to_corner(UP+LEFT) formula.add_background_rectangle() plane = NumberPlane( space_unit_to_x_unit = 0.75, x_radius = FRAME_WIDTH, ) plane.fade() plane.add_coordinates() self.add(formula) self.play(Write(plane, run_time = 2), Animation(formula)) self.wait() self.plane = plane self.formula = formula self.lhs = VGroup(*formula[1][:8]) self.rhs = VGroup(formula[1][-1]) def draw_graph(self): graphs = VGroup(*[ FunctionGraph( lambda x : u*np.sqrt(x/np.sin(x)), num_steps = 200, x_min = x_min+0.1, x_max = x_max-0.1, ) for u in [-1, 1] for x_min, x_max in [ (-4*np.pi, -2*np.pi), (-np.pi, np.pi), (2*np.pi, 4*np.pi), ] ]) graphs.stretch(self.plane.space_unit_to_x_unit, dim = 0) self.play( ShowCreation( graphs, run_time = 3, lag_ratio = 0 ), Animation(self.formula) ) self.wait() self.graphs = graphs def emphasize_meaning_of_points(self): graph = self.graphs[4] dot = Dot(color = self.example_color) label = OldTex("(x, y)") label.add_background_rectangle() label.set_color(self.example_color) def update_dot(dot, alpha): prop = interpolate(0.9, 0.1, alpha) point = graph.point_from_proportion(prop) dot.move_to(point) return dot def update_label(label): point = dot.get_center() vect = np.array(point)/get_norm(point) vect[0] *= 2 vect[1] *= -1 label.move_to( point + vect*0.4*label.get_width() ) update_dot(dot, 0) update_label(label) self.play( ShowCreation(dot), Write(label), run_time = 1 ) self.play( UpdateFromAlphaFunc(dot, update_dot), UpdateFromFunc(label, update_label), run_time = 3, ) self.wait() self.play(*[ ApplyMethod( label[1][i].copy().move_to, self.formula[1][j], run_time = 3, rate_func = squish_rate_func(smooth, count/6., count/6.+2./3) ) for count, (i, j) in enumerate([(1, 4), (1, 9), (3, 6)]) ]) movers = self.get_mobjects_from_last_animation() self.wait() self.play( UpdateFromAlphaFunc(dot, update_dot), UpdateFromFunc(label, update_label), run_time = 3, rate_func = lambda t : 1-smooth(t) ) self.wait() self.play(*[ ApplyMethod(mover.set_fill, None, 0, remover = True) for mover in movers ]) self.dot = dot self.label = label def zoom_in(self): dot = self.dot label = self.label self.activate_zooming() self.little_rectangle.scale(self.zoom_factor) self.little_rectangle.move_to(dot) self.wait() for mob in VGroup(dot, label), self.little_rectangle: self.play( ApplyMethod( mob.scale, 1./self.zoom_factor, method_kwargs = {"about_point" : dot.get_center()}, run_time = 1, ) ) self.wait() def show_tiny_step(self): dot = self.dot label = self.label point = dot.get_center() step_vect = 1.2*(UP+LEFT)/float(self.zoom_factor) new_point = point + step_vect interim_point = new_point[0]*RIGHT + point[1]*UP dx_line = Line(point, interim_point, color = GREEN) dy_line = Line(interim_point, new_point, color = RED) for line, tex, vect in (dx_line, "dx", DOWN), (dy_line, "dy", LEFT): label = OldTex(tex) label.next_to(line, vect, buff = SMALL_BUFF) label.set_color(line.get_color()) label.scale(1./self.zoom_factor, about_point = line.get_center()) label.add_background_rectangle() line.label = label arrow = Arrow( point, new_point, buff = 0, tip_length = 0.15/self.zoom_factor, color = WHITE ) self.play(ShowCreation(arrow)) for line in dx_line, dy_line: self.play(ShowCreation(line), Animation(arrow)) self.play(Write(line.label, run_time = 1)) self.wait() self.step_group = VGroup( arrow, dx_line, dx_line.label, dy_line, dy_line.label ) def ask_about_derivatives(self): formula = self.formula lhs, rhs = self.lhs, self.rhs word = OldTexText("Change?") word.add_background_rectangle() word.next_to( Line(lhs.get_center(), rhs.get_center()), DOWN, buff = 1.5*LARGE_BUFF ) arrows = VGroup(*[ Arrow(word, part) for part in (lhs, rhs) ]) self.play(FocusOn(formula)) self.play( Write(word), ShowCreation(arrows) ) self.wait() self.play(*list(map(FadeOut, [word, arrows]))) def differentiate_lhs(self): formula = self.formula lhs = self.lhs brace = Brace(lhs, DOWN, buff = SMALL_BUFF) sine_x = VGroup(*lhs[:6]) sine_rect = BackgroundRectangle(sine_x) y_squared = VGroup(*lhs[6:]) mnemonic = OldTexText( "``", "Left", " d-Right", " + ", "Right", " d-Left" "''", arg_separator = "" ) mnemonic.set_color_by_tex("d-Right", RED) mnemonic.set_color_by_tex("d-Left", GREEN) mnemonic.add_background_rectangle() mnemonic.set_width(FRAME_X_RADIUS-2*MED_LARGE_BUFF) mnemonic.next_to(ORIGIN, UP) mnemonic.to_edge(LEFT) derivative = OldTex( "\\sin(x)", "(2y\\,dy)", "+", "y^2", "(\\cos(x)\\,dx)", ) derivative.set_color_by_tex("dx", GREEN) derivative.set_color_by_tex("dy", RED) derivative.set_width(FRAME_X_RADIUS - 2*MED_LARGE_BUFF) derivative.next_to( brace, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) derivative_rects = [ BackgroundRectangle(VGroup(*subset)) for subset in (derivative[:2], derivative[2:]) ] derivative_rects[1].stretch(1.05, dim = 0) self.play(GrowFromCenter(brace)) self.play(Write(mnemonic)) self.wait() pairs = [ (sine_rect, derivative_rects[0]), (sine_x, derivative[0]), (y_squared, derivative[1]), (sine_rect, derivative_rects[1]), (y_squared, derivative[2]), (y_squared, derivative[3]), (sine_x, derivative[4]), ] for pairs_subset in pairs[:3], pairs[3:]: self.play(*[ ReplacementTransform(m1.copy(), m2, path_arc = np.pi/2) for m1, m2 in pairs_subset ]) self.wait() self.play(Indicate(pairs_subset[-1][1])) self.wait() self.wait() self.play(FadeOut(mnemonic)) self.lhs_derivative = VGroup(*derivative_rects+[derivative]) self.lhs_brace = brace def differentiate_rhs(self): lhs_derivative = self.lhs_derivative lhs_brace = self.lhs_brace rhs = self.rhs equals, dx = equals_dx = OldTex("=", "dx") equals_dx.scale(0.9) equals_dx.set_color_by_tex("dx", GREEN) equals_dx.add_background_rectangle() equals_dx.next_to(lhs_derivative, RIGHT, buff = SMALL_BUFF) circle = Circle(color = GREEN) circle.replace(self.rhs) circle.scale(1.7) arrow = Arrow(rhs.get_right(), dx.get_top()) arrow.set_color(GREEN) self.play(ReplacementTransform(lhs_brace, circle)) self.play(ShowCreation(arrow)) self.play(Write(equals_dx)) self.wait() self.play(*list(map(FadeOut, [circle, arrow]))) self.equals_dx = equals_dx def put_step_on_curve(self): dot = self.dot point = dot.get_center() graph = self.graphs[4] arrow, dx_line, dx_line.label, dy_line, dy_line.label = self.step_group #Find graph point at right x_val arrow_end = arrow.get_end() graph_points = [ graph.point_from_proportion(alpha) for alpha in np.linspace(0, 1, 1000) ] distances = np.apply_along_axis( lambda p : np.abs(p[0] - arrow_end[0]), 1, graph_points ) index = np.argmin(distances) new_end_point = graph_points[index] lil_rect = self.little_rectangle self.play( arrow.put_start_and_end_on, point, new_end_point, dy_line.put_start_and_end_on, dy_line.get_start(), new_end_point, MaintainPositionRelativeTo(dy_line.label, dy_line), lil_rect.shift, lil_rect.get_height()*DOWN/3, run_time = 2 ) self.wait(2) def emphasize_equality(self): self.play(FocusOn(self.lhs)) self.wait() for mob in self.lhs, self.rhs: self.play(Indicate(mob)) self.wait() def manipulate_to_find_dy_dx(self): full_derivative = VGroup( self.lhs_derivative, self.equals_dx ) brace = Brace(full_derivative, DOWN, buff = SMALL_BUFF) words = brace.get_text( "Commonly, solve for", "$dy/dx$", buff = SMALL_BUFF ) VGroup(*words[1][:2]).set_color(RED) VGroup(*words[1][3:]).set_color(GREEN) words.add_background_rectangle() self.play(GrowFromCenter(brace)) self.play(Write(words)) self.wait() randy = Randolph() randy.to_corner(DOWN+LEFT) randy.look_at(full_derivative) self.play(FadeIn(randy)) self.play(randy.change_mode, "confused") self.play(Blink(randy)) self.wait(2) self.play(randy.change_mode, "pondering") self.play(Blink(randy)) self.wait() class AskAboutNaturalLog(TeacherStudentsScene): def construct(self): exp_deriv = OldTex("\\frac{d(e^x)}{dx} = e^x") for i in 2, 3, 9, 10: exp_deriv[i].set_color(BLUE) log_deriv = OldTex("\\frac{d(\\ln(x))}{dx} = ???") VGroup(*log_deriv[2:2+5]).set_color(GREEN) for deriv in exp_deriv, log_deriv: deriv.next_to(self.get_teacher().get_corner(UP+LEFT), UP) self.teacher_says( """We can find new derivatives""", target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.play(RemovePiCreatureBubble( self.get_teacher(), target_mode = "raise_right_hand" )) self.play(Write(exp_deriv)) self.wait() self.play( Write(log_deriv), exp_deriv.next_to, log_deriv, UP, LARGE_BUFF, *[ ApplyMethod(pi.change_mode, "confused") for pi in self.get_pi_creatures() ] ) self.wait(3) class DerivativeOfNaturalLog(ZoomedScene): CONFIG = { "zoom_factor" : 10, "zoomed_canvas_corner" : DOWN+RIGHT, "example_color" : MAROON_B, } def construct(self): should_skip_animations = self.skip_animations self.skip_animations = True self.add_plane() self.draw_graph() self.describe_as_implicit_curve() self.slope_gives_derivative() self.rearrange_equation() self.take_derivative() self.show_tiny_nudge() self.note_derivatives() self.solve_for_dy_dx() self.skip_animations = should_skip_animations self.show_slope_above_x() def add_plane(self): plane = NumberPlane() plane.fade() plane.add_coordinates() self.add(plane) self.plane = plane def draw_graph(self): graph = FunctionGraph( np.log, x_min = 0.01, x_max = FRAME_X_RADIUS, num_steps = 100 ) formula = OldTex("y = \\ln(x)") formula.next_to(ORIGIN, LEFT, buff = MED_LARGE_BUFF) formula.to_edge(UP) formula.add_background_rectangle() self.add(formula) self.play(ShowCreation(graph)) self.wait() self.formula = formula self.graph = graph def describe_as_implicit_curve(self): formula = self.formula #y = ln(x) graph = self.graph dot = Dot(color = self.example_color) label = OldTex("(x, y)") label.add_background_rectangle() label.set_color(self.example_color) def update_dot(dot, alpha): prop = interpolate(0.1, 0.7, alpha) point = graph.point_from_proportion(prop) dot.move_to(point) return dot def update_label(label): point = dot.get_center() vect = point - FRAME_Y_RADIUS*(DOWN+RIGHT) vect = vect/get_norm(vect) label.move_to( point + vect*0.5*label.get_width() ) update_dot(dot, 0) update_label(label) self.play(*list(map(FadeIn, [dot, label]))) self.play( UpdateFromAlphaFunc(dot, update_dot), UpdateFromFunc(label, update_label), run_time = 3, ) self.wait() xy_start = VGroup(label[1][1], label[1][3]).copy() xy_end = VGroup(formula[1][5], formula[1][0]).copy() xy_end.set_color(self.example_color) self.play(Transform( xy_start, xy_end, run_time = 2, )) self.wait() self.play( UpdateFromAlphaFunc(dot, update_dot), UpdateFromFunc(label, update_label), run_time = 3, rate_func = lambda t : 1-0.6*smooth(t), ) self.play(*list(map(FadeOut, [xy_start, label]))) self.dot = dot def slope_gives_derivative(self): dot = self.dot point = dot.get_center() line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) slope = 1./point[0] line.rotate(np.arctan(slope)) line.move_to(point) new_point = line.point_from_proportion(0.6) interim_point = point[0]*RIGHT + new_point[1]*UP dy_line = Line(point, interim_point, color = RED) dx_line = Line(interim_point, new_point, color = GREEN) equation = OldTex( "\\text{Slope} = ", "\\frac{dy}{dx} = ", "\\frac{d(\\ln(x))}{dx}", ) VGroup(*equation[1][:2]).set_color(RED) VGroup(*equation[2][:8]).set_color(RED) VGroup(*equation[1][3:5]).set_color(GREEN) VGroup(*equation[2][-2:]).set_color(GREEN) for part in equation: rect = BackgroundRectangle(part) rect.stretch_in_place(1.2, 0) part.add_to_back(rect) equation.scale(0.8) equation.next_to(ORIGIN, RIGHT) equation.to_edge(UP, buff = MED_SMALL_BUFF) self.play( GrowFromCenter(line), Animation(dot) ) self.play(ShowCreation(VGroup(dy_line, dx_line))) for part in equation: self.play(Write(part, run_time = 2)) self.wait() self.dx_line, self.dy_line = dx_line, dy_line self.slope_equation = equation self.tangent_line = line def rearrange_equation(self): formula = self.formula y, eq = formula[1][:2] ln = VGroup(*formula[1][2:4]) x = formula[1][5] new_formula = OldTex("e", "^y", "=", "x") e, new_y, new_eq, new_x = new_formula new_formula.next_to( formula, DOWN, buff = MED_LARGE_BUFF, ) rect = BackgroundRectangle(new_formula) y = new_y.copy().replace(y) self.play(Indicate(formula, scale_factor = 1)) self.play(ReplacementTransform(ln.copy(), e)) self.play(ReplacementTransform(y, new_y)) self.play(ReplacementTransform(eq.copy(), new_eq)) self.play( FadeIn(rect), Animation(VGroup(e, new_y, new_eq)), ReplacementTransform(x.copy(), new_x) ) self.wait(2) for mob in e, new_y, new_x: self.play(Indicate(mob)) self.wait() self.new_formula = new_formula def take_derivative(self): new_formula = self.new_formula e, y, eq, x = new_formula derivative = OldTex("e", "^y", "\\,dy", "=", "dx") new_e, new_y, dy, new_eq, dx = derivative derivative.next_to(new_formula, DOWN, MED_LARGE_BUFF) derivative.add_background_rectangle() dx.set_color(GREEN) dy.set_color(RED) pairs = [ (VGroup(e, y), VGroup(new_e, new_y)), (new_y, dy), (eq, new_eq), (x, dx) ] for start, target in pairs: self.play( ReplacementTransform(start.copy(), target) ) self.play(FadeIn(derivative[0]), Animation(derivative[1])) self.remove(derivative, pairs[0][1]) self.add(derivative) self.wait() self.derivative = derivative def show_tiny_nudge(self): dot = self.dot point = dot.get_center() dx_line = self.dx_line dy_line = self.dy_line group = VGroup(dot, dx_line, dy_line) self.play(group.scale, 1./self.zoom_factor, point) for line, tex, vect in (dx_line, "dx", UP), (dy_line, "dy", LEFT): label = OldTex(tex) label.add_background_rectangle() label.next_to(line, vect, buff = SMALL_BUFF) label.set_color(line.get_color()) label.scale( 1./self.zoom_factor, about_point = line.get_center() ) line.label = label self.activate_zooming() lil_rect = self.little_rectangle lil_rect.move_to(group) lil_rect.scale(self.zoom_factor) self.play(lil_rect.scale, 1./self.zoom_factor) self.play(Write(dx_line.label)) self.play(Write(dy_line.label)) self.wait() def note_derivatives(self): e, y, dy, eq, dx = self.derivative[1] self.play(FocusOn(e)) self.play(Indicate(VGroup(e, y, dy))) self.wait() self.play(Indicate(dx)) self.wait() def solve_for_dy_dx(self): e, y, dy, eq, dx = self.derivative[1] ey_group = VGroup(e, y) original_rect = self.derivative[0] rearranged = OldTex( "{dy \\over ", " dx}", "=", "{1 \\over ", "e", "^y}" ) new_dy, new_dx, new_eq, one_over, new_e, new_y = rearranged new_ey_group = VGroup(new_e, new_y) new_dx.set_color(GREEN) new_dy.set_color(RED) rearranged.shift(eq.get_center() - new_eq.get_center()) rearranged.shift(MED_SMALL_BUFF*DOWN) new_rect = BackgroundRectangle(rearranged) self.play(*[ ReplacementTransform( m1, m2, run_time = 2, path_arc = -np.pi/2, ) for m1, m2 in [ (original_rect, new_rect), (dx, new_dx), (dy, new_dy), (eq, new_eq), (ey_group, new_ey_group), (e.copy(), one_over) ] ]) self.wait() #Change denominator e, y, eq, x = self.new_formula ey_group = VGroup(e, y).copy() ey_group.set_color(YELLOW) x_copy = x.copy() self.play(new_ey_group.set_color, YELLOW) self.play(Transform(new_ey_group, ey_group)) self.play( new_ey_group.set_color, WHITE, x_copy.set_color, YELLOW ) self.play(x_copy.next_to, one_over, DOWN, MED_SMALL_BUFF) self.wait(2) equals_one_over_x = VGroup( new_eq, one_over, x_copy ).copy() rect = BackgroundRectangle(equals_one_over_x) rect.stretch_in_place(1.1, dim = 0) equals_one_over_x.add_to_back(rect) self.play( equals_one_over_x.next_to, self.slope_equation, RIGHT, 0, run_time = 2 ) self.wait() def show_slope_above_x(self): line = self.tangent_line start_x = line.get_center()[0] target_x = 0.2 graph = FunctionGraph( lambda x : 1./x, x_min = 0.1, x_max = FRAME_X_RADIUS, num_steps = 100, color = PINK, ) def update_line(line, alpha): x = interpolate(start_x, target_x, alpha) point = x*RIGHT + np.log(x)*UP angle = np.arctan(1./x) line.rotate(angle - line.get_angle()) line.move_to(point) self.play(UpdateFromAlphaFunc( line, update_line, rate_func = there_and_back, run_time = 6 )) self.wait() self.play(ShowCreation(graph, run_time = 3)) self.wait() self.play(UpdateFromAlphaFunc( line, update_line, rate_func = there_and_back, run_time = 6 )) self.wait() class FinalWords(TeacherStudentsScene): def construct(self): words = OldTexText( "This is a peek into \\\\", "Multivariable", "calculus" ) mvc = VGroup(*words[1:]) words.set_color_by_tex("Multivariable", YELLOW) formula = OldTex("f(x, y) = \\sin(x)y^2") formula.next_to(self.get_teacher().get_corner(UP+LEFT), UP) self.teacher_says(words) self.play_student_changes("erm", "hooray", "sassy") self.play( FadeOut(self.teacher.bubble), FadeOut(VGroup(*words[:1])), mvc.to_corner, UP+LEFT, self.teacher.change_mode, "raise_right_hand", self.teacher.look_at, formula, Write(formula, run_time = 2), ) self.play_student_changes("pondering", "confused", "thinking") self.wait(3) ##Show series series = VideoSeries() series.to_edge(UP) video = series[5] lim = OldTex("\\lim_{h \\to 0} \\frac{f(x+h)-f(x)}{h}") self.play( FadeOut(mvc), FadeOut(formula), self.teacher.change_mode, "plain", FadeIn( series, run_time = 2, lag_ratio = 0.5, ), ) self.play( video.set_color, YELLOW, video.shift, video.get_height()*DOWN/2 ) lim.next_to(video, DOWN) self.play( Write(lim), *it.chain(*[ [pi.change_mode, "pondering", pi.look_at, lim] for pi in self.get_pi_creatures() ]) ) self.wait(3) class Chapter6PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Meshal Alshammari", "CrypticSwarm ", "Nathan Pellegrin", "Karan Bhargava", "Justin Helps", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Justin Helps", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Daan Smedinga", "Jonathan Eppele", "Nils Schneider", "Albert Nguyen", "Mustafa Mahdi", "Mathew Bramson", "Guido Gambardella", "Jerry Ling", "Mark Govea", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } class Thumbnail(AlternateExample): def construct(self): title = VGroup(*list(map(TexText, [ "Implicit", "Differentiation" ]))) title.arrange(DOWN) title.scale(3) title.next_to(ORIGIN, UP) for word in title: word.add_background_rectangle() self.add_plane() self.draw_graph() self.graphs.set_stroke(width = 8) self.remove(self.formula) self.add(title)
videos_3b1b/_2017/eoc/chapter3.py
from manim_imports_ext import * from _2017.eoc.chapter2 import DISTANCE_COLOR, TIME_COLOR, \ VELOCITY_COLOR, Car, MoveCar OUTPUT_COLOR = DISTANCE_COLOR INPUT_COLOR = TIME_COLOR DERIVATIVE_COLOR = VELOCITY_COLOR class Chapter3OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "You know, for a mathematician, he did not have \\\\ enough", "imagination.", "But he has become a poet and \\\\ now he is fine.", ], "highlighted_quote_terms" : { "imagination." : BLUE, }, "author" : "David Hilbert" } class PoseAbstractDerivative(TeacherStudentsScene): def construct(self): self.teacher_says(""" Given $f(x) = x^2 \\sin(x)$, \\\\ compute $\\frac{df}{dx}(x)$ """) content_copy = self.teacher.bubble.content.copy() self.play_student_changes("sad", "confused", "erm") self.wait() self.student_says( "Why?", target_mode = "sassy", added_anims = [ content_copy.scale, 0.8, content_copy.to_corner, UP+LEFT ] ) self.play(self.teacher.change_mode, "pondering") self.wait(2) class ContrastAbstractAndConcrete(Scene): def construct(self): v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) l_title = OldTexText("Abstract functions") l_title.shift(FRAME_X_RADIUS*LEFT/2) l_title.to_edge(UP) r_title = OldTexText("Applications") r_title.shift(FRAME_X_RADIUS*RIGHT/2) r_title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.shift((r_title.get_bottom()[1]-MED_SMALL_BUFF)*UP) functions = VGroup(*list(map(Tex, [ "f(x) = 2x^2 - x^3", "f(x) = \\sin(x)", "f(x) = e^x", "\\v_dots" ]))) functions.arrange( DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ) functions.shift(FRAME_X_RADIUS*LEFT/2) functions[-1].shift(MED_LARGE_BUFF*RIGHT) self.add(l_title, r_title) self.play(*list(map(ShowCreation, [h_line, v_line]))) self.play(Write(functions)) self.wait() anims = [ method(func_mob) for func_mob, method in zip(functions, [ self.get_car_anim, self.get_spring_anim, self.get_population_anim, ]) ] for anim in anims: self.play(FadeIn(anim.mobject)) self.play(anim) self.play(FadeOut(anim.mobject)) def get_car_anim(self, alignement_mob): car = Car() point = 2*RIGHT + alignement_mob.get_bottom()[1]*UP target_point = point + 5*RIGHT car.move_to(point) return MoveCar( car, target_point, run_time = 5, ) def get_spring_anim(self, alignement_mob): compact_spring, extended_spring = [ ParametricCurve( lambda t : (t/denom)*RIGHT+np.sin(t)*UP+np.cos(t)*OUT, t_max = 12*np.pi, ) for denom in (12.0, 4.0) ] for spring in compact_spring, extended_spring: spring.scale(0.5) spring.rotate(np.pi/6, UP) spring.set_color(GREY) spring.next_to(ORIGIN, RIGHT) spring.shift( alignement_mob.get_center()[1]*UP + SMALL_BUFF*RIGHT \ -spring.get_points()[0] ) weight = Square( side_length = 0.5, stroke_width = 0, fill_color = GREY_B, fill_opacity = 1, ) weight.move_to(spring.get_points()[-1]) spring.add(weight) return Transform( compact_spring, extended_spring, rate_func = lambda t : 1+np.sin(6*np.pi*t), run_time = 5 ) def get_population_anim(self, alignement_mob): colors = color_gradient([BLUE_B, BLUE_E], 12) pis = VGroup(*[ Randolph( mode = "happy", color = random.choice(colors) ).shift( 4*x*RIGHT + 4*y*UP + \ 2*random.random()*RIGHT + \ 2*random.random()*UP ) for x in range(20) for y in range(10) ]) pis.set_height(3) pis.center() pis.to_edge(DOWN, buff = SMALL_BUFF) pis.shift(FRAME_X_RADIUS*RIGHT/2.) anims = [] for index, pi in enumerate(pis): if index < 2: anims.append(FadeIn(pi)) continue mom_index, dad_index = random.choice( list(it.combinations(list(range(index)), 2)) ) pi.parents = VGroup(pis[mom_index], pis[dad_index]).copy() pi.parents.set_fill(opacity = 0) exp = 1 while 2**exp < len(pis): low_index = 2**exp high_index = min(2**(exp+1), len(pis)) these_pis = pis[low_index:high_index] anims.append(Transform( VGroup(*[pi.parents for pi in these_pis]), VGroup(*[VGroup(pi, pi.copy()) for pi in these_pis]), lag_ratio = 0.5, run_time = 2, )) exp += 1 return Succession(*anims, rate_func=linear) class ApplicationNames(Scene): def construct(self): for name in "Velocity", "Oscillation", "Population growth": mob = OldTexText(name) mob.scale(2) self.play(Write(mob)) self.wait(2) self.play(FadeOut(mob)) class ListOfRules(PiCreatureScene): CONFIG = { "use_morty" : False, } def construct(self): rules = VGroup(*list(map(Tex, [ "\\frac{d}{dx} x^n = nx^{n-1}", "\\frac{d}{dx} \\sin(x) = \\cos(x)", "\\frac{d}{dx} \\cos(x) = -\\sin(x)", "\\frac{d}{dx} a^x = \\ln(a) a^x", "\\vdots" ]))) rules.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT, ) rules[-1].shift(MED_LARGE_BUFF*RIGHT) rules.set_height(FRAME_HEIGHT-1) rules.next_to(self.pi_creature, RIGHT) rules.to_edge(DOWN) self.play( Write(rules), self.pi_creature.change_mode, "pleading", ) self.change_mode("tired") self.wait() class DerivativeOfXSquaredAsGraph(GraphScene, ZoomedScene, PiCreatureScene): CONFIG = { "start_x" : 2, "big_x" : 3, "dx" : 0.1, "x_min" : -9, "x_labeled_nums" : list(range(-8, 0, 2)) + list(range(2, 10, 2)), "y_labeled_nums" : list(range(2, 12, 2)), "little_rect_nudge" : 0.5*(1.5*UP+RIGHT), "graph_origin" : 2.5*DOWN + LEFT, "zoomed_canvas_corner" : UP+LEFT, "zoomed_canvas_frame_shape" : (4, 4), } def construct(self): self.draw_graph() self.ask_about_df_dx() self.show_differing_slopes() self.mention_alternate_view() def draw_graph(self): self.setup_axes(animate = True) graph = self.get_graph(lambda x : x**2) label = self.get_graph_label( graph, "f(x) = x^2", ) self.play(ShowCreation(graph)) self.play(Write(label)) self.wait() self.graph = graph def ask_about_df_dx(self): ss_group = self.get_secant_slope_group( self.start_x, self.graph, dx = self.dx, dx_label = "dx", df_label = "df", ) secant_line = ss_group.secant_line ss_group.remove(secant_line) v_line, nudged_v_line = [ self.get_vertical_line_to_graph( x, self.graph, line_class = DashedLine, color = RED, dash_length = 0.025 ) for x in (self.start_x, self.start_x+self.dx) ] df_dx = OldTex("\\frac{df}{dx} ?") VGroup(*df_dx[:2]).set_color(ss_group.df_line.get_color()) VGroup(*df_dx[3:5]).set_color(ss_group.dx_line.get_color()) df_dx.next_to( self.input_to_graph_point(self.start_x, self.graph), DOWN+RIGHT, buff = MED_SMALL_BUFF ) derivative_q = OldTexText("Derivative?") derivative_q.next_to(self.pi_creature.get_corner(UP+LEFT), UP) self.play( Write(derivative_q, run_time = 1), self.pi_creature.change_mode, "speaking" ) self.wait() self.play( FadeOut(derivative_q), self.pi_creature.change_mode, "plain" ) self.play(ShowCreation(v_line)) self.wait() self.play(Transform(v_line.copy(), nudged_v_line)) self.remove(self.get_mobjects_from_last_animation()[0]) self.add(nudged_v_line) self.wait() self.activate_zooming() self.little_rectangle.replace(self.big_rectangle) self.play( FadeIn(self.little_rectangle), FadeIn(self.big_rectangle), ) self.play( ApplyFunction( lambda r : self.position_little_rectangle(r, ss_group), self.little_rectangle ), self.pi_creature.change_mode, "pondering", self.pi_creature.look_at, ss_group ) self.play( ShowCreation(ss_group.dx_line), Write(ss_group.dx_label), ) self.wait() self.play( ShowCreation(ss_group.df_line), Write(ss_group.df_label), ) self.wait() self.play(Write(df_dx)) self.wait() self.play(*list(map(FadeOut, [ v_line, nudged_v_line, ]))) self.ss_group = ss_group def position_little_rectangle(self, rect, ss_group): rect.set_width(3*self.dx) rect.move_to( ss_group.dx_line.get_left() ) rect.shift( self.dx*self.little_rect_nudge ) return rect def show_differing_slopes(self): ss_group = self.ss_group def rect_update(rect): self.position_little_rectangle(rect, ss_group) self.play( ShowCreation(ss_group.secant_line), self.pi_creature.change_mode, "thinking" ) ss_group.add(ss_group.secant_line) self.wait() for target_x in self.big_x, -self.dx/2, 1, 2: self.animate_secant_slope_group_change( ss_group, target_x = target_x, added_anims = [ UpdateFromFunc(self.little_rectangle, rect_update) ] ) self.wait() def mention_alternate_view(self): self.remove(self.pi_creature) everything = VGroup(*self.get_mobjects()) self.add(self.pi_creature) self.disactivate_zooming() self.play( ApplyMethod( everything.shift, FRAME_WIDTH*LEFT, rate_func = lambda t : running_start(t, -0.1) ), self.pi_creature.change_mode, "happy" ) self.say("Let's try \\\\ another view.", target_mode = "speaking") self.wait(2) class NudgeSideLengthOfSquare(PiCreatureScene): CONFIG = { "square_width" : 3, "alt_square_width" : 5, "dx" : 0.25, "alt_dx" : 0.01, "square_color" : GREEN, "square_fill_opacity" : 0.75, "three_color" : GREEN, "dx_color" : BLUE_B, "is_recursing_on_dx" : False, "is_recursing_on_square_width" : False, } def construct(self): ApplyMethod(self.pi_creature.change_mode, "speaking").update(1) self.add_function_label() self.introduce_square() self.increase_area() self.write_df_equation() self.set_color_shapes() self.examine_thin_rectangles() self.examine_tiny_square() self.show_smaller_dx() self.rule_of_thumb() self.write_out_derivative() def add_function_label(self): label = OldTex("f(x) = x^2") label.next_to(ORIGIN, RIGHT, buff = (self.square_width-3)/2.) label.to_edge(UP) self.add(label) self.function_label = label def introduce_square(self): square = Square( side_length = self.square_width, stroke_width = 0, fill_opacity = self.square_fill_opacity, fill_color = self.square_color, ) square.to_corner(UP+LEFT, buff = LARGE_BUFF) x_squared = OldTex("x^2") x_squared.move_to(square) braces = VGroup() for vect in RIGHT, DOWN: brace = Brace(square, vect) text = brace.get_text("$x$") brace.add(text) braces.add(brace) self.play( DrawBorderThenFill(square), self.pi_creature.change_mode, "plain" ) self.play(*list(map(GrowFromCenter, braces))) self.play(Write(x_squared)) self.change_mode("pondering") self.wait() self.square = square self.side_braces = braces def increase_area(self): color_kwargs = { "fill_color" : YELLOW, "fill_opacity" : self.square_fill_opacity, "stroke_width" : 0, } right_rect = Rectangle( width = self.dx, height = self.square_width, **color_kwargs ) bottom_rect = right_rect.copy().rotate(-np.pi/2) right_rect.next_to(self.square, RIGHT, buff = 0) bottom_rect.next_to(self.square, DOWN, buff = 0) corner_square = Square( side_length = self.dx, **color_kwargs ) corner_square.next_to(self.square, DOWN+RIGHT, buff = 0) right_line = Line( self.square.get_corner(UP+RIGHT), self.square.get_corner(DOWN+RIGHT), stroke_width = 0 ) bottom_line = Line( self.square.get_corner(DOWN+RIGHT), self.square.get_corner(DOWN+LEFT), stroke_width = 0 ) corner_point = VectorizedPoint( self.square.get_corner(DOWN+RIGHT) ) little_braces = VGroup() for vect in RIGHT, DOWN: brace = Brace( corner_square, vect, buff = SMALL_BUFF, ) text = brace.get_text("$dx$", buff = SMALL_BUFF) text.set_color(self.dx_color) brace.add(text) little_braces.add(brace) right_brace, bottom_brace = self.side_braces self.play( Transform(right_line, right_rect), Transform(bottom_line, bottom_rect), Transform(corner_point, corner_square), right_brace.next_to, right_rect, RIGHT, SMALL_BUFF, bottom_brace.next_to, bottom_rect, DOWN, SMALL_BUFF, ) self.remove(corner_point, bottom_line, right_line) self.add(corner_square, bottom_rect, right_rect) self.play(*list(map(GrowFromCenter, little_braces))) self.wait() self.play(*it.chain(*[ [mob.shift, vect*SMALL_BUFF] for mob, vect in [ (right_rect, RIGHT), (bottom_rect, DOWN), (corner_square, DOWN+RIGHT), (right_brace, RIGHT), (bottom_brace, DOWN), (little_braces, DOWN+RIGHT) ] ])) self.change_mode("thinking") self.wait() self.right_rect = right_rect self.bottom_rect = bottom_rect self.corner_square = corner_square self.little_braces = little_braces def write_df_equation(self): right_rect = self.right_rect bottom_rect = self.bottom_rect corner_square = self.corner_square df_equation = VGroup( OldTex("df").set_color(right_rect.get_color()), OldTex("="), right_rect.copy(), OldTexText("+"), right_rect.copy(), OldTex("+"), corner_square.copy() ) df_equation.arrange() df_equation.next_to( self.function_label, DOWN, aligned_edge = LEFT, buff = SMALL_BUFF ) df, equals, r1, plus1, r2, plus2, s = df_equation pairs = [ (df, self.function_label[0]), (r1, right_rect), (r2, bottom_rect), (s, corner_square), ] for mover, origin in pairs: mover.save_state() Transform(mover, origin).update(1) self.play(df.restore) self.wait() self.play( *[ mob.restore for mob in (r1, r2, s) ]+[ Write(symbol) for symbol in (equals, plus1, plus2) ], run_time = 2 ) self.change_mode("happy") self.wait() self.df_equation = df_equation def set_color_shapes(self): df, equals, r1, plus1, r2, plus2, s = self.df_equation tups = [ (self.right_rect, self.bottom_rect, r1, r2), (self.corner_square, s) ] for tup in tups: self.play( *it.chain(*[ [m.scale, 1.2, m.set_color, RED] for m in tup ]), rate_func = there_and_back ) self.wait() def examine_thin_rectangles(self): df, equals, r1, plus1, r2, plus2, s = self.df_equation rects = VGroup(r1, r2) thin_rect_brace = Brace(rects, DOWN) text = thin_rect_brace.get_text("$2x \\, dx$") VGroup(*text[-2:]).set_color(self.dx_color) text.save_state() alt_text = thin_rect_brace.get_text("$2(3)(0.01)$") alt_text[2].set_color(self.three_color) VGroup(*alt_text[-5:-1]).set_color(self.dx_color) example_value = OldTex("=0.06") example_value.next_to(alt_text, DOWN) self.play(GrowFromCenter(thin_rect_brace)) self.play( Write(text), self.pi_creature.change_mode, "pondering" ) self.wait() xs = VGroup(*[ brace[-1] for brace in self.side_braces ]) dxs = VGroup(*[ brace[-1] for brace in self.little_braces ]) for group, tex, color in (xs, "3", self.three_color), (dxs, "0.01", self.dx_color): group.save_state() group.generate_target() for submob in group.target: number = OldTex(tex) number.set_color(color) number.move_to(submob, LEFT) Transform(submob, number).update(1) self.play(MoveToTarget(xs)) self.play(MoveToTarget(dxs)) self.wait() self.play(Transform(text, alt_text)) self.wait() self.play(Write(example_value)) self.wait() self.play( FadeOut(example_value), *[ mob.restore for mob in (xs, dxs, text) ] ) self.remove(text) text.restore() self.add(text) self.wait() self.dxs = dxs self.thin_rect_brace = thin_rect_brace self.thin_rect_area = text def examine_tiny_square(self): text = OldTex("dx^2") VGroup(*text[:2]).set_color(self.dx_color) text.next_to(self.df_equation[-1], UP) text.save_state() alt_text = OldTexText("0.0001") alt_text.move_to(text) self.play(Write(text)) self.change_mode("surprised") self.wait() self.play( MoveToTarget(self.dxs), self.pi_creature.change_mode, "plain" ) for submob in self.dxs.target: number = OldTex("0.01") number.set_color(self.dx_color) number.move_to(submob, LEFT) Transform(submob, number).update(1) self.play(MoveToTarget(self.dxs)) self.play( Transform(text, alt_text), self.pi_creature.change_mode, "raise_right_hand" ) self.wait(2) self.play(*[ mob.restore for mob in (self.dxs, text) ] + [ self.pi_creature.change_mode, "erm" ]) self.dx_squared = text def show_smaller_dx(self): self.mobjects_at_start_of_show_smaller_dx = [ mob.copy() for mob in self.get_mobjects() ] if self.is_recursing_on_dx: return alt_scene = self.__class__( skip_animations = True, dx = self.alt_dx, is_recursing_on_dx = True ) for mob in self.get_mobjects(): mob.save_state() self.play(*[ Transform(*pair) for pair in zip( self.get_mobjects(), alt_scene.mobjects_at_start_of_show_smaller_dx, ) ]) self.wait() self.play(*[ mob.restore for mob in self.get_mobjects() ]) self.change_mode("happy") self.wait() def rule_of_thumb(self): circle = Circle(color = RED) dx_squared_group = VGroup(self.dx_squared, self.df_equation[-1]) circle.replace(dx_squared_group, stretch = True) dx_squared_group.add(self.df_equation[-2]) circle.scale(1.5) safe_to_ignore = OldTexText("Safe to ignore") safe_to_ignore.next_to(circle, DOWN, aligned_edge = LEFT) safe_to_ignore.set_color(circle.get_color()) self.play(ShowCreation(circle)) self.play( Write(safe_to_ignore, run_time = 2), self.pi_creature.change_mode, "raise_right_hand" ) self.play( FadeOut(circle), FadeOut(safe_to_ignore), dx_squared_group.fade, 0.5, dx_squared_group.to_corner, UP+RIGHT, self.pi_creature.change_mode, "plain" ) self.wait() def write_out_derivative(self): df, equals, r1, plus1, r2, plus2, s = self.df_equation frac_line = OldTex("-") frac_line.stretch_to_fit_width(df.get_width()) frac_line.move_to(df) dx = VGroup(*self.thin_rect_area[-2:]) x = self.thin_rect_area[1] self.play( Transform(r1, self.right_rect), Transform(r2, self.bottom_rect), FadeOut(plus1), FadeOut(self.thin_rect_brace) ) self.play( self.thin_rect_area.next_to, VGroup(df, equals), RIGHT, MED_SMALL_BUFF, UP, self.pi_creature.change_mode, "thinking" ) self.wait(2) self.play( ApplyMethod(df.next_to, frac_line, UP, SMALL_BUFF), ApplyMethod(dx.next_to, frac_line, DOWN, SMALL_BUFF), Write(frac_line), path_arc = -np.pi ) self.wait() brace_xs = [ brace[-1] for brace in self.side_braces ] xs = list(brace_xs) + [x] for x_mob in xs: number = OldTex("(%d)"%self.square_width) number.move_to(x_mob, LEFT) number.shift( (x_mob.get_bottom()[1] - number[1].get_bottom()[1])*UP ) x_mob.save_state() x_mob.target = number self.play(*list(map(MoveToTarget, xs))) self.wait(2) #Recursively transform to what would have happened #with a wider square width self.mobjects_at_end_of_write_out_derivative = self.get_mobjects() if self.is_recursing_on_square_width or self.is_recursing_on_dx: return alt_scene = self.__class__( skip_animations = True, square_width = self.alt_square_width, is_recursing_on_square_width = True, ) self.play(*[ Transform(*pair) for pair in zip( self.mobjects_at_end_of_write_out_derivative, alt_scene.mobjects_at_end_of_write_out_derivative ) ]) self.change_mode("happy") self.wait(2) class ChangeInAreaOverChangeInX(Scene): def construct(self): fractions = [] for pair in ("Change in area", "Change in $x$"), ("$d(x^2)$", "$dx$"): top, bottom = list(map(TexText, pair)) top.set_color(YELLOW) bottom.set_color(BLUE_B) frac_line = OldTex("-") frac_line.stretch_to_fit_width(top.get_width()) top.next_to(frac_line, UP, SMALL_BUFF) bottom.next_to(frac_line, DOWN, SMALL_BUFF) fractions.append(VGroup( top, frac_line, bottom )) words, symbols = fractions self.play(Write(words[0], run_time = 1)) self.play(*list(map(Write, words[1:])), run_time = 1) self.wait() self.play(Transform(words, symbols)) self.wait() class NudgeSideLengthOfCube(Scene): CONFIG = { "x_color" : BLUE, "dx_color" : GREEN, "df_color" : YELLOW, "use_morty" : False, "x" : 3, "dx" : 0.2, "alt_dx" : 0.02, "offset_vect" : OUT, "pose_angle" : np.pi/12, "pose_axis" : UP+RIGHT, "small_piece_scaling_factor" : 0.7, "allow_recursion" : True, } def construct(self): self.states = dict() if self.allow_recursion: self.alt_scene = self.__class__( skip_animations = True, allow_recursion = False, dx = self.alt_dx, ) self.add_title() self.introduce_cube() self.write_df_equation() self.write_derivative() def add_title(self): title = OldTex("f(x) = x^3") title.shift(FRAME_X_RADIUS*LEFT/2) title.to_edge(UP) self.play(Write(title)) self.wait() def introduce_cube(self): cube = self.get_cube() cube.to_edge(LEFT, buff = 2*LARGE_BUFF) cube.shift(DOWN) dv_pieces = self.get_dv_pices(cube) original_dx = self.dx self.dx = 0 alt_dv_pieces = self.get_dv_pices(cube) self.dx = original_dx alt_dv_pieces.set_fill(opacity = 0) x_brace = Brace(cube, LEFT, buff = SMALL_BUFF) dx_brace = Brace( dv_pieces[1], LEFT, buff = SMALL_BUFF, ) dx_brace.stretch_in_place(1.5, 1) for brace, tex in (x_brace, "x"), (dx_brace, "dx"): brace.scale(0.95) brace.rotate(-np.pi/96) brace.shift(0.3*(UP+LEFT)) brace.add(brace.get_text("$%s$"%tex)) cube_group = VGroup(cube, dv_pieces, alt_dv_pieces) self.pose_3d_mobject(cube_group) self.play(DrawBorderThenFill(cube)) self.play(GrowFromCenter(x_brace)) self.wait() self.play(Transform(alt_dv_pieces, dv_pieces)) self.remove(alt_dv_pieces) self.add(dv_pieces) self.play(GrowFromCenter(dx_brace)) self.wait() for piece in dv_pieces: piece.on_cube_state = piece.copy() self.play(*[ ApplyMethod( piece.shift, 0.5*(piece.get_center()-cube.get_center()) ) for piece in dv_pieces ]+[ ApplyMethod(dx_brace.shift, 0.7*UP) ]) self.wait() self.cube = cube self.dx_brace = dx_brace self.faces, self.bars, self.corner_cube = [ VGroup(*[ piece for piece in dv_pieces if piece.type == target_type ]) for target_type in ("face", "bar", "corner_cube") ] def write_df_equation(self): df_equation = VGroup( OldTex("df"), OldTex("="), self.organize_faces(self.faces.copy()), OldTex("+"), self.organize_bars(self.bars.copy()), OldTex("+"), self.corner_cube.copy() ) df, equals, faces, plus1, bars, plus2, corner_cube = df_equation df.set_color(self.df_color) for three_d_mob in faces, bars, corner_cube: three_d_mob.scale(self.small_piece_scaling_factor) # self.pose_3d_mobject(three_d_mob) faces.set_fill(opacity = 0.3) df_equation.arrange(RIGHT) df_equation.next_to(ORIGIN, RIGHT) df_equation.to_edge(UP) faces_brace = Brace(faces, DOWN) derivative = faces_brace.get_tex("3x^2", "\\, dx") extras_brace = Brace(VGroup(bars, corner_cube), DOWN) ignore_text = extras_brace.get_text( "Multiple \\\\ of $dx^2$" ) ignore_text.scale(0.7) x_squared_dx = OldTex("x^2", "\\, dx") self.play(*list(map(Write, [df, equals]))) self.grab_pieces(self.faces, faces) self.wait() self.shrink_dx("Faces are introduced") face = self.faces[0] face.save_state() self.play(face.shift, FRAME_X_RADIUS*RIGHT) x_squared_dx.next_to(face, LEFT) self.play(Write(x_squared_dx, run_time = 1)) self.wait() for submob, sides in zip(x_squared_dx, [face[0], VGroup(*face[1:])]): self.play( submob.set_color, RED, sides.set_color, RED, rate_func = there_and_back ) self.wait() self.play( face.restore, Transform( x_squared_dx, derivative, replace_mobject_with_target_in_scene = True ), GrowFromCenter(faces_brace) ) self.wait() self.grab_pieces(self.bars, bars, plus1) self.grab_pieces(self.corner_cube, corner_cube, plus2) self.play( GrowFromCenter(extras_brace), Write(ignore_text) ) self.wait() self.play(*[ ApplyMethod(mob.fade, 0.7) for mob in [ plus1, bars, plus2, corner_cube, extras_brace, ignore_text ] ]) self.wait() self.df_equation = df_equation self.derivative = derivative def write_derivative(self): df, equals, faces, plus1, bars, plus2, corner_cube = self.df_equation df = df.copy() equals = equals.copy() df_equals = VGroup(df, equals) derivative = self.derivative.copy() dx = derivative[1] extra_stuff = OldTex("+(\\dots)", "dx^2") dx_squared = extra_stuff[1] derivative.generate_target() derivative.target.shift(2*DOWN) extra_stuff.next_to(derivative.target) self.play( MoveToTarget(derivative), df_equals.next_to, derivative.target[0], LEFT, df_equals.shift, 0.07*DOWN ) self.play(Write(extra_stuff)) self.wait() frac_line = OldTex("-") frac_line.replace(df) extra_stuff.generate_target() extra_stuff.target.next_to(derivative[0]) frac_line2 = OldTex("-") frac_line2.stretch_to_fit_width( extra_stuff.target[1].get_width() ) frac_line2.move_to(extra_stuff.target[1]) extra_stuff.target[1].next_to(frac_line2, UP, buff = SMALL_BUFF) dx_below_dx_squared = OldTex("dx") dx_below_dx_squared.next_to(frac_line2, DOWN, buff = SMALL_BUFF) self.play( FadeIn(frac_line), FadeIn(frac_line2), df.next_to, frac_line, UP, SMALL_BUFF, dx.next_to, frac_line, DOWN, SMALL_BUFF, MoveToTarget(extra_stuff), Write(dx_below_dx_squared), path_arc = -np.pi ) self.wait() inner_dx = VGroup(*dx_squared[:-1]) self.play( FadeOut(frac_line2), FadeOut(dx_below_dx_squared), dx_squared[-1].set_color, BLACK, inner_dx.next_to, extra_stuff[0], RIGHT, SMALL_BUFF ) self.wait() self.shrink_dx("Derivative is written", restore = False) self.play(*[ ApplyMethod(mob.fade, 0.7) for mob in (extra_stuff, inner_dx) ]) self.wait(2) anims = [] for mob in list(self.faces)+list(self.bars)+list(self.corner_cube): vect = mob.get_center()-self.cube.get_center() anims += [ mob.shift, -(1./3)*vect ] anims += self.dx_brace.shift, 0.7*DOWN self.play(*anims) self.wait() def grab_pieces(self, start_pieces, end_pices, to_write = None): for piece in start_pieces: piece.generate_target() piece.target.rotate( np.pi/12, piece.get_center()-self.cube.get_center() ) piece.target.set_color(RED) self.play(*list(map(MoveToTarget, start_pieces)), rate_func = wiggle) self.wait() added_anims = [] if to_write is not None: added_anims.append(Write(to_write)) self.play( Transform(start_pieces.copy(), end_pices), *added_anims ) def shrink_dx(self, state_name, restore = True): mobjects = self.get_mobjects() mobjects_with_points = [ m for m in mobjects if m.get_num_points() > 0 ] #Alt_scene will reach this point, and save copy of self #in states dict self.states[state_name] = [ mob.copy() for mob in mobjects_with_points ] if not self.allow_recursion: return if restore: movers = self.states[state_name] for mob in movers: mob.save_state() self.remove(*mobjects) else: movers = mobjects_with_points self.play(*[ Transform(*pair) for pair in zip( movers, self.alt_scene.states[state_name] ) ]) self.wait() if restore: self.play(*[m.restore for m in movers]) self.remove(*movers) self.mobjects = mobjects def get_cube(self): cube = self.get_prism(self.x, self.x, self.x) cube.set_fill(color = BLUE, opacity = 0.3) cube.set_stroke(color = WHITE, width = 1) return cube def get_dv_pices(self, cube): pieces = VGroup() for vect in it.product([0, 1], [0, 1], [0, 1]): if np.all(vect == ORIGIN): continue args = [ self.x if bit is 0 else self.dx for bit in vect ] piece = self.get_prism(*args) piece.next_to(cube, np.array(vect), buff = 0) pieces.add(piece) if sum(vect) == 1: piece.type = "face" elif sum(vect) == 2: piece.type = "bar" else: piece.type = "corner_cube" return pieces def organize_faces(self, faces): self.unpose_3d_mobject(faces) for face in faces: dimensions = [ face.length_over_dim(dim) for dim in range(3) ] thin_dim = np.argmin(dimensions) if thin_dim == 0: face.rotate(np.pi/2, DOWN) elif thin_dim == 1: face.rotate(np.pi/2, RIGHT) faces.arrange(OUT, buff = LARGE_BUFF) self.pose_3d_mobject(faces) return faces def organize_bars(self, bars): self.unpose_3d_mobject(bars) for bar in bars: dimensions = [ bar.length_over_dim(dim) for dim in range(3) ] thick_dim = np.argmax(dimensions) if thick_dim == 0: bar.rotate(np.pi/2, OUT) elif thick_dim == 2: bar.rotate(np.pi/2, LEFT) bars.arrange(OUT, buff = LARGE_BUFF) self.pose_3d_mobject(bars) return bars def get_corner_cube(self): return self.get_prism(self.dx, self.dx, self.dx) def get_prism(self, width, height, depth): color_kwargs = { "fill_color" : YELLOW, "fill_opacity" : 0.4, "stroke_color" : WHITE, "stroke_width" : 0.1, } front = Rectangle( width = width, height = height, **color_kwargs ) face = VGroup(front) for vect in LEFT, RIGHT, UP, DOWN: if vect is LEFT or vect is RIGHT: side = Rectangle( height = height, width = depth, **color_kwargs ) else: side = Rectangle( height = depth, width = width, **color_kwargs ) side.next_to(front, vect, buff = 0) side.rotate( np.pi/2, rotate_vector(vect, -np.pi/2), about_point = front.get_edge_center(vect) ) face.add(side) return face def pose_3d_mobject(self, mobject): mobject.rotate(self.pose_angle, self.pose_axis) return mobject def unpose_3d_mobject(self, mobject): mobject.rotate(-self.pose_angle, self.pose_axis) return mobject class ShowCubeDVIn3D(Scene): def construct(self): raise Exception("This scene is only here for the stage_scenes script.") class GraphOfXCubed(GraphScene): CONFIG = { "x_min" : -6, "x_max" : 6, "x_axis_width" : FRAME_WIDTH, "x_labeled_nums" : list(range(-6, 7)), "y_min" : -35, "y_max" : 35, "y_axis_height" : FRAME_HEIGHT, "y_tick_frequency" : 5, "y_labeled_nums" : list(range(-30, 40, 10)), "graph_origin" : ORIGIN, "dx" : 0.2, "deriv_x_min" : -3, "deriv_x_max" : 3, } def construct(self): self.setup_axes(animate = False) graph = self.get_graph(lambda x : x**3) label = self.get_graph_label( graph, "f(x) = x^3", direction = LEFT, ) deriv_graph, full_deriv_graph = [ self.get_derivative_graph( graph, color = DERIVATIVE_COLOR, x_min = low_x, x_max = high_x, ) for low_x, high_x in [ (self.deriv_x_min, self.deriv_x_max), (self.x_min, self.x_max), ] ] deriv_label = self.get_graph_label( deriv_graph, "\\frac{df}{dx}(x) = 3x^2", x_val = -3, direction = LEFT ) deriv_label.shift(0.5*DOWN) ss_group = self.get_secant_slope_group( self.deriv_x_min, graph, dx = self.dx, dx_line_color = WHITE, df_line_color = WHITE, secant_line_color = YELLOW, ) self.play(ShowCreation(graph)) self.play(Write(label, run_time = 1)) self.wait() self.play(Write(deriv_label, run_time = 1)) self.play(ShowCreation(ss_group, lag_ratio = 0)) self.animate_secant_slope_group_change( ss_group, target_x = self.deriv_x_max, run_time = 10, added_anims = [ ShowCreation(deriv_graph, run_time = 10) ] ) self.play(FadeIn(full_deriv_graph)) self.wait() for x_val in -2, -self.dx/2, 2: self.animate_secant_slope_group_change( ss_group, target_x = x_val, run_time = 2 ) if x_val != -self.dx/2: v_line = self.get_vertical_line_to_graph( x_val, deriv_graph, line_class = DashedLine ) self.play(ShowCreation(v_line)) self.play(FadeOut(v_line)) class PatternForPowerRule(PiCreatureScene): CONFIG = { "num_exponents" : 5, } def construct(self): self.introduce_pattern() self.generalize_pattern() self.show_hopping() def introduce_pattern(self): exp_range = list(range(1, 1+self.num_exponents)) colors = color_gradient([BLUE_D, YELLOW], self.num_exponents) derivatives = VGroup() for exponent, color in zip(exp_range, colors): derivative = OldTex( "\\frac{d(x^%d)}{dx} = "%exponent, "%d x^{%d}"%(exponent, exponent-1) ) VGroup(*derivative[0][2:4]).set_color(color) derivatives.add(derivative) derivatives.arrange( DOWN, aligned_edge = LEFT, buff = MED_LARGE_BUFF ) derivatives.set_height(FRAME_HEIGHT-1) derivatives.to_edge(LEFT) self.play(FadeIn(derivatives[0])) for d1, d2 in zip(derivatives, derivatives[1:]): self.play(Transform( d1.copy(), d2, replace_mobject_with_target_in_scene = True )) self.change_mode("thinking") self.wait() for derivative in derivatives[-2:]: derivative.save_state() self.play( derivative.scale, 2, derivative.next_to, derivative, RIGHT, SMALL_BUFF, DOWN, ) self.wait(2) self.play(derivative.restore) self.remove(derivative) derivative.restore() self.add(derivative) self.derivatives = derivatives self.colors = colors def generalize_pattern(self): derivatives = self.derivatives power_rule = OldTex( "\\frac{d (x^n)}{dx} = ", "nx^{n-1}" ) title = OldTexText("``Power rule''") title.next_to(power_rule, UP, MED_LARGE_BUFF) lines = VGroup(*[ Line( deriv.get_right(), power_rule.get_left(), buff = MED_SMALL_BUFF, color = deriv[0][2].get_color() ) for deriv in derivatives ]) self.play( Transform( VGroup(*[d[0].copy() for d in derivatives]), VGroup(power_rule[0]), replace_mobject_with_target_in_scene = True ), ShowCreation(lines), lag_ratio = 0.5, run_time = 2, ) self.wait() self.play(Write(power_rule[1])) self.wait() self.play( Write(title), self.pi_creature.change_mode, "speaking" ) self.wait() def show_hopping(self): exp_range = list(range(2, 2+self.num_exponents-1)) self.change_mode("tired") for exp, color in zip(exp_range, self.colors[1:]): form = OldTex( "x^", str(exp), "\\rightarrow", str(exp), "x^", str(exp-1) ) form.set_color(color) form.to_corner(UP+RIGHT, buff = LARGE_BUFF) lhs = VGroup(*form[:2]) lhs_copy = lhs.copy() rhs = VGroup(*form[-2:]) arrow = form[2] self.play(Write(lhs)) self.play( lhs_copy.move_to, rhs, DOWN+LEFT, Write(arrow) ) self.wait() self.play( ApplyMethod( lhs_copy[1].replace, form[3], path_arc = np.pi, rate_func = running_start, ), FadeIn( form[5], rate_func = squish_rate_func(smooth, 0.5, 1) ) ) self.wait() self.play( self.pi_creature.change_mode, "hesitant", self.pi_creature.look_at, lhs_copy ) self.play(*list(map(FadeOut, [form, lhs_copy]))) class PowerRuleAlgebra(Scene): CONFIG = { "dx_color" : YELLOW, "x_color" : BLUE, } def construct(self): x_to_n = OldTex("x^n") down_arrow = Arrow(UP, DOWN, buff = MED_LARGE_BUFF) paren_strings = ["(", "x", "+", "dx", ")"] x_dx_to_n = OldTex(*paren_strings +["^n"]) equals = OldTex("=") equals2 = OldTex("=") full_product = OldTex( *paren_strings*3+["\\cdots"]+paren_strings ) x_to_n.set_color(self.x_color) for mob in x_dx_to_n, full_product: mob.set_color_by_tex("dx", self.dx_color) mob.set_color_by_tex("x", self.x_color) nudge_group = VGroup(x_to_n, down_arrow, x_dx_to_n) nudge_group.arrange(DOWN) nudge_group.to_corner(UP+LEFT) down_arrow.next_to(x_to_n[0], DOWN) equals.next_to(x_dx_to_n) full_product.next_to(equals) equals2.next_to(equals, DOWN, 1.5*LARGE_BUFF) nudge_brace = Brace(x_dx_to_n, DOWN) nudged_output = nudge_brace.get_text("Nudged \\\\ output") product_brace = Brace(full_product, UP) product_brace.add(product_brace.get_text("$n$ times")) self.add(x_to_n) self.play(ShowCreation(down_arrow)) self.play( FadeIn(x_dx_to_n), GrowFromCenter(nudge_brace), GrowFromCenter(nudged_output) ) self.wait() self.play( Write(VGroup(equals, full_product)), GrowFromCenter( product_brace, rate_func = squish_rate_func(smooth, 0.6, 1) ), run_time = 3 ) self.wait() self.workout_product(equals2, full_product) def workout_product(self, equals, full_product): product_part_tex_pairs = list(zip(full_product, full_product.expression_parts)) xs, dxs = [ VGroup(*[ submob for submob, tex in product_part_tex_pairs if tex == target_tex ]) for target_tex in ("x", "dx") ] x_to_n = OldTex("x^n") extra_stuff = OldTex("+(\\text{Multiple of }\\, dx^2)") # extra_stuff.scale(0.8) VGroup(*extra_stuff[-4:-2]).set_color(self.dx_color) x_to_n.next_to(equals, RIGHT, align_using_submobjects = True) x_to_n.set_color(self.x_color) xs_copy = xs.copy() full_product.save_state() self.play(full_product.set_color, WHITE) self.play(xs_copy.set_color, self.x_color) self.play( Write(equals), Transform(xs_copy, x_to_n) ) self.wait() brace, derivative_term = self.pull_out_linear_terms( x_to_n, product_part_tex_pairs, xs, dxs ) self.wait() circle = Circle(color = DERIVATIVE_COLOR) circle.replace(derivative_term, stretch = True) circle.scale(1.4) circle.rotate( Line( derivative_term.get_corner(DOWN+LEFT), derivative_term.get_corner(UP+RIGHT), ).get_angle() ) extra_stuff.next_to(brace, aligned_edge = UP) self.play(Write(extra_stuff), full_product.restore) self.wait() self.play(ShowCreation(circle)) self.wait() def pull_out_linear_terms(self, x_to_n, product_part_tex_pairs, xs, dxs): last_group = None all_linear_terms = VGroup() for dx_index, dx in enumerate(dxs): if dx is dxs[-1]: v_dots = OldTex("\\vdots") v_dots.next_to(last_group[0], DOWN) h_dots_list = [ submob for submob, tex in product_part_tex_pairs if tex == "\\cdots" ] h_dots_copy = h_dots_list[0].copy() self.play(ReplacementTransform( h_dots_copy, v_dots, )) last_group.add(v_dots) all_linear_terms.add(v_dots) dx_copy = dx.copy() xs_copy = xs.copy() xs_copy.remove(xs_copy[dx_index]) self.play( dx_copy.set_color, self.dx_color, xs_copy.set_color, self.x_color, rate_func = squish_rate_func(smooth, 0, 0.5) ) dx_copy.generate_target() xs_copy.generate_target() target_list = [dx_copy.target] + list(xs_copy.target) target_list.sort( key=lambda m: m.get_center()[0] ) dots = OldTex("+", ".", ".", "\\dots") for dot_index, dot in enumerate(dots): target_list.insert(2*dot_index, dot) group = VGroup(*target_list) group.arrange(RIGHT, SMALL_BUFF) if last_group is None: group.next_to(x_to_n, RIGHT) else: group.next_to(last_group, DOWN, aligned_edge = LEFT) last_group = group self.play( MoveToTarget(dx_copy), MoveToTarget(xs_copy), Write(dots) ) all_linear_terms.add(dx_copy, xs_copy, dots) all_linear_terms.generate_target() all_linear_terms.target.scale(0.7) brace = Brace(all_linear_terms.target, UP) compact = OldTex("+\\,", "n", "x^{n-1}", "\\,dx") compact.set_color_by_tex("x^{n-1}", self.x_color) compact.set_color_by_tex("\\,dx", self.dx_color) compact.next_to(brace, UP) brace.add(compact) derivative_term = VGroup(*compact[1:3]) VGroup(brace, all_linear_terms.target).shift( x_to_n[0].get_right()+MED_LARGE_BUFF*RIGHT - \ compact[0].get_left() ) self.play(MoveToTarget(all_linear_terms)) self.play(Write(brace, run_time = 1)) return brace, derivative_term class ReactToFullExpansion(Scene): def construct(self): randy = Randolph() self.add(randy) self.play(randy.change_mode, "pleading") self.play(Blink(randy)) self.play(randy.change_mode, "angry") self.wait() self.play(randy.change_mode, "thinking") self.play(Blink(randy)) self.wait() class OneOverX(PiCreatureScene, GraphScene): CONFIG = { "unit_length" : 3.0, "graph_origin" : (FRAME_X_RADIUS - LARGE_BUFF)*LEFT + 2*DOWN, "rectangle_color_kwargs" : { "fill_color" : BLUE, "fill_opacity" : 0.5, "stroke_width" : 1, "stroke_color" : WHITE, }, "x_axis_label" : "", "y_axis_label" : "", "x_min" : 0, "y_min" : 0, "x_tick_frequency" : 0.5, "y_tick_frequency" : 0.5, "x_labeled_nums" : list(range(0, 4)), "y_labeled_nums" : [1], "y_axis_height" : 10, "morty_scale_val" : 0.8, "area_label_scale_factor" : 0.75, "dx" : 0.1, "start_x_value" : 1.3, "dx_color" : GREEN, "df_color" : RED, } def setup(self): for c in self.__class__.__bases__: c.setup(self) self.x_max = self.x_axis_width/self.unit_length self.y_max = self.y_axis_height/self.unit_length def construct(self): self.force_skipping() self.introduce_function() self.introduce_puddle() self.introduce_graph() self.perform_nudge() def introduce_function(self): func = OldTex("f(x) = ", "\\frac{1}{x}") func.to_edge(UP) recip_copy = func[1].copy() x_to_neg_one = OldTex("x^{-1}") x_to_neg_one.submobjects.reverse() neg_one = VGroup(*x_to_neg_one[:2]) neg_two = OldTex("-2") self.play( Write(func), self.pi_creature.change_mode, "pondering" ) self.wait() self.play( recip_copy.next_to, self.pi_creature, UP+LEFT, self.pi_creature.change_mode, "raise_right_hand" ) x_to_neg_one.move_to(recip_copy) neg_two.replace(neg_one) self.play(ReplacementTransform(recip_copy, x_to_neg_one)) self.wait() self.play( neg_one.scale, 1.5, neg_one.next_to, x_to_neg_one, LEFT, SMALL_BUFF, DOWN, rate_func = running_start, path_arc = np.pi ) self.play(FadeIn(neg_two)) self.wait() self.say( "More geometry!", target_mode = "hooray", added_anims = [ FadeOut(x_to_neg_one), FadeOut(neg_two), ], run_time = 2 ) self.wait() self.play(RemovePiCreatureBubble(self.pi_creature)) def introduce_puddle(self): rect_group = self.get_rectangle_group(self.start_x_value) self.play( DrawBorderThenFill(rect_group.rectangle), Write(rect_group.area_label), self.pi_creature.change_mode, "thinking" ) self.play( GrowFromCenter(rect_group.x_brace), Write(rect_group.x_label), ) self.wait() self.play( GrowFromCenter(rect_group.recip_brace), Write(rect_group.recip_label), ) self.setup_axes(animate = True) self.wait() for d in 2, 3: self.change_rectangle_group( rect_group, d, target_group_kwargs = { "x_label" : str(d), "one_over_x_label" : "\\frac{1}{%d}"%d, }, run_time = 2 ) self.wait() self.change_rectangle_group(rect_group, 3) self.wait() self.rect_group = rect_group def introduce_graph(self): rect_group = self.rect_group graph = self.get_graph(lambda x : 1./x) graph.set_points(list(reversed(graph.get_points()))) self.change_rectangle_group( rect_group, 0.01, added_anims = [ ShowCreation(graph) ], run_time = 5, ) self.change_mode("happy") self.change_rectangle_group(rect_group, self.start_x_value) self.wait() self.graph = graph def perform_nudge(self): rect_group = self.rect_group graph = self.graph rect_copy = rect_group.rectangle.copy() rect_copy.set_fill(opacity = 0) new_rect = self.get_rectangle( self.start_x_value + self.dx ) recip_brace = rect_group.recip_brace recip_brace.generate_target() recip_brace.target.next_to( new_rect, RIGHT, buff = SMALL_BUFF, aligned_edge = DOWN, ) recip_label = rect_group.recip_label recip_label.generate_target() recip_label.target.next_to(recip_brace.target, RIGHT) h_lines = VGroup(*[ DashedLine( ORIGIN, (rect_copy.get_width()+LARGE_BUFF)*RIGHT, color = self.df_color, stroke_width = 2 ).move_to(rect.get_corner(UP+LEFT), LEFT) for rect in (rect_group.rectangle, new_rect) ]) v_lines = VGroup(*[ DashedLine( ORIGIN, (rect_copy.get_height()+MED_LARGE_BUFF)*UP, color = self.dx_color, stroke_width = 2 ).move_to(rect.get_corner(DOWN+RIGHT), DOWN) for rect in (rect_group.rectangle, new_rect) ]) dx_brace = Brace(v_lines, UP, buff = 0) dx_label = dx_brace.get_text("$dx$") dx_brace.add(dx_label) df_brace = Brace(h_lines, RIGHT, buff = 0) df_label = df_brace.get_text("$d\\left(\\frac{1}{x}\\right)$") df_brace.add(df_label) negative = OldTexText("Negative") negative.set_color(RED) negative.next_to(df_label, UP+RIGHT) negative.shift(RIGHT) negative_arrow = Arrow( negative.get_left(), df_label.get_corner(UP+RIGHT), color = RED ) area_changes = VGroup() point_pairs = [ (new_rect.get_corner(UP+RIGHT), rect_copy.get_corner(DOWN+RIGHT)), (new_rect.get_corner(UP+LEFT), rect_copy.get_corner(UP+RIGHT)) ] for color, point_pair in zip([self.dx_color, self.df_color], point_pairs): area_change_rect = Rectangle( fill_opacity = 1, fill_color = color, stroke_width = 0 ) area_change_rect.replace( VGroup(*list(map(VectorizedPoint, point_pair))), stretch = True ) area_changes.add(area_change_rect) area_gained, area_lost = area_changes area_gained_label = OldTexText("Area gained") area_gained_label.scale(0.75) area_gained_label.next_to( rect_copy.get_corner(DOWN+RIGHT), UP+LEFT, buff = SMALL_BUFF ) area_gained_arrow = Arrow( area_gained_label.get_top(), area_gained.get_center(), buff = 0, color = WHITE ) area_lost_label = OldTexText("Area lost") area_lost_label.scale(0.75) area_lost_label.next_to(rect_copy.get_left(), RIGHT) area_lost_arrow = Arrow( area_lost_label.get_top(), area_lost.get_center(), buff = 0, color = WHITE ) question = OldTex( "\\frac{d(1/x)}{dx} = ???" ) question.next_to( self.pi_creature.get_corner(UP+LEFT), UP, buff = MED_SMALL_BUFF, ) self.play( FadeOut(rect_group.area_label), ReplacementTransform(rect_copy, new_rect), MoveToTarget(recip_brace), MoveToTarget(recip_label), self.pi_creature.change_mode, "pondering" ) self.play( GrowFromCenter(dx_brace), *list(map(ShowCreation, v_lines)) ) self.wait() self.play( GrowFromCenter(df_brace), *list(map(ShowCreation, h_lines)) ) self.change_mode("confused") self.wait() self.play( FadeIn(area_gained), Write(area_gained_label, run_time = 2), ShowCreation(area_gained_arrow) ) self.wait() self.play( FadeIn(area_lost), Write(area_lost_label, run_time = 2), ShowCreation(area_lost_arrow) ) self.wait() self.revert_to_original_skipping_status()### self.play( Write(negative), ShowCreation(negative_arrow) ) self.wait() self.play( Write(question), self.pi_creature.change_mode, "raise_right_hand" ) self.wait(2) ######## def create_pi_creature(self): morty = PiCreatureScene.create_pi_creature(self) morty.scale( self.morty_scale_val, about_point = morty.get_corner(DOWN+RIGHT) ) return morty def draw_graph(self): self.setup_axes() graph = self.get_graph(lambda x : 1./x) rect_group = self.get_rectangle_group(0.5) self.add(rect_group) self.wait() self.change_rectangle_group( rect_group, 2, target_group_kwargs = { "x_label" : "2", "one_over_x_label" : "\\frac{1}{2}", }, added_anims = [ShowCreation(graph)] ) self.wait() def get_rectangle_group( self, x, x_label = "x", one_over_x_label = "\\frac{1}{x}" ): result = VGroup() result.x_val = x result.rectangle = self.get_rectangle(x) result.x_brace, result.recip_brace = braces = [ Brace(result.rectangle, vect) for vect in (UP, RIGHT) ] result.labels = VGroup() for brace, label in zip(braces, [x_label, one_over_x_label]): brace.get_text("$%s$"%label) result.labels.add(brace.get_text("$%s$"%label)) result.x_label, result.recip_label = result.labels area_label = OldTexText("Area = 1") area_label.scale(self.area_label_scale_factor) max_width = max(result.rectangle.get_width()-2*SMALL_BUFF, 0) if area_label.get_width() > max_width: area_label.set_width(max_width) area_label.move_to(result.rectangle) result.area_label = area_label result.add( result.rectangle, result.x_brace, result.recip_brace, result.labels, result.area_label, ) return result def get_rectangle(self, x): try: y = 1./x except ZeroDivisionError: y = 100 rectangle = Rectangle( width = x*self.unit_length, height = y*self.unit_length, **self.rectangle_color_kwargs ) rectangle.move_to(self.graph_origin, DOWN+LEFT) return rectangle def change_rectangle_group( self, rect_group, target_x, target_group_kwargs = None, added_anims = [], **anim_kwargs ): target_group_kwargs = target_group_kwargs or {} if "run_time" not in anim_kwargs: anim_kwargs["run_time"] = 3 target_group = self.get_rectangle_group(target_x, **target_group_kwargs) target_labels = target_group.labels labels_transform = Transform( rect_group.labels, target_group.labels ) start_x = float(rect_group.x_val) def update_rect_group(group, alpha): x = interpolate(start_x, target_x, alpha) new_group = self.get_rectangle_group(x, **target_group_kwargs) Transform(group, new_group).update(1) labels_transform.update(alpha) for l1, l2 in zip(rect_group.labels, new_group.labels): l1.move_to(l2) return rect_group self.play( UpdateFromAlphaFunc(rect_group, update_rect_group), *added_anims, **anim_kwargs ) rect_group.x_val = target_x class AskRecipriocalQuestion(Scene): def construct(self): tex = OldTex( "(\\text{What number?})", "\\cdot x = 1" ) arrow = Arrow(DOWN+LEFT, UP+RIGHT) arrow.move_to(tex[0].get_top(), DOWN+LEFT) self.play(Write(tex)) self.play(ShowCreation(arrow)) self.wait() class SquareRootOfX(Scene): CONFIG = { "square_color_kwargs" : { "stroke_color" : WHITE, "stroke_width" : 1, "fill_color" : BLUE_E, "fill_opacity" : 1, }, "bigger_square_color_kwargs" : { "stroke_color" : WHITE, "stroke_width" : 1, "fill_color" : YELLOW, "fill_opacity" : 0.7, }, "square_corner" : 6*LEFT+3*UP, "square_width" : 3, "d_sqrt_x" : 0.3, } def construct(self): self.add_title() self.introduce_square() self.nudge_square() def add_title(self): title = OldTex("f(x) = \\sqrt{x}") title.next_to(ORIGIN, RIGHT) title.to_edge(UP) self.add(title) def introduce_square(self): square = Square( side_length = self.square_width, **self.square_color_kwargs ) square.move_to(self.square_corner, UP+LEFT) area_label = OldTexText("Area $ = x$") area_label.move_to(square) bottom_brace, right_brace = braces = VGroup(*[ Brace(square, vect) for vect in (DOWN, RIGHT) ]) for brace in braces: brace.add(brace.get_text("$\\sqrt{x}$")) self.play( DrawBorderThenFill(square), Write(area_label) ) self.play(*list(map(FadeIn, braces))) self.wait() self.square = square self.area_label = area_label self.braces = braces def nudge_square(self): square = self.square area_label = self.area_label bottom_brace, right_brace = self.braces bigger_square = Square( side_length = self.square_width + self.d_sqrt_x, **self.bigger_square_color_kwargs ) bigger_square.move_to(self.square_corner, UP+LEFT) square_copy = square.copy() lines = VGroup(*[ DashedLine( ORIGIN, (self.square_width + MED_LARGE_BUFF)*vect, color = WHITE, stroke_width = 3 ).shift(s.get_corner(corner)) for corner, vect in [(DOWN+LEFT, RIGHT), (UP+RIGHT, DOWN)] for s in [square, bigger_square] ]) little_braces = VGroup(*[ Brace(VGroup(*line_pair), vect, buff = 0) for line_pair, vect in [(lines[:2], RIGHT), (lines[2:], DOWN)] ]) for brace in little_braces: tex = brace.get_text("$d\\sqrt{x}$", buff = SMALL_BUFF) tex.scale(0.8) brace.add(tex) area_increase = OldTexText("$dx$ = New area") area_increase.set_color(bigger_square.get_color()) area_increase.next_to(square, RIGHT, 4) question = OldTex("\\frac{d\\sqrt{x}}{dx} = ???") VGroup(*question[5:7]).set_color(bigger_square.get_color()) question.next_to( area_increase, DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ) self.play( Transform(square_copy, bigger_square), Animation(square), Animation(area_label), bottom_brace.next_to, bigger_square, DOWN, SMALL_BUFF, LEFT, right_brace.next_to, bigger_square, RIGHT, SMALL_BUFF, UP, ) self.play(Write(area_increase)) self.play(*it.chain( list(map(ShowCreation, lines)), list(map(FadeIn, little_braces)) )) self.play(Write(question)) self.wait() class MentionSine(TeacherStudentsScene): def construct(self): self.teacher_says("Let's tackle $\\sin(\\theta)$") self.play_student_changes("pondering", "hooray", "erm") self.wait(2) self.student_thinks("") self.zoom_in_on_thought_bubble() class NameUnitCircle(Scene): def construct(self): words = OldTexText("Unit circle") words.scale(2) words.set_color(BLUE) self.play(Write(words)) self.wait() class DerivativeOfSineIsSlope(Scene): def construct(self): tex = OldTex( "\\frac{d(\\sin(\\theta))}{d\\theta} = ", "\\text{Slope of this graph}" ) tex.set_width(FRAME_WIDTH-1) tex.to_edge(DOWN) VGroup(*tex[0][2:8]).set_color(BLUE) VGroup(*tex[1][-9:]).set_color(BLUE) self.play(Write(tex, run_time = 2)) self.wait() class IntroduceUnitCircleWithSine(GraphScene): CONFIG = { "unit_length" : 2.5, "graph_origin" : ORIGIN, "x_axis_width" : 15, "y_axis_height" : 10, "x_min" : -3, "x_max" : 3, "y_min" : -2, "y_max" : 2, "x_labeled_nums" : [-2, -1, 1, 2], "y_labeled_nums" : [-1, 1], "x_tick_frequency" : 0.5, "y_tick_frequency" : 0.5, "circle_color" : BLUE, "example_radians" : 0.8, "rotations_per_second" : 0.25, "include_radial_line_dot" : True, "remove_angle_label" : True, "line_class" : DashedLine, "theta_label" : "= 0.8", } def construct(self): self.setup_axes() self.add_title() self.introduce_unit_circle() self.draw_example_radians() self.label_sine() self.walk_around_circle() def add_title(self): title = OldTex("f(\\theta) = \\sin(\\theta)") title.to_corner(UP+LEFT) self.add(title) self.title = title def introduce_unit_circle(self): circle = self.get_unit_circle() radial_line = Line(ORIGIN, self.unit_length*RIGHT) radial_line.set_color(RED) if self.include_radial_line_dot: dot = Dot() dot.move_to(radial_line.get_end()) radial_line.add(dot) self.play(ShowCreation(radial_line)) self.play( ShowCreation(circle), Rotate(radial_line, 2*np.pi), run_time = 2, ) self.wait() self.circle = circle self.radial_line = radial_line def draw_example_radians(self): circle = self.circle radial_line = self.radial_line line = Line( ORIGIN, self.example_radians*self.unit_length*UP, color = YELLOW, ) line.shift(FRAME_X_RADIUS*RIGHT/3).to_edge(UP) line.insert_n_curves(10) line.make_smooth() arc = Arc( self.example_radians, radius = self.unit_length, color = line.get_color(), ) arc_copy = arc.copy().set_color(WHITE) brace = Brace(line, RIGHT) brace_text = brace.get_text("$\\theta%s$"%self.theta_label) brace_text.set_color(line.get_color()) theta_copy = brace_text[0].copy() self.play( GrowFromCenter(line), GrowFromCenter(brace), ) self.play(Write(brace_text)) self.wait() self.play( line.move_to, radial_line.get_end(), DOWN, FadeOut(brace) ) self.play(ReplacementTransform(line, arc)) self.wait() self.play( Rotate(radial_line, self.example_radians), ShowCreation(arc_copy) ) self.wait() arc_copy.generate_target() arc_copy.target.scale(0.2) theta_copy.generate_target() theta_copy.target.next_to( arc_copy.target, RIGHT, aligned_edge = DOWN, buff = SMALL_BUFF ) theta_copy.target.shift(SMALL_BUFF*UP) self.play(*list(map(MoveToTarget, [arc_copy, theta_copy]))) self.wait() self.angle_label = VGroup(arc_copy, theta_copy) self.example_theta_equation = brace_text def label_sine(self): radial_line = self.radial_line drop_point = radial_line.get_end()[0]*RIGHT v_line = self.line_class(radial_line.get_end(), drop_point) brace = Brace(v_line, RIGHT) brace_text = brace.get_text("$\\sin(\\theta)$") brace_text[-2].set_color(YELLOW) self.play(ShowCreation(v_line)) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() faders = [brace, brace_text, self.example_theta_equation] if self.remove_angle_label: faders += self.angle_label self.play(*list(map(FadeOut, faders))) self.v_line = v_line def walk_around_circle(self): radial_line = self.radial_line v_line = self.v_line def v_line_update(v_line): drop_point = radial_line.get_end()[0]*RIGHT v_line.put_start_and_end_on( radial_line.get_end(), drop_point ) return v_line filler_arc = self.circle.copy() filler_arc.set_color(YELLOW) curr_arc_portion = self.example_radians/(2*np.pi) filler_portion = 1 - curr_arc_portion filler_arc.pointwise_become_partial(filler_arc, curr_arc_portion, 1) self.play( Rotate(radial_line, filler_portion*2*np.pi), ShowCreation(filler_arc), UpdateFromFunc(v_line, v_line_update), run_time = filler_portion/self.rotations_per_second, rate_func=linear, ) for x in range(5): self.play( Rotate(radial_line, 2*np.pi), UpdateFromFunc(v_line, v_line_update), run_time = 1./self.rotations_per_second, rate_func=linear, ) ############## def setup_axes(self): GraphScene.setup_axes(self) VGroup(*self.x_axis.numbers[:2]).shift(MED_SMALL_BUFF*LEFT) VGroup(*self.x_axis.numbers[2:]).shift(SMALL_BUFF*RIGHT) self.y_axis.numbers[0].shift(MED_SMALL_BUFF*DOWN) self.y_axis.numbers[1].shift(MED_SMALL_BUFF*UP) def get_unit_circle(self): return Circle( radius = self.unit_length, color = self.circle_color, ) class DerivativeIntuitionFromSineGraph(GraphScene): CONFIG = { "graph_origin" : 6*LEFT, "x_axis_width" : 11, "x_min" : 0, "x_max" : 4*np.pi, "x_labeled_nums" : np.arange(0, 4*np.pi, np.pi), "x_tick_frequency" : np.pi/4, "x_axis_label" : "$\\theta$", "y_axis_height" : 6, "y_min" : -2, "y_max" : 2, "y_tick_frequency" : 0.5, "y_axis_label" : "", } def construct(self): self.setup_axes() self.draw_sine_graph() self.draw_derivative_from_slopes() self.alter_derivative_graph() def draw_sine_graph(self): graph = self.get_graph(np.sin) v_line = DashedLine(ORIGIN, UP) rps = IntroduceUnitCircleWithSine.CONFIG["rotations_per_second"] self.play( ShowCreation(graph), UpdateFromFunc(v_line, lambda v : self.v_line_update(v, graph)), run_time = 2./rps, rate_func=linear ) self.wait() self.graph = graph def draw_derivative_from_slopes(self): ss_group = self.get_secant_slope_group( 0, self.graph, dx = 0.01, secant_line_color = RED, ) deriv_graph = self.get_graph(np.cos, color = DERIVATIVE_COLOR) v_line = DashedLine( self.graph_origin, self.coords_to_point(0, 1), color = RED ) self.play(ShowCreation(ss_group, lag_ratio = 0)) self.play(ShowCreation(v_line)) self.wait() last_theta = 0 next_theta = np.pi/2 while last_theta < self.x_max: deriv_copy = deriv_graph.copy() self.animate_secant_slope_group_change( ss_group, target_x = next_theta, added_anims = [ ShowCreation( deriv_copy, rate_func = lambda t : interpolate( last_theta/self.x_max, next_theta/self.x_max, smooth(t) ), run_time = 3, ), UpdateFromFunc( v_line, lambda v : self.v_line_update(v, deriv_copy), run_time = 3 ), ] ) self.wait() if next_theta == 2*np.pi: words = OldTexText("Looks a lot like $\\cos(\\theta)$") words.next_to(self.graph_origin, RIGHT) words.to_edge(UP) arrow = Arrow( words.get_bottom(), deriv_graph.point_from_proportion(0.45) ) VGroup(words, arrow).set_color(deriv_graph.get_color()) self.play( Write(words), ShowCreation(arrow) ) self.remove(deriv_copy) last_theta = next_theta next_theta += np.pi/2 self.add(deriv_copy) self.deriv_graph = deriv_copy def alter_derivative_graph(self): func_list = [ lambda x : 0.5*(np.cos(x)**3 + np.cos(x)), lambda x : 0.75*(np.sign(np.cos(x))*np.cos(x)**2 + np.cos(x)), lambda x : 2*np.cos(x), lambda x : np.cos(x), ] for func in func_list: new_graph = self.get_graph(func, color = DERIVATIVE_COLOR) self.play( Transform(self.deriv_graph, new_graph), run_time = 2 ) self.wait() ###### def v_line_update(self, v_line, graph): point = graph.point_from_proportion(1) drop_point = point[0]*RIGHT v_line.put_start_and_end_on(drop_point, point) return v_line def setup_axes(self): GraphScene.setup_axes(self) self.x_axis.remove(self.x_axis.numbers) self.remove(self.x_axis.numbers) for x in range(1, 4): if x == 1: label = OldTex("\\pi") else: label = OldTex("%d\\pi"%x) label.next_to(self.coords_to_point(x*np.pi, 0), DOWN, MED_LARGE_BUFF) self.add(label) self.x_axis_label_mob.set_color(YELLOW) class LookToFunctionsMeaning(TeacherStudentsScene): def construct(self): self.teacher_says(""" Look to the function's actual meaning """) self.play_student_changes(*["pondering"]*3) self.wait(3) class DerivativeFromZoomingInOnSine(IntroduceUnitCircleWithSine, ZoomedScene): CONFIG = { "zoom_factor" : 10, "zoomed_canvas_frame_shape" : (3, 4.5), "include_radial_line_dot" : False, "remove_angle_label" : False, "theta_label" : "", "line_class" : Line, "example_radians" : 1.0, "zoomed_canvas_corner_buff" : SMALL_BUFF, "d_theta" : 0.05, } def construct(self): self.setup_axes() self.add_title() self.introduce_unit_circle() self.draw_example_radians() self.label_sine() self.zoom_in() self.perform_nudge() self.show_similar_triangles() self.analyze_ratios() def zoom_in(self): self.activate_zooming() self.little_rectangle.next_to(self.radial_line.get_end(), UP, LARGE_BUFF) self.play(*list(map(FadeIn, [ self.little_rectangle, self.big_rectangle ]))) self.play( self.little_rectangle.move_to, self.radial_line.get_end(), DOWN+RIGHT, self.little_rectangle.shift, SMALL_BUFF*(DOWN+RIGHT) ) self.wait() def perform_nudge(self): d_theta_arc = Arc( start_angle = self.example_radians, angle = self.d_theta, radius = self.unit_length, color = MAROON_B, stroke_width = 6 ) d_theta_arc.scale(self.zoom_factor) d_theta_brace = Brace( d_theta_arc, rotate_vector(RIGHT, self.example_radians) ) d_theta_label = OldTex("d\\theta") d_theta_label.next_to( d_theta_brace.get_center(), d_theta_brace.direction, MED_LARGE_BUFF ) d_theta_label.set_color(d_theta_arc.get_color()) group = VGroup(d_theta_arc, d_theta_brace, d_theta_label) group.scale(1./self.zoom_factor) point = self.radial_line.get_end() nudged_point = d_theta_arc.point_from_proportion(1) interim_point = nudged_point[0]*RIGHT+point[1]*UP h_line = DashedLine( interim_point, point, dash_length = 0.01 ) d_sine_line = Line(interim_point, nudged_point, color = DERIVATIVE_COLOR) d_sine_brace = Brace(Line(ORIGIN, UP), LEFT) d_sine_brace.set_height(d_sine_line.get_height()) d_sine_brace.next_to(d_sine_line, LEFT, buff = SMALL_BUFF/self.zoom_factor) d_sine = OldTex("d(\\sin(\\theta))") d_sine.set_color(d_sine_line.get_color()) d_sine.set_width(1.5*self.d_theta*self.unit_length) d_sine.next_to(d_sine_brace, LEFT, SMALL_BUFF/self.zoom_factor) self.play(ShowCreation(d_theta_arc)) self.play( GrowFromCenter(d_theta_brace), FadeIn(d_theta_label) ) self.wait() self.play( ShowCreation(h_line), ShowCreation(d_sine_line) ) self.play( GrowFromCenter(d_sine_brace), Write(d_sine) ) self.wait() self.little_triangle = Polygon( nudged_point, point, interim_point ) self.d_theta_group = VGroup(d_theta_brace, d_theta_label) self.d_sine_group = VGroup(d_sine_brace, d_sine) def show_similar_triangles(self): little_triangle = self.little_triangle big_triangle = Polygon( self.graph_origin, self.radial_line.get_end(), self.radial_line.get_end()[0]*RIGHT, ) for triangle in little_triangle, big_triangle: triangle.set_color(GREEN) triangle.set_fill(GREEN, opacity = 0.5) big_triangle_copy = big_triangle.copy() big_triangle_copy.next_to(ORIGIN, UP+LEFT) new_angle_label = self.angle_label.copy() new_angle_label.scale( little_triangle.get_width()/big_triangle.get_height() ) new_angle_label.rotate(-np.pi/2) new_angle_label.shift(little_triangle.get_points()[0]) new_angle_label[1].rotate(np.pi/2) little_triangle_lines = VGroup(*[ Line(*list(map(little_triangle.get_corner, pair))) for pair in [ (DOWN+RIGHT, UP+LEFT), (UP+LEFT, DOWN+LEFT) ] ]) little_triangle_lines.set_color(little_triangle.get_color()) self.play(DrawBorderThenFill(little_triangle)) self.play( little_triangle.scale, 2, little_triangle.get_corner(DOWN+RIGHT), little_triangle.set_color, YELLOW, rate_func = there_and_back ) self.wait() groups = [self.d_theta_group, self.d_sine_group] for group, line in zip(groups, little_triangle_lines): self.play(ApplyMethod( line.rotate, np.pi/12, rate_func = wiggle, remover = True, )) self.play( group.scale, 1.2, group.get_corner(DOWN+RIGHT), group.set_color, YELLOW, rate_func = there_and_back, ) self.wait() self.play(ReplacementTransform( little_triangle.copy().set_fill(opacity = 0), big_triangle_copy, path_arc = np.pi/2, run_time = 2 )) self.wait() self.play( ReplacementTransform(big_triangle_copy, big_triangle), Animation(self.angle_label) ) self.wait() self.play( self.radial_line.rotate, np.pi/12, Animation(big_triangle), rate_func = wiggle, ) self.wait() self.play( ReplacementTransform( big_triangle.copy().set_fill(opacity = 0), little_triangle, path_arc = -np.pi/2, run_time = 3, ), ReplacementTransform( self.angle_label.copy(), new_angle_label, path_arc = -np.pi/2, run_time = 3, ), ) self.play( new_angle_label.scale, 2, new_angle_label.set_color, RED, rate_func = there_and_back ) self.wait() def analyze_ratios(self): d_ratio = OldTex("\\frac{d(\\sin(\\theta))}{d\\theta} = ") VGroup(*d_ratio[:9]).set_color(GREEN) VGroup(*d_ratio[10:12]).set_color(MAROON_B) trig_ratio = OldTex("\\frac{\\text{Adj.}}{\\text{Hyp.}}") VGroup(*trig_ratio[:4]).set_color(GREEN) VGroup(*trig_ratio[5:9]).set_color(MAROON_B) cos = OldTex("= \\cos(\\theta)") cos.add_background_rectangle() group = VGroup(d_ratio, trig_ratio, cos) group.arrange() group.next_to( self.title, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) for mob in group: self.play(Write(mob)) self.wait() class TryWithCos(Scene): def construct(self): words = OldTexText("What about $\\cos(\\theta)$?") words.set_color(YELLOW) self.play(Write(words)) self.wait() class NextVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() next_video = series[3] series.to_edge(UP) d_sum = OldTex("\\frac{d}{dx}(x^3 + x^2)") d_product = OldTex("\\frac{d}{dx} \\sin(x)x^2") d_composition = OldTex("\\frac{d}{dx} \\cos\\left(\\frac{1}{x}\\right)") group = VGroup(d_sum, d_product, d_composition) group.arrange(RIGHT, buff = 2*LARGE_BUFF) group.next_to(VGroup(*self.get_pi_creatures()), UP, buff = LARGE_BUFF) self.play( FadeIn( series, lag_ratio = 0.5, run_time = 3, ), *[ ApplyMethod(pi.look_at, next_video) for pi in self.get_pi_creatures() ] ) self.play( next_video.set_color, YELLOW, next_video.shift, MED_LARGE_BUFF*DOWN ) self.wait() for mob in group: self.play( Write(mob, run_time = 1), *[ ApplyMethod(pi.look_at, mob) for pi in self.get_pi_creatures() ] ) self.wait(3) class Chapter3PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "CrypticSwarm ", "Yu Jun", "Shelby Doolittle", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Guido Gambardella", "Jerry Ling", "Mark Govea", "Vecht ", "Jonathan Eppele", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } class Promotion(PiCreatureScene): CONFIG = { "seconds_to_blink" : 5, } def construct(self): url = OldTexText("https://brilliant.org/3b1b/") url.to_corner(UP+LEFT) rect = Rectangle(height = 9, width = 16) rect.set_height(5.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) self.play( Write(url), self.pi_creature.change, "raise_right_hand" ) self.play(ShowCreation(rect)) self.wait(2) self.change_mode("thinking") self.wait() self.look_at(url) self.wait(10) self.change_mode("happy") self.wait(10) self.change_mode("raise_right_hand") self.wait(10) class Thumbnail(NudgeSideLengthOfCube): def construct(self): self.introduce_cube() VGroup(*self.get_mobjects()).to_edge(DOWN) formula = OldTex( "\\frac{d(x^3)}{dx} = 3x^2" ) VGroup(*formula[:5]).set_color(YELLOW) VGroup(*formula[-3:]).set_color(GREEN_B) formula.set_width(FRAME_X_RADIUS-1) formula.to_edge(RIGHT) self.add(formula) title = OldTexText("Geometric derivatives") title.set_width(FRAME_WIDTH-1) title.to_edge(UP) self.add(title)
videos_3b1b/_2017/eoc/chapter9.py
import scipy import fractions from manim_imports_ext import * class Chapter9OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "We often hear that mathematics consists mainly of", "proving theorems.", "Is a writer's job mainly that of\\\\", "writing sentences?" ], "highlighted_quote_terms" : { "proving theorems." : MAROON_B, "writing sentences?" : MAROON_B, }, "author" : "Gian-Carlo Rota", } class AverageOfContinuousVariable(GraphScene): CONFIG = { "bounds" : [1, 7], "bound_colors" : [RED, GREEN], } def construct(self): self.setup_axes() graph = self.get_graph( lambda x : 0.1*x*(x-3)*(x-6) + 4 ) graph_label = self.get_graph_label(graph, "f(x)") boundary_lines = self.get_vertical_lines_to_graph( graph, *self.bounds, num_lines = 2, line_class = DashedLine ) for line, color in zip(boundary_lines, self.bound_colors): line.set_color(color) v_line = self.get_vertical_line_to_graph( self.bounds[0], graph, color = YELLOW, ) question = OldTexText( "What is the average \\\\ value of $f(x)$?" ) question.next_to(boundary_lines, UP) self.play(ShowCreation(graph), Write(graph_label)) self.play(ShowCreation(boundary_lines)) self.play(FadeIn( question, run_time = 2, lag_ratio = 0.5, )) self.play(ShowCreation(v_line)) for bound in reversed(self.bounds): self.play(self.get_v_line_change_anim( v_line, graph, bound, run_time = 3, )) self.wait() self.wait() def get_v_line_change_anim(self, v_line, graph, target_x, **kwargs): start_x = self.x_axis.point_to_number(v_line.get_bottom()) def update(v_line, alpha): new_x = interpolate(start_x, target_x, alpha) v_line.put_start_and_end_on( self.coords_to_point(new_x, 0), self.input_to_graph_point(new_x, graph) ) return v_line return UpdateFromAlphaFunc(v_line, update, **kwargs) class ThisVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) this_video = series[8] self.play(FadeIn(series, lag_ratio = 0.5)) self.teacher_says( "A new view of \\\\ the fundamental theorem", bubble_config = {"height" : 3}, added_anims = [ this_video.shift, this_video.get_height()*DOWN/2, this_video.set_color, YELLOW, ] ) self.play_student_changes(*["pondering"]*3) self.wait(3) class AverageOfSineStart(AverageOfContinuousVariable): CONFIG = { "y_min" : -2, "y_max" : 2, "x_min" : -1, "x_max" : 2.5*np.pi, "x_leftmost_tick" : 0, "x_tick_frequency" : np.pi/4, "x_axis_width" : 12, "graph_origin" : 5*LEFT, "x_label_scale_val" : 0.75, "func" : np.sin, "graph_color" : BLUE, "bounds" : [0, np.pi], } def construct(self): self.setup_axes() self.add_graph() self.ask_about_average() def add_graph(self, run_time = 1): graph = self.get_graph(self.func, color = self.graph_color) graph_label = self.get_graph_label( graph, "\\sin(x)", direction = UP ) self.play( ShowCreation(graph), Write(graph_label), run_time = run_time ) self.graph = graph self.graph_label = graph_label def ask_about_average(self): half_period_graph = self.get_graph_portion_between_bounds() question = OldTexText("Average height?") question.to_edge(UP) arrow = Arrow(question.get_bottom(), half_period_graph.get_top()) midpoint = np.mean(self.bounds) v_line = self.get_vertical_line_to_graph( midpoint, self.graph, line_class = DashedLine, color = WHITE ) self.play(FadeIn(half_period_graph)) self.play( Write(question, run_time = 2), ShowCreation(arrow) ) self.play(ShowCreation(v_line)) for bound in self.bounds + [midpoint]: self.play(self.get_v_line_change_anim( v_line, self.graph, bound, run_time = 3 )) ######### def get_graph_portion_between_bounds(self): self.graph_portion_between_bounds = self.get_graph( self.func, x_min = self.bounds[0], x_max = self.bounds[1], color = YELLOW ) return self.graph_portion_between_bounds def setup_axes(self): GraphScene.setup_axes(self) self.add_x_axis_labels() def add_x_axis_labels(self): labels_and_x_values = [ ("\\pi/2", np.pi/2), ("\\pi", np.pi), ("3\\pi/2", 3*np.pi/2), ("2\\pi", 2*np.pi), ] self.x_axis_labels = VGroup() for label, x in labels_and_x_values: tex_mob = OldTex(label) tex_mob.scale(self.x_label_scale_val) tex_mob.move_to( self.coords_to_point(x, -3*self.x_axis.tick_size), ) self.add(tex_mob) self.x_axis_labels.add(tex_mob) class LengthOfDayGraph(GraphScene): CONFIG = { "x_min" : 0, "x_max" : 365, "x_axis_width" : 12, "x_tick_frequency" : 25, "x_labeled_nums" : list(range(50, 365, 50)), "x_axis_label" : "Days since March 21", "y_min" : 0, "y_max" : 16, "y_axis_height" : 6, "y_tick_frequency" : 1, "y_labeled_nums" : list(range(2, 15, 2)), "y_axis_label" : "Hours of daylight", "graph_origin" : 6*LEFT + 3*DOWN, "camera_class" : ThreeDCamera, "camera_config" : { "shading_factor" : 1, } } def construct(self): self.setup_axes() self.add_graph() self.show_solar_pannel() self.set_color_summer_months() self.mention_constants() def add_graph(self): x_label = self.x_axis_label_mob y_label = self.y_axis_label_mob graph = self.get_graph( lambda x : 2.7*np.sin((2*np.pi)*x/365 ) + 12.4, color = GREEN, ) graph_label = OldTex("2.7\\sin(2\\pi x/365) + 12.4") graph_label.to_corner(UP+RIGHT).shift(LEFT) VGroup(*graph_label[3:6]).set_color(graph.get_color()) graph_label[9].set_color(YELLOW) self.remove(x_label, y_label) for label in y_label, x_label: self.play(FadeIn( label, run_time = 2, lag_ratio = 0.5 )) self.play( ShowCreation(graph, rate_func=linear), FadeIn( graph_label, rate_func = squish_rate_func(smooth, 0.5, 1), lag_ratio = 0.5 ), run_time = 3, ) self.wait() self.graph = graph self.graph_label = graph_label def show_solar_pannel(self): randy = Randolph() randy.to_edge(DOWN) panel = ThreeDMobject(*[ Rectangle( height = 0.7, width = 0.25, fill_color = GREY_D, fill_opacity = 1, stroke_width = 1, stroke_color = GREY, ) for x in range(6) ]) panel.arrange(RIGHT, buff = SMALL_BUFF) panel.center() panels = ThreeDMobject(panel, panel.copy(), panel.copy()) panels.arrange(DOWN) panels.rotate(4*np.pi/12, DOWN) panels.rotate(-np.pi/6, OUT) side_vect = RIGHT side_vect = rotate_vector(side_vect, 4*np.pi/12, DOWN) side_vect = rotate_vector(side_vect, -np.pi/3, OUT) panels.next_to(randy.get_corner(UP+RIGHT), RIGHT) self.play(FadeIn(randy)) self.play( randy.change, "thinking", panels.get_right(), FadeIn( panels, run_time = 2, lag_ratio = 0.5 ) ) for angle in -np.pi/4, np.pi/4: self.play(*[ Rotate( panel, angle, axis = side_vect, in_place = True, run_time = 2, rate_func = squish_rate_func(smooth, a, a+0.8) ) for panel, a in zip(panels, np.linspace(0, 0.2, len(panels))) ]) self.play(Blink(randy)) self.play(*list(map(FadeOut, [randy, panels]))) def set_color_summer_months(self): summer_rect = Rectangle() summer_rect.set_stroke(width = 0) summer_rect.set_fill(YELLOW, opacity = 0.25) summer_rect.replace(Line( self.graph_origin, self.coords_to_point(365/2, 15.5) ), stretch = True) winter_rect = Rectangle() winter_rect.set_stroke(width = 0) winter_rect.set_fill(BLUE, opacity = 0.25) winter_rect.replace(Line( self.coords_to_point(365/2, 15.5), self.coords_to_point(365, 0), ), stretch = True) summer_words, winter_words = [ OldTexText("%s \\\\ months"%s).move_to(rect) for s, rect in [ ("Summer", summer_rect), ("Winter", winter_rect), ] ] for rect, words in (summer_rect, summer_words), (winter_rect, winter_words): self.play( FadeIn(rect), Write(words, run_time = 2) ) self.wait() def mention_constants(self): #2.7\\sin(2\\pi t/365) + 12.4 constants = VGroup(*[ VGroup(*self.graph_label[i:j]) for i, j in [(0, 3), (7, 9), (11, 14), (16, 20)] ]) self.play(*[ ApplyFunction( lambda c : c.scale(0.9).shift(SMALL_BUFF*DOWN).set_color(RED), constant, run_time = 3, rate_func = squish_rate_func(there_and_back, a, a+0.7) ) for constant, a in zip( constants, np.linspace(0, 0.3, len(constants)) ) ]) self.wait() ##### class AskAboutAverageOfContinuousVariables(TeacherStudentsScene): def construct(self): self.student_says( "The average \\dots of a \\\\ continuous thing?", target_mode = "sassy", ) self.play_student_changes("confused", "sassy", "confused") self.play(self.teacher.change_mode, "happy") self.wait(2) class AverageOfFiniteSet(Scene): CONFIG = { "lengths" : [1, 4, 2, 5] } def construct(self): lengths = self.lengths lines = VGroup(*[ Line(ORIGIN, length*RIGHT) for length in lengths ]) colors = Color(BLUE).range_to(RED, len(lengths)) lines.set_color_by_gradient(*colors) lines.arrange(RIGHT) lines.generate_target() lines.target.arrange(RIGHT, buff = 0) for mob in lines, lines.target: mob.shift(UP) brace = Brace(lines.target, UP) labels = VGroup(*[ OldTex(str(d)).next_to(line, UP).set_color(line.get_color()) for d, line in zip(lengths, lines) ]) plusses = [Tex("+") for x in range(len(lengths)-1)] symbols = VGroup(* plusses + [Tex("=")] ) symbols.set_fill(opacity = 0) labels.generate_target() symbols.generate_target() symbols.target.set_fill(opacity = 1) sum_eq = VGroup(*it.chain(*list(zip(labels.target, symbols.target)))) sum_eq.arrange(RIGHT) sum_eq.next_to(brace, UP) sum_mob = OldTex(str(sum(lengths))) sum_mob.next_to(sum_eq, RIGHT) dividing_lines = VGroup(*[ DashedLine(p + MED_SMALL_BUFF*UP, p + MED_LARGE_BUFF*DOWN) for alpha in np.linspace(0, 1, len(lengths)+1) for p in [interpolate( lines.target.get_left(), lines.target.get_right(), alpha )] ]) lower_braces = VGroup(*[ Brace(VGroup(*dividing_lines[i:i+2]), DOWN) for i in range(len(lengths)) ]) averages = VGroup(*[ lb.get_text("$%d/%d$"%(sum(lengths), len(lengths))) for lb in lower_braces ]) circle = Circle(color = YELLOW) circle.replace(averages[1], stretch = True) circle.scale(1.5) self.add(lines) self.play(FadeIn( labels, lag_ratio = 0.5, run_time = 3 )) self.wait() self.play( GrowFromCenter(brace), *list(map(MoveToTarget, [lines, labels, symbols])), run_time = 2 ) self.play(Write(sum_mob)) self.wait() self.play(ShowCreation(dividing_lines, run_time = 2)) self.play(*it.chain( list(map(Write, averages)), list(map(GrowFromCenter, lower_braces)) )) self.play(ShowCreation(circle)) self.wait(2) class TryToAddInfinitelyManyPoints(AverageOfSineStart): CONFIG = { "max_denominator" : 40, } def construct(self): self.add_graph() self.try_to_add_infinitely_many_values() self.show_continuum() self.mention_integral() def add_graph(self): self.setup_axes() AverageOfSineStart.add_graph(self, run_time = 0) self.add(self.get_graph_portion_between_bounds()) self.graph_label.to_edge(RIGHT) self.graph_label.shift(DOWN) def try_to_add_infinitely_many_values(self): v_lines = VGroup(*[ self.get_vertical_line_to_graph( numerator*np.pi/denominator, self.graph, color = YELLOW, stroke_width = 6./denominator ) for denominator in range(self.max_denominator) for numerator in range(1, denominator) if fractions.gcd(numerator, denominator) == 1 ]) ghost_lines = v_lines.copy().set_stroke(GREY) v_lines.generate_target() start_lines = VGroup(*v_lines.target[:15]) end_lines = VGroup(*v_lines.target[15:]) plusses = VGroup(*[Tex("+") for x in start_lines]) sum_eq = VGroup(*it.chain(*list(zip(start_lines, plusses)))) sum_eq.add(*end_lines) sum_eq.arrange(RIGHT) sum_eq.next_to(v_lines[0], UP, aligned_edge = LEFT) sum_eq.to_edge(UP, buff = MED_SMALL_BUFF) h_line = Line(LEFT, RIGHT) h_line.set_width(start_lines.get_width()) h_line.set_color(WHITE) h_line.next_to(sum_eq, DOWN, aligned_edge = LEFT) infinity = OldTex("\\infty") infinity.next_to(h_line, DOWN) self.play(ShowCreation( v_lines, run_time = 3, )) self.add(ghost_lines, v_lines) self.wait(2) self.play( MoveToTarget( v_lines, run_time = 3, lag_ratio = 0.5 ), Write(plusses) ) self.play(ShowCreation(h_line)) self.play(Write(infinity)) self.wait() def show_continuum(self): arrow = Arrow(ORIGIN, UP+LEFT) input_range = Line(*[ self.coords_to_point(bound, 0) for bound in self.bounds ]) VGroup(arrow, input_range).set_color(RED) self.play(FadeIn(arrow)) self.play( arrow.next_to, input_range.get_start(), DOWN+RIGHT, SMALL_BUFF ) self.play( arrow.next_to, input_range.copy().get_end(), DOWN+RIGHT, SMALL_BUFF, ShowCreation(input_range), run_time = 3, ) self.play( arrow.next_to, input_range.get_start(), DOWN+RIGHT, SMALL_BUFF, run_time = 3 ) self.play(FadeOut(arrow)) self.wait() def mention_integral(self): randy = Randolph() randy.to_edge(DOWN) randy.shift(3*LEFT) self.play(FadeIn(randy)) self.play(PiCreatureBubbleIntroduction( randy, "Use an integral!", bubble_type = ThoughtBubble, target_mode = "hooray" )) self.play(Blink(randy)) curr_bubble = randy.bubble new_bubble = randy.get_bubble("Somehow...") self.play( Transform(curr_bubble, new_bubble), Transform(curr_bubble.content, new_bubble.content), randy.change_mode, "shruggie", ) self.play(Blink(randy)) self.wait() class FiniteSample(TryToAddInfinitelyManyPoints): CONFIG = { "dx" : 0.1, "graph_origin" : 6*LEFT + 0.5*DOWN, } def construct(self): self.add_graph() self.show_finite_sample() def show_finite_sample(self): v_lines = self.get_sample_lines(dx = self.dx) summed_v_lines = v_lines.copy() plusses = VGroup(*[ OldTex("+").scale(0.75) for l in v_lines ]) numerator = VGroup(*it.chain(*list(zip(summed_v_lines, plusses)))) for group in numerator, plusses: group.remove(plusses[-1]) numerator.arrange( RIGHT, buff = SMALL_BUFF, aligned_edge = DOWN ) # numerator.set_width(FRAME_X_RADIUS) numerator.scale(0.5) numerator.move_to(self.coords_to_point(3*np.pi/2, 0)) numerator.to_edge(UP) frac_line = OldTex("\\over \\,") frac_line.stretch_to_fit_width(numerator.get_width()) frac_line.next_to(numerator, DOWN) denominator = OldTexText("(Num. samples)") denominator.next_to(frac_line, DOWN) self.play(ShowCreation(v_lines, run_time = 3)) self.wait() self.play( ReplacementTransform( v_lines.copy(), summed_v_lines, run_time = 3, lag_ratio = 0.5 ), Write( plusses, rate_func = squish_rate_func(smooth, 0.3, 1) ) ) self.play(Write(frac_line, run_time = 1)) self.play(Write(denominator)) self.wait() self.plusses = plusses self.average = VGroup(numerator, frac_line, denominator) self.v_lines = v_lines ### def get_sample_lines(self, dx, color = YELLOW, stroke_width = 2): return VGroup(*[ self.get_vertical_line_to_graph( x, self.graph, color = color, stroke_width = stroke_width, ) for x in np.arange( self.bounds[0]+dx, self.bounds[1], dx ) ]) class FiniteSampleWithMoreSamplePoints(FiniteSample): CONFIG = { "dx" : 0.05 } class FeelsRelatedToAnIntegral(TeacherStudentsScene): def construct(self): self.student_says( "Seems integral-ish...", target_mode = "maybe" ) self.play(self.teacher.change_mode, "happy") self.wait(2) class IntegralOfSine(FiniteSample): CONFIG = { "thin_dx" : 0.01, "rect_opacity" : 0.75, } def construct(self): self.force_skipping() FiniteSample.construct(self) self.remove(self.y_axis_label_mob) self.remove(*self.x_axis_labels[::2]) self.revert_to_original_skipping_status() self.put_average_in_corner() self.write_integral() self.show_riemann_rectangles() self.let_dx_approach_zero() self.bring_back_average() self.distribute_dx() self.let_dx_approach_zero(restore = False) self.write_area_over_width() self.show_moving_v_line() def put_average_in_corner(self): self.average.save_state() self.plusses.set_stroke(width = 0.5) self.play( self.average.scale, 0.75, self.average.to_corner, DOWN+RIGHT, ) def write_integral(self): integral = OldTex("\\int_0^\\pi", "\\sin(x)", "\\,dx") integral.move_to(self.graph_portion_between_bounds) integral.to_edge(UP) self.play(Write(integral)) self.wait(2) self.integral = integral def show_riemann_rectangles(self): kwargs = { "dx" : self.dx, "x_min" : self.bounds[0], "x_max" : self.bounds[1], "fill_opacity" : self.rect_opacity, } rects = self.get_riemann_rectangles(self.graph, **kwargs) rects.set_stroke(YELLOW, width = 1) flat_rects = self.get_riemann_rectangles( self.get_graph(lambda x : 0), **kwargs ) thin_kwargs = dict(kwargs) thin_kwargs["dx"] = self.thin_dx thin_kwargs["stroke_width"] = 0 self.thin_rects = self.get_riemann_rectangles( self.graph, **thin_kwargs ) start_index = 20 end_index = start_index + 5 low_opacity = 0.5 high_opacity = 1 start_rect = rects[start_index] side_brace = Brace(start_rect, LEFT, buff = SMALL_BUFF) bottom_brace = Brace(start_rect, DOWN, buff = SMALL_BUFF) sin_x = OldTex("\\sin(x)") sin_x.next_to(side_brace, LEFT, SMALL_BUFF) dx = bottom_brace.get_text("$dx$", buff = SMALL_BUFF) self.transform_between_riemann_rects( flat_rects, rects, replace_mobject_with_target_in_scene = True, ) self.remove(self.v_lines) self.wait() rects.save_state() self.play(*it.chain( [ ApplyMethod( rect.set_style_data, BLACK, 1, None, #Fill color high_opacity if rect is start_rect else low_opacity ) for rect in rects ], list(map(GrowFromCenter, [side_brace, bottom_brace])), list(map(Write, [sin_x, dx])), )) self.wait() for i in range(start_index+1, end_index): self.play( rects[i-1].set_fill, None, low_opacity, rects[i].set_fill, None, high_opacity, side_brace.set_height, rects[i].get_height(), side_brace.next_to, rects[i], LEFT, SMALL_BUFF, bottom_brace.next_to, rects[i], DOWN, SMALL_BUFF, MaintainPositionRelativeTo(sin_x, side_brace), MaintainPositionRelativeTo(dx, bottom_brace), ) self.wait() self.play( rects.restore, *list(map(FadeOut, [sin_x, dx, side_brace, bottom_brace])) ) self.rects = rects self.dx_brace = bottom_brace self.dx_label = dx def let_dx_approach_zero(self, restore = True): start_state = self.rects.copy() self.transform_between_riemann_rects( self.rects, self.thin_rects, run_time = 3 ) self.wait(2) if restore: self.transform_between_riemann_rects( self.rects, start_state.copy(), run_time = 2, ) self.remove(self.rects) self.rects = start_state self.rects.set_fill(opacity = 1) self.play( self.rects.set_fill, None, self.rect_opacity, ) self.wait() def bring_back_average(self): num_samples = self.average[-1] example_dx = OldTex("0.1") example_dx.move_to(self.dx_label) input_range = Line(*[ self.coords_to_point(bound, 0) for bound in self.bounds ]) input_range.set_color(RED) #Bring back average self.play( self.average.restore, self.average.center, self.average.to_edge, UP, self.integral.to_edge, DOWN, run_time = 2 ) self.wait() self.play( Write(self.dx_brace), Write(self.dx_label), ) self.wait() self.play( FadeOut(self.dx_label), FadeIn(example_dx) ) self.play(Indicate(example_dx)) self.wait() self.play(ShowCreation(input_range)) self.play(FadeOut(input_range)) self.wait() #Ask how many there are num_samples_copy = num_samples.copy() v_lines = self.v_lines self.play(*[ ApplyFunction( lambda l : l.shift(0.5*UP).set_color(GREEN), line, rate_func = squish_rate_func( there_and_back, a, a+0.3 ), run_time = 3, ) for line, a in zip( self.v_lines, np.linspace(0, 0.7, len(self.v_lines)) ) ] + [ num_samples_copy.set_color, GREEN ]) self.play(FadeOut(v_lines)) self.wait() #Count number of samples num_samples_copy.generate_target() num_samples_copy.target.shift(DOWN + 0.5*LEFT) rhs = OldTex("\\approx", "\\pi", "/", "0.1") rhs.next_to(num_samples_copy.target, RIGHT) self.play( MoveToTarget(num_samples_copy), Write(rhs.get_part_by_tex("approx")), ) self.play(ShowCreation(input_range)) self.play(ReplacementTransform( self.x_axis_labels[1].copy(), rhs.get_part_by_tex("pi") )) self.play(FadeOut(input_range)) self.play( ReplacementTransform( example_dx.copy(), rhs.get_part_by_tex("0.1") ), Write(rhs.get_part_by_tex("/")) ) self.wait(2) #Substitute number of samples self.play(ReplacementTransform( example_dx, self.dx_label )) dx = rhs.get_part_by_tex("0.1") self.play(Transform( dx, OldTex("dx").move_to(dx) )) self.wait(2) approx = rhs.get_part_by_tex("approx") rhs.remove(approx) self.play( FadeOut(num_samples), FadeOut(num_samples_copy), FadeOut(approx), rhs.next_to, self.average[1], DOWN ) self.wait() self.pi_over_dx = rhs def distribute_dx(self): numerator, frac_line, denominator = self.average pi, over, dx = self.pi_over_dx integral = self.integral dx.generate_target() lp, rp = parens = OldTex("()") parens.set_height(numerator.get_height()) lp.next_to(numerator, LEFT) rp.next_to(numerator, RIGHT) dx.target.next_to(rp, RIGHT) self.play( MoveToTarget(dx, path_arc = np.pi/2), Write(parens), frac_line.stretch_to_fit_width, parens.get_width() + dx.get_width(), frac_line.shift, dx.get_width()*RIGHT/2, FadeOut(over) ) self.wait(2) average = VGroup(parens, numerator, dx, frac_line, pi) integral.generate_target() over_pi = OldTex("\\frac{\\phantom{\\int \\sin(x)\\dx}}{\\pi}") integral.target.set_width(over_pi.get_width()) integral.target.next_to(over_pi, UP) integral_over_pi = VGroup(integral.target, over_pi) integral_over_pi.to_corner(UP+RIGHT) arrow = Arrow(LEFT, RIGHT) arrow.next_to(integral.target, LEFT) self.play( average.scale, 0.9, average.next_to, arrow, LEFT, average.shift_onto_screen, ShowCreation(arrow), Write(over_pi), MoveToTarget(integral, run_time = 2) ) self.wait(2) self.play(*list(map(FadeOut, [self.dx_label, self.dx_brace]))) self.integral_over_pi = VGroup(integral, over_pi) self.average = average self.average_arrow = arrow def write_area_over_width(self): self.play( self.integral_over_pi.shift, 2*LEFT, *list(map(FadeOut, [self.average, self.average_arrow])) ) average_height = OldTexText("Average height = ") area_over_width = OldTex( "{\\text{Area}", "\\over\\,", "\\text{Width}}", "=" ) area_over_width.get_part_by_tex("Area").set_color_by_gradient( BLUE, GREEN ) area_over_width.next_to(self.integral_over_pi[1][0], LEFT) average_height.next_to(area_over_width, LEFT) self.play(*list(map(FadeIn, [average_height, area_over_width]))) self.wait() def show_moving_v_line(self): mean = np.mean(self.bounds) v_line = self.get_vertical_line_to_graph( mean, self.graph, line_class = DashedLine, color = WHITE, ) self.play(ShowCreation(v_line)) for count in range(2): for x in self.bounds + [mean]: self.play(self.get_v_line_change_anim( v_line, self.graph, x, run_time = 3 )) class Approx31(Scene): def construct(self): tex = OldTex("\\approx 31") tex.set_width(FRAME_WIDTH - LARGE_BUFF) tex.to_edge(LEFT) self.play(Write(tex)) self.wait(3) class LetsSolveThis(TeacherStudentsScene): def construct(self): expression = OldTex( "{\\int_0^\\pi ", " \\sin(x)", "\\,dx \\over \\pi}" ) expression.to_corner(UP+LEFT) question = OldTexText( "What's the antiderivative \\\\ of", "$\\sin(x)$", "?" ) for tex_mob in expression, question: tex_mob.set_color_by_tex("sin", BLUE) self.add(expression) self.teacher_says("Let's compute it.") self.wait() self.student_thinks(question) self.wait(2) class Antiderivative(AverageOfSineStart): CONFIG = { "antideriv_color" : GREEN, "deriv_color" : BLUE, "riemann_rect_dx" : 0.01, "y_axis_label" : "", "graph_origin" : 4*LEFT + DOWN, } def construct(self): self.setup_axes() self.add_x_axis_labels() self.negate_derivative_of_cosine() self.walk_through_slopes() self.apply_ftoc() self.show_difference_in_antiderivative() self.comment_on_area() self.divide_by_pi() self.set_color_antiderivative_fraction() self.show_slope() self.bring_back_derivative() self.show_tangent_slope() def add_x_axis_labels(self): AverageOfSineStart.add_x_axis_labels(self) self.remove(*self.x_axis_labels[::2]) def negate_derivative_of_cosine(self): cos, neg_cos, sin, neg_sin = graphs = [ self.get_graph(func) for func in [ np.cos, lambda x : -np.cos(x), np.sin, lambda x : -np.sin(x), ] ] VGroup(cos, neg_cos).set_color(self.antideriv_color) VGroup(sin, neg_sin).set_color(self.deriv_color) labels = ["\\cos(x)", "-\\cos(x)", "\\sin(x)", "-\\sin(x)"] x_vals = [2*np.pi, 2*np.pi, 5*np.pi/2, 5*np.pi/2] vects = [UP, DOWN, UP, DOWN] for graph, label, x_val, vect in zip(graphs, labels, x_vals, vects): graph.label = self.get_graph_label( graph, label, x_val = x_val, direction = vect, buff = SMALL_BUFF ) derivs = [] for F, f in ("\\cos", "-\\sin"), ("-\\cos", "\\sin"): deriv = OldTex( "{d(", F, ")", "\\over\\,", "dx}", "(x)", "=", f, "(x)" ) deriv.set_color_by_tex(F, self.antideriv_color) deriv.set_color_by_tex(f, self.deriv_color) deriv.to_edge(UP) derivs.append(deriv) cos_deriv, neg_cos_deriv = derivs self.add(cos_deriv) for graph in cos, neg_sin: self.play( ShowCreation(graph, rate_func = smooth), Write( graph.label, rate_func = squish_rate_func(smooth, 0.3, 1) ), run_time = 2 ) self.wait() self.wait() self.play(*[ ReplacementTransform(*pair) for pair in [ (derivs), (cos, neg_cos), (cos.label, neg_cos.label), (neg_sin, sin), (neg_sin.label, sin.label), ] ]) self.wait(2) self.neg_cos = neg_cos self.sin = sin self.deriv = neg_cos_deriv def walk_through_slopes(self): neg_cos = self.neg_cos sin = self.sin faders = sin, sin.label for mob in faders: mob.save_state() sin_copy = self.get_graph( np.sin, x_min = 0, x_max = 2*np.pi, color = BLUE, ) v_line = self.get_vertical_line_to_graph( 0, neg_cos, line_class = DashedLine, color = WHITE ) ss_group = self.get_secant_slope_group( 0, neg_cos, dx = 0.001, secant_line_color = YELLOW ) def quad_smooth(t): return 0.25*(np.floor(4*t) + smooth((4*t) % 1)) self.play(*[ ApplyMethod(m.fade, 0.6) for m in faders ]) self.wait() self.play(*list(map(ShowCreation, ss_group)), run_time = 2) kwargs = { "run_time" : 20, "rate_func" : quad_smooth, } v_line_anim = self.get_v_line_change_anim( v_line, sin_copy, 2*np.pi, **kwargs ) self.animate_secant_slope_group_change( ss_group, target_x = 2*np.pi, added_anims = [ ShowCreation(sin_copy, **kwargs), v_line_anim ], **kwargs ) self.play( *list(map(FadeOut, [ss_group, v_line, sin_copy])) ) self.wait() self.ss_group = ss_group def apply_ftoc(self): deriv = self.deriv integral = OldTex( "\\int", "^\\pi", "_0", "\\sin(x)", "\\,dx" ) rhs = OldTex( "=", "\\big(", "-\\cos", "(", "\\pi", ")", "\\big)", "-", "\\big(", "-\\cos", "(", "0", ")", "\\big)", ) rhs.next_to(integral, RIGHT) equation = VGroup(integral, rhs) equation.to_corner(UP+RIGHT, buff = MED_SMALL_BUFF) (start_pi, end_pi), (start_zero, end_zero) = start_end_pairs = [ [ m.get_part_by_tex(tex) for m in (integral, rhs) ] for tex in ("\\pi", "0") ] for tex_mob in integral, rhs: tex_mob.set_color_by_tex("sin", self.deriv_color) tex_mob.set_color_by_tex("cos", self.antideriv_color) tex_mob.set_color_by_tex("0", YELLOW) tex_mob.set_color_by_tex("\\pi", YELLOW) self.play( Write(integral), self.deriv.scale, 0.5, self.deriv.center, self.deriv.to_edge, LEFT, MED_SMALL_BUFF, self.deriv.shift, UP, ) self.wait() self.play(FadeIn( VGroup(*[part for part in rhs if part not in [end_pi, end_zero]]), lag_ratio = 0.5, run_time = 2, )) self.wait() for start, end in start_end_pairs: self.play(ReplacementTransform( start.copy(), end, path_arc = np.pi/6, run_time = 2 )) self.wait() self.integral = integral self.rhs = rhs def show_difference_in_antiderivative(self): pi_point, zero_point = points = [ self.input_to_graph_point(x, self.neg_cos) for x in reversed(self.bounds) ] interim_point = pi_point[0]*RIGHT + zero_point[1]*UP pi_dot, zero_dot = dots = [ Dot(point, color = YELLOW) for point in points ] v_line = DashedLine(pi_point, interim_point) h_line = DashedLine(interim_point, zero_point) v_line_brace = Brace(v_line, RIGHT) two_height_label = v_line_brace.get_text( "$2$", buff = SMALL_BUFF ) two_height_label.add_background_rectangle() pi = self.x_axis_labels[1] #Horrible hack black_pi = pi.copy().set_color(BLACK) self.add(black_pi, pi) cos_tex = self.rhs.get_part_by_tex("cos") self.play(ReplacementTransform( cos_tex.copy(), pi_dot )) self.wait() moving_dot = pi_dot.copy() self.play( ShowCreation(v_line), # Animation(pi), pi.shift, 0.8*pi.get_width()*(LEFT+UP), moving_dot.move_to, interim_point, ) self.play( ShowCreation(h_line), ReplacementTransform(moving_dot, zero_dot) ) self.play(GrowFromCenter(v_line_brace)) self.wait(2) self.play(Write(two_height_label)) self.wait(2) self.v_line = v_line self.h_line = h_line self.pi_dot = pi_dot self.zero_dot = zero_dot self.v_line_brace = v_line_brace self.two_height_label = two_height_label def comment_on_area(self): rects = self.get_riemann_rectangles( self.sin, dx = self.riemann_rect_dx, stroke_width = 0, fill_opacity = 0.7, x_min = self.bounds[0], x_max = self.bounds[1], ) area_two = OldTex("2").replace( self.two_height_label ) self.play(Write(rects)) self.wait() self.play(area_two.move_to, rects) self.wait(2) self.rects = rects self.area_two = area_two def divide_by_pi(self): integral = self.integral rhs = self.rhs equals = rhs[0] rhs_without_eq = VGroup(*rhs[1:]) frac_lines = VGroup(*[ OldTex("\\over\\,").stretch_to_fit_width( mob.get_width() ).move_to(mob) for mob in (integral, rhs_without_eq) ]) frac_lines.shift( (integral.get_height()/2 + SMALL_BUFF)*DOWN ) pi_minus_zeros = VGroup(*[ OldTex("\\pi", "-", "0").next_to(line, DOWN) for line in frac_lines ]) for tex_mob in pi_minus_zeros: for tex in "pi", "0": tex_mob.set_color_by_tex(tex, YELLOW) answer = OldTex(" = \\frac{2}{\\pi}") answer.next_to( frac_lines, RIGHT, align_using_submobjects = True ) answer.shift_onto_screen() self.play( equals.next_to, frac_lines[0].copy(), RIGHT, rhs_without_eq.next_to, frac_lines[1].copy(), UP, *list(map(Write, frac_lines)) ) self.play(*[ ReplacementTransform( integral.get_part_by_tex(tex).copy(), pi_minus_zeros[0].get_part_by_tex(tex) ) for tex in ("\\pi","0") ] + [ Write(pi_minus_zeros[0].get_part_by_tex("-")) ]) self.play(*[ ReplacementTransform( rhs.get_part_by_tex( tex, substring = False ).copy(), pi_minus_zeros[1].get_part_by_tex(tex) ) for tex in ("\\pi", "-", "0") ]) self.wait(2) full_equation = VGroup( integral, frac_lines, rhs, pi_minus_zeros ) background_rect = BackgroundRectangle(full_equation, fill_opacity = 1) background_rect.stretch_in_place(1.2, dim = 1) full_equation.add_to_back(background_rect) self.play( full_equation.shift, (answer.get_width()+MED_LARGE_BUFF)*LEFT ) self.play(Write(answer)) self.wait() self.antiderivative_fraction = VGroup( rhs_without_eq, frac_lines[1], pi_minus_zeros[1] ) self.integral_fraction = VGroup( integral, frac_lines[0], pi_minus_zeros[0], equals ) def set_color_antiderivative_fraction(self): fraction = self.antiderivative_fraction big_rect = Rectangle( stroke_width = 0, fill_color = BLACK, fill_opacity = 0.75, ) big_rect.set_width(FRAME_WIDTH) big_rect.set_height(FRAME_HEIGHT) morty = Mortimer() morty.to_corner(DOWN+RIGHT) self.play( FadeIn(big_rect), FadeIn(morty), Animation(fraction) ) self.play(morty.change, "raise_right_hand", fraction) self.play(Blink(morty)) self.wait(2) self.play( FadeOut(big_rect), FadeOut(morty), Animation(fraction) ) def show_slope(self): line = Line( self.zero_dot.get_center(), self.pi_dot.get_center(), ) line.set_color(RED) line.scale(1.2) new_v_line = self.v_line.copy().set_color(RED) new_h_line = self.h_line.copy().set_color(RED) pi = OldTex("\\pi") pi.next_to(self.h_line, DOWN) self.play( FadeOut(self.rects), FadeOut(self.area_two) ) self.play(ShowCreation(new_v_line)) self.play( ShowCreation(new_h_line), Write(pi) ) self.wait() self.play(ShowCreation(line, run_time = 2)) self.wait() def bring_back_derivative(self): self.play( FadeOut(self.integral_fraction), self.deriv.scale, 1.7, self.deriv.to_corner, UP+LEFT, MED_LARGE_BUFF, self.deriv.shift, MED_SMALL_BUFF*DOWN, ) self.wait() def show_tangent_slope(self): ss_group = self.get_secant_slope_group( 0, self.neg_cos, dx = 0.001, secant_line_color = YELLOW, secant_line_length = 4, ) self.play(*list(map(ShowCreation, ss_group)), run_time = 2) for count in range(2): for x in reversed(self.bounds): self.animate_secant_slope_group_change( ss_group, target_x = x, run_time = 6, ) class GeneralAverage(AverageOfContinuousVariable): CONFIG = { "bounds" : [1, 6], "bound_colors" : [GREEN, RED], "graph_origin" : 5*LEFT + 2*DOWN, "num_rect_iterations" : 4, "max_dx" : 0.25, } def construct(self): self.setup_axes() self.add_graph() self.ask_about_average() self.show_signed_area() self.put_area_away() self.show_finite_sample() self.show_improving_samples() def add_graph(self): graph = self.get_graph(self.func) graph_label = self.get_graph_label(graph, "f(x)") v_lines = VGroup(*[ self.get_vertical_line_to_graph( x, graph, line_class = DashedLine ) for x in self.bounds ]) for line, color in zip(v_lines, self.bound_colors): line.set_color(color) labels = list(map(Tex, "ab")) for line, label in zip(v_lines, labels): vect = line.get_start()-line.get_end() label.next_to(line, vect/get_norm(vect)) label.set_color(line.get_color()) self.y_axis_label_mob.shift(0.7*LEFT) self.play( ShowCreation(graph), Write( graph_label, rate_func = squish_rate_func(smooth, 0.5, 1) ), run_time = 2 ) for line, label in zip(v_lines, labels): self.play( Write(label), ShowCreation(line) ) self.wait() self.graph = graph self.graph_label = graph_label self.bounds_labels = labels self.bound_lines = v_lines def ask_about_average(self): v_line = self.get_vertical_line_to_graph( self.bounds[0], self.graph, line_class = DashedLine, color = WHITE ) average = OldTexText("Average = ") fraction = OldTex( "{\\displaystyle \\int", "^b", "_a", "f(x)", "\\,dx", "\\over", "b", "-", "a}" ) for color, tex in zip(self.bound_colors, "ab"): fraction.set_color_by_tex(tex, color) fraction.set_color_by_tex("displaystyle", WHITE) integral = VGroup(*fraction[:5]) denominator = VGroup(*fraction[5:]) average.next_to(fraction.get_part_by_tex("over"), LEFT) group = VGroup(average, fraction) group.center().to_edge(UP).shift(LEFT) self.count = 0 def next_v_line_anim(): target = self.bounds[0] if self.count%2 == 1 else self.bounds[1] self.count += 1 return self.get_v_line_change_anim( v_line, self.graph, target, run_time = 4, ) self.play( next_v_line_anim(), Write(average, run_time = 2), ) self.play( next_v_line_anim(), Write( VGroup(*[ fraction.get_part_by_tex(tex) for tex in ("int", "f(x)", "dx", "over") ]), rate_func = squish_rate_func(smooth, 0.25, 0.75), run_time = 4 ), *[ ReplacementTransform( label.copy(), fraction.get_part_by_tex(tex, substring = False), run_time = 2 ) for label, tex in zip( self.bounds_labels, ["_a", "^b"] ) ] ) self.play( next_v_line_anim(), Write( fraction.get_part_by_tex("-"), run_time = 4, rate_func = squish_rate_func(smooth, 0.5, 0.75), ), *[ ReplacementTransform( label.copy(), fraction.get_part_by_tex(tex, substring = False), run_time = 4, rate_func = squish_rate_func(smooth, 0.25, 0.75) ) for label, tex in zip( self.bounds_labels, ["a}", "b"] ) ] ) self.play(next_v_line_anim()) self.play(FadeOut(v_line)) self.average_expression = VGroup(average, fraction) def show_signed_area(self): rect_list = self.get_riemann_rectangles_list( self.graph, self.num_rect_iterations, max_dx = self.max_dx, x_min = self.bounds[0], x_max = self.bounds[1], end_color = BLUE, fill_opacity = 0.75, stroke_width = 0.25, ) rects = rect_list[0] plus = OldTex("+") plus.move_to(self.coords_to_point(2, 2)) minus = OldTex("-") minus.move_to(self.coords_to_point(5.24, -1)) self.play(FadeIn( rects, run_time = 2, lag_ratio = 0.5 )) for new_rects in rect_list[1:]: self.transform_between_riemann_rects(rects, new_rects) self.play(Write(plus)) self.play(Write(minus)) self.wait(2) self.area = VGroup(rects, plus, minus) def put_area_away(self): self.play( FadeOut(self.area), self.average_expression.scale, 0.75, self.average_expression.to_corner, DOWN+RIGHT, ) self.wait() def show_finite_sample(self): v_lines = self.get_vertical_lines_to_graph( self.graph, x_min = self.bounds[0], x_max = self.bounds[1], color = GREEN ) for line in v_lines: if self.y_axis.point_to_number(line.get_end()) < 0: line.set_color(RED) line.save_state() line_pair = VGroup(*v_lines[6:8]) brace = Brace(line_pair, DOWN) dx = brace.get_text("$dx$") num_samples = OldTexText("Num. samples") approx = OldTex("\\approx") rhs = OldTex("{b", "-", "a", "\\over", "dx}") for tex, color in zip("ab", self.bound_colors): rhs.set_color_by_tex(tex, color) expression = VGroup(num_samples, approx, rhs) expression.arrange(RIGHT) expression.next_to(self.y_axis, RIGHT) rhs_copy = rhs.copy() f_brace = Brace(line_pair, LEFT, buff = 0) f_x = f_brace.get_text("$f(x)$") add_up_f_over = OldTex("\\text{Add up $f(x)$}", "\\over") add_up_f_over.next_to(num_samples, UP) add_up_f_over.to_edge(UP) self.play(ShowCreation(v_lines, run_time = 2)) self.play(*list(map(Write, [brace, dx]))) self.wait() self.play(Write(VGroup(num_samples, approx, *rhs[:-1]))) self.play(ReplacementTransform( dx.copy(), rhs.get_part_by_tex("dx") )) self.wait(2) self.play( FadeIn(add_up_f_over), *[ ApplyFunction( lambda m : m.fade().set_stroke(width = 2), v_line ) for v_line in v_lines ] ) self.play(*[ ApplyFunction( lambda m : m.restore().set_stroke(width = 5), v_line, run_time = 3, rate_func = squish_rate_func( there_and_back, a, a+0.2 ) ) for v_line, a in zip(v_lines, np.linspace(0, 0.8, len(v_lines))) ]) self.play(*[vl.restore for vl in v_lines]) self.play(rhs_copy.next_to, add_up_f_over, DOWN) self.wait(2) frac_line = add_up_f_over[1] self.play( FadeOut(rhs_copy.get_part_by_tex("over")), rhs_copy.get_part_by_tex("dx").next_to, add_up_f_over[0], RIGHT, SMALL_BUFF, frac_line.scale_about_point, 1.2, frac_line.get_left(), frac_line.stretch_to_fit_height, frac_line.get_height(), ) rhs_copy.remove(rhs_copy.get_part_by_tex("over")) self.wait(2) int_fraction = self.average_expression[1].copy() int_fraction.generate_target() int_fraction.target.next_to(add_up_f_over, RIGHT, LARGE_BUFF) int_fraction.target.shift_onto_screen() double_arrow = OldTex("\\Leftrightarrow") double_arrow.next_to( int_fraction.target.get_part_by_tex("over"), LEFT ) self.play( MoveToTarget(int_fraction), VGroup(add_up_f_over, rhs_copy).shift, 0.4*DOWN ) self.play(Write(double_arrow)) self.play(*list(map(FadeOut, [ dx, brace, num_samples, approx, rhs ]))) self.wait() self.v_lines = v_lines def show_improving_samples(self): stroke_width = self.v_lines[0].get_stroke_width() new_v_lines_list = [ self.get_vertical_lines_to_graph( self.graph, x_min = self.bounds[0], x_max = self.bounds[1], num_lines = len(self.v_lines)*(2**n), color = GREEN, stroke_width = float(stroke_width)/n ) for n in range(1, 4) ] for new_v_lines in new_v_lines_list: for line in new_v_lines: if self.y_axis.point_to_number(line.get_end()) < 0: line.set_color(RED) for new_v_lines in new_v_lines_list: self.play(Transform( self.v_lines, new_v_lines, run_time = 2, lag_ratio = 0.5 )) self.wait() #### def func(self, x): return 0.09*(x+1)*(x-4)*(x-8) class GeneralAntiderivative(GeneralAverage): def construct(self): self.force_skipping() self.setup_axes() self.add_graph() self.revert_to_original_skipping_status() self.fade_existing_graph() self.add_fraction() self.add_antiderivative_graph() self.show_average_in_terms_of_F() self.draw_slope() self.show_tangent_line_slopes() def fade_existing_graph(self): self.graph.fade(0.3) self.graph_label.fade(0.3) self.bound_lines.fade(0.3) def add_fraction(self): fraction = OldTex( "{\\displaystyle \\int", "^b", "_a", "f(x)", "\\,dx", "\\over", "b", "-", "a}" ) for tex, color in zip("ab", self.bound_colors): fraction.set_color_by_tex(tex, color) fraction.set_color_by_tex("display", WHITE) fraction.scale(0.8) fraction.next_to(self.y_axis, RIGHT) fraction.to_edge(UP, buff = MED_SMALL_BUFF) self.add(fraction) self.fraction = fraction def add_antiderivative_graph(self): x_max = 9.7 antideriv_graph = self.get_graph( lambda x : scipy.integrate.quad( self.graph.underlying_function, 1, x )[0], color = YELLOW, x_max = x_max, ) antideriv_graph_label = self.get_graph_label( antideriv_graph, "F(x)", x_val = x_max ) deriv = OldTex( "{dF", "\\over", "dx}", "(x)", "=", "f(x)" ) deriv.set_color_by_tex("dF", antideriv_graph.get_color()) deriv.set_color_by_tex("f(x)", BLUE) deriv.next_to( antideriv_graph_label, DOWN, MED_LARGE_BUFF, LEFT ) self.play( ShowCreation(antideriv_graph), Write( antideriv_graph_label, rate_func = squish_rate_func(smooth, 0.5, 1) ), run_time = 2, ) self.wait() self.play(Write(deriv)) self.wait() self.antideriv_graph = antideriv_graph def show_average_in_terms_of_F(self): new_fraction = OldTex( "=", "{F", "(", "b", ")", "-", "F", "(", "a", ")", "\\over", "b", "-", "a}" ) for tex, color in zip("abF", self.bound_colors+[YELLOW]): new_fraction.set_color_by_tex(tex, color) new_fraction.next_to( self.fraction.get_part_by_tex("over"), RIGHT, align_using_submobjects = True ) to_write = VGroup(*it.chain(*[ new_fraction.get_parts_by_tex(tex) for tex in "=F()-" ])) to_write.remove(new_fraction.get_parts_by_tex("-")[-1]) numerator = VGroup(*new_fraction[1:10]) denominator = VGroup(*new_fraction[-3:]) self.play(Write(to_write)) self.play(*[ ReplacementTransform( label.copy(), new_fraction.get_part_by_tex(tex), run_time = 2, rate_func = squish_rate_func(smooth, a, a+0.7) ) for label, tex, a in zip( self.bounds_labels, "ab", [0, 0.3] ) ]) self.wait() self.show_change_in_height(numerator.copy()) self.shift_antideriv_graph_up_and_down() self.play(Write(VGroup(*new_fraction[-4:]))) self.wait() h_line_brace = Brace(self.h_line, DOWN) denominator_copy = denominator.copy() a_label = self.bounds_labels[0] self.play( GrowFromCenter(h_line_brace), a_label.shift, 0.7*a_label.get_width()*LEFT, a_label.shift, 2.2*a_label.get_height()*UP, ) self.play( denominator_copy.next_to, h_line_brace, DOWN, SMALL_BUFF ) self.wait(3) def show_change_in_height(self, numerator): numerator.add_to_back(BackgroundRectangle(numerator)) a_point, b_point = points = [ self.input_to_graph_point(x, self.antideriv_graph) for x in self.bounds ] interim_point = b_point[0]*RIGHT + a_point[1]*UP v_line = Line(b_point, interim_point) h_line = Line(interim_point, a_point) VGroup(v_line, h_line).set_color(WHITE) brace = Brace(v_line, RIGHT, buff = SMALL_BUFF) graph_within_bounds = self.get_graph( self.antideriv_graph.underlying_function, x_min = self.bounds[0], x_max = self.bounds[1], color = self.antideriv_graph.get_color() ) b_label = self.bounds_labels[1] self.play( self.antideriv_graph.fade, 0.7, Animation(graph_within_bounds) ) self.play( ShowCreation(v_line), b_label.shift, b_label.get_width()*RIGHT, b_label.shift, 1.75*b_label.get_height()*DOWN, ) self.play(ShowCreation(h_line)) self.play( numerator.scale, 0.75, numerator.next_to, brace.copy(), RIGHT, SMALL_BUFF, GrowFromCenter(brace), ) self.wait(2) self.antideriv_graph.add( graph_within_bounds, v_line, h_line, numerator, brace ) self.h_line = h_line self.graph_points_at_bounds = points def shift_antideriv_graph_up_and_down(self): for vect in 2*UP, 3*DOWN, UP: self.play( self.antideriv_graph.shift, vect, run_time = 2 ) self.wait() def draw_slope(self): line = Line(*self.graph_points_at_bounds) line.set_color(PINK) line.scale(1.3) self.play(ShowCreation(line, run_time = 2)) self.wait() def show_tangent_line_slopes(self): ss_group = self.get_secant_slope_group( x = self.bounds[0], graph = self.antideriv_graph, dx = 0.001, secant_line_color = BLUE, secant_line_length = 2, ) self.play(*list(map(ShowCreation, ss_group))) for x in range(2): for bound in reversed(self.bounds): self.animate_secant_slope_group_change( ss_group, target_x = bound, run_time = 5, ) class LastVideoWrapper(Scene): def construct(self): title = OldTexText("Chapter 8: Integrals") title.to_edge(UP) rect = Rectangle(height = 9, width = 16) rect.set_stroke(WHITE) rect.set_height(1.5*FRAME_Y_RADIUS) rect.next_to(title, DOWN) self.play(Write(title), ShowCreation(rect)) self.wait(5) class ASecondIntegralSensation(TeacherStudentsScene): def construct(self): finite_average = OldTex("{1+5+4+2 \\over 4}") numbers = VGroup(*finite_average[0:7:2]) plusses = VGroup(*finite_average[1:7:2]) denominator = VGroup(*finite_average[7:]) finite_average.to_corner(UP+LEFT) finite_average.to_edge(LEFT) continuum = UnitInterval( color = GREY, unit_size = 6 ) continuum.next_to(finite_average, RIGHT, 2) line = Line(continuum.get_left(), continuum.get_right()) line.set_color(YELLOW) arrow = Arrow(DOWN+RIGHT, ORIGIN) arrow.next_to(line.get_start(), DOWN+RIGHT, SMALL_BUFF) sigma_to_integral = OldTex( "\\sum \\Leftrightarrow \\int" ) sigma_to_integral.next_to( self.teacher.get_corner(UP+LEFT), UP, MED_LARGE_BUFF ) self.teacher_says( "A second integral \\\\ sensation" ) self.play_student_changes(*["erm"]*3) self.wait() self.play( Write(numbers), RemovePiCreatureBubble(self.teacher), ) self.play_student_changes( *["pondering"]*3, look_at = numbers ) self.play(Write(plusses)) self.wait() self.play(Write(denominator)) self.wait() self.play_student_changes( *["confused"]*3, look_at = continuum, added_anims = [Write(continuum, run_time = 2)] ) self.play(ShowCreation(arrow)) arrow.save_state() self.play( arrow.next_to, line.copy().get_end(), DOWN+RIGHT, SMALL_BUFF, ShowCreation(line), run_time = 2 ) self.play(*list(map(FadeOut, [arrow]))) self.wait(2) self.play_student_changes( *["pondering"]*3, look_at = sigma_to_integral, added_anims = [ Write(sigma_to_integral), self.teacher.change_mode, "raise_right_hand" ] ) self.wait(3) class Chapter9PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "CrypticSwarm", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Zac Wentzell", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Jonathan Eppele", "Mathew Bramson", "Jerry Ling", "Mark Govea", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], } class Thumbnail(GraphScene): CONFIG = { "x_min" : -0.2, "x_max" : 3.5, "x_leftmost_tick" : 0, "x_tick_frequency" : np.pi/4, "x_axis_label" : "", "y_min" : -0.75, "y_max" : 0.75, "y_axis_height" : 4.5, "y_tick_frequency" : 0.25, "y_axis_label" : "" } def construct(self): self.setup_axes() self.remove(self.axes) sine = self.get_graph(np.sin) rects = self.get_riemann_rectangles( sine, x_min = 0, x_max = np.pi, dx = 0.01, stroke_width = 0, ) sine.add_to_back(rects) sine.add(self.axes.copy()) sine.to_corner(UP+LEFT, buff = SMALL_BUFF) sine.scale(0.9) area = OldTexText("Area") area.scale(3) area.move_to(rects) cosine = self.get_graph(lambda x : -np.cos(x)) cosine.set_stroke(GREEN, 8) line = self.get_secant_slope_group( 0.75*np.pi, cosine, dx = 0.01 ).secant_line line.set_stroke(PINK, 7) cosine.add(line) cosine.add(self.axes.copy()) cosine.scale(0.7) cosine.to_corner(DOWN+RIGHT, buff = MED_SMALL_BUFF) slope = OldTexText("Slope") slope.scale(3) # slope.next_to(cosine, LEFT, buff = 0) # slope.to_edge(DOWN) slope.to_corner(DOWN+RIGHT) double_arrow = DoubleArrow( area.get_bottom(), slope.get_left(), color = YELLOW, tip_length = 0.75, buff = MED_LARGE_BUFF ) double_arrow.set_stroke(width = 18) triangle = Polygon( ORIGIN, UP, UP+RIGHT, stroke_width = 0, fill_color = BLUE_E, fill_opacity = 0.5, ) triangle.stretch_to_fit_width(FRAME_WIDTH) triangle.stretch_to_fit_height(FRAME_HEIGHT) triangle.to_corner(UP+LEFT, buff = 0) alt_triangle = triangle.copy() alt_triangle.rotate(np.pi) alt_triangle.set_fill(BLACK, 1) self.add( triangle, sine, area, alt_triangle, cosine, slope, double_arrow, )
videos_3b1b/_2017/eoc/chapter2.py
from manim_imports_ext import * DISTANCE_COLOR = BLUE TIME_COLOR = YELLOW VELOCITY_COLOR = GREEN #### Warning, scenes here not updated based on most recent GraphScene changes ####### class IncrementNumber(Succession): CONFIG = { "start_num" : 0, "changes_per_second" : 1, "run_time" : 11, } def __init__(self, num_mob, **kwargs): digest_config(self, kwargs) n_iterations = int(self.run_time * self.changes_per_second) new_num_mobs = [ OldTex(str(num)).move_to(num_mob, LEFT) for num in range(self.start_num, self.start_num+n_iterations) ] transforms = [ Transform( num_mob, new_num_mob, run_time = 1.0/self.changes_per_second, rate_func = squish_rate_func(smooth, 0, 0.5) ) for new_num_mob in new_num_mobs ] Succession.__init__( self, *transforms, **{ "rate_func" : None, "run_time" : self.run_time, } ) class IncrementTest(Scene): def construct(self): num = OldTex("0") num.shift(UP) self.play(IncrementNumber(num)) self.wait() ############################ class Chapter2OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "So far as the theories of mathematics are about", "reality,", "they are not", "certain;", "so far as they are", "certain,", "they are not about", "reality.", ], "highlighted_quote_terms" : { "reality," : BLUE, "certain;" : GREEN, "certain," : GREEN, "reality." : BLUE, }, "author" : "Albert Einstein" } class Introduction(TeacherStudentsScene): def construct(self): goals = OldTexText( "Goals: ", "1) Learn derivatives", ", 2) Avoid paradoxes.", arg_separator = "" ) goals[1].set_color(MAROON_B) goals[2].set_color(RED) goals[2][0].set_color(WHITE) goals.to_edge(UP) self.add(*goals[:2]) self.student_says( "What is a derivative?", run_time = 2 ) self.play(self.get_teacher().change_mode, "happy") self.wait() self.teacher_says( "It's actually a \\\\", "very subtle idea", target_mode = "well" ) self.play_student_changes(None, "pondering", "thinking") self.play(Write(goals[2], run_time = 2)) self.play_student_changes("erm") self.student_says( "Instantaneous rate of change", "?", index = 0, ) self.wait() bubble = self.get_students()[0].bubble phrase = bubble.content[0] bubble.content.remove(phrase) self.play( FadeOut(bubble), FadeOut(bubble.content), FadeOut(goals), phrase.center, phrase.scale, 1.5, phrase.to_edge, UP, *it.chain(*[ [ pi.change_mode, mode, pi.look_at, FRAME_Y_RADIUS*UP ] for pi, mode in zip(self.get_pi_creatures(), [ "speaking", "pondering", "confused", "confused", ]) ]) ) self.wait() change = VGroup(*phrase[-len("change"):]) instantaneous = VGroup(*phrase[:len("instantaneous")]) change_brace = Brace(change) change_description = change_brace.get_text( "Requires multiple \\\\ points in time" ) instantaneous_brace = Brace(instantaneous) instantaneous_description = instantaneous_brace.get_text( "One point \\\\ in time" ) clock = Clock() clock.next_to(change_description, DOWN) def get_clock_anim(run_time = 3): return ClockPassesTime( clock, hours_passed = 0.4*run_time, run_time = run_time, ) self.play(FadeIn(clock)) self.play( change.set_color_by_gradient, BLUE, YELLOW, GrowFromCenter(change_brace), Write(change_description), get_clock_anim() ) self.play(get_clock_anim(1)) stopped_clock = clock.copy() stopped_clock.next_to(instantaneous_description, DOWN) self.play( instantaneous.set_color, BLUE, GrowFromCenter(instantaneous_brace), Transform(change_description.copy(), instantaneous_description), clock.copy().next_to, instantaneous_description, DOWN, get_clock_anim(3) ) self.play(get_clock_anim(12)) class FathersOfCalculus(Scene): CONFIG = { "names" : [ "Barrow", "Newton", "Leibniz", "Cauchy", "Weierstrass", ], "picture_height" : 2.5, } def construct(self): title = OldTexText("(A few) Fathers of Calculus") title.to_edge(UP) self.add(title) men = Mobject() for name in self.names: image = ImageMobject(name, invert = False) image.set_height(self.picture_height) title = OldTexText(name) title.scale(0.8) title.next_to(image, DOWN) image.add(title) men.add(image) men.arrange(RIGHT, aligned_edge = UP) men.shift(DOWN) discover_brace = Brace(Mobject(*men[:3]), UP) discover = discover_brace.get_text("Discovered it") VGroup(discover_brace, discover).set_color(BLUE) rigor_brace = Brace(Mobject(*men[3:]), UP) rigor = rigor_brace.get_text("Made it rigorous") rigor.shift(0.1*DOWN) VGroup(rigor_brace, rigor).set_color(YELLOW) for man in men: self.play(FadeIn(man)) self.play( GrowFromCenter(discover_brace), Write(discover, run_time = 1) ) self.play( GrowFromCenter(rigor_brace), Write(rigor, run_time = 1) ) self.wait() class IntroduceCar(Scene): CONFIG = { "should_transition_to_graph" : True, "show_distance" : True, "point_A" : DOWN+4*LEFT, "point_B" : DOWN+5*RIGHT, } def construct(self): point_A, point_B = self.point_A, self.point_B A = Dot(point_A) B = Dot(point_B) line = Line(point_A, point_B) VGroup(A, B, line).set_color(WHITE) for dot, tex in (A, "A"), (B, "B"): label = OldTex(tex).next_to(dot, DOWN) dot.add(label) car = Car() self.car = car #For introduce_added_mobjects use in subclasses car.move_to(point_A) front_line = car.get_front_line() time_label = OldTexText("Time (in seconds):", "0") time_label.shift(2*UP) distance_brace = Brace(line, UP) # distance_brace.set_fill(opacity = 0.5) distance = distance_brace.get_text("100m") self.add(A, B, line, car, time_label) self.play(ShowCreation(front_line)) self.play(FadeOut(front_line)) self.introduce_added_mobjects() self.play( MoveCar(car, point_B, run_time = 10), IncrementNumber(time_label[1], run_time = 11), *self.get_added_movement_anims() ) front_line = car.get_front_line() self.play(ShowCreation(front_line)) self.play(FadeOut(front_line)) if self.show_distance: self.play( GrowFromCenter(distance_brace), Write(distance) ) self.wait() if self.should_transition_to_graph: self.play( car.move_to, point_A, FadeOut(time_label), FadeOut(distance_brace), FadeOut(distance), ) graph_scene = GraphCarTrajectory(skip_animations = True) origin = graph_scene.graph_origin top = graph_scene.coords_to_point(0, 100) new_length = get_norm(top-origin) new_point_B = point_A + new_length*RIGHT car_line_group = VGroup(car, A, B, line) for mob in car_line_group: mob.generate_target() car_line_group.target = VGroup(*[ m.target for m in car_line_group ]) B = car_line_group[2] B.target.shift(new_point_B - point_B) line.target.put_start_and_end_on( point_A, new_point_B ) car_line_group.target.rotate(np.pi/2, about_point = point_A) car_line_group.target.shift(graph_scene.graph_origin - point_A) self.play(MoveToTarget(car_line_group, path_arc = np.pi/2)) self.wait() def introduce_added_mobjects(self): pass def get_added_movement_anims(self): return [] class GraphCarTrajectory(GraphScene): CONFIG = { "x_min" : 0, "x_max" : 10, "x_labeled_nums" : list(range(1, 11)), "x_axis_label" : "Time (seconds)", "y_min" : 0, "y_max" : 110, "y_tick_frequency" : 10, "y_labeled_nums" : list(range(10, 110, 10)), "y_axis_label" : "Distance traveled \\\\ (meters)", "graph_origin" : 2.5*DOWN + 5*LEFT, "default_graph_colors" : [DISTANCE_COLOR, VELOCITY_COLOR], "default_derivative_color" : VELOCITY_COLOR, "time_of_journey" : 10, "care_movement_rate_func" : smooth, } def construct(self): self.setup_axes(animate = False) graph = self.graph_sigmoid_trajectory_function() origin = self.coords_to_point(0, 0) self.introduce_graph(graph, origin) self.comment_on_slope(graph, origin) self.show_velocity_graph() self.ask_critically_about_velocity() def graph_sigmoid_trajectory_function(self, **kwargs): graph = self.get_graph( lambda t : 100*smooth(t/10.), **kwargs ) self.s_graph = graph return graph def introduce_graph(self, graph, origin): h_line, v_line = [ Line(origin, origin, color = color, stroke_width = 2) for color in (TIME_COLOR, DISTANCE_COLOR) ] def h_update(h_line, proportion = 1): end = graph.point_from_proportion(proportion) t_axis_point = end[0]*RIGHT + origin[1]*UP h_line.put_start_and_end_on(t_axis_point, end) def v_update(v_line, proportion = 1): end = graph.point_from_proportion(proportion) d_axis_point = origin[0]*RIGHT + end[1]*UP v_line.put_start_and_end_on(d_axis_point, end) car = Car() car.rotate(np.pi/2) car.move_to(origin) car_target = origin*RIGHT + graph.point_from_proportion(1)*UP self.add(car) self.play( ShowCreation( graph, rate_func=linear, ), MoveCar( car, car_target, rate_func = self.care_movement_rate_func ), UpdateFromFunc(h_line, h_update), UpdateFromFunc(v_line, v_update), run_time = self.time_of_journey, ) self.wait() self.play(*list(map(FadeOut, [h_line, v_line, car]))) #Show example vertical distance h_update(h_line, 0.6) t_dot = Dot(h_line.get_start(), color = h_line.get_color()) t_dot.save_state() t_dot.move_to(self.x_axis_label_mob) t_dot.set_fill(opacity = 0) dashed_h = DashedLine(*h_line.get_start_and_end()) dashed_h.set_color(h_line.get_color()) brace = Brace(dashed_h, RIGHT) brace_text = brace.get_text("Distance traveled") self.play(t_dot.restore) self.wait() self.play(ShowCreation(dashed_h)) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait(2) self.play(*list(map(FadeOut, [t_dot, dashed_h, brace, brace_text]))) #Name graph s_of_t = OldTex("s(t)") s_of_t.next_to( graph.point_from_proportion(1), DOWN+RIGHT, buff = SMALL_BUFF ) s = s_of_t[0] d = OldTex("d") d.move_to(s, DOWN) d.set_color(DISTANCE_COLOR) self.play(Write(s_of_t)) self.wait() s.save_state() self.play(Transform(s, d)) self.wait() self.play(s.restore) def comment_on_slope(self, graph, origin): delta_t = 1 curr_time = 0 ghost_line = Line( origin, self.coords_to_point(delta_t, self.y_max) ) rect = Rectangle().replace(ghost_line, stretch = True) rect.set_stroke(width = 0) rect.set_fill(TIME_COLOR, opacity = 0.3) change_lines = self.get_change_lines(curr_time, delta_t) self.play(FadeIn(rect)) self.wait() self.play(Write(change_lines)) self.wait() for x in range(1, 10): curr_time = x new_change_lines = self.get_change_lines(curr_time, delta_t) self.play( rect.move_to, self.coords_to_point(curr_time, 0), DOWN+LEFT, Transform(change_lines, new_change_lines) ) if curr_time == 5: text = change_lines[-1].get_text( "$\\frac{\\text{meters}}{\\text{second}}$" ) self.play(Write(text)) self.wait() self.play(FadeOut(text)) else: self.wait() self.play(*list(map(FadeOut, [rect, change_lines]))) self.rect = rect def get_change_lines(self, curr_time, delta_t = 1): p1 = self.input_to_graph_point( curr_time, self.s_graph ) p2 = self.input_to_graph_point( curr_time+delta_t, self.s_graph ) interim_point = p2[0]*RIGHT + p1[1]*UP delta_t_line = Line(p1, interim_point, color = TIME_COLOR) delta_s_line = Line(interim_point, p2, color = DISTANCE_COLOR) brace = Brace(delta_s_line, RIGHT, buff = SMALL_BUFF) return VGroup(delta_t_line, delta_s_line, brace) def show_velocity_graph(self): velocity_graph = self.get_derivative_graph(self.s_graph) self.play(ShowCreation(velocity_graph)) def get_velocity_label(v_graph): result = self.get_graph_label( v_graph, label = "v(t)", direction = UP+RIGHT, x_val = 5, buff = SMALL_BUFF, ) self.remove(result) return result label = get_velocity_label(velocity_graph) self.play(Write(label)) self.wait() self.rect.move_to(self.coords_to_point(0, 0), DOWN+LEFT) self.play(FadeIn(self.rect)) self.wait() for time, show_slope in (4.5, True), (9, False): self.play( self.rect.move_to, self.coords_to_point(time, 0), DOWN+LEFT ) if show_slope: change_lines = self.get_change_lines(time) self.play(FadeIn(change_lines)) self.wait() self.play(FadeOut(change_lines)) else: self.wait() self.play(FadeOut(self.rect)) #Change distance and velocity graphs self.s_graph.save_state() velocity_graph.save_state() label.save_state() def shallow_slope(t): return 100*smooth(t/10., inflection = 4) def steep_slope(t): return 100*smooth(t/10., inflection = 25) def double_smooth_graph_function(t): if t < 5: return 50*smooth(t/5.) else: return 50*(1+smooth((t-5)/5.)) graph_funcs = [ shallow_slope, steep_slope, double_smooth_graph_function, ] for graph_func in graph_funcs: new_graph = self.get_graph( graph_func, color = DISTANCE_COLOR, ) self.remove(new_graph) new_velocity_graph = self.get_derivative_graph( graph = new_graph, ) new_velocity_label = get_velocity_label(new_velocity_graph) self.play(Transform(self.s_graph, new_graph)) self.play( Transform(velocity_graph, new_velocity_graph), Transform(label, new_velocity_label), ) self.wait(2) self.play(self.s_graph.restore) self.play( velocity_graph.restore, label.restore, ) self.wait(2) def ask_critically_about_velocity(self): morty = Mortimer().flip() morty.to_corner(DOWN+LEFT) self.play(PiCreatureSays(morty, "Think critically about \\\\", "what velocity means." )) self.play(Blink(morty)) self.wait() class ShowSpeedometer(IntroduceCar): CONFIG = { "num_ticks" : 8, "tick_length" : 0.2, "needle_width" : 0.1, "needle_height" : 0.8, "should_transition_to_graph" : False, "show_distance" : False, "speedometer_title_text" : "Speedometer", } def setup(self): start_angle = -np.pi/6 end_angle = 7*np.pi/6 speedometer = Arc( start_angle = start_angle, angle = end_angle-start_angle ) tick_angle_range = np.linspace(end_angle, start_angle, self.num_ticks) for index, angle in enumerate(tick_angle_range): vect = rotate_vector(RIGHT, angle) tick = Line((1-self.tick_length)*vect, vect) label = OldTex(str(10*index)) label.set_height(self.tick_length) label.shift((1+self.tick_length)*vect) speedometer.add(tick, label) needle = Polygon( LEFT, UP, RIGHT, stroke_width = 0, fill_opacity = 1, fill_color = YELLOW ) needle.stretch_to_fit_width(self.needle_width) needle.stretch_to_fit_height(self.needle_height) needle.rotate(end_angle-np.pi/2) speedometer.add(needle) speedometer.needle = needle speedometer.center_offset = speedometer.get_center() speedometer_title = OldTexText(self.speedometer_title_text) speedometer_title.to_corner(UP+LEFT) speedometer.next_to(speedometer_title, DOWN) self.speedometer = speedometer self.speedometer_title = speedometer_title def introduce_added_mobjects(self): speedometer = self.speedometer speedometer_title = self.speedometer_title speedometer.save_state() speedometer.rotate(-np.pi/2, UP) speedometer.set_height(self.car.get_height()/4) speedometer.move_to(self.car) speedometer.shift((self.car.get_width()/4)*RIGHT) self.play(speedometer.restore, run_time = 2) self.play(Write(speedometer_title, run_time = 1)) def get_added_movement_anims(self, **kwargs): needle = self.speedometer.needle center = self.speedometer.get_center() - self.speedometer.center_offset default_kwargs = { "about_point" : center, "radians" : -np.pi/2, "run_time" : 10, "rate_func" : there_and_back, } default_kwargs.update(kwargs) return [Rotating(needle, **default_kwargs)] # def construct(self): # self.add(self.speedometer) # self.play(*self.get_added_movement_anims()) class VelocityInAMomentMakesNoSense(Scene): def construct(self): randy = Randolph() randy.next_to(ORIGIN, DOWN+LEFT) words = OldTexText("Velocity in \\\\ a moment") words.next_to(randy, UP+RIGHT) randy.look_at(words) q_marks = OldTexText("???") q_marks.next_to(randy, UP) self.play( randy.change_mode, "confused", Write(words) ) self.play(Blink(randy)) self.play(Write(q_marks)) self.play(Blink(randy)) self.wait() class SnapshotOfACar(Scene): def construct(self): car = Car() car.scale(1.5) car.move_to(3*LEFT+DOWN) flash_box = Rectangle( width = FRAME_WIDTH, height = FRAME_HEIGHT, stroke_width = 0, fill_color = WHITE, fill_opacity = 1, ) speed_lines = VGroup(*[ Line(point, point+0.5*LEFT) for point in [ 0.5*UP+0.25*RIGHT, ORIGIN, 0.5*DOWN+0.25*RIGHT ] ]) question = OldTexText(""" How fast is this car going? """) self.play(MoveCar( car, RIGHT+DOWN, run_time = 2, rate_func = rush_into )) car.get_tires().set_color(GREY) speed_lines.next_to(car, LEFT) self.add(speed_lines) self.play( flash_box.set_fill, None, 0, rate_func = rush_from ) question.next_to(car, UP, buff = LARGE_BUFF) self.play(Write(question, run_time = 2)) self.wait(2) class CompareTwoTimes(Scene): CONFIG = { "start_distance" : 30, "start_time" : 4, "end_distance" : 50, "end_time" : 5, "fade_at_the_end" : True, } def construct(self): self.introduce_states() self.show_equation() if self.fade_at_the_end: self.fade_all_but_one_moment() def introduce_states(self): state1 = self.get_car_state(self.start_distance, self.start_time) state2 = self.get_car_state(self.end_distance, self.end_time) state1.to_corner(UP+LEFT) state2.to_corner(DOWN+LEFT) dividers = VGroup( Line(FRAME_X_RADIUS*LEFT, RIGHT), Line(RIGHT+FRAME_Y_RADIUS*UP, RIGHT+FRAME_Y_RADIUS*DOWN), ) dividers.set_color(GREY) self.add(dividers, state1) self.wait() copied_state = state1.copy() self.play(copied_state.move_to, state2) self.play(Transform(copied_state, state2)) self.wait(2) self.keeper = state1 def show_equation(self): velocity = OldTexText("Velocity") change_over_change = OldTex( "\\frac{\\text{Change in distance}}{\\text{Change in time}}" ) formula = OldTex( "\\frac{(%s - %s) \\text{ meters}}{(%s - %s) \\text{ seconds}}"%( str(self.end_distance), str(self.start_distance), str(self.end_time), str(self.start_time), ) ) ed_len = len(str(self.end_distance)) sd_len = len(str(self.start_distance)) et_len = len(str(self.end_time)) st_len = len(str(self.start_time)) seconds_len = len("seconds") VGroup( VGroup(*formula[1:1+ed_len]), VGroup(*formula[2+ed_len:2+ed_len+sd_len]) ).set_color(DISTANCE_COLOR) VGroup( VGroup(*formula[-2-seconds_len-et_len-st_len:-2-seconds_len-st_len]), VGroup(*formula[-1-seconds_len-st_len:-1-seconds_len]), ).set_color(TIME_COLOR) down_arrow1 = OldTex("\\Downarrow") down_arrow2 = OldTex("\\Downarrow") group = VGroup( velocity, down_arrow1, change_over_change, down_arrow2, formula, ) group.arrange(DOWN) group.to_corner(UP+RIGHT) self.play(FadeIn( group, lag_ratio = 0.5, run_time = 3 )) self.wait(3) self.formula = formula def fade_all_but_one_moment(self): anims = [ ApplyMethod(mob.fade, 0.5) for mob in self.get_mobjects() ] anims.append(Animation(self.keeper.copy())) self.play(*anims) self.wait() def get_car_state(self, distance, time): line = Line(3*LEFT, 3*RIGHT) dots = list(map(Dot, line.get_start_and_end())) line.add(*dots) car = Car() car.move_to(line.get_start()) car.shift((distance/10)*RIGHT) front_line = car.get_front_line() brace = Brace(VGroup(dots[0], front_line), DOWN) distance_label = brace.get_text( str(distance), " meters" ) distance_label.set_color_by_tex(str(distance), DISTANCE_COLOR) brace.add(distance_label) time_label = OldTexText( "Time:", str(time), "seconds" ) time_label.set_color_by_tex(str(time), TIME_COLOR) time_label.next_to( VGroup(line, car), UP, aligned_edge = LEFT ) return VGroup(line, car, front_line, brace, time_label) class VelocityAtIndividualPointsVsPairs(GraphCarTrajectory): CONFIG = { "start_time" : 6.5, "end_time" : 3, "dt" : 1.0, } def construct(self): self.setup_axes(animate = False) distance_graph = self.graph_function(lambda t : 100*smooth(t/10.)) distance_label = self.label_graph( distance_graph, label = "s(t)", proportion = 1, direction = RIGHT, buff = SMALL_BUFF ) velocity_graph = self.get_derivative_graph() self.play(ShowCreation(velocity_graph)) velocity_label = self.label_graph( velocity_graph, label = "v(t)", proportion = self.start_time/10.0, direction = UP, buff = MED_SMALL_BUFF ) velocity_graph.add(velocity_label) self.show_individual_times_to_velocity(velocity_graph) self.play(velocity_graph.fade, 0.4) self.show_two_times_on_distance() self.show_confused_pi_creature() def show_individual_times_to_velocity(self, velocity_graph): start_time = self.start_time end_time = self.end_time line = self.get_vertical_line_to_graph(start_time, velocity_graph) def line_update(line, alpha): time = interpolate(start_time, end_time, alpha) line.put_start_and_end_on( self.coords_to_point(time, 0), self.input_to_graph_point(time, graph = velocity_graph) ) self.play(ShowCreation(line)) self.wait() self.play(UpdateFromAlphaFunc( line, line_update, run_time = 4, rate_func = there_and_back )) self.wait() velocity_graph.add(line) def show_two_times_on_distance(self): line1 = self.get_vertical_line_to_graph(self.start_time-self.dt/2.0) line2 = self.get_vertical_line_to_graph(self.start_time+self.dt/2.0) p1 = line1.get_end() p2 = line2.get_end() interim_point = p2[0]*RIGHT+p1[1]*UP dt_line = Line(p1, interim_point, color = TIME_COLOR) ds_line = Line(interim_point, p2, color = DISTANCE_COLOR) dt_brace = Brace(dt_line, DOWN, buff = SMALL_BUFF) ds_brace = Brace(ds_line, RIGHT, buff = SMALL_BUFF) dt_text = dt_brace.get_text("Change in time", buff = SMALL_BUFF) ds_text = ds_brace.get_text("Change in distance", buff = SMALL_BUFF) self.play(ShowCreation(VGroup(line1, line2))) for line, brace, text in (dt_line, dt_brace, dt_text), (ds_line, ds_brace, ds_text): brace.set_color(line.get_color()) text.set_color(line.get_color()) text.add_background_rectangle() self.play( ShowCreation(line), GrowFromCenter(brace), Write(text) ) self.wait() def show_confused_pi_creature(self): randy = Randolph() randy.to_corner(DOWN+LEFT) randy.shift(2*RIGHT) self.play(randy.change_mode, "confused") self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) self.play(randy.change_mode, "erm") self.wait() self.play(Blink(randy)) self.wait(2) class FirstRealWorld(TeacherStudentsScene): def construct(self): self.teacher_says("First, the real world.") self.play_student_changes( "happy", "hooray", "happy" ) self.wait(3) class SidestepParadox(Scene): def construct(self): car = Car() car.shift(DOWN) show_speedometer = ShowSpeedometer(skip_animations = True) speedometer = show_speedometer.speedometer speedometer.next_to(car, UP) title = OldTexText( "Instantaneous", "rate of change" ) title.to_edge(UP) cross = OldTex("\\times") cross.replace(title[0], stretch = True) cross.set_fill(RED, opacity = 0.8) new_words = OldTexText("over a small time") new_words.next_to(title[1], DOWN) new_words.set_color(TIME_COLOR) self.add(title, car) self.play(Write(speedometer)) self.wait() self.play(Write(cross)) self.wait() self.play(Write(new_words)) self.wait() class CompareTwoVerySimilarTimes(CompareTwoTimes): CONFIG = { "start_distance" : 20, "start_time" : 3, "end_distance" : 20.21, "end_time" : 3.01, "fade_at_the_end" : False, } def construct(self): CompareTwoTimes.construct(self) formula = self.formula ds_symbols, dt_symbols = [ VGroup(*[ mob for mob in formula if mob.get_color() == Color(color) ]) for color in (DISTANCE_COLOR, TIME_COLOR) ] ds_brace = Brace(ds_symbols, UP) ds_text = ds_brace.get_text("$ds$", buff = SMALL_BUFF) ds_text.set_color(DISTANCE_COLOR) dt_brace = Brace(dt_symbols, DOWN) dt_text = dt_brace.get_text("$dt$", buff = SMALL_BUFF) dt_text.set_color(TIME_COLOR) self.play( GrowFromCenter(dt_brace), Write(dt_text) ) formula.add(dt_brace, dt_text) self.wait(2) formula.generate_target() VGroup( ds_brace, ds_text, formula.target ).move_to(formula, UP).shift(0.5*UP) self.play( MoveToTarget(formula), GrowFromCenter(ds_brace), Write(ds_text) ) self.wait(2) class DsOverDtGraphically(GraphCarTrajectory, ZoomedScene): CONFIG = { "dt" : 0.1, "zoom_factor" : 4,#Before being shrunk by dt "start_time" : 3, "end_time" : 7, } def construct(self): self.setup_axes(animate = False) distance_graph = self.graph_function( lambda t : 100*smooth(t/10.), animate = False, ) distance_label = self.label_graph( distance_graph, label = "s(t)", proportion = 0.9, direction = UP+LEFT, buff = SMALL_BUFF ) input_point_line = self.get_vertical_line_to_graph( self.start_time, line_kwargs = { "dash_length" : 0.02, "stroke_width" : 4, "color" : WHITE, }, ) def get_ds_dt_group(time): point1 = self.input_to_graph_point(time) point2 = self.input_to_graph_point(time+self.dt) interim_point = point2[0]*RIGHT+point1[1]*UP dt_line = Line(point1, interim_point, color = TIME_COLOR) ds_line = Line(interim_point, point2, color = DISTANCE_COLOR) result = VGroup() for line, char, vect in (dt_line, "t", DOWN), (ds_line, "s", RIGHT): line.scale(1./self.dt) brace = Brace(line, vect) text = brace.get_text("$d%s$"%char) text.next_to(brace, vect) text.set_color(line.get_color()) subgroup = VGroup(line, brace, text) subgroup.scale(self.dt) result.add(subgroup) return result def align_little_rectangle_on_ds_dt_group(rect): rect.move_to(ds_dt_group, DOWN+RIGHT) rect.shift(self.dt*(DOWN+RIGHT)/4) return rect ds_dt_group = get_ds_dt_group(self.start_time) #Initially zoom in self.play(ShowCreation(input_point_line)) self.activate_zooming() self.play(*list(map(FadeIn, [self.big_rectangle, self.little_rectangle]))) self.play( ApplyFunction( align_little_rectangle_on_ds_dt_group, self.little_rectangle ) ) self.little_rectangle.generate_target() self.little_rectangle.target.scale(self.zoom_factor*self.dt) align_little_rectangle_on_ds_dt_group( self.little_rectangle.target ) self.play( MoveToTarget(self.little_rectangle), run_time = 3 ) for subgroup in ds_dt_group: line, brace, text= subgroup self.play(ShowCreation(line)) self.play( GrowFromCenter(brace), Write(text) ) self.wait() #Show as function frac = OldTex("\\frac{ds}{dt}") VGroup(*frac[:2]).set_color(DISTANCE_COLOR) VGroup(*frac[-2:]).set_color(TIME_COLOR) frac.next_to(self.input_to_graph_point(5.25), DOWN+RIGHT) rise_over_run = OldTex( "=\\frac{\\text{rise}}{\\text{run}}" ) rise_over_run.next_to(frac, RIGHT) of_t = OldTex("(t)") of_t.next_to(frac, RIGHT, buff = SMALL_BUFF) dt_choice = OldTex("dt = 0.01") dt_choice.set_color(TIME_COLOR) dt_choice.next_to(of_t, UP, aligned_edge = LEFT, buff = LARGE_BUFF) full_formula = OldTex( "=\\frac{s(t+dt) - s(t)}{dt}" ) full_formula.next_to(of_t) s_t_plus_dt = VGroup(*full_formula[1:8]) s_t = VGroup(*full_formula[9:13]) numerator = VGroup(*full_formula[1:13]) lower_dt = VGroup(*full_formula[-2:]) upper_dt = VGroup(*full_formula[5:7]) equals = full_formula[0] frac_line = full_formula[-3] s_t_plus_dt.set_color(DISTANCE_COLOR) s_t.set_color(DISTANCE_COLOR) lower_dt.set_color(TIME_COLOR) upper_dt.set_color(TIME_COLOR) velocity_graph = self.get_derivative_graph() t_tick_marks = VGroup(*[ Line( UP, DOWN, color = TIME_COLOR, stroke_width = 3, ).scale(0.1).move_to(self.coords_to_point(t, 0)) for t in np.linspace(0, 10, 75) ]) v_line_at_t, v_line_at_t_plus_dt = [ self.get_vertical_line_to_graph( time, line_class = Line, line_kwargs = {"color" : MAROON_B} ) for time in (self.end_time, self.end_time + self.dt) ] self.play(Write(frac)) self.play(Write(rise_over_run)) self.wait() def input_point_line_update(line, alpha): time = interpolate(self.start_time, self.end_time, alpha) line.put_start_and_end_on( self.coords_to_point(time, 0), self.input_to_graph_point(time), ) def ds_dt_group_update(group, alpha): time = interpolate(self.start_time, self.end_time, alpha) new_group = get_ds_dt_group(time) Transform(group, new_group).update(1) self.play( UpdateFromAlphaFunc(input_point_line, input_point_line_update), UpdateFromAlphaFunc(ds_dt_group, ds_dt_group_update), UpdateFromFunc(self.little_rectangle, align_little_rectangle_on_ds_dt_group), run_time = 6, ) self.play(FadeOut(input_point_line)) self.wait() self.play(FadeOut(rise_over_run)) self.play(Write(of_t)) self.wait(2) self.play(ShowCreation(velocity_graph)) velocity_label = self.label_graph( velocity_graph, label = "v(t)", proportion = 0.6, direction = DOWN+LEFT, buff = SMALL_BUFF ) self.wait(2) self.play(Write(dt_choice)) self.wait() for anim_class in FadeIn, FadeOut: self.play(anim_class( t_tick_marks, lag_ratio = 0.5, run_time = 2 )) self.play( Write(equals), Write(numerator) ) self.wait() self.play(ShowCreation(v_line_at_t)) self.wait() self.play(ShowCreation(v_line_at_t_plus_dt)) self.wait() self.play(*list(map(FadeOut, [v_line_at_t, v_line_at_t_plus_dt]))) self.play( Write(frac_line), Write(lower_dt) ) self.wait(2) #Show different curves self.disactivate_zooming() self.remove(ds_dt_group) self.graph.save_state() velocity_graph.save_state() velocity_label.save_state() def steep_slope(t): return 100*smooth(t/10., inflection = 25) def sin_wiggle(t): return (10/(2*np.pi/10.))*(np.sin(2*np.pi*t/10.) + 2*np.pi*t/10.) def double_smooth_graph_function(t): if t < 5: return 50*smooth(t/5.) else: return 50*(1+smooth((t-5)/5.)) graph_funcs = [ steep_slope, sin_wiggle, double_smooth_graph_function, ] for graph_func in graph_funcs: new_graph = self.graph_function( graph_func, color = DISTANCE_COLOR, is_main_graph = False ) self.remove(new_graph) new_velocity_graph = self.get_derivative_graph( graph = new_graph, ) self.play(Transform(self.graph, new_graph)) self.play(Transform(velocity_graph, new_velocity_graph)) self.wait(2) self.play(self.graph.restore) self.play( velocity_graph.restore, velocity_label.restore, ) #Pause and reflect randy = Randolph() randy.to_corner(DOWN+LEFT).shift(2*RIGHT) randy.look_at(frac_line) self.play(FadeIn(randy)) self.play(randy.change_mode, "pondering") self.wait() self.play(Blink(randy)) self.play(randy.change_mode, "thinking") self.wait() self.play(Blink(randy)) self.wait() class DefineTrueDerivative(Scene): def construct(self): title = OldTexText("The true derivative") title.to_edge(UP) lhs = OldTex("\\frac{ds}{dt}(t) = ") VGroup(*lhs[:2]).set_color(DISTANCE_COLOR) VGroup(*lhs[3:5]).set_color(TIME_COLOR) lhs.shift(3*LEFT+UP) dt_rhs = self.get_fraction("dt") numerical_rhs_list = [ self.get_fraction("0.%s1"%("0"*x)) for x in range(7) ] for rhs in [dt_rhs] + numerical_rhs_list: rhs.next_to(lhs, RIGHT) brace, dt_to_zero = self.get_brace_and_text(dt_rhs) self.add(lhs, dt_rhs) self.play(Write(title)) self.wait() dt_rhs.save_state() for num_rhs in numerical_rhs_list: self.play(Transform(dt_rhs, num_rhs)) self.wait() self.play(dt_rhs.restore) self.play( GrowFromCenter(brace), Write(dt_to_zero) ) self.wait() def get_fraction(self, dt_string): tex_mob = OldTex( "\\frac{s(t + %s) - s(t)}{%s}"%(dt_string, dt_string) ) part_lengths = [ 0, len("s(t+"), 1,#1 and -1 below are purely for transformation quirks len(dt_string)-1, len(")-s(t)_"),#Underscore represents frac_line 1, len(dt_string)-1, ] pl_cumsum = np.cumsum(part_lengths) result = VGroup(*[ VGroup(*tex_mob[i1:i2]) for i1, i2 in zip(pl_cumsum, pl_cumsum[1:]) ]) VGroup(*result[1:3]+result[4:6]).set_color(TIME_COLOR) return result def get_brace_and_text(self, deriv_frac): brace = Brace(VGroup(deriv_frac), DOWN) dt_to_zero = brace.get_text("$dt \\to 0$") VGroup(*dt_to_zero[:2]).set_color(TIME_COLOR) return brace, dt_to_zero class SecantLineToTangentLine(GraphCarTrajectory, DefineTrueDerivative): CONFIG = { "start_time" : 6, "end_time" : 2, "alt_end_time" : 10, "start_dt" : 2, "end_dt" : 0.01, "secant_line_length" : 10, } def construct(self): self.setup_axes(animate = False) self.remove(self.y_axis_label_mob, self.x_axis_label_mob) self.add_derivative_definition(self.y_axis_label_mob) self.add_graph() self.draw_axes() self.show_tangent_line() self.best_constant_approximation_around_a_point() def get_ds_dt_group(self, dt, animate = False): points = [ self.input_to_graph_point(time, self.graph) for time in (self.curr_time, self.curr_time+dt) ] dots = list(map(Dot, points)) for dot in dots: dot.scale(0.5) secant_line = Line(*points) secant_line.set_color(VELOCITY_COLOR) secant_line.scale( self.secant_line_length/secant_line.get_length() ) interim_point = points[1][0]*RIGHT + points[0][1]*UP dt_line = Line(points[0], interim_point, color = TIME_COLOR) ds_line = Line(interim_point, points[1], color = DISTANCE_COLOR) dt = OldTex("dt") dt.set_color(TIME_COLOR) if dt.get_width() > dt_line.get_width(): dt.scale( dt_line.get_width()/dt.get_width(), about_point = dt.get_top() ) dt.next_to(dt_line, DOWN, buff = SMALL_BUFF) ds = OldTex("ds") ds.set_color(DISTANCE_COLOR) if ds.get_height() > ds_line.get_height(): ds.scale( ds_line.get_height()/ds.get_height(), about_point = ds.get_left() ) ds.next_to(ds_line, RIGHT, buff = SMALL_BUFF) group = VGroup( secant_line, ds_line, dt_line, ds, dt, *dots ) if animate: self.play( ShowCreation(dt_line), Write(dt), ShowCreation(dots[0]), ) self.play( ShowCreation(ds_line), Write(ds), ShowCreation(dots[1]), ) self.play( ShowCreation(secant_line), Animation(VGroup(*dots)) ) return group def add_graph(self): def double_smooth_graph_function(t): if t < 5: return 50*smooth(t/5.) else: return 50*(1+smooth((t-5)/5.)) self.graph = self.get_graph(double_smooth_graph_function) self.graph_label = self.get_graph_label( self.graph, "s(t)", x_val = self.x_max, direction = DOWN+RIGHT, buff = SMALL_BUFF, ) def add_derivative_definition(self, target_upper_left): deriv_frac = self.get_fraction("dt") lhs = OldTex("\\frac{ds}{dt}(t)=") VGroup(*lhs[:2]).set_color(DISTANCE_COLOR) VGroup(*lhs[3:5]).set_color(TIME_COLOR) lhs.next_to(deriv_frac, LEFT) brace, text = self.get_brace_and_text(deriv_frac) deriv_def = VGroup(lhs, deriv_frac, brace, text) deriv_word = OldTexText("Derivative") deriv_word.next_to(deriv_def, UP, buff = MED_LARGE_BUFF) deriv_def.add(deriv_word) rect = Rectangle(color = WHITE) rect.replace(deriv_def, stretch = True) rect.scale(1.2) deriv_def.add(rect) deriv_def.scale(0.7) deriv_def.move_to(target_upper_left, UP+LEFT) self.add(deriv_def) return deriv_def def draw_axes(self): self.x_axis.remove(self.x_axis_label_mob) self.y_axis.remove(self.y_axis_label_mob) self.play(Write( VGroup( self.x_axis, self.y_axis, self.graph, self.graph_label ), run_time = 4 )) self.wait() def show_tangent_line(self): self.curr_time = self.start_time ds_dt_group = self.get_ds_dt_group(2, animate = True) self.wait() def update_ds_dt_group(ds_dt_group, alpha): new_dt = interpolate(self.start_dt, self.end_dt, alpha) new_group = self.get_ds_dt_group(new_dt) Transform(ds_dt_group, new_group).update(1) self.play( UpdateFromAlphaFunc(ds_dt_group, update_ds_dt_group), run_time = 15 ) self.wait() def update_as_tangent_line(ds_dt_group, alpha): self.curr_time = interpolate(self.start_time, self.end_time, alpha) new_group = self.get_ds_dt_group(self.end_dt) Transform(ds_dt_group, new_group).update(1) self.play( UpdateFromAlphaFunc(ds_dt_group, update_as_tangent_line), run_time = 8, rate_func = there_and_back ) self.wait() what_dt_is_not_text = self.what_this_is_not_saying() self.wait() self.play( UpdateFromAlphaFunc(ds_dt_group, update_ds_dt_group), run_time = 8, rate_func = lambda t : 1-there_and_back(t) ) self.wait() self.play(FadeOut(what_dt_is_not_text)) v_line = self.get_vertical_line_to_graph( self.curr_time, self.graph, line_class = Line, line_kwargs = { "color" : MAROON_B, "stroke_width" : 3 } ) def v_line_update(v_line): v_line.put_start_and_end_on( self.coords_to_point(self.curr_time, 0), self.input_to_graph_point(self.curr_time, self.graph), ) return v_line self.play(ShowCreation(v_line)) self.wait() original_end_time = self.end_time for end_time in self.alt_end_time, original_end_time, self.start_time: self.end_time = end_time self.play( UpdateFromAlphaFunc(ds_dt_group, update_as_tangent_line), UpdateFromFunc(v_line, v_line_update), run_time = abs(self.curr_time-self.end_time), ) self.start_time = end_time self.play(FadeOut(v_line)) def what_this_is_not_saying(self): phrases = [ OldTexText( "$dt$", "is", "not", s ) for s in ("``infinitely small''", "0") ] for phrase in phrases: phrase[0].set_color(TIME_COLOR) phrase[2].set_color(RED) phrases[0].shift(DOWN+2*RIGHT) phrases[1].next_to(phrases[0], DOWN, aligned_edge = LEFT) for phrase in phrases: self.play(Write(phrase)) return VGroup(*phrases) def best_constant_approximation_around_a_point(self): words = OldTexText(""" Best constant approximation around a point """) words.next_to(self.x_axis, UP, aligned_edge = RIGHT) circle = Circle( radius = 0.25, color = WHITE ).shift(self.input_to_graph_point(self.curr_time)) self.play(Write(words)) self.play(ShowCreation(circle)) self.wait() class UseOfDImpliesApproaching(TeacherStudentsScene): def construct(self): statement = OldTexText(""" Using ``$d$'' announces that $dt \\to 0$ """) VGroup(*statement[-4:-2]).set_color(TIME_COLOR) self.teacher_says(statement) self.play_student_changes(*["pondering"]*3) self.wait(4) class LeadIntoASpecificExample(TeacherStudentsScene, SecantLineToTangentLine): def setup(self): TeacherStudentsScene.setup(self) def construct(self): dot = Dot() #Just to coordinate derivative definition dot.to_corner(UP+LEFT, buff = SMALL_BUFF) deriv_def = self.add_derivative_definition(dot) self.remove(deriv_def) self.teacher_says("An example \\\\ should help.") self.wait() self.play( Write(deriv_def), *it.chain(*[ [pi.change_mode, "thinking", pi.look_at, dot] for pi in self.get_students() ]) ) self.random_blink(3) # self.teacher_says( # """ # The idea of # ``approaching'' # actually makes # things easier # """, # height = 3, # target_mode = "hooray" # ) # self.wait(2) class TCubedExample(SecantLineToTangentLine): CONFIG = { "y_axis_label" : "Distance", "y_min" : 0, "y_max" : 16, "y_tick_frequency" : 1, "y_labeled_nums" : list(range(0, 17, 2)), "x_min" : 0, "x_max" : 4, "x_labeled_nums" : list(range(1, 5)), "graph_origin" : 2.5*DOWN + 6*LEFT, "start_time" : 2, "end_time" : 0.5, "start_dt" : 0.25, "end_dt" : 0.001, "secant_line_length" : 0.01, } def construct(self): self.draw_graph() self.show_vertical_lines() self.bear_with_me() self.add_ds_dt_group() self.brace_for_details() self.show_expansion() self.react_to_simplicity() def draw_graph(self): self.setup_axes(animate = False) self.x_axis_label_mob.shift(0.5*DOWN) # self.y_axis_label_mob.next_to(self.y_axis, UP) graph = self.graph_function(lambda t : t**3, animate = True) self.label_graph( graph, label = "s(t) = t^3", proportion = 0.62, direction = LEFT, buff = SMALL_BUFF ) self.wait() def show_vertical_lines(self): for t in 1, 2: v_line = self.get_vertical_line_to_graph( t, line_kwargs = {"color" : WHITE} ) brace = Brace(v_line, RIGHT) text = OldTex("%d^3 = %d"%(t, t**3)) text.next_to(brace, RIGHT) text.shift(0.2*UP) group = VGroup(v_line, brace, text) if t == 1: self.play(ShowCreation(v_line)) self.play( GrowFromCenter(brace), Write(text) ) last_group = group else: self.play(Transform(last_group, group)) self.wait() self.play(FadeOut(last_group)) def bear_with_me(self): morty = Mortimer() morty.to_corner(DOWN+RIGHT) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, "Bear with \\\\ me here", target_mode = "sassy" )) self.play(Blink(morty)) self.wait() self.play(*list(map( FadeOut, [morty, morty.bubble, morty.bubble.content] ))) def add_ds_dt_group(self): self.curr_time = self.start_time self.curr_dt = self.start_dt ds_dt_group = self.get_ds_dt_group(dt = self.start_dt) v_lines = self.get_vertical_lines() lhs = OldTex("\\frac{ds}{dt}(2) = ") lhs.next_to(ds_dt_group, UP+RIGHT, buff = MED_LARGE_BUFF) ds = VGroup(*lhs[:2]) dt = VGroup(*lhs[3:5]) ds.set_color(DISTANCE_COLOR) dt.set_color(TIME_COLOR) ds.target, dt.target = ds_dt_group[3:5] for mob in ds, dt: mob.save_state() mob.move_to(mob.target) nonzero_size = OldTexText("Nonzero size...for now") nonzero_size.set_color(TIME_COLOR) nonzero_size.next_to(dt, DOWN+2*RIGHT, buff = LARGE_BUFF) arrow = Arrow(nonzero_size, dt) rhs = OldTex( "\\frac{s(2+dt) - s(2)}{dt}" ) rhs.next_to(lhs[-1]) VGroup(*rhs[4:6]).set_color(TIME_COLOR) VGroup(*rhs[-2:]).set_color(TIME_COLOR) numerator = VGroup(*rhs[:-3]) non_numerator = VGroup(*rhs[-3:]) numerator_non_minus = VGroup(*numerator) numerator_non_minus.remove(rhs[7]) s_pair = rhs[0], rhs[8] lp_pair = rhs[6], rhs[11] for s, lp in zip(s_pair, lp_pair): s.target = OldTex("3").scale(0.7) s.target.move_to(lp.get_corner(UP+RIGHT), LEFT) self.play(Write(ds_dt_group, run_time = 2)) self.play( FadeIn(lhs), *[mob.restore for mob in (ds, dt)] ) self.play(ShowCreation(v_lines[0])) self.wait() self.play( ShowCreation(arrow), Write(nonzero_size), ) self.wait(2) self.play(*list(map(FadeOut, [arrow, nonzero_size]))) self.play(Write(numerator)) self.play(ShowCreation(v_lines[1])) self.wait() self.play( v_lines[0].set_color, YELLOW, rate_func = there_and_back ) self.wait() self.play(Write(non_numerator)) self.wait(2) self.play( *list(map(MoveToTarget, s_pair)), **{ "path_arc" : -np.pi/2 } ) self.play(numerator_non_minus.shift, 0.2*LEFT) self.wait() self.vertical_lines = v_lines self.ds_dt_group = ds_dt_group self.lhs = lhs self.rhs = rhs def get_vertical_lines(self): return VGroup(*[ self.get_vertical_line_to_graph( time, line_class = DashedLine, line_kwargs = { "color" : WHITE, "dash_length" : 0.05, } ) for time in (self.start_time, self.start_time+self.start_dt) ]) def brace_for_details(self): morty = Mortimer() morty.next_to(self.rhs, DOWN, buff = LARGE_BUFF) self.play(FadeIn(morty)) self.play( morty.change_mode, "hooray", morty.look_at, self.rhs ) self.play(Blink(morty)) self.wait() self.play( morty.change_mode, "sassy", morty.look, OUT ) self.play(Blink(morty)) self.play(morty.change_mode, "pondering") self.wait() self.play(FadeOut(morty)) def show_expansion(self): expression = OldTex(""" \\frac{ 2^3 + 3 (2)^2 dt + 3 (2)(dt)^2 + (dt)^3 - 2^3 }{dt} """) expression.set_width( VGroup(self.lhs, self.rhs).get_width() ) expression.next_to( self.lhs, DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ) term_lens = [ len("23+"), len("3(2)2dt"), len("+3(2)(dt)2+"), len("(dt)3"), len("-23"), len("_"),#frac bar len("dt"), ] terms = [ VGroup(*expression[i1:i2]) for i1, i2 in zip( [0]+list(np.cumsum(term_lens)), np.cumsum(term_lens) ) ] dts = [ VGroup(*terms[1][-2:]), VGroup(*terms[2][6:8]), VGroup(*terms[3][1:3]), terms[-1] ] VGroup(*dts).set_color(TIME_COLOR) two_cubed_terms = terms[0], terms[4] for term in terms: self.play(FadeIn(term)) self.wait() #Cancel out two_cubed terms self.play(*it.chain(*[ [ tc.scale, 1.3, tc.get_corner(vect), tc.set_color, RED ] for tc, vect in zip( two_cubed_terms, [DOWN+RIGHT, DOWN+LEFT] ) ])) self.play(*list(map(FadeOut, two_cubed_terms))) numerator = VGroup(*terms[1:4]) self.play( numerator.scale, 1.4, numerator.get_bottom(), terms[-1].scale, 1.4, terms[-1].get_top() ) self.wait(2) #Cancel out dt #This is all way too hacky... faders = VGroup( terms[-1], VGroup(*terms[1][-2:]), #"3(2)^2 dt" terms[2][-2], # "+3(2)(dt)2+" terms[3][-1], # "(dt)3" ) new_exp = OldTex("2").replace(faders[-1], dim_to_match = 1) self.play( faders.set_color, BLACK, FadeIn(new_exp), run_time = 2, ) self.wait() terms[3].add(new_exp) shift_val = 0.4*DOWN self.play( FadeOut(terms[-2]),#frac_line terms[1].shift, shift_val + 0.45*RIGHT, terms[2].shift, shift_val, terms[3].shift, shift_val, ) #Isolate dominant term arrow = Arrow( self.lhs[4].get_bottom(), terms[1][2].get_top(), color = WHITE, buff = MED_SMALL_BUFF ) brace = Brace(VGroup(terms[2][0], terms[3][-1]), DOWN) brace_text = brace.get_text("Contains $dt$") VGroup(*brace_text[-2:]).set_color(TIME_COLOR) self.play(ShowCreation(arrow)) self.wait() self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait(2) #Shink dt faders = VGroup(*terms[2:4] + [brace, brace_text]) def ds_dt_group_update(group, alpha): new_dt = interpolate(self.start_dt, self.end_dt, alpha) new_group = self.get_ds_dt_group(new_dt) Transform(group, new_group).update(1) self.play(FadeOut(self.vertical_lines)) self.secant_line_length = 10 self.play(Transform( self.ds_dt_group, self.get_ds_dt_group(self.start_dt) )) self.play( UpdateFromAlphaFunc(self.ds_dt_group, ds_dt_group_update), faders.fade, 0.7, run_time = 5 ) self.wait(2) #Show as derivative deriv_term = VGroup(*terms[1][:5]) deriv_term.generate_target() lhs_copy = self.lhs.copy() lhs_copy.generate_target() lhs_copy.target.shift(3*DOWN) #hack a little, hack a lot deriv_term.target.scale(1.1) deriv_term.target.next_to(lhs_copy.target) deriv_term.target.shift(0.07*DOWN) self.play( FadeOut(arrow), FadeOut(faders), MoveToTarget(deriv_term), MoveToTarget(lhs_copy), ) arrow = Arrow( self.rhs.get_bottom(), deriv_term.target.get_top(), buff = MED_SMALL_BUFF, color = WHITE ) approach_text = OldTexText("As $dt \\to 0$") approach_text.next_to(arrow.get_center(), RIGHT) VGroup(*approach_text[2:4]).set_color(TIME_COLOR) self.play( ShowCreation(arrow), Write(approach_text) ) self.wait(2) self.wait() #Ephasize slope v_line = self.vertical_lines[0] slope_text = OldTexText("Slope = $12$") slope_text.set_color(VELOCITY_COLOR) slope_text.next_to(v_line.get_end(), LEFT) self.play(Write(slope_text)) self.play( self.ds_dt_group.rotate, np.pi/24, rate_func = wiggle ) self.play(ShowCreation(v_line)) self.wait() self.play(FadeOut(v_line)) self.play(FadeOut(slope_text)) #Generalize to more t twos = [ self.lhs[6], self.rhs[2], self.rhs[10], lhs_copy[6], deriv_term[2] ] for two in twos: two.target = OldTex("t") two.target.replace(two, dim_to_match = 1) self.play(*list(map(MoveToTarget, twos))) def update_as_tangent_line(group, alpha): self.curr_time = interpolate(self.start_time, self.end_time, alpha) new_group = self.get_ds_dt_group(self.end_dt) Transform(group, new_group).update(1) self.play( UpdateFromAlphaFunc(self.ds_dt_group, update_as_tangent_line), run_time = 5, rate_func = there_and_back ) self.wait(2) self.lhs_copy = lhs_copy self.deriv_term = deriv_term self.approach_text = approach_text def react_to_simplicity(self): morty = Mortimer().flip().to_corner(DOWN+LEFT) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, "That's \\\\ beautiful!", target_mode = "hooray" )) self.play(Blink(morty)) self.play( morty.change_mode, 'happy', *list(map(FadeOut, [morty.bubble, morty.bubble.content])) ) numerator = VGroup(*self.rhs[:12]) denominator = VGroup(*self.rhs[-2:]) for mob in numerator, denominator, self.approach_text, self.deriv_term: mob.generate_target() mob.target.scale(1.2) mob.target.set_color(MAROON_B) self.play( MoveToTarget( mob, rate_func = there_and_back, run_time = 1.5, ), morty.look_at, mob ) self.wait() self.play(Blink(morty)) self.wait() class YouWouldntDoThisEveryTime(TeacherStudentsScene): def construct(self): self.play_student_changes( "pleading", "guilty", "hesitant", run_time = 0 ) self.teacher_says( "You wouldn't do this \\\\ every time" ) self.play_student_changes(*["happy"]*3) self.wait(2) self.student_thinks( "$\\frac{d(t^3)}{dt} = 3t^2$", ) self.wait(3) series = VideoSeries() series.set_width(FRAME_WIDTH-1) series.to_edge(UP) this_video = series[1] next_video = series[2] this_video.save_state() this_video.set_color(YELLOW) self.play(FadeIn(series, lag_ratio = 0.5)) self.play( this_video.restore, next_video.set_color, YELLOW, next_video.shift, 0.5*DOWN ) self.wait(2) class ContrastConcreteDtWithLimit(Scene): def construct(self): v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) self.add(v_line) l_title = OldTexText(""" If $dt$ has a specific size. """) VGroup(*l_title[2:4]).set_color(TIME_COLOR) r_title = OldTex("dt \\to 0") VGroup(*r_title[:2]).set_color(TIME_COLOR) for title, vect in (l_title, LEFT), (r_title, RIGHT): title.to_edge(UP) title.shift(FRAME_X_RADIUS*vect/2) self.add(title) l_formula = OldTex(""" \\frac{d(t^3)}{dt} = \\frac{ t^3+ 3t^2 \\, dt + 3t \\, (dt)^2 + (dt)^3 - t^3 }{dt} """) VGroup(*it.chain( l_formula[6:8], l_formula[15:17], l_formula[21:23], l_formula[27:29], l_formula[35:37], )).set_color(TIME_COLOR) l_formula.set_width(FRAME_X_RADIUS-MED_LARGE_BUFF) l_formula.to_edge(LEFT) l_brace = Brace(l_formula, DOWN) l_text = l_brace.get_text("Messy") l_text.set_color(RED) r_formula = OldTex( "\\frac{d(t^3)}{dt} = 3t^2" ) VGroup(*r_formula[6:8]).set_color(TIME_COLOR) r_formula.shift(FRAME_X_RADIUS*RIGHT/2) r_brace = Brace(r_formula, DOWN) r_text = r_brace.get_text("Simple") r_text.set_color(GREEN) triplets = [ (l_formula, l_brace, l_text), (r_formula, r_brace, r_text), ] for formula, brace, text in triplets: self.play(Write(formula, run_time = 1)) self.play( GrowFromCenter(brace), Write(text) ) self.wait(2) class TimeForAnActualParadox(TeacherStudentsScene): def construct(self): words = OldTexText("``Instantaneous rate of change''") paradoxes = OldTexText("Paradoxes") arrow = Arrow(ORIGIN, DOWN, buff = 0) group = VGroup(words, arrow, paradoxes) group.arrange(DOWN) group.to_edge(UP) teacher = self.get_teacher() self.play( teacher.change_mode, "raise_right_hand", teacher.look_at, words, Write(words) ) self.play(*list(map(Write, [arrow, paradoxes]))) self.play(*it.chain(*[ [pi.change_mode, mode, pi.look_at, words] for pi, mode in zip( self.get_students(), ["pondering", "happy", "hesitant"] ) ])) self.wait(4) class ParadoxAtTEquals0(TCubedExample): CONFIG = { "tangent_line_length" : 20, } def construct(self): self.draw_graph() self.ask_question() self.show_derivative_text() self.show_tangent_line() self.if_not_then_when() self.single_out_question() def draw_graph(self): self.setup_axes(animate = False) self.x_axis_label_mob.set_fill(opacity = 0) graph = self.graph_function(lambda t : t**3, animate = False) graph_x_max = 3.0 graph.pointwise_become_partial(graph, 0, graph_x_max/self.x_max) origin = self.coords_to_point(0, 0) h_line = Line(LEFT, RIGHT, color = TIME_COLOR) v_line = Line(UP, DOWN, color = DISTANCE_COLOR) VGroup(h_line, v_line).set_stroke(width = 2) def h_line_update(h_line): point = graph.point_from_proportion(1) y_axis_point = origin[0]*RIGHT + point[1]*UP h_line.put_start_and_end_on(y_axis_point, point) return h_line def v_line_update(v_line): point = graph.point_from_proportion(1) x_axis_point = point[0]*RIGHT + origin[1]*UP v_line.put_start_and_end_on(x_axis_point, point) return v_line car = Car() car.rotate(np.pi/2) car.move_to(origin) self.add(car) #Should be 0, 1, but for some reason I don't know #the car was lagging the graph. car_target_point = self.coords_to_point(0, 1.15) self.play( MoveCar( car, car_target_point, rate_func = lambda t : (t*graph_x_max)**3 ), ShowCreation(graph, rate_func=linear), UpdateFromFunc(h_line, h_line_update), UpdateFromFunc(v_line, v_line_update), run_time = 5 ) self.play(*list(map(FadeOut, [h_line, v_line]))) self.label_graph( graph, label = "s(t) = t^3", proportion = 0.8, direction = RIGHT, buff = SMALL_BUFF ) self.wait() self.car = car def ask_question(self): question = OldTexText( "At time $t=0$,", "is \\\\ the car moving?" ) VGroup(*question[0][-4:-1]).set_color(RED) question.next_to( self.coords_to_point(0, 10), RIGHT ) origin = self.coords_to_point(0, 0) arrow = Arrow(question.get_bottom(), origin) self.play(Write(question[0], run_time = 1)) self.play(MoveCar(self.car, origin)) self.wait() self.play(Write(question[1])) self.play(ShowCreation(arrow)) self.wait(2) self.question = question def show_derivative_text(self): derivative = OldTex( "\\frac{ds}{dt}(t) = 3t^2", "= 3(0)^2", "= 0", "\\frac{\\text{m}}{\\text{s}}", ) VGroup(*derivative[0][:2]).set_color(DISTANCE_COLOR) VGroup(*derivative[0][3:5]).set_color(TIME_COLOR) derivative[1][3].set_color(RED) derivative[-1].scale(0.7) derivative.to_edge(RIGHT, buff = LARGE_BUFF) derivative.shift(2*UP) self.play(Write(derivative[0])) self.wait() self.play(FadeIn(derivative[1])) self.play(*list(map(FadeIn, derivative[2:]))) self.wait(2) self.derivative = derivative def show_tangent_line(self): dot = Dot() line = Line(ORIGIN, RIGHT, color = VELOCITY_COLOR) line.scale(self.tangent_line_length) start_time = 2 end_time = 0 def get_time_and_point(alpha): time = interpolate(start_time, end_time, alpha) point = self.input_to_graph_point(time) return time, point def dot_update(dot, alpha): dot.move_to(get_time_and_point(alpha)[1]) def line_update(line, alpha): time, point = get_time_and_point(alpha) line.rotate( self.angle_of_tangent(time)-line.get_angle() ) line.move_to(point) dot_update(dot, 0) line_update(line, 0) self.play( ShowCreation(line), ShowCreation(dot) ) self.play( UpdateFromAlphaFunc(line, line_update), UpdateFromAlphaFunc(dot, dot_update), run_time = 4 ) self.wait(2) self.tangent_line = line def if_not_then_when(self): morty = Mortimer() morty.scale(0.7) morty.to_corner(DOWN+RIGHT) self.play(FadeIn(morty)) self.play(PiCreatureSays( morty, "If not at $t=0$, when?", target_mode = "maybe" )) self.play(Blink(morty)) self.play(MoveCar( self.car, self.coords_to_point(0, 1), rate_func = lambda t : (3*t)**3, run_time = 5 )) self.play( morty.change_mode, "pondering", FadeOut(morty.bubble), FadeOut(morty.bubble.content), ) self.play(MoveCar(self.car, self.coords_to_point(0, 0))) self.play(Blink(morty)) self.wait(2) self.morty = morty def single_out_question(self): morty, question = self.morty, self.question #Shouldn't need this morty.bubble.content.set_fill(opacity = 0) morty.bubble.set_fill(opacity = 0) morty.bubble.set_stroke(width = 0) change_word = VGroup(*question[1][-7:-1]) moment_word = question[0] brace = Brace(VGroup(*self.derivative[1:])) brace_text = brace.get_text("Best constant \\\\ approximation") self.remove(question, morty) pre_everything = Mobject(*self.get_mobjects()) everything = Mobject(*pre_everything.family_members_with_points()) everything.save_state() self.play( everything.fade, 0.8, question.center, morty.change_mode, "confused", morty.look_at, ORIGIN ) self.play(Blink(morty)) for word in change_word, moment_word: self.play( word.scale, 1.2, word.set_color, YELLOW, rate_func = there_and_back, run_time = 1.5 ) self.wait(2) self.play( everything.restore, FadeOut(question), morty.change_mode, "raise_right_hand", morty.look_at, self.derivative ) self.play( GrowFromCenter(brace), FadeIn(brace_text) ) self.wait() self.play( self.tangent_line.rotate, np.pi/24, rate_func = wiggle, run_time = 1 ) self.play(Blink(morty)) self.wait() class TinyMovement(ZoomedScene): CONFIG = { "distance" : 0.05, "distance_label" : "(0.1)^3 = 0.001", "time_label" : "0.1", } def construct(self): self.activate_zooming() self.show_initial_motion() self.show_ratios() def show_initial_motion(self): car = Car() car.move_to(ORIGIN) car_points = car.get_all_points() lowest_to_highest_indices = np.argsort(car_points[:,1]) wheel_point = car_points[lowest_to_highest_indices[2]] target_wheel_point = wheel_point+self.distance*RIGHT dots = VGroup(*[ Dot(point, radius = self.distance/10) for point in (wheel_point, target_wheel_point) ]) brace = Brace(Line(ORIGIN, RIGHT)) distance_label = OldTex(self.distance_label) distance_label.next_to(brace, DOWN) distance_label.set_color(DISTANCE_COLOR) brace.add(distance_label) brace.scale(self.distance) brace.next_to(dots, DOWN, buff = self.distance/5) zoom_rect = self.little_rectangle zoom_rect.scale(2) zoom_rect.move_to(wheel_point) time_label = OldTexText("Time $t = $") time_label.next_to(car, UP, buff = LARGE_BUFF) start_time = OldTex("0") end_time = OldTex(self.time_label) for time in start_time, end_time: time.set_color(TIME_COLOR) time.next_to(time_label, RIGHT) self.add(car, time_label, start_time) self.play( zoom_rect.scale, 10*self.distance / zoom_rect.get_width() ) self.play(ShowCreation(dots[0])) self.play(Transform(start_time, end_time)) self.play(MoveCar(car, self.distance*RIGHT)) self.play(ShowCreation(dots[1])) self.play(Write(brace, run_time = 1)) self.play( zoom_rect.scale, 0.5, zoom_rect.move_to, brace ) self.wait() def show_ratios(self): ratios = [ self.get_ratio(n) for n in range(1, 5) ] ratio = ratios[0] self.play(FadeIn(ratio)) self.wait(2) for new_ratio in ratios[1:]: self.play(Transform(ratio, new_ratio)) self.wait() def get_ratio(self, power = 1): dt = "0.%s1"%("0"*(power-1)) ds_dt = "0.%s1"%("0"*(2*power-1)) expression = OldTex(""" \\frac{(%s)^3 \\text{ meters}}{%s \\text{ seconds}} = %s \\frac{\\text{meters}}{\\text{second}} """%(dt, dt, ds_dt)) expression.next_to(ORIGIN, DOWN, buff = LARGE_BUFF) lengths = [ 0, len("("), len(dt), len(")3meters_"), len(dt), len("seconds="), len(ds_dt), len("meters_second") ] result = VGroup(*[ VGroup(*expression[i1:i2]) for i1, i2 in zip( np.cumsum(lengths), np.cumsum(lengths)[1:], ) ]) result[1].set_color(DISTANCE_COLOR) result[3].set_color(TIME_COLOR) result[5].set_color(VELOCITY_COLOR) return result class NextVideos(TeacherStudentsScene): def construct(self): series = VideoSeries() series.set_width(FRAME_WIDTH - 1) series.to_edge(UP) series[1].set_color(YELLOW) self.add(series) brace = Brace(VGroup(*series[2:6])) brace_text = brace.get_text("More derivative stuffs") self.play( GrowFromCenter(brace), self.get_teacher().change_mode, "raise_right_hand" ) self.play( Write(brace_text), *it.chain(*[ [pi.look_at, brace] for pi in self.get_students() ]) ) self.wait(2) self.play_student_changes(*["thinking"]*3) self.wait(3) class Chapter2PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Meshal Alshammari", "Ali Yahya", "CrypticSwarm ", "Yu Jun", "Shelby Doolittle", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph Cox", "Luc Ritchie", "Mark Govea", "Guido Gambardella", "Vecht", "Jonathan Eppele", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } class Promotion(PiCreatureScene): CONFIG = { "camera_class" : ThreeDCamera, "seconds_to_blink" : 5, } def construct(self): aops_logo = AoPSLogo() aops_logo.next_to(self.pi_creature, UP+LEFT) url = OldTexText( "AoPS.com/", "3blue1brown", arg_separator = "" ) url.to_corner(UP+LEFT) url_rect = Rectangle(color = BLUE) url_rect.replace( url.get_part_by_tex("3blue1brown"), stretch = True ) url_rect.stretch_in_place(1.1, dim = 1) rect = Rectangle(height = 9, width = 16) rect.set_height(4.5) rect.next_to(url, DOWN) rect.to_edge(LEFT) mathy = Mathematician() mathy.flip() mathy.to_corner(DOWN+RIGHT) morty = self.pi_creature morty.save_state() book_spot = mathy.get_corner(UP+LEFT) + UP+LEFT mathy.get_center = mathy.get_top self.play( self.pi_creature.change_mode, "raise_right_hand", *[ DrawBorderThenFill( submob, run_time = 3, rate_func = squish_rate_func(double_smooth, a, a+0.5) ) for submob, a in zip(aops_logo, np.linspace(0, 0.5, len(aops_logo))) ] ) self.play(Write(url)) self.play( morty.change_mode, "plain", morty.flip, morty.scale, 0.7, morty.next_to, mathy, LEFT, LARGE_BUFF, morty.to_edge, DOWN, FadeIn(mathy), ) self.play( PiCreatureSays( mathy, "", bubble_config = {"width" : 5}, look_at = morty.eyes, ), aops_logo.shift, 1.5*UP + 0.5*RIGHT ) self.change_mode("happy") self.wait(2) self.play(Blink(mathy)) self.wait() self.play( RemovePiCreatureBubble( mathy, target_mode = "happy" ), aops_logo.to_corner, UP+RIGHT, aops_logo.shift, MED_SMALL_BUFF*DOWN, ) self.play( mathy.look_at, morty.eyes, morty.look_at, mathy.eyes, ) self.wait(2) self.play( Animation(VectorizedPoint(book_spot)), mathy.change, "raise_right_hand", book_spot, morty.change, "pondering", ) self.wait(3) self.play(Blink(mathy)) self.wait(7) self.play( ShowCreation(rect), morty.restore, morty.change, "happy", rect, FadeOut(mathy), ) self.wait(10) self.play(ShowCreation(url_rect)) self.play( FadeOut(url_rect), url.get_part_by_tex("3blue1brown").set_color, BLUE, ) self.wait(3) class Thumbnail(SecantLineToTangentLine): def construct(self): self.setup_axes(animate = False) self.add_graph() self.curr_time = 6 ds_dt_group = self.get_ds_dt_group(1) self.add(ds_dt_group) self.remove(self.x_axis_label_mob) self.remove(self.y_axis_label_mob) VGroup(*self.get_mobjects()).fade(0.4) title = OldTexText("Derivative paradox") title.set_width(FRAME_WIDTH-1) title.to_edge(UP) title.add_background_rectangle() title.set_color_by_gradient(GREEN, YELLOW) randy = Randolph(mode = "confused") randy.scale(1.7) randy.to_corner(DOWN+LEFT) randy.shift(RIGHT) deriv = OldTex("\\frac{ds}{dt}(t)") VGroup(*deriv[:2]).set_color(DISTANCE_COLOR) VGroup(*deriv[3:5]).set_color(TIME_COLOR) deriv.scale(3) # deriv.next_to(randy, RIGHT, buff = 2) deriv.to_edge(RIGHT, buff = LARGE_BUFF) randy.look_at(deriv) self.add(title, randy, deriv)
videos_3b1b/_2017/eoc/chapter8.py
import scipy from manim_imports_ext import * from _2017.eoc.chapter1 import Thumbnail as Chapter1Thumbnail from _2017.eoc.chapter2 import Car, MoveCar, ShowSpeedometer, \ IncrementNumber, GraphCarTrajectory, SecantLineToTangentLine, \ VELOCITY_COLOR, TIME_COLOR, DISTANCE_COLOR def v_rate_func(t): return 4*t - 4*(t**2) def s_rate_func(t): return 3*(t**2) - 2*(t**3) def v_func(t): return t*(8-t) def s_func(t): return 4*t**2 - (t**3)/3. class Chapter8OpeningQuote(OpeningQuote, PiCreatureScene): CONFIG = { "quote" : [ " One should never try to prove anything that \\\\ is not ", "almost obvious", ". " ], "quote_arg_separator" : "", "highlighted_quote_terms" : { "almost obvious" : BLUE, }, "author" : "Alexander Grothendieck" } def construct(self): self.remove(self.pi_creature) OpeningQuote.construct(self) words_copy = self.quote.get_part_by_tex("obvious").copy() author = self.author author.save_state() formula = self.get_formula() formula.next_to(author, DOWN, MED_LARGE_BUFF) formula.to_edge(LEFT) self.revert_to_original_skipping_status() self.play(FadeIn(self.pi_creature)) self.play( author.next_to, self.pi_creature.get_corner(UP+LEFT), UP, self.pi_creature.change_mode, "raise_right_hand" ) self.wait(3) self.play( author.restore, self.pi_creature.change_mode, "plain" ) self.play( words_copy.next_to, self.pi_creature, LEFT, MED_SMALL_BUFF, UP, self.pi_creature.change_mode, "thinking" ) self.wait(2) self.play( Write(formula), self.pi_creature.change_mode, "confused" ) self.wait() def get_formula(self): result = OldTex( "{d(\\sin(\\theta)) \\over \\,", "d\\theta}", "=", "\\lim_{", "h", " \\to 0}", "{\\sin(\\theta+", "h", ") - \\sin(\\theta) \\over", " h}", "=", "\\lim_{", "h", " \\to 0}", "{\\big[ \\sin(\\theta)\\cos(", "h", ") + ", "\\sin(", "h", ")\\cos(\\theta)\\big] - \\sin(\\theta) \\over", "h}", "= \\dots" ) result.set_color_by_tex("h", GREEN, substring = False) result.set_color_by_tex("d\\theta", GREEN) result.set_width(FRAME_WIDTH - 2*MED_SMALL_BUFF) return result class ThisVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) this_video = series[7] this_video.save_state() next_video = series[8] deriv, integral, v_t, dt, equals, v_T = formula = OldTex( "\\frac{d}{dT}", "\\int_0^T", "v(t)", "\\,dt", "=", "v(T)" ) formula.set_color_by_tex("v", VELOCITY_COLOR) formula.next_to(self.teacher.get_corner(UP+LEFT), UP, MED_LARGE_BUFF) self.play(FadeIn(series, lag_ratio = 0.5)) self.play( this_video.shift, this_video.get_height()*DOWN/2, this_video.set_color, YELLOW, self.teacher.change_mode, "raise_right_hand", ) self.play(Write(VGroup(integral, v_t, dt))) self.play_student_changes(*["erm"]*3) self.wait() self.play(Write(VGroup(deriv, equals, v_T)), ) self.play_student_changes(*["confused"]*3) self.wait(3) self.play( this_video.restore, next_video.shift, next_video.get_height()*DOWN/2, next_video.set_color, YELLOW, integral[0].copy().next_to, next_video, DOWN, MED_LARGE_BUFF, FadeOut(formula), *it.chain(*[ [pi.change_mode, "plain", pi.look_at, next_video] for pi in self.pi_creatures ]) ) self.wait(2) class InCarRestrictedView(ShowSpeedometer): CONFIG = { "speedometer_title_text" : "Your view", } def construct(self): car = Car() car.move_to(self.point_A) self.car = car car.randy.save_state() Transform(car.randy, Randolph()).update(1) car.randy.next_to(car, RIGHT, MED_LARGE_BUFF) car.randy.look_at(car) window = car[1][6].copy() window.is_subpath = False window.set_fill(BLACK, opacity = 0.75) window.set_stroke(width = 0) square = Square(stroke_color = WHITE) square.replace(VGroup(self.speedometer, self.speedometer_title)) square.scale(1.5) square.pointwise_become_partial(square, 0.25, 0.75) time_label = OldTexText("Time (in seconds):", "0") time_label.shift(2*UP) dots = VGroup(*list(map(Dot, [self.point_A, self.point_B]))) line = Line(*dots, buff = 0) line.set_color(DISTANCE_COLOR) brace = Brace(line, DOWN) brace_text = brace.get_text("Distance traveled?") #Sit in car self.add(car) self.play(Blink(car.randy)) self.play(car.randy.restore, Animation(car)) self.play(ShowCreation(window, run_time = 2)) self.wait() #Show speedometer self.introduce_added_mobjects() self.play(ShowCreation(square)) self.wait() #Travel self.play(FadeIn(time_label)) self.play( MoveCar(car, self.point_B, rate_func = s_rate_func), IncrementNumber(time_label[1], run_time = 8), MaintainPositionRelativeTo(window, car), *self.get_added_movement_anims( rate_func = v_rate_func, radians = -(16.0/70)*4*np.pi/3 ), run_time = 8 ) eight = OldTex("8").move_to(time_label[1]) self.play(Transform( time_label[1], eight, rate_func = squish_rate_func(smooth, 0, 0.5) )) self.wait() #Ask about distance self.play(*list(map(ShowCreation, dots))) self.play(ShowCreation(line)) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait(2) class GraphDistanceVsTime(GraphCarTrajectory): CONFIG = { "y_min" : 0, "y_max" : 100, "y_axis_height" : 6, "y_tick_frequency" : 10, "y_labeled_nums" : list(range(10, 100, 10)), "y_axis_label" : "Distance (in meters)", "x_min" : -1, "x_max" : 9, "x_axis_width" : 9, "x_tick_frequency" : 1, "x_leftmost_tick" : None, #Change if different from x_min "x_labeled_nums" : list(range(1, 9)), "x_axis_label" : "$t$", "time_of_journey" : 8, "care_movement_rate_func" : s_rate_func, "num_graph_anchor_points" : 100 } def construct(self): self.setup_axes() graph = self.get_graph( s_func, color = DISTANCE_COLOR, x_min = 0, x_max = 8, ) origin = self.coords_to_point(0, 0) graph_label = self.get_graph_label( graph, "s(t)", color = DISTANCE_COLOR ) self.introduce_graph(graph, origin) class PlotVelocity(GraphScene): CONFIG = { "x_min" : -1, "x_max" : 9, "x_axis_width" : 9, "x_tick_frequency" : 1, "x_labeled_nums" : list(range(1, 9)), "x_axis_label" : "$t$", "y_min" : 0, "y_max" : 25, "y_axis_height" : 6, "y_tick_frequency" : 5, "y_labeled_nums" : list(range(5, 30, 5)), "y_axis_label" : "Velocity in $\\frac{\\text{meters}}{\\text{second}}$", "num_graph_anchor_points" : 50, } def construct(self): self.setup_axes() self.add_speedometer() self.plot_points() self.draw_curve() def add_speedometer(self): speedometer = Speedometer() speedometer.next_to(self.y_axis_label_mob, RIGHT, LARGE_BUFF) speedometer.to_edge(UP) self.play(DrawBorderThenFill( speedometer, lag_ratio = 0.5, rate_func=linear, )) self.speedometer = speedometer def plot_points(self): times = list(range(0, 9)) points = [ self.coords_to_point(t, v_func(t)) for t in times ] dots = VGroup(*[Dot(p, radius = 0.07) for p in points]) dots.set_color(VELOCITY_COLOR) pre_dots = VGroup() dot_intro_anims = [] for time, dot in zip(times, dots): pre_dot = dot.copy() self.speedometer.move_needle_to_velocity(v_func(time)) pre_dot.move_to(self.speedometer.get_needle_tip()) pre_dot.set_fill(opacity = 0) pre_dots.add(pre_dot) dot_intro_anims += [ ApplyMethod( pre_dot.set_fill, YELLOW, 1, run_time = 0.1, ), ReplacementTransform( pre_dot, dot, run_time = 0.9, ) ] self.speedometer.move_needle_to_velocity(0) self.play( Succession( *dot_intro_anims, rate_func=linear ), ApplyMethod( self.speedometer.move_needle_to_velocity, v_func(4), rate_func = squish_rate_func( lambda t : 1-v_rate_func(t), 0, 0.95, ) ), run_time = 5 ) self.wait() def draw_curve(self): graph, label = self.get_v_graph_and_label() self.revert_to_original_skipping_status() self.play(ShowCreation(graph, run_time = 3)) self.play(Write(graph_label)) self.wait() ## def get_v_graph_and_label(self): graph = self.get_graph( v_func, x_min = 0, x_max = 8, color = VELOCITY_COLOR ) graph_label = OldTex("v(t)", "=t(8-t)") graph_label.set_color_by_tex("v(t)", VELOCITY_COLOR) graph_label.next_to( graph.point_from_proportion(7./8.), UP+RIGHT ) self.v_graph = graph self.v_graph_label = graph_label return graph, graph_label class Chapter2Wrapper(Scene): CONFIG = { "title" : "Chapter 2: The paradox of the derivative", } def construct(self): title = OldTexText(self.title) title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = WHITE) rect.set_height(1.5*FRAME_Y_RADIUS) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait(3) class GivenDistanceWhatIsVelocity(GraphCarTrajectory): def construct(self): self.force_skipping() self.setup_axes() graph = self.graph_sigmoid_trajectory_function() origin = self.coords_to_point(0, 0) self.introduce_graph(graph, origin) self.comment_on_slope(graph, origin) self.revert_to_original_skipping_status() self.show_velocity_graph() class DerivativeOfDistance(SecantLineToTangentLine): def construct(self): self.setup_axes() self.remove(self.y_axis_label_mob, self.x_axis_label_mob) self.add_derivative_definition(self.y_axis_label_mob) self.add_graph() self.draw_axes() self.show_tangent_line() class AskAboutAntiderivative(PlotVelocity): def construct(self): self.setup_axes() self.add_v_graph() self.write_s_formula() self.write_antiderivative() def add_v_graph(self): graph, label = self.get_v_graph_and_label() self.play(ShowCreation(graph)) self.play(Write(label)) self.graph = graph self.graph_label = label def write_s_formula(self): ds_dt = OldTex("ds", "\\over\\,", "dt") ds_dt.set_color_by_tex("ds", DISTANCE_COLOR) ds_dt.set_color_by_tex("dt", TIME_COLOR) ds_dt.next_to(self.graph_label, UP, LARGE_BUFF) v_t = self.graph_label.get_part_by_tex("v(t)") arrow = Arrow( ds_dt.get_bottom(), v_t.get_top(), color = WHITE, ) self.play( Write(ds_dt, run_time = 2), ShowCreation(arrow) ) self.wait() def write_antiderivative(self): randy = Randolph() randy.to_corner(DOWN+LEFT) randy.shift(2*RIGHT) words = OldTex( "{d(", "???", ") \\over \\,", "dt}", "=", "t(8-t)" ) words.set_color_by_tex("t(8-t)", VELOCITY_COLOR) words.set_color_by_tex("???", DISTANCE_COLOR) words.set_color_by_tex("dt", TIME_COLOR) words.scale(0.7) self.play(FadeIn(randy)) self.play(PiCreatureSays( randy, words, target_mode = "confused", bubble_config = {"height" : 3, "width" : 4}, )) self.play(Blink(randy)) self.wait() class Antiderivative(PiCreatureScene): def construct(self): functions = self.get_functions("t^2", "2t") alt_functions = self.get_functions("???", "t(8-t)") top_arc, bottom_arc = arcs = self.get_arcs(functions) derivative, antiderivative = self.get_arc_labels(arcs) group = VGroup(functions, arcs, derivative, antiderivative) self.add(functions, top_arc, derivative) self.wait() self.play( ShowCreation(bottom_arc), Write(antiderivative), self.pi_creature.change_mode, "raise_right_hand" ) self.wait(2) for pair in reversed(list(zip(functions, alt_functions))): self.play( Transform(*pair), self.pi_creature.change_mode, "pondering" ) self.wait(2) self.pi_creature_says( "But first!", target_mode = "surprised", look_at = 50*OUT, added_anims = [group.to_edge, LEFT], run_time = 1, ) self.wait() def get_functions(self, left_tex, right_tex): left = OldTex(left_tex) left.shift(2*LEFT) left.set_color(DISTANCE_COLOR) right = OldTex(right_tex) right.shift(2*RIGHT) right.set_color(VELOCITY_COLOR) result = VGroup(left, right) result.shift(UP) return result def get_arcs(self, functions): f1, f2 = functions top_line = Line(f1.get_corner(UP+RIGHT), f2.get_corner(UP+LEFT)) bottom_line = Line(f1.get_corner(DOWN+RIGHT), f2.get_corner(DOWN+LEFT)) top_arc = Arc(start_angle = 5*np.pi/6, angle = -2*np.pi/3) bottom_arc = top_arc.copy() bottom_arc.rotate(np.pi) arcs = VGroup(top_arc, bottom_arc) arcs.set_width(top_line.get_width()) for arc in arcs: arc.add_tip() top_arc.next_to(top_line, UP) bottom_arc.next_to(bottom_line, DOWN) bottom_arc.set_color(MAROON_B) return arcs def get_arc_labels(self, arcs): top_arc, bottom_arc = arcs derivative = OldTexText("Derivative") derivative.next_to(top_arc, UP) antiderivative = OldTexText("``Antiderivative''") antiderivative.next_to(bottom_arc, DOWN) antiderivative.set_color(bottom_arc.get_color()) return VGroup(derivative, antiderivative) class AreaUnderVGraph(PlotVelocity): def construct(self): self.setup_axes() self.add(*self.get_v_graph_and_label()) self.show_rects() def show_rects(self): rect_list = self.get_riemann_rectangles_list( self.v_graph, 7, max_dx = 1.0, x_min = 0, x_max = 8, ) flat_graph = self.get_graph(lambda t : 0) rects = self.get_riemann_rectangles( flat_graph, x_min = 0, x_max = 8, dx = 1.0 ) for new_rects in rect_list: new_rects.set_fill(opacity = 0.8) rects.align_family(new_rects) for alt_rect in rects[::2]: alt_rect.set_fill(opacity = 0) self.play(Transform( rects, new_rects, run_time = 2, lag_ratio = 0.5 )) self.wait() class ConstantVelocityCar(Scene): def construct(self): car = Car() car.move_to(5*LEFT + 3*DOWN) self.add(car) self.wait() self.play(MoveCar( car, 7*RIGHT+3*DOWN, run_time = 5, rate_func=linear, )) self.wait() class ConstantVelocityPlot(PlotVelocity): CONFIG = { "x_axis_label" : "Time", "units_of_area_color" : BLUE_E, } def construct(self): self.setup_axes() self.x_axis_label_mob.shift(DOWN) self.draw_graph() self.show_product() self.comment_on_area_wierdness() self.note_units() def draw_graph(self): graph = self.get_graph( lambda t : 10, x_min = 0, x_max = 8, color = VELOCITY_COLOR ) self.play(ShowCreation(graph, rate_func=linear, run_time = 3)) self.wait() self.graph = graph def show_product(self): rect = Rectangle( stroke_width = 0, fill_color = DISTANCE_COLOR, fill_opacity = 0.5 ) rect.replace( VGroup(self.graph, VectorizedPoint(self.graph_origin)), stretch = True ) right_brace = Brace(rect, RIGHT) top_brace = Brace(rect, UP) v_label = right_brace.get_text( "$10 \\frac{\\text{meters}}{\\text{second}}$", ) v_label.set_color(VELOCITY_COLOR) t_label = top_brace.get_text( "8 seconds" ) t_label.set_color(TIME_COLOR) s_label = OldTex("10", "\\times", "8", "\\text{ meters}") s_label.set_color_by_tex("10", VELOCITY_COLOR) s_label.set_color_by_tex("8", TIME_COLOR) s_label.move_to(rect) self.play( GrowFromCenter(right_brace), Write(v_label), ) self.play( GrowFromCenter(top_brace), Write(t_label), ) self.play( FadeIn(rect), Write(s_label), Animation(self.graph) ) self.wait(2) self.area_rect = rect self.s_label = s_label def comment_on_area_wierdness(self): randy = Randolph() randy.to_corner(DOWN+LEFT) bubble = randy.get_bubble( "Distance \\\\ is area?", bubble_type = ThoughtBubble, height = 3, width = 4, fill_opacity = 1, ) bubble.content.scale(0.8) bubble.content.shift(SMALL_BUFF*UP) VGroup(bubble[-1], bubble.content).shift(1.5*LEFT) self.play(FadeIn(randy)) self.play(randy.change_mode, "pondering") self.play( self.area_rect.set_color, YELLOW, *list(map(Animation, self.get_mobjects())), rate_func = there_and_back ) self.play(Blink(randy)) self.play( randy.change_mode, "confused", randy.look_at, randy.bubble, ShowCreation(bubble), Write(bubble.content), ) self.wait() self.play(Blink(randy)) self.wait() self.play( randy.change_mode, "pondering", FadeOut(bubble), FadeOut(bubble.content), ) self.randy = randy def note_units(self): x_line, y_line = lines = VGroup(*[ axis.copy() for axis in (self.x_axis, self.y_axis) ]) lines.set_color(TIME_COLOR) square = Square( stroke_color = BLACK, stroke_width = 1, fill_color = self.units_of_area_color, fill_opacity = 1, ) square.replace( VGroup(*[ VectorizedPoint(self.coords_to_point(i, i)) for i in (0, 1) ]), stretch = True ) units_of_area = VGroup(*[ square.copy().move_to( self.coords_to_point(x, y), DOWN+LEFT ) for x in range(8) for y in range(10) ]) self.play(ShowCreation(x_line)) self.play(Indicate(self.x_axis_label_mob)) self.play(FadeOut(x_line)) self.play( ShowCreation(y_line), self.randy.look_at, self.y_axis_label_mob ) self.play(Indicate(self.y_axis_label_mob)) self.play(FadeOut(y_line)) for FadeClass in FadeIn, FadeOut: self.play( FadeClass( units_of_area, lag_ratio = 0.5, run_time = 3 ), Animation(self.s_label), self.randy.look_at, self.area_rect ) self.play(Blink(self.randy)) self.wait() class PiecewiseConstantCar(Scene): def construct(self): car = Car() start_point = 5*LEFT car.move_to(start_point) self.add(car) self.wait() for shift in 2, 6, 12: car.randy.rotate(np.pi/8) anim = MoveCar( car, start_point+shift*RIGHT, rate_func=linear ) anim.target_mobject[0].rotate(-np.pi/8) # for mob in anim.starting_mobject, anim.mobject: # mob.randy.rotate(np.pi/6) self.play(anim) self.wait() class PiecewiseConstantPlot(PlotVelocity): CONFIG = { "y_axis_label" : "", "min_graph_proportion" : 0.1, "max_graph_proportion" : 0.8, "num_riemann_approximations" : 7, "riemann_rect_fill_opacity" : 0.75, "tick_size" : 0.2, } def construct(self): self.setup_graph() self.always_changing() self.show_piecewise_constant_graph() self.compute_distance_on_each_interval() self.approximate_original_curve() self.revert_to_specific_approximation() self.show_specific_rectangle() self.show_v_dt_for_all_rectangles() self.write_integral_symbol() self.roles_of_dt() self.what_does_sum_approach() self.label_integral() def setup_graph(self): self.setup_axes() self.add(*self.get_v_graph_and_label()) def always_changing(self): dot = Dot() arrow = Arrow(LEFT, RIGHT) words = OldTexText("Always changing") group = VGroup(dot, arrow, words) def update_group(group, alpha): dot, arrow, words = group prop = interpolate( self.min_graph_proportion, self.max_graph_proportion, alpha ) graph_point = self.v_graph.point_from_proportion(prop) dot.move_to(graph_point) x_val = self.x_axis.point_to_number(graph_point) angle = self.angle_of_tangent(x_val, self.v_graph) angle += np.pi/2 vect = rotate_vector(RIGHT, angle) arrow.rotate(angle - arrow.get_angle() + np.pi) arrow.shift( graph_point + MED_SMALL_BUFF*vect - arrow.get_end() ) words.next_to(arrow.get_start(), UP) return group update_group(group, 0) self.play( Write(words), ShowCreation(arrow), DrawBorderThenFill(dot), run_time = 1 ) self.play(UpdateFromAlphaFunc( group, update_group, rate_func = there_and_back, run_time = 5 )) self.wait() self.play(FadeOut(group)) def show_piecewise_constant_graph(self): pw_constant_graph = self.get_pw_constant_graph() alt_lines = [ line.copy().set_color(YELLOW) for line in pw_constant_graph[:4] ] for line in alt_lines: line.start_dot = Dot(line.get_start()) line.end_dot = Dot(line.get_end()) VGroup(line.start_dot, line.end_dot).set_color(line.get_color()) line = alt_lines[0] faders = [self.v_graph, self.v_graph_label] for mob in faders: mob.save_state() mob.generate_target() mob.target.fade(0.7) self.play(*list(map(MoveToTarget, faders))) self.play(ShowCreation(pw_constant_graph, run_time = 2)) self.wait() self.play(ShowCreation(line)) self.wait() for new_line in alt_lines[1:]: for mob in line.end_dot, new_line.start_dot, new_line: self.play(Transform( line, mob, run_time = 1./3 )) self.remove(line) self.add(new_line) self.wait(2) line = new_line self.play(FadeOut(line)) self.pw_constant_graph = pw_constant_graph def compute_distance_on_each_interval(self): rect_list = self.get_riemann_rectangles_list( self.v_graph, self.num_riemann_approximations, max_dx = 1, x_min = 0, x_max = 8, ) for rects in rect_list: rects.set_fill(opacity = self.riemann_rect_fill_opacity) flat_rects = self.get_riemann_rectangles( self.get_graph(lambda t : 0), x_min = 0, x_max = 8, dx = 1 ) rects = rect_list[0] rect = rects[1] flat_rects.submobjects[1] = rect.copy() right_brace = Brace(rect, RIGHT) top_brace = Brace(rect, UP) right_brace.label = right_brace.get_text("$7\\frac{\\text{m}}{\\text{s}}$") top_brace.label = top_brace.get_text("$1$s") self.play(FadeIn(rect)) for brace in right_brace, top_brace: self.play( GrowFromCenter(brace), Write(brace.label, run_time = 1), ) brace.add(brace.label) self.wait() self.play( ReplacementTransform( flat_rects, rects, run_time = 2, lag_ratio = 0.5, ), Animation(right_brace) ) self.play(*list(map(FadeOut, [top_brace, right_brace]))) self.wait() self.rects = rects self.rect_list = rect_list def approximate_original_curve(self): rects = self.rects self.play( FadeOut(self.pw_constant_graph), *[ m.restore for m in (self.v_graph, self.v_graph_label) ]+[Animation(self.rects)] ) for new_rects in self.rect_list[1:]: self.transform_between_riemann_rects(rects, new_rects) self.wait() def revert_to_specific_approximation(self): rects = self.rects rects.save_state() target_rects = self.rect_list[2] target_rects.set_fill(opacity = 1) ticks = self.get_ticks(target_rects) tick_pair = VGroup(*ticks[4:6]) brace = Brace(tick_pair, DOWN, buff = 0) dt_label = brace.get_text("$dt$", buff = SMALL_BUFF) example_text = OldTexText( "For example, \\\\", "$dt$", "$=0.25$" ) example_text.to_corner(UP+RIGHT) example_text.set_color_by_tex("dt", YELLOW) self.play(ReplacementTransform( rects, target_rects, run_time = 2, lag_ratio = 0.5 )) rects.restore() self.wait() self.play( ShowCreation(ticks), FadeOut(self.x_axis.numbers) ) self.play( GrowFromCenter(brace), Write(dt_label) ) self.wait() self.play( FadeIn( example_text, run_time = 2, lag_ratio = 0.5, ), ReplacementTransform( dt_label.copy(), example_text.get_part_by_tex("dt") ) ) self.wait() self.rects = rects = target_rects self.ticks = ticks self.dt_brace = brace self.dt_label = dt_label self.dt_example_text = example_text def show_specific_rectangle(self): rects = self.rects rect = rects[4].copy() rect_top = Line( rect.get_corner(UP+LEFT), rect.get_corner(UP+RIGHT), color = self.v_graph.get_color() ) t_vals = [1, 1.25] t_labels = VGroup(*[ OldTex("t=%s"%str(t)) for t in t_vals ]) t_labels.scale(0.7) t_labels.next_to(rect, DOWN) for vect, label in zip([LEFT, RIGHT], t_labels): label.shift(1.5*vect) label.add(Arrow( label.get_edge_center(-vect), rect.get_corner(DOWN+vect), buff = SMALL_BUFF, tip_length = 0.15, color = WHITE )) v_lines = VGroup() h_lines = VGroup() height_labels = VGroup() for t in t_vals: v_line = self.get_vertical_line_to_graph( t, self.v_graph, color = YELLOW ) y_axis_point = self.graph_origin[0]*RIGHT y_axis_point += v_line.get_end()[1]*UP h_line = DashedLine(v_line.get_end(), y_axis_point) label = OldTex("%.1f"%v_func(t)) label.scale(0.5) label.next_to(h_line, LEFT, SMALL_BUFF) v_lines.add(v_line) h_lines.add(h_line) height_labels.add(label) circle = Circle(radius = 0.25, color = WHITE) circle.move_to(rect.get_top()) self.play( rects.set_fill, None, 0.25, Animation(rect) ) self.wait() for label in t_labels: self.play(FadeIn(label)) self.wait() for v_line, h_line, label in zip(v_lines, h_lines, height_labels): self.play(ShowCreation(v_line)) self.play(ShowCreation(h_line)) self.play(Write(label, run_time = 1)) self.wait() self.wait() t_label_copy = t_labels[0].copy() self.play( t_label_copy.scale, 1./0.7, t_label_copy.next_to, self.v_graph_label, DOWN+LEFT, 0 ) self.wait() self.play(FadeOut(t_label_copy)) self.wait() self.play(ShowCreation(circle)) self.play(ShowCreation(rect_top)) self.play(FadeOut(circle)) rect.add(rect_top) self.wait() for x in range(2): self.play( rect.stretch_to_fit_height, v_lines[1].get_height(), rect.move_to, rect.get_bottom(), DOWN, Animation(v_lines), run_time = 4, rate_func = there_and_back ) self.play(*list(map(FadeOut, [ group[1] for group in (v_lines, h_lines, height_labels) ]))) self.play( v_lines[0].set_color, RED, rate_func = there_and_back, ) self.wait() area = OldTexText( "7$\\frac{\\text{m}}{\\text{s}}$", "$\\times$", "0.25s", "=", "1.75m" ) area.next_to(rect, RIGHT, LARGE_BUFF) arrow = Arrow( area.get_left(), rect.get_center(), buff = 0, color = WHITE ) area.shift(SMALL_BUFF*RIGHT) self.play( Write(area), ShowCreation(arrow) ) self.wait(2) self.play(*list(map(FadeOut, [ area, arrow, v_lines[0], h_lines[0], height_labels[0], rect, t_labels ]))) def show_v_dt_for_all_rectangles(self): dt_brace_group = VGroup(self.dt_brace, self.dt_label) rects_subset = self.rects[10:20] last_rect = None for rect in rects_subset: brace = Brace(rect, LEFT, buff = 0) v_t = OldTex("v(t)") v_t.next_to(brace, LEFT, SMALL_BUFF) anims = [ rect.set_fill, None, 1, dt_brace_group.next_to, rect, DOWN, SMALL_BUFF ] if last_rect is not None: anims += [ last_rect.set_fill, None, 0.25, ReplacementTransform(last_brace, brace), ReplacementTransform(last_v_t, v_t), ] else: anims += [ GrowFromCenter(brace), Write(v_t) ] self.play(*anims) self.wait() last_rect = rect last_brace = brace last_v_t = v_t self.v_t = last_v_t self.v_t_brace = last_brace def write_integral_symbol(self): integral = OldTex( "\\int", "^8", "_0", "v(t)", "\\,dt" ) integral.to_corner(UP+RIGHT) int_copy = integral.get_part_by_tex("int").copy() bounds = list(map(integral.get_part_by_tex, ["0", "8"])) sum_word = OldTexText("``Sum''") sum_word.next_to(integral, DOWN, MED_LARGE_BUFF, LEFT) alt_sum_word = sum_word.copy() int_symbol = OldTex("\\int") int_symbol.replace(alt_sum_word[1], dim_to_match = 1) alt_sum_word.submobjects[1] = int_symbol self.play(FadeOut(self.dt_example_text)) self.play(Write(integral.get_part_by_tex("int"))) self.wait() self.play(Transform(int_copy, int_symbol)) self.play(Write(alt_sum_word), Animation(int_copy)) self.remove(int_copy) self.play(ReplacementTransform(alt_sum_word, sum_word)) self.wait() for bound in bounds: self.play(Write(bound)) self.wait() for bound, num in zip(bounds, [0, 8]): bound_copy = bound.copy() point = self.coords_to_point(num, 0) self.play( bound_copy.scale, 1.5, bound_copy.next_to, point, DOWN, MED_LARGE_BUFF ) self.play(ApplyWave(self.ticks, direction = UP)) self.wait() for mob, tex in (self.v_t, "v(t)"), (self.dt_label, "dt"): self.play(ReplacementTransform( mob.copy().set_color(YELLOW), integral.get_part_by_tex(tex), run_time = 2 )) self.wait() self.integral = integral self.sum_word = sum_word def roles_of_dt(self): rects = self.rects next_rects = self.rect_list[3] morty = Mortimer().flip() morty.to_corner(DOWN+LEFT) int_dt = self.integral.get_part_by_tex("dt") dt_copy = int_dt.copy() self.play(FadeIn(morty)) self.play( morty.change_mode, "raise_right_hand", morty.look, UP+RIGHT, dt_copy.next_to, morty.get_corner(UP+RIGHT), UP, dt_copy.set_color, YELLOW ) self.play(Blink(morty)) self.play( ReplacementTransform( dt_copy.copy(), int_dt, run_time = 2 ), morty.look_at, int_dt ) self.wait(2) self.play( ReplacementTransform(dt_copy.copy(), self.dt_label), morty.look_at, self.dt_label ) self.play(*[ ApplyMethod( tick.shift, tick.get_height()*UP/2, run_time = 2, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.2, ) ) for tick, alpha in zip( self.ticks, np.linspace(0, 0.8, len(self.ticks)) ) ]) self.wait() #Shrink dt just a bit self.play( morty.change_mode, "pondering", rects.set_fill, None, 0.75, *list(map(FadeOut, [ dt_copy, self.v_t, self.v_t_brace ])) ) rects.align_family(next_rects) for every_other_rect in rects[::2]: every_other_rect.set_fill(opacity = 0) self.play( self.dt_brace.stretch, 0.5, 0, self.dt_brace.move_to, self.dt_brace, LEFT, ReplacementTransform( rects, next_rects, run_time = 2, lag_ratio = 0.5 ), Transform( self.ticks, self.get_ticks(next_rects), run_time = 2, lag_ratio = 0.5, ), ) self.rects = rects = next_rects self.wait() self.play(Blink(morty)) self.play(*[ ApplyFunction( lambda r : r.shift(0.2*UP).set_fill(None, 1), rect, run_time = 2, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.2, ) ) for rect, alpha in zip( rects, np.linspace(0, 0.8, len(rects)) ) ]+[ morty.change_mode, "thinking", ]) self.wait() self.morty = morty def what_does_sum_approach(self): morty = self.morty rects = self.rects cross = OldTex("\\times") cross.replace(self.sum_word, stretch = True) cross.set_color(RED) brace = Brace(self.integral, DOWN) dt_to_0 = brace.get_text("$dt \\to 0$") distance_words = OldTexText( "Area", "= Distance traveled" ) distance_words.next_to(rects, UP) arrow = Arrow( distance_words[0].get_bottom(), rects.get_center(), color = WHITE ) self.play(PiCreatureSays( morty, "Why not $\\Sigma$?", target_mode = "sassy" )) self.play(Blink(morty)) self.wait() self.play(Write(cross)) self.wait() self.play( RemovePiCreatureBubble(morty, target_mode = "plain"), *list(map(FadeOut, [ cross, self.sum_word, self.ticks, self.dt_brace, self.dt_label, ])) ) self.play(FadeIn(brace), FadeIn(dt_to_0)) for new_rects in self.rect_list[4:]: rects.align_family(new_rects) for every_other_rect in rects[::2]: every_other_rect.set_fill(opacity = 0) self.play( Transform( rects, new_rects, run_time = 2, lag_ratio = 0.5 ), morty.look_at, rects, ) self.wait() self.play( Write(distance_words), ShowCreation(arrow), morty.change_mode, "pondering", morty.look_at, distance_words, ) self.wait() self.play(Blink(morty)) self.wait() self.area_arrow = arrow def label_integral(self): words = OldTexText("``Integral of $v(t)$''") words.to_edge(UP) arrow = Arrow( words.get_right(), self.integral.get_left() ) self.play(Indicate(self.integral)) self.play(Write(words, run_time = 2)) self.play(ShowCreation(arrow)) self.wait() self.play(*[ ApplyFunction( lambda r : r.shift(0.2*UP).set_fill(None, 1), rect, run_time = 3, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.2, ) ) for rect, alpha in zip( self.rects, np.linspace(0, 0.8, len(self.rects)) ) ]+[ Animation(self.area_arrow), self.morty.change_mode, "happy", self.morty.look_at, self.rects, ]) self.wait() ##### def get_pw_constant_graph(self): result = VGroup() for left_x in range(8): xs = [left_x, left_x+1] y = self.v_graph.underlying_function(left_x) line = Line(*[ self.coords_to_point(x, y) for x in xs ]) line.set_color(self.v_graph.get_color()) result.add(line) return result def get_ticks(self, rects): ticks = VGroup(*[ Line( point+self.tick_size*UP/2, point+self.tick_size*DOWN/2 ) for t in np.linspace(0, 8, len(rects)+1) for point in [self.coords_to_point(t, 0)] ]) ticks.set_color(YELLOW) return ticks class DontKnowHowToHandleNonConstant(TeacherStudentsScene): def construct(self): self.play(*[ ApplyMethod(pi.change, "maybe", UP) for pi in self.get_pi_creatures() ]) self.wait(3) class CarJourneyApproximation(Scene): CONFIG = { "n_jumps" : 5, "bottom_words" : "Approximated motion (5 jumps)", } def construct(self): points = [5*LEFT + v for v in (UP, 2*DOWN)] cars = [Car().move_to(point) for point in points] h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) words = [ OldTexText("Real motion (smooth)").shift(3*UP), OldTexText(self.bottom_words).shift(0.5*DOWN), ] words[1].set_color(GREEN) self.add(h_line, *cars + words) self.wait() self.play(*[ MoveCar( car, point+10*RIGHT, run_time = 5, rate_func = rf ) for car, point, rf in zip(cars, points, [ s_rate_func, self.get_approximated_rate_func(self.n_jumps) ]) ]) self.wait() def get_approximated_rate_func(self, n): new_v_rate_func = lambda t : v_rate_func(np.floor(t*n)/n) max_integral, err = scipy.integrate.quad( v_rate_func, 0, 1 ) def result(t): integral, err = scipy.integrate.quad(new_v_rate_func, 0, t) return integral/max_integral return result class LessWrongCarJourneyApproximation(CarJourneyApproximation): CONFIG = { "n_jumps" : 20, "bottom_words" : "Better approximation (20 jumps)", } class TellMeThatsNotSurprising(TeacherStudentsScene): def construct(self): self.teacher_says( "Tell me that's \\\\ not surprising!", target_mode = "hooray", run_time = 1 ) self.wait(3) class HowDoesThisHelp(TeacherStudentsScene): def construct(self): self.student_says( "How does this help\\textinterrobang", target_mode = "angry", run_time = 1 ) self.play_student_changes( "confused", "angry", "confused", ) self.wait(2) self.teacher_says( "You're right.", target_mode = "shruggie", run_time = 1 ) self.play_student_changes(*["sassy"]*3) self.wait(2) class AreaUnderACurve(GraphScene): CONFIG = { "y_max" : 4, "y_min" : 0, "num_iterations" : 7 } def construct(self): self.setup_axes() graph = self.get_graph(self.func) rect_list = self.get_riemann_rectangles_list( graph, self.num_iterations ) VGroup(*rect_list).set_fill(opacity = 0.8) rects = rect_list[0] self.play(ShowCreation(graph)) self.play(Write(rects)) for new_rects in rect_list[1:]: rects.align_family(new_rects) for every_other_rect in rects[::2]: every_other_rect.set_fill(opacity = 0) self.play(Transform( rects, new_rects, run_time = 2, lag_ratio = 0.5 )) self.wait() def func(self, x): return np.sin(x) + 1 class AltAreaUnderCurve(AreaUnderACurve): CONFIG = { "graph_origin" : 2*DOWN, "x_min" : -3, "x_max" : 3, "x_axis_width" : 12, "y_max" : 2, "y_axis_height" : 4, } def func(self, x): return np.exp(-x**2) class Chapter1Wrapper(Chapter2Wrapper): CONFIG = { "title" : "Essence of calculus, chapter 1", } class AreaIsDerivative(PlotVelocity, ReconfigurableScene): CONFIG = { "y_axis_label" : "", "num_rects" : 400, "dT" : 0.25, "variable_point_label" : "T", "area_opacity" : 0.8, } def setup(self): PlotVelocity.setup(self) ReconfigurableScene.setup(self) self.setup_axes() self.add(*self.get_v_graph_and_label()) self.x_axis_label_mob.shift(MED_LARGE_BUFF*DOWN) self.v_graph_label.shift(MED_LARGE_BUFF*DOWN) self.foreground_mobjects = [] def construct(self): self.introduce_variable_area() self.write_integral() self.nudge_input() self.show_rectangle_approximation() def introduce_variable_area(self): area = self.area = self.get_area(0, 6) x_nums = self.x_axis.numbers self.play(Write(area, run_time = 2)) self.play(FadeOut(self.x_axis.numbers)) self.add_T_label(6) self.change_area_bounds( new_t_max = 4, rate_func = there_and_back, run_time = 2 ) self.wait() def write_integral(self): integral = OldTex("\\int", "^T", "_0", "v(t)", "\\,dt") integral.to_corner(UP+RIGHT) integral.shift(2*LEFT) top_T = integral.get_part_by_tex("T") moving_T = self.T_label_group[0] s_T = OldTex("s(T)", "= ") s_T.set_color_by_tex("s", DISTANCE_COLOR) s_T.next_to(integral, LEFT) int_arrow, s_arrow = [ Arrow( mob.get_left(), self.area.get_center(), color = WHITE ) for mob in (integral, s_T) ] distance_word = OldTexText("Distance") distance_word.move_to(self.area) self.play(Write(integral)) self.play(ShowCreation(int_arrow)) self.foreground_mobjects.append(int_arrow) self.wait() self.change_area_bounds( new_t_max = 8, rate_func = there_and_back, run_time = 3, ) self.play(Indicate(top_T)) self.play(ReplacementTransform( top_T.copy(), moving_T )) self.change_area_bounds( new_t_max = 3, rate_func = there_and_back, run_time = 3 ) self.wait() self.play(Write(distance_word, run_time = 2)) self.play( ReplacementTransform(int_arrow, s_arrow), FadeIn(s_T) ) self.wait() self.play(FadeOut(distance_word)) self.change_area_bounds(new_t_max = 0, run_time = 2) self.change_area_bounds( new_t_max = 8, rate_func=linear, run_time = 7.9, ) self.wait() self.change_area_bounds(new_t_max = 5) self.wait() def nudge_input(self): dark_area = self.area.copy() dark_area.set_fill(BLACK, opacity = 0.5) curr_T = self.x_axis.point_to_number(self.area.get_right()) new_T = curr_T + self.dT rect = Rectangle( stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.75 ) rect.replace( VGroup( VectorizedPoint(self.coords_to_point(new_T, 0)), self.right_v_line, ), stretch = True ) dT_brace = Brace(rect, DOWN, buff = 0) dT_label = dT_brace.get_text("$dT$", buff = SMALL_BUFF) dT_label_group = VGroup(dT_label, dT_brace) ds_label = OldTex("ds") ds_label.next_to(rect, RIGHT, LARGE_BUFF, UP) ds_label.set_color(DISTANCE_COLOR) ds_arrow = Arrow(ds_label.get_left(), rect.get_left()) ds_arrow.set_color(WHITE) v_brace = Brace(rect, LEFT, buff = SMALL_BUFF) v_T_label = v_brace.get_text("$v(T)$", buff = SMALL_BUFF) self.change_area_bounds(new_t_max = new_T) self.play( FadeIn(dark_area), *list(map(Animation, self.foreground_mobjects)) ) self.play( FadeOut(self.T_label_group), FadeIn(dT_label_group) ) self.wait() self.play(Write(ds_label)) self.play(ShowCreation(ds_arrow)) self.wait(2) self.play(GrowFromCenter(v_brace)) self.play(ReplacementTransform( self.v_graph_label.get_part_by_tex("v").copy(), v_T_label, run_time = 2 )) self.wait() self.play(Indicate(dT_label)) self.wait() self.rect = rect self.dT_label_group = dT_label_group self.v_T_label_group = VGroup(v_T_label, v_brace) self.dark_area = dark_area self.ds_label = ds_label self.ds_arrow = ds_arrow def show_rectangle_approximation(self): formula1 = OldTex("ds", "=", "v(T)", "dT") formula2 = OldTex("{ds", "\\over\\,", "dT}", "=", "v(T)") for formula in formula1, formula2: formula.next_to(self.v_graph_label, UP, LARGE_BUFF) formula.set_color_by_tex("ds", DISTANCE_COLOR) self.play( DrawBorderThenFill(self.rect), Animation(self.ds_arrow) ) self.wait() self.play(*[ ReplacementTransform( mob, formula1.get_part_by_tex(tex), run_time = 2 ) for mob, tex in [ (self.ds_label, "ds"), (self.ds_arrow, "="), (self.v_T_label_group[0].copy(), "v(T)"), (self.dT_label_group[0].copy(), "dT"), ] ]) self.wait() self.transition_to_alt_config( dT = self.dT/5.0, transformation_kwargs = {"run_time" : 2}, ) self.wait() self.play(*[ ReplacementTransform( formula1.get_part_by_tex(tex), formula2.get_part_by_tex(tex), ) for tex in ("ds", "=", "v(T)", "dT") ] + [ Write(formula2.get_part_by_tex("over")) ]) self.wait() #### def add_T_label(self, x_val, **kwargs): triangle = RegularPolygon(n=3, start_angle = np.pi/2) triangle.set_height(MED_SMALL_BUFF) triangle.move_to(self.coords_to_point(x_val, 0), UP) triangle.set_fill(WHITE, 1) triangle.set_stroke(width = 0) T_label = OldTex(self.variable_point_label) T_label.next_to(triangle, DOWN) v_line = self.get_vertical_line_to_graph( x_val, self.v_graph, color = YELLOW ) self.play( DrawBorderThenFill(triangle), ShowCreation(v_line), Write(T_label, run_time = 1), **kwargs ) self.T_label_group = VGroup(T_label, triangle) self.right_v_line = v_line def get_area(self, t_min, t_max): numerator = max(t_max - t_min, 0.01) dx = float(numerator) / self.num_rects return self.get_riemann_rectangles( self.v_graph, x_min = t_min, x_max = t_max, dx = dx, stroke_width = 0, ).set_fill(opacity = self.area_opacity) def change_area_bounds(self, new_t_min = None, new_t_max = None, **kwargs): curr_t_min = self.x_axis.point_to_number(self.area.get_left()) curr_t_max = self.x_axis.point_to_number(self.area.get_right()) if new_t_min is None: new_t_min = curr_t_min if new_t_max is None: new_t_max = curr_t_max group = VGroup(self.area, self.right_v_line, self.T_label_group) def update_group(group, alpha): area, v_line, T_label = group t_min = interpolate(curr_t_min, new_t_min, alpha) t_max = interpolate(curr_t_max, new_t_max, alpha) new_area = self.get_area(t_min, t_max) new_v_line = self.get_vertical_line_to_graph( t_max, self.v_graph ) new_v_line.set_color(v_line.get_color()) T_label.move_to(new_v_line.get_bottom(), UP) #Fade close to 0 T_label[0].set_fill(opacity = min(1, t_max)) Transform(area, new_area).update(1) Transform(v_line, new_v_line).update(1) return group self.play( UpdateFromAlphaFunc(group, update_group), *list(map(Animation, self.foreground_mobjects)), **kwargs ) class DirectInterpretationOfDsDt(TeacherStudentsScene): def construct(self): equation = OldTex("{ds", "\\over\\,", "dT}", "(T)", "=", "v(T)") ds, over, dt, of_T, equals, v = equation equation.next_to(self.get_pi_creatures(), UP, LARGE_BUFF) equation.shift(RIGHT) v.set_color(VELOCITY_COLOR) s_words = OldTexText("Tiny change in", "distance") s_words.next_to(ds, UP+LEFT, LARGE_BUFF) s_words.shift_onto_screen() s_arrow = Arrow(s_words[1].get_bottom(), ds.get_left()) s_words.add(s_arrow) s_words.set_color(DISTANCE_COLOR) t_words = OldTexText("Tiny change in", "time") t_words.next_to(dt, DOWN+LEFT) t_words.to_edge(LEFT) t_arrow = Arrow(t_words[1].get_top(), dt.get_left()) t_words.add(t_arrow) t_words.set_color(TIME_COLOR) self.add(ds, over, dt, of_T) for words, part in (s_words, ds), (t_words, dt): self.play( FadeIn( words, run_time = 2, lag_ratio = 0.5, ), self.students[1].change_mode, "raise_right_hand" ) self.play(part.set_color, words.get_color()) self.wait() self.play(Write(VGroup(equals, v))) self.play_student_changes(*["pondering"]*3) self.wait(3) class FindAntiderivative(Antiderivative): def construct(self): self.introduce() self.first_part() self.second_part() self.combine() self.add_plus_C() def introduce(self): q_marks, rhs = functions = self.get_functions("???", "t(8-t)") expanded_rhs = OldTex("8t - t^2") expanded_rhs.move_to(rhs, LEFT) expanded_rhs.set_color(rhs.get_color()) self.v_part1 = VGroup(*expanded_rhs[:2]) self.v_part2 = VGroup(*expanded_rhs[2:]) for part in self.v_part1, self.v_part2: part.save_state() top_arc, bottom_arc = arcs = self.get_arcs(functions) derivative, antiderivative = words = self.get_arc_labels(arcs) self.add(functions) self.play(*list(map(ShowCreation, arcs))) for word in words: self.play(FadeIn(word, lag_ratio = 0.5)) self.wait() self.change_mode("confused") self.wait(2) self.play(*[ ReplacementTransform( rhs[i], expanded_rhs[j], run_time = 2, path_arc = np.pi ) for i, j in enumerate([1, 4, 0, 2, 3, 4]) ]+[ self.pi_creature.change_mode, "hesitant" ]) self.wait() self.q_marks = q_marks self.arcs = arcs self.words = words def first_part(self): four_t_squared, two_t = self.get_functions("4t^2", "2t") four = four_t_squared[0] four.shift(UP) four.set_fill(opacity = 0) t_squared = VGroup(*four_t_squared[1:]) two_t.move_to(self.v_part1, LEFT) self.play(self.v_part2.to_corner, UP+RIGHT) self.play( self.pi_creature.change, "plain", self.v_part1 ) self.play(ApplyWave( self.q_marks, direction = UP, amplitude = SMALL_BUFF )) self.wait(2) self.play( FadeOut(self.q_marks), FadeIn(t_squared), self.v_part1.shift, DOWN+RIGHT, ) self.play(*[ ReplacementTransform( t_squared[i].copy(), two_t[1-i], run_time = 2, path_arc = -np.pi/6. ) for i in (0, 1) ]) self.change_mode("thinking") self.wait() self.play(four.set_fill, YELLOW, 1) self.play(four.shift, DOWN) self.play(FadeOut(two_t)) self.play(self.v_part1.restore) self.play(four.set_color, DISTANCE_COLOR) self.wait(2) self.s_part1 = four_t_squared def second_part(self): self.arcs_copy = self.arcs.copy() self.words_copy = self.words.copy() part1_group = VGroup( self.s_part1, self.v_part1, self.arcs_copy, self.words_copy ) neg_third_t_cubed, three_t_squared = self.get_functions( "- \\frac{1}{3} t^3", "3t^2" ) three_t_squared.move_to(self.v_part1, LEFT) neg = neg_third_t_cubed[0] third = VGroup(*neg_third_t_cubed[1:4]) t_cubed = VGroup(*neg_third_t_cubed[4:]) three = three_t_squared[0] t_squared = VGroup(*three_t_squared[1:]) self.play( part1_group.scale, 0.5, part1_group.to_corner, UP+LEFT, self.pi_creature.change_mode, "plain" ) self.play( self.v_part2.restore, self.v_part2.shift, LEFT ) self.play(FadeIn(self.q_marks)) self.wait() self.play( FadeOut(self.q_marks), FadeIn(t_cubed), self.v_part2.shift, DOWN+RIGHT ) self.play(*[ ReplacementTransform( t_cubed[i].copy(), three_t_squared[j], path_arc = -np.pi/6, run_time = 2, ) for i, j in [(0, 1), (1, 0), (1, 2)] ]) self.wait() self.play(FadeIn(third)) self.play(FadeOut(three)) self.wait(2) self.play(Write(neg)) self.play( FadeOut(t_squared), self.v_part2.shift, UP+LEFT ) self.wait(2) self.s_part2 = neg_third_t_cubed def combine(self): self.play( self.v_part1.restore, self.v_part2.restore, self.s_part1.scale, 2, self.s_part1.next_to, self.s_part2, LEFT, FadeOut(self.arcs_copy), FadeOut(self.words_copy), run_time = 2, ) self.change_mode("happy") self.wait(2) def add_plus_C(self): s_group = VGroup(self.s_part1, self.s_part2) plus_Cs = [ OldTex("+%d"%d) for d in range(1, 8) ] for plus_C in plus_Cs: plus_C.set_color(YELLOW) plus_C.move_to(s_group, RIGHT) plus_C = plus_Cs[0] self.change_mode("sassy") self.wait() self.play( s_group.next_to, plus_C.copy(), LEFT, GrowFromCenter(plus_C), ) self.wait() for new_plus_C in plus_Cs[1:]: self.play(Transform(plus_C, new_plus_C)) self.wait() class GraphSPlusC(GraphDistanceVsTime): CONFIG = { "y_axis_label" : "Distance" } def construct(self): self.setup_axes() graph = self.get_graph( s_func, color = DISTANCE_COLOR, x_min = 0, x_max = 8, ) tangent = self.get_secant_slope_group( 6, graph, dx = 0.01 ).secant_line v_line = self.get_vertical_line_to_graph( 6, graph, line_class = DashedLine ) v_line.scale(2) v_line.set_color(WHITE) graph_label, plus_C = full_label = OldTex( "s(t) = 4t^2 - \\frac{1}{3}t^3", "+C" ) plus_C.set_color(YELLOW) full_label.next_to(graph.get_points()[-1], DOWN) full_label.to_edge(RIGHT) self.play(ShowCreation(graph)) self.play(FadeIn(graph_label)) self.wait() self.play( graph.shift, UP, run_time = 2, rate_func = there_and_back ) self.play(ShowCreation(tangent)) graph.add(tangent) self.play(ShowCreation(v_line)) self.play( graph.shift, 2*DOWN, run_time = 4, rate_func = there_and_back, ) self.play(Write(plus_C)) self.play( graph.shift, 2*UP, rate_func = there_and_back, run_time = 4, ) self.wait() class LowerBound(AreaIsDerivative): CONFIG = { "graph_origin" : 2.5*DOWN + 6*LEFT } def construct(self): self.add_integral_and_area() self.mention_lower_bound() self.drag_right_endpoint_to_zero() self.write_antiderivative_difference() self.show_alternate_antiderivative_difference() self.add_constant_to_antiderivative() def add_integral_and_area(self): self.area = self.get_area(0, 6) self.integral = self.get_integral("0", "T") self.remove(self.x_axis.numbers) self.add(self.area, self.integral) self.add_T_label(6, run_time = 0) def mention_lower_bound(self): lower_bound = self.integral.get_part_by_tex("0") circle = Circle(color = YELLOW) circle.replace(lower_bound) circle.scale(3) zero_label = lower_bound.copy() self.play(ShowCreation(circle)) self.play(Indicate(lower_bound)) self.play( zero_label.scale, 1.5, zero_label.next_to, self.graph_origin, DOWN, MED_LARGE_BUFF, FadeOut(circle) ) self.wait() self.zero_label = zero_label def drag_right_endpoint_to_zero(self): zero_integral = self.get_integral("0", "0") zero_integral[1].set_color(YELLOW) zero_int_bounds = list(reversed( zero_integral.get_parts_by_tex("0") )) for bound in zero_int_bounds: circle = Circle(color = YELLOW) circle.replace(bound) circle.scale(3) bound.circle = circle self.integral.save_state() equals_zero = OldTex("=0") equals_zero.next_to(zero_integral, RIGHT) equals_zero.set_color(GREEN) self.change_area_bounds(0, 0, run_time = 3) self.play(ReplacementTransform( self.zero_label.copy(), equals_zero )) self.play(Transform(self.integral, zero_integral)) self.wait(2) for bound in zero_int_bounds: self.play(ShowCreation(bound.circle)) self.play(FadeOut(bound.circle)) self.play(*[ ReplacementTransform( bound.copy(), VGroup(equals_zero[1]) ) for bound in zero_int_bounds ]) self.wait(2) self.change_area_bounds(0, 5) self.play( self.integral.restore, FadeOut(equals_zero) ) self.zero_integral = zero_integral def write_antiderivative_difference(self): antideriv_diff = self.get_antiderivative_difference("0", "T") equals, at_T, minus, at_zero = antideriv_diff antideriv_diff_at_eight = self.get_antiderivative_difference("0", "8") at_eight = antideriv_diff_at_eight.left_part integral_at_eight = self.get_integral("0", "8") for part in at_T, at_zero, at_eight: part.brace = Brace(part, DOWN, buff = SMALL_BUFF) part.brace.save_state() antideriv_text = at_T.brace.get_text("Antiderivative", buff = SMALL_BUFF) antideriv_text.set_color(MAROON_B) value_at_eight = at_eight.brace.get_text( "%.2f"%s_func(8) ) happens_to_be_zero = at_zero.brace.get_text(""" Happens to equal 0 """) big_brace = Brace(VGroup(at_T, at_zero)) cancel_text = big_brace.get_text("Cancels when $T=0$") self.play(*list(map(Write, [equals, at_T]))) self.play( GrowFromCenter(at_T.brace), Write(antideriv_text, run_time = 2) ) self.change_area_bounds(0, 5.5, rate_func = there_and_back) self.wait() self.play( ReplacementTransform(at_T.copy(), at_zero), Write(minus) ) self.wait() self.play( ReplacementTransform(at_T.brace, big_brace), ReplacementTransform(antideriv_text, cancel_text) ) self.change_area_bounds(0, 0, run_time = 4) self.wait() self.play( ReplacementTransform(big_brace, at_zero.brace), ReplacementTransform(cancel_text, happens_to_be_zero), ) self.wait(2) self.change_area_bounds(0, 8, run_time = 2) self.play( Transform(self.integral, integral_at_eight), Transform(antideriv_diff, antideriv_diff_at_eight), MaintainPositionRelativeTo(at_zero.brace, at_zero), MaintainPositionRelativeTo(happens_to_be_zero, at_zero.brace), ) self.play( GrowFromCenter(at_eight.brace), Write(value_at_eight) ) self.wait(2) self.play(*list(map(FadeOut, [ at_eight.brace, value_at_eight, at_zero.brace, happens_to_be_zero, ]))) self.antideriv_diff = antideriv_diff def show_alternate_antiderivative_difference(self): new_integral = self.get_integral("1", "7") new_antideriv_diff = self.get_antiderivative_difference("1", "7") numbers = [ OldTex("%d"%d).next_to( self.coords_to_point(d, 0), DOWN, MED_LARGE_BUFF ) for d in (1, 7) ] tex_mobs = [new_integral]+new_antideriv_diff[1::2]+numbers for tex_mob in tex_mobs: tex_mob.set_color_by_tex("1", RED) tex_mob.set_color_by_tex("7", GREEN) tex_mob.set_color_by_tex("\\frac{1}{3}", WHITE) self.change_area_bounds(1, 7, run_time = 2) self.play( self.T_label_group[0].set_fill, None, 0, *list(map(FadeIn, numbers)) ) self.play( Transform(self.integral, new_integral), Transform(self.antideriv_diff, new_antideriv_diff), ) self.wait(3) for part in self.antideriv_diff[1::2]: self.play(Indicate(part, scale_factor = 1.1)) self.wait() def add_constant_to_antiderivative(self): antideriv_diff = self.antideriv_diff plus_fives = VGroup(*[Tex("+5") for i in range(2)]) plus_fives.set_color(YELLOW) for five, part in zip(plus_fives, antideriv_diff[1::2]): five.next_to(part, DOWN) group = VGroup( plus_fives[0], antideriv_diff[2].copy(), plus_fives[1] ) self.play(Write(plus_fives, run_time = 2)) self.wait(2) self.play( group.arrange, group.next_to, antideriv_diff, DOWN, MED_LARGE_BUFF ) self.wait() self.play(FadeOut(group, run_time = 2)) self.wait() ##### def get_integral(self, lower_bound, upper_bound): result = OldTex( "\\int", "^"+upper_bound, "_"+lower_bound, "t(8-t)", "\\,dt" ) result.next_to(self.graph_origin, RIGHT, MED_LARGE_BUFF) result.to_edge(UP) return result def get_antiderivative_difference(self, lower_bound, upper_bound): strings = [] for bound in upper_bound, lower_bound: try: d = int(bound) strings.append("(%d)"%d) except: strings.append(bound) parts = [] for s in strings: part = OldTex( "\\left(", "4", s, "^2", "-", "\\frac{1}{3}", s, "^3" "\\right))" ) part.set_color_by_tex(s, YELLOW, substring = False) parts.append(part) result = VGroup( OldTex("="), parts[0], OldTex("-"), parts[1], ) result.left_part, result.right_part = parts result.arrange(RIGHT) result.scale(0.9) result.next_to(self.integral, RIGHT) return result class FundamentalTheorem(GraphScene): CONFIG = { "lower_bound" : 1, "upper_bound" : 7, "lower_bound_color" : RED, "upper_bound_color" : GREEN, "n_riemann_iterations" : 6, } def construct(self): self.add_graph_and_integral() self.show_f_dx_sum() self.show_rects_approaching_area() self.write_antiderivative() self.write_fundamental_theorem_of_calculus() self.show_integral_considering_continuum() self.show_antiderivative_considering_bounds() def add_graph_and_integral(self): self.setup_axes() integral = OldTex("\\int", "^b", "_a", "f(x)", "\\,dx") integral.next_to(ORIGIN, LEFT) integral.to_edge(UP) integral.set_color_by_tex("a", self.lower_bound_color) integral.set_color_by_tex("b", self.upper_bound_color) graph = self.get_graph( lambda x : -0.01*x*(x-3)*(x-6)*(x-12) + 3, ) self.add(integral, graph) self.graph = graph self.integral = integral self.bound_labels = VGroup() self.v_lines = VGroup() for bound, tex in (self.lower_bound, "a"), (self.upper_bound, "b"): label = integral.get_part_by_tex(tex).copy() label.scale(1.5) label.next_to(self.coords_to_point(bound, 0), DOWN) v_line = self.get_vertical_line_to_graph( bound, graph, color = label.get_color() ) self.bound_labels.add(label) self.v_lines.add(v_line) self.add(label, v_line) def show_f_dx_sum(self): kwargs = { "x_min" : self.lower_bound, "x_max" : self.upper_bound, "fill_opacity" : 0.75, "stroke_width" : 0.25, } low_opacity = 0.25 start_rect_index = 3 num_shown_sum_steps = 5 last_rect_index = start_rect_index + num_shown_sum_steps + 1 self.rect_list = self.get_riemann_rectangles_list( self.graph, self.n_riemann_iterations, **kwargs ) rects = self.rects = self.rect_list[0] rects.save_state() start_rect = rects[start_rect_index] f_brace = Brace(start_rect, LEFT, buff = 0) dx_brace = Brace(start_rect, DOWN, buff = 0) f_brace.label = f_brace.get_text("$f(x)$") dx_brace.label = dx_brace.get_text("$dx$") flat_rects = self.get_riemann_rectangles( self.get_graph(lambda x : 0), dx = 0.5, **kwargs ) self.transform_between_riemann_rects( flat_rects, rects, replace_mobject_with_target_in_scene = True, ) self.play(*[ ApplyMethod( rect.set_fill, None, 1 if rect is start_rect else low_opacity ) for rect in rects ]) self.play(*it.chain( list(map(GrowFromCenter, [f_brace, dx_brace])), list(map(Write, [f_brace.label, dx_brace.label])), )) self.wait() for i in range(start_rect_index+1, last_rect_index): self.play( rects[i-1].set_fill, None, low_opacity, rects[i].set_fill, None, 1, f_brace.set_height, rects[i].get_height(), f_brace.next_to, rects[i], LEFT, 0, dx_brace.next_to, rects[i], DOWN, 0, *[ MaintainPositionRelativeTo(brace.label, brace) for brace in (f_brace, dx_brace) ] ) self.wait() self.play(*it.chain( list(map(FadeOut, [ f_brace, dx_brace, f_brace.label, dx_brace.label ])), [rects.set_fill, None, kwargs["fill_opacity"]] )) def show_rects_approaching_area(self): for new_rects in self.rect_list: self.transform_between_riemann_rects( self.rects, new_rects ) def write_antiderivative(self): deriv = OldTex( "{d", "F", "\\over\\,", "dx}", "(x)", "=", "f(x)" ) deriv_F = deriv.get_part_by_tex("F") deriv.next_to(self.integral, DOWN, MED_LARGE_BUFF) rhs = OldTex(*"=F(b)-F(a)") rhs.set_color_by_tex("a", self.lower_bound_color) rhs.set_color_by_tex("b", self.upper_bound_color) rhs.next_to(self.integral, RIGHT) self.play(Write(deriv)) self.wait(2) self.play(*it.chain( [ ReplacementTransform(deriv_F.copy(), part) for part in rhs.get_parts_by_tex("F") ], [ Write(VGroup(*rhs.get_parts_by_tex(tex))) for tex in "=()-" ] )) for tex in "b", "a": self.play(ReplacementTransform( self.integral.get_part_by_tex(tex).copy(), rhs.get_part_by_tex(tex) )) self.wait() self.wait(2) self.deriv = deriv self.rhs = rhs def write_fundamental_theorem_of_calculus(self): words = OldTexText(""" Fundamental theorem of calculus """) words.to_edge(RIGHT) self.play(Write(words)) self.wait() def show_integral_considering_continuum(self): self.play(*[ ApplyMethod(mob.set_fill, None, 0.2) for mob in (self.deriv, self.rhs) ]) self.play( self.rects.restore, run_time = 3, rate_func = there_and_back ) self.wait() for x in range(2): self.play(*[ ApplyFunction( lambda m : m.shift(MED_SMALL_BUFF*UP).set_fill(opacity = 1), rect, run_time = 3, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.2 ) ) for rect, alpha in zip( self.rects, np.linspace(0, 0.8, len(self.rects)) ) ]) self.wait() def show_antiderivative_considering_bounds(self): self.play( self.integral.set_fill, None, 0.5, self.deriv.set_fill, None, 1, self.rhs.set_fill, None, 1, ) for label, line in reversed(list(zip(self.bound_labels, self.v_lines))): new_line = line.copy().set_color(YELLOW) label.save_state() self.play(label.set_color, YELLOW) self.play(ShowCreation(new_line)) self.play(ShowCreation(line)) self.remove(new_line) self.play(label.restore) self.wait() self.play(self.integral.set_fill, None, 1) self.wait(3) class LetsRecap(TeacherStudentsScene): def construct(self): self.teacher_says( "Let's recap", target_mode = "hesitant", ) self.play_student_changes(*["happy"]*3) self.wait(3) class NegativeArea(GraphScene): CONFIG = { "x_axis_label" : "Time", "y_axis_label" : "Velocity", "graph_origin" : 1.5*DOWN + 5*LEFT, "y_min" : -3, "y_max" : 7, "small_dx" : 0.01, "sample_input" : 5, } def construct(self): self.setup_axes() self.add_graph_and_area() self.write_negative_area() self.show_negative_point() self.show_car_going_backwards() self.write_v_dt() self.show_rectangle() self.write_signed_area() def add_graph_and_area(self): graph = self.get_graph( lambda x : -0.02*(x+1)*(x-3)*(x-7)*(x-10), x_min = 0, x_max = 8, color = VELOCITY_COLOR ) area = self.get_riemann_rectangles( graph, x_min = 0, x_max = 8, dx = self.small_dx, start_color = BLUE_D, end_color = BLUE_D, fill_opacity = 0.75, stroke_width = 0, ) self .play( ShowCreation(graph), FadeIn( area, run_time = 2, lag_ratio = 0.5, ) ) self.graph = graph self.area = area def write_negative_area(self): words = OldTexText("Negative area") words.set_color(RED) words.next_to( self.coords_to_point(7, -2), RIGHT, ) arrow = Arrow(words, self.coords_to_point( self.sample_input, -1, )) self.play( Write(words, run_time = 2), ShowCreation(arrow) ) self.wait(2) self.play(*list(map(FadeOut, [self.area, arrow]))) self.negative_area_words = words def show_negative_point(self): v_line = self.get_vertical_line_to_graph( self.sample_input, self.graph, color = RED ) self.play(ShowCreation(v_line)) self.wait() self.v_line = v_line def show_car_going_backwards(self): car = Car() start_point = 3*RIGHT + 2*UP end_point = start_point + LEFT nudged_end_point = end_point + MED_SMALL_BUFF*LEFT car.move_to(start_point) arrow = Arrow(RIGHT, LEFT, color = RED) arrow.next_to(car, UP+LEFT) arrow.shift(MED_LARGE_BUFF*RIGHT) self.play(FadeIn(car)) self.play(ShowCreation(arrow)) self.play(MoveCar( car, end_point, moving_forward = False, run_time = 3 )) self.wait() ghost_car = car.copy().fade() right_nose_line = self.get_car_nose_line(car) self.play(ShowCreation(right_nose_line)) self.add(ghost_car) self.play(MoveCar( car, nudged_end_point, moving_forward = False )) left_nose_line = self.get_car_nose_line(car) self.play(ShowCreation(left_nose_line)) self.nose_lines = VGroup(left_nose_line, right_nose_line) self.car = car self.ghost_car = ghost_car def write_v_dt(self): brace = Brace(self.nose_lines, DOWN, buff = 0) equation = OldTex("ds", "=", "v(t)", "dt") equation.next_to(brace, DOWN, SMALL_BUFF, LEFT) equation.set_color_by_tex("ds", DISTANCE_COLOR) equation.set_color_by_tex("dt", TIME_COLOR) negative = OldTexText("Negative") negative.set_color(RED) negative.next_to(equation.get_corner(UP+RIGHT), UP, LARGE_BUFF) ds_arrow, v_arrow = arrows = VGroup(*[ Arrow( negative.get_bottom(), equation.get_part_by_tex(tex).get_top(), color = RED, ) for tex in ("ds", "v(t)") ]) self.play( GrowFromCenter(brace), Write(equation) ) self.wait() self.play(FadeIn(negative)) self.play(ShowCreation(v_arrow)) self.wait(2) self.play(ReplacementTransform( v_arrow.copy(), ds_arrow )) self.wait(2) self.ds_equation = equation self.negative_word = negative self.negative_word_arrows = arrows def show_rectangle(self): rect_list = self.get_riemann_rectangles_list( self.graph, x_min = 0, x_max = 8, n_iterations = 6, start_color = BLUE_D, end_color = BLUE_D, fill_opacity = 0.75, ) rects = rect_list[0] rect = rects[len(rects)*self.sample_input//8] dt_brace = Brace(rect, UP, buff = 0) v_brace = Brace(rect, LEFT, buff = 0) dt_label = dt_brace.get_text("$dt$", buff = SMALL_BUFF) dt_label.set_color(YELLOW) v_label = v_brace.get_text("$v(t)$", buff = SMALL_BUFF) v_label.add_background_rectangle() self.play(FadeOut(self.v_line), FadeIn(rect)) self.play( GrowFromCenter(dt_brace), GrowFromCenter(v_brace), Write(dt_label), Write(v_label), ) self.wait(2) self.play(*it.chain( [FadeIn(r) for r in rects if r is not rect], list(map(FadeOut, [ dt_brace, v_brace, dt_label, v_label ])) )) self.wait() for new_rects in rect_list[1:]: self.transform_between_riemann_rects(rects, new_rects) self.wait() def write_signed_area(self): words = OldTexText("``Signed area''") words.next_to(self.coords_to_point(self.sample_input, 0), UP) symbols = VGroup(*[ OldTex(sym).move_to(self.coords_to_point(*coords)) for sym, coords in [ ("+", (1, 2)), ("-", (5, -1)), ("+", (7.6, 0.5)), ] ]) self.play(Write(words)) self.play(Write(symbols)) self.wait() #### def get_car_nose_line(self, car): line = DashedLine(car.get_top(), car.get_bottom()) line.move_to(car.get_right()) return line class NextVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) next_video = series[8] integral = OldTex("\\int") integral.next_to(next_video, DOWN, LARGE_BUFF) self.play(FadeIn(series, lag_ratio = 0.5)) self.play( next_video.set_color, YELLOW, next_video.shift, next_video.get_height()*DOWN/2, self.teacher.change_mode, "raise_right_hand" ) self.play(Write(integral)) self.wait(5) class Chapter8PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "CrypticSwarm", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Jonathan Eppele", "Mathew Bramson", "Jerry Ling", "Mark Govea", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class Thumbnail(Chapter1Thumbnail): CONFIG = { "x_axis_label" : "", "y_axis_label" : "", "graph_origin" : 1.5*DOWN + 4*LEFT, "y_axis_height" : 5, "x_max" : 5, "x_axis_width" : 11, } def construct(self): self.setup_axes() self.remove(*self.x_axis.numbers) self.remove(*self.y_axis.numbers) graph = self.get_graph(self.func) rects = self.get_riemann_rectangles( graph, x_min = 0, x_max = 4, dx = 0.25, ) words = OldTexText("Integrals") words.set_width(8) words.to_edge(UP) self.add(graph, rects, words)
videos_3b1b/_2017/eoc/chapter10.py
from manim_imports_ext import * def derivative(func, x, n = 1, dx = 0.01): samples = [func(x + (k - n/2)*dx) for k in range(n+1)] while len(samples) > 1: samples = [ (s_plus_dx - s)/dx for s, s_plus_dx in zip(samples, samples[1:]) ] return samples[0] def taylor_approximation(func, highest_term, center_point = 0): derivatives = [ derivative(func, center_point, n = n) for n in range(highest_term + 1) ] coefficients = [ d/math.factorial(n) for n, d in enumerate(derivatives) ] return lambda x : sum([ c*((x-center_point)**n) for n, c in enumerate(coefficients) ]) class Chapter10OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "For me, mathematics is a collection of ", "examples", "; a ", "theorem", " is a statement about a collection of ", "examples", " and the purpose of proving ", "theorems", " is to classify and explain the ", "examples", "." ], "quote_arg_separator" : "", "highlighted_quote_terms" : { "examples" : BLUE, }, "author" : "John B. Conway", "fade_in_kwargs" : { "run_time" : 7, } } class ExampleApproximation(GraphScene): CONFIG = { "function" : lambda x : np.exp(-x**2), "function_tex" : "e^{-x^2}", "function_color" : BLUE, "order_sequence" : [0, 2, 4], "center_point" : 0, "approximation_terms" : ["1 ", "-x^2", "+\\frac{1}{2}x^4"], "approximation_color" : GREEN, "x_min" : -3, "x_max" : 3, "y_min" : -1, "y_max" : 2, "graph_origin" : DOWN + 2*LEFT, } def construct(self): self.setup_axes() func_graph = self.get_graph( self.function, self.function_color, ) approx_graphs = [ self.get_graph( taylor_approximation(self.function, n), self.approximation_color ) for n in self.order_sequence ] near_text = OldTexText( "Near %s $= %d$"%( self.x_axis_label, self.center_point ) ) near_text.to_corner(UP + RIGHT) near_text.add_background_rectangle() equation = OldTex( self.function_tex, "\\approx", *self.approximation_terms ) equation.next_to(near_text, DOWN, MED_LARGE_BUFF) equation.to_edge(RIGHT) near_text.next_to(equation, UP, MED_LARGE_BUFF) equation.set_color_by_tex( self.function_tex, self.function_color, substring = False ) approx_terms = VGroup(*[ equation.get_part_by_tex(tex, substring = False) for tex in self.approximation_terms ]) approx_terms.set_fill( self.approximation_color, opacity = 0, ) equation.add_background_rectangle() approx_graph = VectorizedPoint( self.input_to_graph_point(self.center_point, func_graph) ) self.play( ShowCreation(func_graph, run_time = 2), Animation(equation), Animation(near_text), ) for graph, term in zip(approx_graphs, approx_terms): self.play( Transform(approx_graph, graph, run_time = 2), Animation(equation), Animation(near_text), term.set_fill, None, 1, ) self.wait() self.wait(2) class ExampleApproximationWithSine(ExampleApproximation): CONFIG = { "function" : np.sin, "function_tex" : "\\sin(x)", "order_sequence" : [1, 3, 5], "center_point" : 0, "approximation_terms" : [ "x", "-\\frac{1}{6}x^3", "+\\frac{1}{120}x^5", ], "approximation_color" : GREEN, "x_min" : -2*np.pi, "x_max" : 2*np.pi, "x_tick_frequency" : np.pi/2, "y_min" : -2, "y_max" : 2, "graph_origin" : DOWN + 2*LEFT, } class ExampleApproximationWithExp(ExampleApproximation): CONFIG = { "function" : np.exp, "function_tex" : "e^x", "order_sequence" : [1, 2, 3, 4], "center_point" : 0, "approximation_terms" : [ "1 + x", "+\\frac{1}{2}x^2", "+\\frac{1}{6}x^3", "+\\frac{1}{24}x^4", ], "approximation_color" : GREEN, "x_min" : -3, "x_max" : 4, "y_min" : -1, "y_max" : 10, "graph_origin" : 2*DOWN + 3*LEFT, } class Pendulum(ReconfigurableScene): CONFIG = { "anchor_point" : 3*UP + 4*LEFT, "radius" : 4, "weight_radius" : 0.2, "angle" : np.pi/6, "approx_tex" : [ "\\approx 1 - ", "{\\theta", "^2", "\\over", "2}" ], "leave_original_cosine" : False, "perform_substitution" : True, } def construct(self): self.draw_pendulum() self.show_oscillation() self.show_height() self.get_angry_at_cosine() self.substitute_approximation() self.show_confusion() def draw_pendulum(self): pendulum = self.get_pendulum() ceiling = self.get_ceiling() self.add(ceiling) self.play(ShowCreation(pendulum.line)) self.play(DrawBorderThenFill(pendulum.weight, run_time = 1)) self.pendulum = pendulum def show_oscillation(self): trajectory_dots = self.get_trajectory_dots() kwargs = self.get_swing_kwargs() self.play( ShowCreation( trajectory_dots, rate_func=linear, run_time = kwargs["run_time"] ), Rotate(self.pendulum, -2*self.angle, **kwargs), ) for m in 2, -2, 2: self.play(Rotate(self.pendulum, m*self.angle, **kwargs)) self.wait() def show_height(self): v_line = self.get_v_line() h_line = self.get_h_line() radius_brace = self.get_radius_brace() height_brace = self.get_height_brace() height_tex = self.get_height_brace_tex(height_brace) arc, theta = self.get_arc_and_theta() height_tex_R = height_tex.get_part_by_tex("R") height_tex_theta = height_tex.get_part_by_tex("\\theta") to_write = VGroup(*[ part for part in height_tex if part not in [height_tex_R, height_tex_theta] ]) self.play( ShowCreation(h_line), GrowFromCenter(height_brace) ) self.play( ShowCreation(v_line), ShowCreation(arc), Write(theta), ) self.play( GrowFromCenter(radius_brace) ) self.wait(2) self.play( Write(to_write), ReplacementTransform( radius_brace[-1].copy(), height_tex_R ), ReplacementTransform( theta.copy(), height_tex_theta ), run_time = 2 ) self.wait(2) self.arc = arc self.theta = theta self.height_tex_R = height_tex_R self.cosine = VGroup(*[ height_tex.get_part_by_tex(tex) for tex in ("cos", "theta", ")") ]) self.one_minus = VGroup(*[ height_tex.get_part_by_tex(tex) for tex in ("\\big(1-", "\\big)") ]) def get_angry_at_cosine(self): cosine = self.cosine morty = Mortimer() morty.to_corner(DOWN+RIGHT) cosine.generate_target() cosine.save_state() cosine.target.next_to(morty, UP) if self.leave_original_cosine: cosine_copy = cosine.copy() self.add(cosine_copy) self.one_minus.add(cosine_copy) self.play(FadeIn(morty)) self.play( MoveToTarget(cosine), morty.change, "angry", cosine.target, ) self.wait() self.play(Blink(morty)) self.wait() self.morty = morty def substitute_approximation(self): morty = self.morty cosine = self.cosine cosine.generate_target() cosine_approx = self.get_cosine_approx() cosine_approx.next_to(cosine, UP+RIGHT) cosine_approx.to_edge(RIGHT) cosine.target.next_to( cosine_approx, LEFT, align_using_submobjects = True ) kwargs = self.get_swing_kwargs() self.play( FadeIn( cosine_approx, run_time = 2, lag_ratio = 0.5 ), MoveToTarget(cosine), morty.change, "pondering", cosine_approx ) self.wait() if not self.perform_substitution: return self.play( ApplyMethod( cosine_approx.theta_squared_over_two.copy().next_to, self.height_tex_R, run_time = 2, ), FadeOut(self.one_minus), morty.look_at, self.height_tex_R, ) self.play(morty.change, "thinking", self.height_tex_R) self.transition_to_alt_config( angle = np.pi/12, transformation_kwargs = {"run_time" : 2}, ) def show_confusion(self): randy = Randolph(color = BLUE_C) randy.scale(0.8) randy.next_to(self.cosine, DOWN+LEFT) randy.to_edge(DOWN) self.play(FadeIn(randy)) self.play( randy.change, "confused", self.cosine ) self.play(randy.look_at, self.height_tex_R) self.wait() self.play(randy.look_at, self.cosine) self.play(Blink(randy)) self.wait() ####### def get_pendulum(self): line = Line( self.anchor_point, self.anchor_point + self.radius*DOWN, color = WHITE ) weight = Circle( radius = self.weight_radius, fill_color = GREY, fill_opacity = 1, stroke_width = 0, ) weight.move_to(line.get_end()) result = VGroup(line, weight) result.rotate( self.angle, about_point = self.anchor_point ) result.line = line result.weight = weight return result def get_ceiling(self): line = Line(LEFT, RIGHT, color = GREY) line.scale(FRAME_X_RADIUS) line.move_to(self.anchor_point[1]*UP) return line def get_trajectory_dots(self, n_dots = 40, color = YELLOW): arc_angle = np.pi/6 proportions = self.swing_rate_func( np.linspace(0, 1, n_dots) ) angles = -2*arc_angle*proportions angle_to_point = lambda a : np.cos(a)*RIGHT + np.sin(a)*UP dots = VGroup(*[ # Line(*map(angle_to_point, pair)) Dot(angle_to_point(angle), radius = 0.005) for angle in angles ]) dots.set_color(color) dots.scale(self.radius) dots.rotate(-np.pi/2 + arc_angle) dots.shift(self.anchor_point) return dots def get_v_line(self): return DashedLine( self.anchor_point, self.anchor_point + self.radius*DOWN, color = WHITE ) def get_h_line(self, color = BLUE): start = self.anchor_point + self.radius*DOWN end = start + self.radius*np.sin(self.angle)*RIGHT return Line(start, end, color = color) def get_radius_brace(self): v_line = self.get_v_line() brace = Brace(v_line, RIGHT) brace.rotate(self.angle, about_point = self.anchor_point) brace.add(brace.get_text("$R$", buff = SMALL_BUFF)) return brace def get_height_brace(self): h_line = self.get_h_line() height = (1 - np.cos(self.angle))*self.radius line = Line( h_line.get_end(), h_line.get_end() + height*UP, ) brace = Brace(line, RIGHT) return brace def get_height_brace_tex(self, brace): tex_mob = OldTex( "R", "\\big(1-", "\\cos(", "\\theta", ")", "\\big)" ) tex_mob.set_color_by_tex("theta", YELLOW) tex_mob.next_to(brace, RIGHT) return tex_mob def get_arc_and_theta(self): arc = Arc( start_angle = -np.pi/2, angle = self.angle, color = YELLOW ) theta = OldTex("\\theta") theta.set_color(YELLOW) theta.next_to( arc.point_from_proportion(0.5), DOWN, SMALL_BUFF ) for mob in arc, theta: mob.shift(self.anchor_point) return arc, theta def get_cosine_approx(self): approx = OldTex(*self.approx_tex) approx.set_color_by_tex("theta", YELLOW) approx.theta_squared_over_two = VGroup(*approx[1:5]) return approx def get_swing_kwargs(self): return { "about_point" : self.anchor_point, "run_time" : 1.7, "rate_func" : self.swing_rate_func, } def swing_rate_func(self, t): return (1-np.cos(np.pi*t))/2.0 class PendulumWithBetterApprox(Pendulum): CONFIG = { "approx_tex" : [ "\\approx 1 - ", "{\\theta", "^2", "\\over", "2}", "+", "{\\theta", "^4", "\\over", "24}" ], "leave_original_cosine" : True, "perform_substitution" : False, } def show_confusion(self): pass class ExampleApproximationWithCos(ExampleApproximationWithSine): CONFIG = { "function" : np.cos, "function_tex" : "\\cos(\\theta)", "order_sequence" : [0, 2], "approximation_terms" : [ "1", "-\\frac{1}{2} \\theta ^2", ], "x_axis_label" : "$\\theta$", "y_axis_label" : "", "x_axis_width" : 13, "graph_origin" : DOWN, } def construct(self): ExampleApproximationWithSine.construct(self) randy = Randolph(color = BLUE_C) randy.to_corner(DOWN+LEFT) high_graph = self.get_graph(lambda x : 4) v_lines, alt_v_lines = [ VGroup(*[ self.get_vertical_line_to_graph( u*dx, high_graph, line_class = DashedLine, color = YELLOW ) for u in (-1, 1) ]) for dx in (0.01, 0.7) ] self.play(*list(map(ShowCreation, v_lines)), run_time = 2) self.play(Transform( v_lines, alt_v_lines, run_time = 2, )) self.play(FadeIn(randy)) self.play(PiCreatureBubbleIntroduction( randy, "How...?", bubble_type = ThoughtBubble, look_at = self.graph_origin, target_mode = "confused" )) self.wait(2) self.play(Blink(randy)) self.wait() def setup_axes(self): GraphScene.setup_axes(self) x_val_label_pairs = [ (-np.pi, "-\\pi"), (np.pi, "\\pi"), (2*np.pi, "2\\pi"), ] self.x_axis_labels = VGroup() for x_val, label in x_val_label_pairs: tex = OldTex(label) tex.next_to(self.coords_to_point(x_val, 0), DOWN) self.add(tex) self.x_axis_labels.add(tex) class ConstructQuadraticApproximation(ExampleApproximationWithCos): CONFIG = { "x_axis_label" : "$x$", "colors" : [BLUE, YELLOW, GREEN], } def construct(self): self.setup_axes() self.add_cosine_graph() self.add_quadratic_graph() self.introduce_quadratic_constants() self.show_value_at_zero() self.set_c0_to_one() self.let_c1_and_c2_vary() self.show_tangent_slope() self.compute_cosine_derivative() self.compute_polynomial_derivative() self.let_c2_vary() self.point_out_negative_concavity() self.compute_cosine_second_derivative() self.show_matching_curvature() self.show_matching_tangent_lines() self.compute_polynomial_second_derivative() self.box_final_answer() def add_cosine_graph(self): cosine_label = OldTex("\\cos(x)") cosine_label.to_corner(UP+LEFT) cosine_graph = self.get_graph(np.cos) dot = Dot(color = WHITE) dot.move_to(cosine_label) for mob in cosine_label, cosine_graph: mob.set_color(self.colors[0]) def update_dot(dot): dot.move_to(cosine_graph.get_points()[-1]) return dot self.play(Write(cosine_label, run_time = 1)) self.play(dot.move_to, cosine_graph.get_points()[0]) self.play( ShowCreation(cosine_graph), UpdateFromFunc(dot, update_dot), run_time = 4 ) self.play(FadeOut(dot)) self.cosine_label = cosine_label self.cosine_graph = cosine_graph def add_quadratic_graph(self): quadratic_graph = self.get_quadratic_graph() self.play(ReplacementTransform( self.cosine_graph.copy(), quadratic_graph, run_time = 3 )) self.quadratic_graph = quadratic_graph def introduce_quadratic_constants(self): quadratic_tex = self.get_quadratic_tex("c_0", "c_1", "c_2") const_terms = quadratic_tex.get_parts_by_tex("c") free_to_change = OldTexText("Free to change") free_to_change.next_to(const_terms, DOWN, LARGE_BUFF) arrows = VGroup(*[ Arrow( free_to_change.get_top(), const.get_bottom(), tip_length = 0.75*Arrow.CONFIG["tip_length"], color = const.get_color() ) for const in const_terms ]) alt_consts_list = [ (0, -1, -0.25), (1, -1, -0.25), (1, 0, -0.25), (), ] self.play(FadeIn( quadratic_tex, run_time = 3, lag_ratio = 0.5 )) self.play( FadeIn(free_to_change), *list(map(ShowCreation, arrows)) ) self.play(*[ ApplyMethod( const.scale, 0.8, run_time = 2, rate_func = squish_rate_func(there_and_back, a, a + 0.75) ) for const, a in zip(const_terms, np.linspace(0, 0.25, len(const_terms))) ]) for alt_consts in alt_consts_list: self.change_quadratic_graph( self.quadratic_graph, *alt_consts ) self.wait() self.quadratic_tex = quadratic_tex self.free_to_change_group = VGroup(free_to_change, *arrows) self.free_to_change_group.arrows = arrows def show_value_at_zero(self): arrow, x_equals_0 = ax0_group = self.get_arrow_x_equals_0_group() ax0_group.next_to( self.cosine_label, RIGHT, align_using_submobjects = True ) one = OldTex("1") one.next_to(arrow, RIGHT) one.save_state() one.move_to(self.cosine_label) one.set_fill(opacity = 0) v_line = self.get_vertical_line_to_graph( 0, self.cosine_graph, line_class = DashedLine, color = YELLOW ) self.play(ShowCreation(v_line)) self.play( ShowCreation(arrow), Write(x_equals_0, run_time = 2) ) self.play(one.restore) self.wait() self.v_line = v_line self.equals_one_group = VGroup(arrow, x_equals_0, one) def set_c0_to_one(self): poly_at_zero = self.get_quadratic_tex( "c_0", "c_1", "c_2", arg = "0" ) poly_at_zero.next_to(self.quadratic_tex, DOWN) equals_c0 = OldTex("=", "c_0", "+0") equals_c0.set_color_by_tex("c_0", self.colors[0]) equals_c0.next_to( poly_at_zero.get_part_by_tex("="), DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) poly_group = VGroup( equals_c0, poly_at_zero, self.quadratic_tex, ) poly_group_target = VGroup( OldTex("=", "1", "+0").set_color_by_tex("1", self.colors[0]), self.get_quadratic_tex("1", "c_1", "c_2", arg = "0"), self.get_quadratic_tex("1", "c_1", "c_2"), ) for start, target in zip(poly_group, poly_group_target): target.move_to(start) self.play(FadeOut(self.free_to_change_group)) self.play(ReplacementTransform( self.quadratic_tex.copy(), poly_at_zero )) self.wait(2) self.play(FadeIn(equals_c0)) self.wait(2) self.play(Transform( poly_group, poly_group_target, run_time = 2, lag_ratio = 0.5 )) self.wait(2) self.play(*list(map(FadeOut, [poly_at_zero, equals_c0]))) self.free_to_change_group.remove( self.free_to_change_group.arrows[0] ) self.play(FadeIn(self.free_to_change_group)) def let_c1_and_c2_vary(self): alt_consts_list = [ (1, 1, -0.25), (1, -1, -0.25), (1, -1, 0.25), (1, 1, -0.1), ] for alt_consts in alt_consts_list: self.change_quadratic_graph( self.quadratic_graph, *alt_consts ) self.wait() def show_tangent_slope(self): graph_point_at_zero = self.input_to_graph_point( 0, self.cosine_graph ) tangent_line = self.get_tangent_line(0, self.cosine_graph) self.play(ShowCreation(tangent_line)) self.change_quadratic_graph( self.quadratic_graph, 1, 0, -0.1 ) self.wait() self.change_quadratic_graph( self.quadratic_graph, 1, 1, -0.1 ) self.wait(2) self.change_quadratic_graph( self.quadratic_graph, 1, 0, -0.1 ) self.wait(2) self.tangent_line = tangent_line def compute_cosine_derivative(self): derivative, rhs = self.get_cosine_derivative() self.play(FadeIn( VGroup(derivative, *rhs[:2]), run_time = 2, lag_ratio = 0.5 )) self.wait(2) self.play(Write(VGroup(*rhs[2:])), run_time = 2) self.wait() self.play(Rotate( self.tangent_line, np.pi/12, in_place = True, run_time = 3, rate_func = wiggle )) self.wait() def compute_polynomial_derivative(self): derivative = self.get_quadratic_derivative("c_1", "c_2") derivative_at_zero = self.get_quadratic_derivative( "c_1", "c_2", arg = "0" ) equals_c1 = OldTex("=", "c_1", "+0") equals_c1.next_to( derivative_at_zero.get_part_by_tex("="), DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT, ) equals_c1.set_color_by_tex("c_1", self.colors[1]) poly_group = VGroup( equals_c1, derivative, self.quadratic_tex ) poly_group_target = VGroup( OldTex("=", "0", "+0").set_color_by_tex( "0", self.colors[1], substring = False ), self.get_quadratic_derivative("0", "c_2", arg = "0"), self.get_quadratic_tex("1", "0", "c_2") ) for start, target in zip(poly_group, poly_group_target): target.move_to(start) self.play(FadeOut(self.free_to_change_group)) self.play(FadeIn( derivative, run_time = 3, lag_ratio = 0.5 )) self.wait() self.play(Transform( derivative, derivative_at_zero, run_time = 2, lag_ratio = 0.5 )) self.wait(2) self.play(Write(equals_c1)) self.wait(2) self.play(Transform( poly_group, poly_group_target, run_time = 3, lag_ratio = 0.5 )) self.wait(2) self.play(*list(map(FadeOut, poly_group[:-1]))) self.free_to_change_group.remove( self.free_to_change_group.arrows[1] ) self.play(FadeIn(self.free_to_change_group)) def let_c2_vary(self): alt_c2_values = [-1, -0.05, 1, -0.2] for alt_c2 in alt_c2_values: self.change_quadratic_graph( self.quadratic_graph, 1, 0, alt_c2 ) self.wait() def point_out_negative_concavity(self): partial_cosine_graph = self.get_graph( np.cos, x_min = -1, x_max = 1, color = PINK ) self.play(ShowCreation(partial_cosine_graph, run_time = 2)) self.wait() for x, run_time in (-1, 2), (1, 4): self.play(self.get_tangent_line_change_anim( self.tangent_line, x, self.cosine_graph, run_time = run_time )) self.wait() self.play(*list(map(FadeOut, [ partial_cosine_graph, self.tangent_line ]))) def compute_cosine_second_derivative(self): second_deriv, rhs = self.get_cosine_second_derivative() self.play(FadeIn( VGroup(second_deriv, *rhs[1][:2]), run_time = 2, lag_ratio = 0.5 )) self.wait(3) self.play(Write(VGroup(*rhs[1][2:]), run_time = 2)) self.wait() def show_matching_curvature(self): alt_consts_list = [ (1, 1, -0.2), (1, 0, -0.2), (1, 0, -0.5), ] for alt_consts in alt_consts_list: self.change_quadratic_graph( self.quadratic_graph, *alt_consts ) self.wait() def show_matching_tangent_lines(self): graphs = [self.quadratic_graph, self.cosine_graph] tangent_lines = [ self.get_tangent_line(0, graph, color = color) for graph, color in zip(graphs, [WHITE, YELLOW]) ] tangent_change_anims = [ self.get_tangent_line_change_anim( line, np.pi/2, graph, run_time = 6, rate_func = there_and_back, ) for line, graph in zip(tangent_lines, graphs) ] self.play(*list(map(ShowCreation, tangent_lines))) self.play(*tangent_change_anims) self.play(*list(map(FadeOut, tangent_lines))) def compute_polynomial_second_derivative(self): c2s = ["c_2", "\\text{\\tiny $\\left(-\\frac{1}{2}\\right)$}"] derivs = [ self.get_quadratic_derivative("0", c2) for c2 in c2s ] second_derivs = [ OldTex( "{d^2 P \\over dx^2}", "(x)", "=", "2", c2 ) for c2 in c2s ] for deriv, second_deriv in zip(derivs, second_derivs): second_deriv[0].scale( 0.7, about_point = second_deriv[0].get_right() ) second_deriv[-1].set_color(self.colors[-1]) second_deriv.next_to( deriv, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) poly_group = VGroup( second_derivs[0], derivs[0], self.quadratic_tex ) poly_group_target = VGroup( second_derivs[1], derivs[1], self.get_quadratic_tex("1", "0", c2s[1]) ) for tex_mob in poly_group_target: tex_mob.get_part_by_tex(c2s[1]).shift(SMALL_BUFF*UP) self.play(FadeOut(self.free_to_change_group)) self.play(FadeIn(derivs[0])) self.wait(2) self.play(Write(second_derivs[0])) self.wait(2) self.play(Transform( poly_group, poly_group_target, run_time = 3, lag_ratio = 0.5 )) self.wait(3) def box_final_answer(self): box = Rectangle(stroke_color = PINK) box.stretch_to_fit_width( self.quadratic_tex.get_width() + MED_LARGE_BUFF ) box.stretch_to_fit_height( self.quadratic_tex.get_height() + MED_LARGE_BUFF ) box.move_to(self.quadratic_tex) self.play(ShowCreation(box, run_time = 2)) self.wait(2) ###### def change_quadratic_graph(self, graph, *args, **kwargs): transformation_kwargs = {} transformation_kwargs["run_time"] = kwargs.pop("run_time", 2) transformation_kwargs["rate_func"] = kwargs.pop("rate_func", smooth) new_graph = self.get_quadratic_graph(*args, **kwargs) self.play(Transform(graph, new_graph, **transformation_kwargs)) graph.underlying_function = new_graph.underlying_function def get_quadratic_graph(self, c0 = 1, c1 = 0, c2 = -0.5): return self.get_graph( lambda x : c0 + c1*x + c2*x**2, color = self.colors[2] ) def get_quadratic_tex(self, c0, c1, c2, arg = "x"): tex_mob = OldTex( "P(", arg, ")", "=", c0, "+", c1, arg, "+", c2, arg, "^2" ) for tex, color in zip([c0, c1, c2], self.colors): tex_mob.set_color_by_tex(tex, color) tex_mob.to_corner(UP+RIGHT) return tex_mob def get_quadratic_derivative(self, c1, c2, arg = "x"): result = OldTex( "{dP \\over dx}", "(", arg, ")", "=", c1, "+", "2", c2, arg ) result[0].scale(0.7, about_point = result[0].get_right()) for index, color in zip([5, 8], self.colors[1:]): result[index].set_color(color) if hasattr(self, "quadratic_tex"): result.next_to( self.quadratic_tex, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) return result def get_arrow_x_equals_0_group(self): arrow = Arrow(LEFT, RIGHT) x_equals_0 = OldTex("x = 0") x_equals_0.scale(0.75) x_equals_0.next_to(arrow.get_center(), UP, 2*SMALL_BUFF) x_equals_0.shift(SMALL_BUFF*LEFT) return VGroup(arrow, x_equals_0) def get_tangent_line(self, x, graph, color = YELLOW): tangent_line = Line(LEFT, RIGHT, color = color) tangent_line.rotate(self.angle_of_tangent(x, graph)) tangent_line.scale(2) tangent_line.move_to(self.input_to_graph_point(x, graph)) return tangent_line def get_tangent_line_change_anim(self, tangent_line, new_x, graph, **kwargs): start_x = self.x_axis.point_to_number( tangent_line.get_center() ) def update(tangent_line, alpha): x = interpolate(start_x, new_x, alpha) new_line = self.get_tangent_line( x, graph, color = tangent_line.get_color() ) Transform(tangent_line, new_line).update(1) return tangent_line return UpdateFromAlphaFunc(tangent_line, update, **kwargs) def get_cosine_derivative(self): if not hasattr(self, "cosine_label"): self.cosine_label = OldTex("\\cos(x)") self.cosine_label.to_corner(UP+LEFT) derivative = OldTex( "{d(", "\\cos", ")", "\\over", "dx}", "(0)", ) derivative.set_color_by_tex("\\cos", self.colors[0]) derivative.scale(0.7) derivative.next_to( self.cosine_label, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) rhs = OldTex("=", "-\\sin(0)", "=", "0") rhs.set_color_by_tex("\\sin", self.colors[1]) rhs.scale(0.75) rhs.next_to( derivative, RIGHT, align_using_submobjects = True ) self.cosine_derivative = VGroup(derivative, rhs) return self.cosine_derivative def get_cosine_second_derivative(self): if not hasattr(self, "cosine_derivative"): self.get_cosine_derivative() second_deriv = OldTex( "{d^2(", "\\cos", ")", "\\over", "dx^2}", "(", "0", ")", ) second_deriv.set_color_by_tex("cos", self.colors[0]) second_deriv.set_color_by_tex("-\\cos", self.colors[2]) second_deriv.scale(0.75) second_deriv.add_background_rectangle() second_deriv.next_to( self.cosine_derivative, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) rhs = OldTex("=", "-\\cos(0)", "=", "-1") rhs.set_color_by_tex("cos", self.colors[2]) rhs.scale(0.8) rhs.next_to( second_deriv, RIGHT, align_using_submobjects = True ) rhs.add_background_rectangle() self.cosine_second_derivative = VGroup(second_deriv, rhs) return self.cosine_second_derivative class ReflectOnQuadraticApproximation(TeacherStudentsScene): def construct(self): self.show_example_approximation() # self.add_polynomial() # self.show_c0() # self.show_c1() # self.show_c2() def show_example_approximation(self): approx_at_x, approx_at_point = [ OldTex( "\\cos(", s, ")", "\\approx", "1 - \\frac{1}{2}", "(", s, ")", "^2" ).next_to(self.get_students(), UP, 2) for s in ("x", "0.1",) ] approx_rhs = OldTex("=", "0.995") approx_rhs.next_to(approx_at_point, RIGHT) real_result = OldTex( "\\cos(", "0.1", ")", "=", "%.7f\\dots"%np.cos(0.1) ) real_result.shift( approx_rhs.get_part_by_tex("=").get_center() -\ real_result.get_part_by_tex("=").get_center() ) for mob in approx_at_point, real_result: mob.set_color_by_tex("0.1", YELLOW) real_result.set_fill(opacity = 0) self.play( Write(approx_at_x, run_time = 2), self.teacher.change_mode, "raise_right_hand" ) self.wait(2) self.play(ReplacementTransform( approx_at_x, approx_at_point, )) self.wait() self.play(Write(approx_rhs)) self.wait(2) self.play( real_result.shift, 1.5*DOWN, real_result.set_fill, None, 1, ) self.play_student_changes(*["hooray"]*3) self.wait(2) self.play_student_changes( *["plain"]*3, added_anims = list(map(FadeOut, [ approx_at_point, approx_rhs, real_result ])), look_at = approx_at_x ) def add_polynomial(self): polynomial = self.get_polynomial() const_terms = polynomial.get_parts_by_tex("c") self.play( Write(polynomial), self.teacher.change, "pondering" ) self.wait(2) self.play(*[ ApplyMethod( const.shift, MED_LARGE_BUFF*UP, run_time = 2, rate_func = squish_rate_func(there_and_back, a, a+0.7) ) for const, a in zip(const_terms, np.linspace(0, 0.3, len(const_terms))) ]) self.wait() self.const_terms = const_terms self.polynomial = polynomial def show_c0(self): c0 = self.polynomial.get_part_by_tex("c_0") c0.save_state() equation = OldTex("P(0) = \\cos(0)") equation.to_corner(UP+RIGHT) new_polynomial = self.get_polynomial(c0 = "1") self.play(c0.shift, UP) self.play(Write(equation)) self.wait() self.play(Transform(self.polynomial, new_polynomial)) self.play(FadeOut(equation)) def show_c1(self): c1 = self.polynomial.get_part_by_tex("c_1") c1.save_state() equation = OldTex( "\\frac{dP}{dx}(0) = \\frac{d(\\cos)}{dx}(0)" ) equation.to_corner(UP+RIGHT) new_polynomial = self.get_polynomial(c0 = "1", c1 = "0") self.play(c1.shift, UP) self.play(Write(equation)) self.wait() self.play(Transform(self.polynomial, new_polynomial)) self.wait() self.play(FadeOut(equation)) def show_c2(self): c2 = self.polynomial.get_part_by_tex("c_2") c2.save_state() equation = OldTex( "\\frac{d^2 P}{dx^2}(0) = \\frac{d^2(\\cos)}{dx^2}(0)" ) equation.to_corner(UP+RIGHT) alt_c2_tex = "\\text{\\tiny $\\left(-\\frac{1}{2}\\right)$}" new_polynomial = self.get_polynomial( c0 = "1", c1 = "0", c2 = alt_c2_tex ) new_polynomial.get_part_by_tex(alt_c2_tex).shift(SMALL_BUFF*UP) self.play(c2.shift, UP) self.play(FadeIn(equation)) self.wait(2) self.play(Transform(self.polynomial, new_polynomial)) self.wait(2) self.play(FadeOut(equation)) ##### def get_polynomial(self, c0 = "c_0", c1 = "c_1", c2 = "c_2"): polynomial = OldTex( "P(x) = ", c0, "+", c1, "x", "+", c2, "x^2" ) colors = ConstructQuadraticApproximation.CONFIG["colors"] for tex, color in zip([c0, c1, c2], colors): polynomial.set_color_by_tex(tex, color, substring = False) polynomial.next_to(self.teacher, UP, LARGE_BUFF) polynomial.to_edge(RIGHT) return polynomial class ReflectionOnQuadraticSupplement(ConstructQuadraticApproximation): def construct(self): self.setup_axes() self.add(self.get_graph(np.cos, color = self.colors[0])) quadratic_graph = self.get_quadratic_graph() self.add(quadratic_graph) self.wait() for c0 in 0, 2, 1: self.change_quadratic_graph( quadratic_graph, c0 = c0 ) self.wait(2) for c1 in 1, -1, 0: self.change_quadratic_graph( quadratic_graph, c1 = c1 ) self.wait(2) for c2 in -0.1, -1, -0.5: self.change_quadratic_graph( quadratic_graph, c2 = c2 ) self.wait(2) class SimilarityOfChangeBehavior(ConstructQuadraticApproximation): def construct(self): colors = [YELLOW, WHITE] max_x = np.pi/2 self.setup_axes() cosine_graph = self.get_graph(np.cos, color = self.colors[0]) quadratic_graph = self.get_quadratic_graph() graphs = VGroup(cosine_graph, quadratic_graph) dots = VGroup() for graph, color in zip(graphs, colors): dot = Dot(color = color) dot.move_to(self.input_to_graph_point(0, graph)) dot.graph = graph dots.add(dot) def update_dot(dot, alpha): x = interpolate(0, max_x, alpha) dot.move_to(self.input_to_graph_point(x, dot.graph)) dot_anims = [ UpdateFromAlphaFunc(dot, update_dot, run_time = 3) for dot in dots ] tangent_lines = VGroup(*[ self.get_tangent_line(0, graph, color) for graph, color in zip(graphs, colors) ]) tangent_line_movements = [ self.get_tangent_line_change_anim( line, max_x, graph, run_time = 5, ) for line, graph in zip(tangent_lines, graphs) ] self.add(cosine_graph, quadratic_graph) self.play(FadeIn(dots)) self.play(*dot_anims) self.play( FadeIn(tangent_lines), FadeOut(dots) ) self.play(*tangent_line_movements + dot_anims, run_time = 6) self.play(*list(map(FadeOut, [tangent_lines, dots]))) self.wait() class MoreTerms(TeacherStudentsScene): def construct(self): self.teacher_says( "More terms!", target_mode = "surprised", ) self.play_student_changes(*["hooray"]*3) self.wait(3) class CubicAndQuarticApproximations(ConstructQuadraticApproximation): CONFIG = { "colors": [BLUE, YELLOW, GREEN, RED, MAROON_B], } def construct(self): self.add_background() self.take_third_derivative_of_cubic() self.show_third_derivative_of_cosine() self.set_c3_to_zero() self.show_cubic_curves() self.add_quartic_term() self.show_fourth_derivative_of_cosine() self.take_fourth_derivative_of_quartic() self.solve_for_c4() self.show_quartic_approximation() def add_background(self): self.setup_axes() self.cosine_graph = self.get_graph( np.cos, color = self.colors[0] ) self.quadratic_graph = self.get_quadratic_graph() self.big_rect = Rectangle( height = FRAME_HEIGHT, width = FRAME_WIDTH, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.5, ) self.add( self.cosine_graph, self.quadratic_graph, self.big_rect ) self.cosine_label = OldTex("\\cos", "(0)", "=1") self.cosine_label.set_color_by_tex("cos", self.colors[0]) self.cosine_label.scale(0.75) self.cosine_label.to_corner(UP+LEFT) self.add(self.cosine_label) self.add(self.get_cosine_derivative()) self.add(self.get_cosine_second_derivative()) self.polynomial = OldTex( "P(x)=", "1", "-\\frac{1}{2}", "x^2" ) self.polynomial.set_color_by_tex("1", self.colors[0]) self.polynomial.set_color_by_tex("-\\frac{1}{2}", self.colors[2]) self.polynomial.to_corner(UP+RIGHT) self.polynomial.quadratic_part = VGroup( *self.polynomial[1:] ) self.add(self.polynomial) def take_third_derivative_of_cubic(self): polynomial = self.polynomial plus_cubic_term = OldTex("+\\,", "c_3", "x^3") plus_cubic_term.next_to(polynomial, RIGHT) plus_cubic_term.to_edge(RIGHT, buff = LARGE_BUFF) plus_cubic_term.set_color_by_tex("c_3", self.colors[3]) plus_cubic_copy = plus_cubic_term.copy() polynomial.generate_target() polynomial.target.next_to(plus_cubic_term, LEFT) self.play(FocusOn(polynomial)) self.play( MoveToTarget(polynomial), GrowFromCenter(plus_cubic_term) ) self.wait() brace = Brace(polynomial.quadratic_part, DOWN) third_derivative = OldTex( "\\frac{d^3 P}{dx^3}(x) = ", "0" ) third_derivative.shift( brace.get_bottom() + MED_SMALL_BUFF*DOWN -\ third_derivative.get_part_by_tex("0").get_top() ) self.play(Write(third_derivative[0])) self.play(GrowFromCenter(brace)) self.play(ReplacementTransform( polynomial.quadratic_part.copy(), VGroup(third_derivative[1]) )) self.wait(2) self.play(plus_cubic_copy.next_to, third_derivative, RIGHT) derivative_term = self.take_derivatives_of_monomial( VGroup(*plus_cubic_copy[1:]) ) third_derivative.add(plus_cubic_copy[0], derivative_term) self.plus_cubic_term = plus_cubic_term self.polynomial_third_derivative = third_derivative self.polynomial_third_derivative_brace = brace def show_third_derivative_of_cosine(self): cosine_third_derivative = self.get_cosine_third_derivative() dot = Dot(fill_opacity = 0.5) dot.move_to(self.polynomial_third_derivative) self.play( dot.move_to, cosine_third_derivative, dot.set_fill, None, 0 ) self.play(ReplacementTransform( self.cosine_second_derivative.copy(), cosine_third_derivative )) self.wait(2) dot.set_fill(opacity = 0.5) self.play( dot.move_to, self.polynomial_third_derivative.get_right(), dot.set_fill, None, 0, ) self.wait() def set_c3_to_zero(self): c3s = VGroup( self.polynomial_third_derivative[-1][-1], self.plus_cubic_term.get_part_by_tex("c_3") ) zeros = VGroup(*[ OldTex("0").move_to(c3) for c3 in c3s ]) zeros.set_color(self.colors[3]) zeros.shift(SMALL_BUFF*UP) zeros[0].shift(0.25*SMALL_BUFF*(UP+LEFT)) self.play(Transform( c3s, zeros, run_time = 2, lag_ratio = 0.5 )) self.wait(2) def show_cubic_curves(self): real_graph = self.quadratic_graph real_graph.save_state() graph = real_graph.copy() graph.save_state() alt_graphs = [ self.get_graph(func, color = real_graph.get_color()) for func in [ lambda x : x*(x-1)*(x+1), lambda x : 1 - 0.5*(x**2) + 0.2*(x**3) ] ] self.play(FadeIn(graph)) real_graph.set_stroke(width = 0) for alt_graph in alt_graphs: self.play(Transform(graph, alt_graph, run_time = 2)) self.wait() self.play(graph.restore, run_time = 2) real_graph.restore() self.play(FadeOut(graph)) def add_quartic_term(self): polynomial = self.polynomial plus_quartic_term = OldTex("+\\,", "c_4", "x^4") plus_quartic_term.next_to(polynomial, RIGHT) plus_quartic_term.set_color_by_tex("c_4", self.colors[4]) self.play(*list(map(FadeOut, [ self.plus_cubic_term, self.polynomial_third_derivative, self.polynomial_third_derivative_brace, ]))) self.play(Write(plus_quartic_term)) self.wait() self.plus_quartic_term = plus_quartic_term def show_fourth_derivative_of_cosine(self): cosine_fourth_derivative = self.get_cosine_fourth_derivative() self.play(FocusOn(self.cosine_third_derivative)) self.play(ReplacementTransform( self.cosine_third_derivative.copy(), cosine_fourth_derivative )) self.wait(3) def take_fourth_derivative_of_quartic(self): quartic_term = VGroup(*self.plus_quartic_term.copy()[1:]) fourth_deriv_lhs = OldTex("{d^4 P \\over dx^4}(x)", "=") fourth_deriv_lhs.next_to( self.polynomial, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) alt_rhs = OldTex("=", "24 \\cdot", "c_4") alt_rhs.next_to( fourth_deriv_lhs.get_part_by_tex("="), DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) alt_rhs.set_color_by_tex("c_4", self.colors[4]) self.play(Write(fourth_deriv_lhs)) self.play( quartic_term.next_to, fourth_deriv_lhs, RIGHT ) self.wait() fourth_deriv_rhs = self.take_derivatives_of_monomial(quartic_term) self.wait() self.play(Write(alt_rhs)) self.wait() self.fourth_deriv_lhs = fourth_deriv_lhs self.fourth_deriv_rhs = fourth_deriv_rhs self.fourth_deriv_alt_rhs = alt_rhs def solve_for_c4(self): c4s = VGroup( self.fourth_deriv_alt_rhs.get_part_by_tex("c_4"), self.fourth_deriv_rhs[-1], self.plus_quartic_term.get_part_by_tex("c_4") ) fraction = OldTex("\\text{\\small $\\frac{1}{24}$}") fraction.set_color(self.colors[4]) fractions = VGroup(*[ fraction.copy().move_to(c4, LEFT) for c4 in c4s ]) fractions.shift(SMALL_BUFF*UP) x_to_4 = self.plus_quartic_term.get_part_by_tex("x^4") x_to_4.generate_target() x_to_4.target.shift(MED_SMALL_BUFF*RIGHT) self.play( Transform( c4s, fractions, run_time = 3, lag_ratio = 0.5, ), MoveToTarget(x_to_4, run_time = 2) ) self.wait(3) def show_quartic_approximation(self): real_graph = self.quadratic_graph graph = real_graph.copy() quartic_graph = self.get_graph( lambda x : 1 - (x**2)/2.0 + (x**4)/24.0, color = graph.get_color(), ) tex_mobs = VGroup(*[ self.polynomial, self.fourth_deriv_rhs, self.fourth_deriv_alt_rhs, self.cosine_label, self.cosine_derivative, self.cosine_second_derivative, self.cosine_third_derivative[1], ]) for tex_mob in tex_mobs: tex_mob.add_to_back(BackgroundRectangle(tex_mob)) self.play(FadeIn(graph)) real_graph.set_stroke(width = 0) self.play( Transform( graph, quartic_graph, run_time = 3, ), Animation(tex_mobs) ) self.wait(3) #### def take_derivatives_of_monomial(self, term, *added_anims): """ Must be a group of pure Texs, last part must be of the form x^n """ n = int(term[-1].get_tex()[-1]) curr_term = term added_anims_iter = iter(added_anims) for k in range(n, 0, -1): exponent = curr_term[-1][-1] exponent_copy = exponent.copy() front_num = OldTex("%d \\cdot"%k) front_num.move_to(curr_term[0][0], LEFT) new_monomial = OldTex("x^%d"%(k-1)) new_monomial.replace(curr_term[-1]) Transform(curr_term[-1], new_monomial).update(1) curr_term.generate_target() curr_term.target.shift( (front_num.get_width()+SMALL_BUFF)*RIGHT ) curr_term[-1][-1].set_fill(opacity = 0) possibly_added_anims = [] try: possibly_added_anims.append(next(added_anims_iter)) except: pass self.play( ApplyMethod( exponent_copy.replace, front_num[0], path_arc = np.pi, ), Write( front_num[1], rate_func = squish_rate_func(smooth, 0.5, 1) ), MoveToTarget(curr_term), *possibly_added_anims, run_time = 2 ) self.remove(exponent_copy) self.add(front_num) curr_term = VGroup(front_num, *curr_term) self.wait() self.play(FadeOut(curr_term[-1])) return VGroup(*curr_term[:-1]) def get_cosine_third_derivative(self): if not hasattr(self, "cosine_second_derivative"): self.get_cosine_second_derivative() third_deriv = OldTex( "{d^3(", "\\cos", ")", "\\over", "dx^3}", "(", "0", ")", ) third_deriv.set_color_by_tex("cos", self.colors[0]) third_deriv.set_color_by_tex("-\\cos", self.colors[3]) third_deriv.scale(0.75) third_deriv.add_background_rectangle() third_deriv.next_to( self.cosine_second_derivative, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) rhs = OldTex("=", "\\sin(0)", "=", "0") rhs.set_color_by_tex("sin", self.colors[3]) rhs.scale(0.8) rhs.next_to( third_deriv, RIGHT, align_using_submobjects = True ) rhs.add_background_rectangle() rhs.background_rectangle.scale(1.2) self.cosine_third_derivative = VGroup(third_deriv, rhs) return self.cosine_third_derivative def get_cosine_fourth_derivative(self): if not hasattr(self, "cosine_third_derivative"): self.get_cosine_third_derivative() fourth_deriv = OldTex( "{d^4(", "\\cos", ")", "\\over", "dx^4}", "(", "0", ")", ) fourth_deriv.set_color_by_tex("cos", self.colors[0]) fourth_deriv.scale(0.75) fourth_deriv.add_background_rectangle() fourth_deriv.next_to( self.cosine_third_derivative, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) rhs = OldTex("=", "\\cos(0)", "=", "1") rhs.set_color_by_tex("cos", self.colors[4]) rhs.scale(0.8) rhs.next_to( fourth_deriv, RIGHT, align_using_submobjects = True ) rhs.add_background_rectangle() rhs.background_rectangle.scale(1.2) self.cosine_fourth_derivative = VGroup(fourth_deriv, rhs) return self.cosine_fourth_derivative class NoticeAFewThings(TeacherStudentsScene): def construct(self): self.teacher_says( "Notice a few things", target_mode = "hesitant" ) self.wait(3) class FactorialTerms(CubicAndQuarticApproximations): def construct(self): lhs_list = [ OldTex( "{d%s"%s, "\\over", "dx%s}"%s, "(", "c_8", "x^8", ")=" ) for i in range(9) for s in ["^%d"%i if i > 1 else ""] ] for lhs in lhs_list: lhs.set_color_by_tex("c_8", YELLOW) lhs.next_to(ORIGIN, LEFT) lhs_list[0].set_fill(opacity = 0) added_anims = [ ReplacementTransform( start_lhs, target_lhs, rate_func = squish_rate_func(smooth, 0, 0.5) ) for start_lhs, target_lhs in zip(lhs_list, lhs_list[1:]) ] term = OldTex("c_8", "x^8") term.next_to(lhs[-1], RIGHT) term.set_color_by_tex("c_8", YELLOW) self.add(term) self.wait() result = self.take_derivatives_of_monomial(term, *added_anims) factorial_term = VGroup(*result[:-1]) brace = Brace(factorial_term) eight_factorial = brace.get_text("$8!$") coefficient = result[-1] words = OldTexText( "Set", "$c_8$", "$ = \\frac{\\text{Desired derivative value}}{8!}" ) words.set_color_by_tex("c_8", YELLOW) words.shift(2*UP) self.play( GrowFromCenter(brace), Write(eight_factorial) ) self.play( ReplacementTransform( coefficient.copy(), words.get_part_by_tex("c_8") ), Write(words), ) self.wait(2) class HigherTermsDontMessUpLowerTerms(Scene): CONFIG = { "colors" : CubicAndQuarticApproximations.CONFIG["colors"][::2], } def construct(self): self.add_polynomial() self.show_second_derivative() def add_polynomial(self): c0_tex = "1" c2_tex = "\\text{\\small $\\left(-\\frac{1}{2}\\right)$}" c4_tex = "c_4" polynomial = OldTex( "P(x) = ", c0_tex, "+", c2_tex, "x^2", "+", c4_tex, "x^4", ) polynomial.shift(2*LEFT + UP) c0, c2, c4 = [ polynomial.get_part_by_tex(tex) for tex in (c0_tex, c2_tex, c4_tex) ] for term, color in zip([c0, c2, c4], self.colors): term.set_color(color) arrows = VGroup(*[ Arrow( c4.get_top(), c.get_top(), path_arc = arc, color = c.get_color() ) for c, arc in [(c2, 0.9*np.pi), (c0, np.pi)] ]) no_affect_words = OldTexText( "Doesn't affect \\\\ previous terms" ) no_affect_words.next_to(arrows, RIGHT) no_affect_words.shift(MED_SMALL_BUFF*(UP+LEFT)) self.add(*polynomial[:-2]) self.wait() self.play(Write(VGroup(*polynomial[-2:]))) self.play( Write(no_affect_words), ShowCreation(arrows), run_time = 3 ) self.wait(2) self.polynomial = polynomial self.c0_tex = c0_tex self.c2_tex = c2_tex self.c4_tex = c4_tex def show_second_derivative(self): second_deriv = OldTex( "{d^2 P \\over dx^2}(", "0", ")", "=", "2", self.c2_tex, "+", "3 \\cdot 4", self.c4_tex, "(", "0", ")", "^2" ) second_deriv.set_color_by_tex(self.c2_tex, self.colors[1]) second_deriv.set_color_by_tex(self.c4_tex, self.colors[2]) second_deriv.set_color_by_tex("0", YELLOW) second_deriv.next_to( self.polynomial, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) higher_terms = VGroup(*second_deriv[-6:]) brace = Brace(higher_terms, DOWN) equals_zero = brace.get_text("=0") second_deriv.save_state() second_deriv.move_to(self.polynomial, LEFT) second_deriv.set_fill(opacity = 0) self.play(second_deriv.restore) self.wait() self.play(GrowFromCenter(brace)) self.wait() self.play(Write(equals_zero)) self.wait(3) class EachTermControlsOneDerivative(Scene): def construct(self): colors = CubicAndQuarticApproximations.CONFIG["colors"] polynomial = OldTex( "P(x) = ", "c_0", "+", "c_1", "x", *it.chain(*[ ["+", "c_%d"%n, "x^%d"%n] for n in range(2, 5) ]) ) consts = polynomial.get_parts_by_tex("c") deriv_words = VGroup(*[ OldTexText("Controls \\\\ $%s(0)$"%tex) for tex in [ "P", "\\frac{dP}{dx}", ] + [ "\\frac{d^%d P}{dx^%d}"%(n, n) for n in range(2, 5) ] ]) deriv_words.arrange( RIGHT, buff = LARGE_BUFF, aligned_edge = UP ) deriv_words.set_width(FRAME_WIDTH - MED_LARGE_BUFF) deriv_words.to_edge(UP) for const, deriv, color in zip(consts, deriv_words, colors): for mob in const, deriv: mob.set_color(color) arrow = Arrow( const.get_top(), deriv.get_bottom(), # buff = SMALL_BUFF, color = color ) deriv.arrow = arrow self.add(polynomial) for deriv in deriv_words: self.play( ShowCreation(deriv.arrow), FadeIn(deriv) ) self.wait() class ApproximateNearNewPoint(CubicAndQuarticApproximations): CONFIG = { "target_approx_centers" : [np.pi/2, np.pi], } def construct(self): self.setup_axes() self.add_cosine_graph() self.shift_approximation_center() self.show_polynomials() def add_cosine_graph(self): self.cosine_graph = self.get_graph( np.cos, self.colors[0] ) self.add(self.cosine_graph) def shift_approximation_center(self): quartic_graph = self.get_quartic_approximation(0) dot = Dot(color = YELLOW) dot.move_to(self.coords_to_point(0, 1)) v_line = self.get_vertical_line_to_graph( self.target_approx_centers[-1], self.cosine_graph, line_class = DashedLine, color = YELLOW ) pi = self.x_axis_labels[1] pi.add_background_rectangle() self.play( ReplacementTransform( self.cosine_graph.copy(), quartic_graph, ), DrawBorderThenFill(dot, run_time = 1) ) for target, rt in zip(self.target_approx_centers, [3, 4, 4]): self.change_approximation_center( quartic_graph, dot, target, run_time = rt ) self.play( ShowCreation(v_line), Animation(pi) ) self.wait() def change_approximation_center(self, graph, dot, target, **kwargs): start = self.x_axis.point_to_number(dot.get_center()) def update_quartic(graph, alpha): new_a = interpolate(start, target, alpha) new_graph = self.get_quartic_approximation(new_a) Transform(graph, new_graph).update(1) return graph def update_dot(dot, alpha): new_x = interpolate(start, target, alpha) dot.move_to(self.input_to_graph_point(new_x, self.cosine_graph)) self.play( UpdateFromAlphaFunc(graph, update_quartic), UpdateFromAlphaFunc(dot, update_dot), **kwargs ) def show_polynomials(self): poly_around_pi = self.get_polynomial("(x-\\pi)", "\\pi") poly_around_pi.to_corner(UP+LEFT) randy = Randolph() randy.to_corner(DOWN+LEFT) self.play(FadeIn( poly_around_pi, run_time = 4, lag_ratio = 0.5 )) self.wait(2) self.play(FadeIn(randy)) self.play(randy.change, "confused", poly_around_pi) self.play(Blink(randy)) self.wait(2) self.play(randy.change_mode, "happy") self.wait(2) ### def get_polynomial(self, arg, center_tex): result = OldTex( "P_{%s}(x)"%center_tex, "=", "c_0", *it.chain(*[ ["+", "c_%d"%d, "%s^%d"%(arg, d)] for d in range(1, 5) ]) ) for d, color in enumerate(self.colors): result.set_color_by_tex("c_%d"%d, color) result.scale(0.85) result.add_background_rectangle() return result def get_quartic_approximation(self, a): coefficients = [ derivative(np.cos, a, n) for n in range(5) ] func = lambda x : sum([ (c/math.factorial(n))*(x - a)**n for n, c in enumerate(coefficients) ]) return self.get_graph(func, color = GREEN) class OnAPhilosophicalLevel(TeacherStudentsScene): def construct(self): self.teacher_says( "And on a \\\\ philosophical level", run_time = 1 ) self.wait(3) class TranslationOfInformation(CubicAndQuarticApproximations): def construct(self): self.add_background() self.mention_information_exchange() self.show_derivative_pattern() self.show_polynomial() self.name_taylor_polynomial() self.draw_new_function_graph() self.write_general_function_derivative() self.replace_coefficients_in_generality() self.walk_through_terms() self.show_polynomial_around_a() def add_background(self): self.setup_axes() self.cosine_graph = self.get_graph( np.cos, color = self.colors[0] ) self.add(self.cosine_graph) def mention_information_exchange(self): deriv_info = OldTexText( "Derivative \\\\ information \\\\ at a point" ) deriv_info.next_to(ORIGIN, LEFT, LARGE_BUFF) deriv_info.to_edge(UP) output_info = OldTexText( "Output \\\\ information \\\\ near that point" ) output_info.next_to(ORIGIN, RIGHT, LARGE_BUFF) output_info.to_edge(UP) arrow = Arrow(deriv_info, output_info) center_v_line = self.get_vertical_line_to_graph( 0, self.cosine_graph, line_class = DashedLine, color = YELLOW ) outer_v_lines = VGroup(*[ center_v_line.copy().shift(vect) for vect in (LEFT, RIGHT) ]) outer_v_lines.set_color(GREEN) dot = Dot(color = YELLOW) dot.move_to(center_v_line.get_top()) dot.save_state() dot.move_to(deriv_info) dot.set_fill(opacity = 0) quadratic_graph = self.get_quadratic_graph() self.play(Write(deriv_info, run_time = 2)) self.play(dot.restore) self.play(ShowCreation(center_v_line)) self.wait() self.play(ShowCreation(arrow)) self.play(Write(output_info, run_time = 2)) self.play(ReplacementTransform( VGroup(center_v_line).copy(), outer_v_lines )) self.play(ReplacementTransform( self.cosine_graph.copy(), quadratic_graph ), Animation(dot)) for x in -1, 1, 0: start_x = self.x_axis.point_to_number(dot.get_center()) self.play(UpdateFromAlphaFunc( dot, lambda d, a : d.move_to(self.input_to_graph_point( interpolate(start_x, x, a), self.cosine_graph )), run_time = 2 )) self.wait() self.play(*list(map(FadeOut, [ deriv_info, arrow, output_info, outer_v_lines ]))) self.quadratic_graph = quadratic_graph self.v_line = center_v_line self.dot = dot def show_derivative_pattern(self): derivs_at_x, derivs_at_zero = [ VGroup(*[ OldTex(tex, "(", arg, ")") for tex in [ "\\cos", "-\\sin", "-\\cos", "\\sin", "\\cos" ] ]) for arg in ("x", "0") ] arrows = VGroup(*[ Arrow( UP, ORIGIN, color = WHITE, buff = 0, tip_length = MED_SMALL_BUFF ) for d in derivs_at_x ]) group = VGroup(*it.chain(*list(zip( derivs_at_x, arrows )))) group.add(OldTex("\\vdots")) group.arrange(DOWN, buff = SMALL_BUFF) group.set_height(FRAME_HEIGHT - MED_LARGE_BUFF) group.to_edge(LEFT) for dx, d0, color in zip(derivs_at_x, derivs_at_zero, self.colors): for d in dx, d0: d.set_color(color) d0.replace(dx) rhs_group = VGroup(*[ OldTex("=", "%d"%d).scale(0.7).next_to(deriv, RIGHT) for deriv, d in zip(derivs_at_zero, [1, 0, -1, 0, 1]) ]) derivative_values = VGroup(*[ rhs[1] for rhs in rhs_group ]) for value, color in zip(derivative_values, self.colors): value.set_color(color) zeros = VGroup(*[ deriv.get_part_by_tex("0") for deriv in derivs_at_zero ]) self.play(FadeIn(derivs_at_x[0])) self.wait() for start_d, arrow, target_d in zip(group[::2], group[1::2], group[2::2]): self.play( ReplacementTransform( start_d.copy(), target_d ), ShowCreation(arrow) ) self.wait() self.wait() self.play(ReplacementTransform( derivs_at_x, derivs_at_zero )) self.wait() self.play(*list(map(Write, rhs_group))) self.wait() for rhs in rhs_group: self.play(Indicate(rhs[1]), color = WHITE) self.wait() self.play(*[ ReplacementTransform( zero.copy(), self.dot, run_time = 3, rate_func = squish_rate_func(smooth, a, a+0.4) ) for zero, a in zip(zeros, np.linspace(0, 0.6, len(zeros))) ]) self.wait() self.cosine_derivative_group = VGroup( derivs_at_zero, arrows, group[-1], rhs_group ) self.derivative_values = derivative_values def show_polynomial(self): derivative_values = self.derivative_values.copy() polynomial = self.get_polynomial("x", 1, 0, -1, 0, 1) polynomial.to_corner(UP+RIGHT) monomial = OldTex("\\frac{1}{4!}", "x^4") monomial = VGroup(VGroup(monomial[0]), monomial[1]) monomial.next_to(polynomial, DOWN, LARGE_BUFF) self.play(*[ Transform( dv, pc, run_time = 2, path_arc = np.pi/2 ) for dv, pc, a in zip( derivative_values, polynomial.coefficients, np.linspace(0, 0.6, len(derivative_values)) ) ]) self.play( Write(polynomial, run_time = 5), Animation(derivative_values) ) self.remove(derivative_values) self.wait(2) to_fade = self.take_derivatives_of_monomial(monomial) self.play(FadeOut(to_fade)) self.wait() self.polynomial = polynomial def name_taylor_polynomial(self): brace = Brace( VGroup( self.polynomial.coefficients, self.polynomial.factorials ), DOWN ) name = brace.get_text("``Taylor polynomial''") name.shift(MED_SMALL_BUFF*RIGHT) quartic_graph = self.get_graph( lambda x : 1 - (x**2)/2.0 + (x**4)/24.0, color = GREEN, x_min = -3.2, x_max = 3.2, ) quartic_graph.set_color(self.colors[4]) self.play(GrowFromCenter(brace)) self.play(Write(name)) self.wait() self.play( Transform( self.quadratic_graph, quartic_graph, run_time = 2 ), Animation(self.dot) ) self.wait(2) self.taylor_name_group = VGroup(brace, name) def draw_new_function_graph(self): def func(x): return (np.sin(x**2 + x)+0.5)*np.exp(-x**2) graph = self.get_graph( func, color = self.colors[0] ) self.play(*list(map(FadeOut, [ self.cosine_derivative_group, self.cosine_graph, self.quadratic_graph, self.v_line, self.dot ]))) self.play(ShowCreation(graph)) self.graph = graph def write_general_function_derivative(self): derivs_at_x, derivs_at_zero, derivs_at_a = deriv_lists = [ VGroup(*[ OldTex("\\text{$%s$}"%args[0], *args[1:]) for args in [ ("f", "(", arg, ")"), ("\\frac{df}{dx}", "(", arg, ")"), ("\\frac{d^2 f}{dx^2}", "(", arg, ")"), ("\\frac{d^3 f}{dx^3}", "(", arg, ")"), ("\\frac{d^4 f}{dx^4}", "(", arg, ")"), ] ]) for arg in ("x", "0", "a") ] derivs_at_x.arrange(DOWN, buff = MED_LARGE_BUFF) derivs_at_x.set_height(FRAME_HEIGHT - MED_LARGE_BUFF) derivs_at_x.to_edge(LEFT) zeros = VGroup(*[ deriv.get_part_by_tex("0") for deriv in derivs_at_zero ]) self.dot.move_to(self.input_to_graph_point(0, self.graph)) self.v_line.put_start_and_end_on( self.graph_origin, self.dot.get_center() ) for color, dx, d0, da in zip(self.colors, *deriv_lists): for d in dx, d0, da: d.set_color(color) d.add_background_rectangle() d0.replace(dx) da.replace(dx) self.play(FadeIn(derivs_at_x[0])) self.wait() for start, target in zip(derivs_at_x, derivs_at_x[1:]): self.play(ReplacementTransform( start.copy(), target )) self.wait() self.wait() self.play(ReplacementTransform( derivs_at_x, derivs_at_zero, )) self.play(ReplacementTransform( zeros.copy(), self.dot, run_time = 2, lag_ratio = 0.5 )) self.play(ShowCreation(self.v_line)) self.wait() self.derivs_at_zero = derivs_at_zero self.derivs_at_a = derivs_at_a def replace_coefficients_in_generality(self): new_polynomial = self.get_polynomial("x", *[ tex_mob.get_tex() for tex_mob in self.derivs_at_zero[:-1] ]) new_polynomial.to_corner(UP+RIGHT) polynomial_fourth_term = VGroup( *self.polynomial[-7:-1] ) self.polynomial.remove(*polynomial_fourth_term) self.play( ReplacementTransform( self.polynomial, new_polynomial, run_time = 2, lag_ratio = 0.5 ), FadeOut(polynomial_fourth_term), FadeOut(self.taylor_name_group), ) self.polynomial = new_polynomial self.wait(3) def walk_through_terms(self): func = self.graph.underlying_function approx_graphs = [ self.get_graph( taylor_approximation(func, n), color = WHITE ) for n in range(7) ] for graph, color in zip(approx_graphs, self.colors): graph.set_color(color) left_mob = self.polynomial.coefficients[0] right_mobs = list(self.polynomial.factorials) right_mobs.append(self.polynomial[-1]) braces = [ Brace( VGroup(left_mob, *right_mobs[:n]), DOWN ) for n in range(len(approx_graphs)) ] brace = braces[0] brace.stretch_to_fit_width(MED_LARGE_BUFF) approx_graph = approx_graphs[0] self.polynomial.add_background_rectangle() self.play(GrowFromCenter(brace)) self.play(ShowCreation(approx_graph)) self.wait() for new_brace, new_graph in zip(braces[1:], approx_graphs[1:]): self.play(Transform(brace, new_brace)) self.play( Transform(approx_graph, new_graph, run_time = 2), Animation(self.polynomial), Animation(self.dot), ) self.wait() self.play(FadeOut(brace)) self.approx_graph = approx_graph self.approx_order = len(approx_graphs) - 1 def show_polynomial_around_a(self): new_polynomial = self.get_polynomial("(x-a)", *[ tex_mob.get_tex() for tex_mob in self.derivs_at_a[:-2] ]) new_polynomial.to_corner(UP+RIGHT) new_polynomial.add_background_rectangle() polynomial_third_term = VGroup( *self.polynomial[1][-7:-1] ) self.polynomial[1].remove(*polynomial_third_term) group = VGroup(self.approx_graph, self.dot, self.v_line) def get_update_function(target_x): def update(group, alpha): graph, dot, line = group start_x = self.x_axis.point_to_number(dot.get_center()) x = interpolate(start_x, target_x, alpha) graph_point = self.input_to_graph_point(x, self.graph) dot.move_to(graph_point) line.put_start_and_end_on( self.coords_to_point(x, 0), graph_point, ) new_approx_graph = self.get_graph( taylor_approximation( self.graph.underlying_function, self.approx_order, center_point = x ), color = graph.get_color() ) Transform(graph, new_approx_graph).update(1) return VGroup(graph, dot, line) return update self.play( UpdateFromAlphaFunc( group, get_update_function(1), run_time = 2 ), Animation(self.polynomial), Animation(polynomial_third_term) ) self.wait() self.play(Transform( self.derivs_at_zero, self.derivs_at_a )) self.play( Transform(self.polynomial, new_polynomial), FadeOut(polynomial_third_term) ) self.wait() for x in -1, np.pi/6: self.play( UpdateFromAlphaFunc( group, get_update_function(x), ), Animation(self.polynomial), run_time = 4, ) self.wait() ##### def get_polynomial(self, arg, *coefficients): result = OldTex( "P(x) = ", str(coefficients[0]), *list(it.chain(*[ ["+", str(c), "{%s"%arg, "^%d"%n, "\\over", "%d!}"%n] for n, c in zip(it.count(1), coefficients[1:]) ])) + [ "+ \\cdots" ] ) result.scale(0.8) coefs = VGroup(result[1], *result[3:-1:6]) for coef, color in zip(coefs, self.colors): coef.set_color(color) result.coefficients = coefs result.factorials = VGroup(*result[7::6]) return result class ThisIsAStandardFormula(TeacherStudentsScene): def construct(self): self.teacher_says( "You will see this \\\\ in your texts", run_time = 1 ) self.play_student_changes( *["sad"]*3, look_at = FRAME_Y_RADIUS*UP ) self.wait(2) class ExpPolynomial(TranslationOfInformation, ExampleApproximationWithExp): CONFIG = { "x_tick_frequency" : 1, "x_leftmost_tick" : -3, "graph_origin" : 2*(DOWN+LEFT), "y_axis_label" : "", } def construct(self): self.setup_axes() self.add_graph() self.show_derivatives() self.show_polynomial() self.walk_through_terms() def add_graph(self): graph = self.get_graph(np.exp) e_to_x = self.get_graph_label(graph, "e^x") self.play( ShowCreation(graph), Write( e_to_x, rate_func = squish_rate_func(smooth, 0.5, 1) ), run_time = 2 ) self.wait() self.graph = graph self.e_to_x = e_to_x def show_derivatives(self): self.e_to_x.generate_target() derivs_at_x, derivs_at_zero = [ VGroup(*[ OldTex("e^%s"%s).set_color(c) for c in self.colors ]) for s in ("x", "0") ] derivs_at_x.submobjects[0] = self.e_to_x.target arrows = VGroup(*[ Arrow( UP, ORIGIN, color = WHITE, buff = SMALL_BUFF, tip_length = 0.2, ) for d in derivs_at_x ]) group = VGroup(*it.chain(*list(zip( derivs_at_x, arrows )))) group.add(OldTex("\\vdots")) group.arrange(DOWN, buff = 2*SMALL_BUFF) group.set_height(FRAME_HEIGHT - MED_LARGE_BUFF) group.to_edge(LEFT) for dx, d0 in zip(derivs_at_x, derivs_at_zero): for d in dx, d0: d.add_background_rectangle() d0.replace(dx) rhs_group = VGroup(*[ OldTex("=", "1").scale(0.7).next_to(deriv, RIGHT) for deriv in derivs_at_zero ]) derivative_values = VGroup(*[ rhs[1] for rhs in rhs_group ]) for value, color in zip(derivative_values, self.colors): value.set_color(color) for arrow in arrows: d_dx = OldTex("d/dx") d_dx.scale(0.5) d_dx.next_to(arrow, RIGHT, SMALL_BUFF) d_dx.shift(SMALL_BUFF*UP) arrow.add(d_dx) self.play(MoveToTarget(self.e_to_x)) derivs_at_x.submobjects[0] = self.e_to_x for start_d, arrow, target_d in zip(group[::2], group[1::2], group[2::2]): self.play( ReplacementTransform( start_d.copy(), target_d ), Write(arrow, run_time = 1) ) self.wait() self.wait() self.play(ReplacementTransform( derivs_at_x, derivs_at_zero )) self.wait() self.play(*list(map(Write, rhs_group))) self.derivative_values = derivative_values def show_polynomial(self): derivative_values = self.derivative_values.copy() polynomial = self.get_polynomial("x", 1, 1, 1, 1, 1) polynomial.to_corner(UP+RIGHT) ##These are to make the walk_through_terms method work self.polynomial = polynomial.copy() self.dot = Dot(fill_opacity = 0) ### polynomial.add_background_rectangle() self.play(*[ Transform( dv, pc, run_time = 2, path_arc = np.pi/2 ) for dv, pc in zip( derivative_values, polynomial.coefficients, ) ]) self.play( Write(polynomial, run_time = 4), Animation(derivative_values) ) #### def setup_axes(self): GraphScene.setup_axes(self) class ShowSecondTerm(TeacherStudentsScene): def construct(self): colors = CubicAndQuarticApproximations.CONFIG["colors"] polynomial = OldTex( "f(a)", "+", "\\frac{df}{dx}(a)", "(x - a)", "+", "\\frac{d^2 f}{dx^2}(a)", "(x - a)^2" ) for tex, color in zip(["f(a)", "df", "d^2 f"], colors): polynomial.set_color_by_tex(tex, color) polynomial.next_to(self.teacher, UP+LEFT) polynomial.shift(MED_LARGE_BUFF*UP) second_term = VGroup(*polynomial[-2:]) box = Rectangle(color = colors[2]) box.replace(second_term, stretch = True) box.stretch_in_place(1.1, 0) box.stretch_in_place(1.2, 1) words = OldTexText("Geometric view") words.next_to(box, UP) self.teacher_says( "Now for \\\\ something fun!", target_mode = "hooray" ) self.wait(2) self.play( RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand" ), Write(polynomial) ) self.play( ShowCreation(box), FadeIn(words), ) self.play_student_changes(*["pondering"]*3) self.wait(3) class SecondTermIntuition(AreaIsDerivative): CONFIG = { "func" : lambda x : x*(x-1)*(x-2) + 2, "num_rects" : 300, "t_max" : 2.3, "x_max" : 4, "x_labeled_nums" : None, "x_axis_label" : "", "y_labeled_nums" : None, "y_axis_label" : "", "y_min" : -1, "y_max" : 5, "y_tick_frequency" : 1, "variable_point_label" : "x", "area_opacity" : 1, "default_riemann_start_color" : BLUE_E, "dx" : 0.15, "skip_reconfiguration" : False, } def setup(self): GraphScene.setup(self) ReconfigurableScene.setup(self) self.foreground_mobjects = [] def construct(self): self.setup_axes() self.introduce_area() self.write_derivative() self.nudge_end_point() self.point_out_triangle() self.relabel_start_and_end() self.compute_triangle_area() self.walk_through_taylor_terms() def introduce_area(self): graph = self.v_graph = self.get_graph( self.func, color = WHITE, ) self.foreground_mobjects.append(graph) area = self.area = self.get_area(0, self.t_max) func_name = OldTex("f_{\\text{area}}(x)") func_name.move_to(self.coords_to_point(0.6, 1)) self.foreground_mobjects.append(func_name) self.add(graph, area, func_name) self.add_T_label(self.t_max) if not self.skip_animations: for target in 1.6, 2.7, self.t_max: self.change_area_bounds( new_t_max = target, run_time = 3, ) self.__name__ = func_name def write_derivative(self): deriv = OldTex("\\frac{df_{\\text{area}}}{dx}(x)") deriv.next_to( self.input_to_graph_point(2.7, self.v_graph), RIGHT ) deriv.shift_onto_screen() self.play(ApplyWave(self.v_graph, direction = UP)) self.play(Write(deriv, run_time = 2)) self.wait() self.deriv_label = deriv def nudge_end_point(self): dark_area = self.area.copy() dark_area.set_fill(BLACK, opacity = 0.5) curr_x = self.x_axis.point_to_number(self.area.get_right()) new_x = curr_x + self.dx rect = Rectangle( stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.75 ) rect.replace( VGroup( VectorizedPoint(self.coords_to_point(new_x, 0)), self.right_v_line, ), stretch = True ) dx_brace = Brace(rect, DOWN, buff = 0) dx_label = dx_brace.get_text("$dx$", buff = SMALL_BUFF) dx_label_group = VGroup(dx_label, dx_brace) height_brace = Brace(rect, LEFT, buff = SMALL_BUFF) self.change_area_bounds(new_t_max = new_x) self.play( FadeIn(dark_area), *list(map(Animation, self.foreground_mobjects)) ) self.play( FadeOut(self.T_label_group), FadeIn(dx_label_group), FadeIn(rect), FadeIn(height_brace) ) self.wait() if not self.skip_reconfiguration: self.transition_to_alt_config( dx = self.dx/10.0, run_time = 3, ) self.play(FadeOut(height_brace)) self.dx_label_group = dx_label_group self.rect = rect self.dark_area = dark_area def point_out_triangle(self): triangle = Polygon(LEFT, ORIGIN, UP) triangle.set_stroke(width = 0) triangle.set_fill(MAROON_B, opacity = 1) triangle.replace( Line( self.rect.get_corner(UP+LEFT), self.right_v_line.get_top() ), stretch = True ) circle = Circle(color = RED) circle.set_height(triangle.get_height()) circle.replace(triangle, dim_to_match = 1) circle.scale(1.3) self.play(DrawBorderThenFill(triangle)) self.play(ShowCreation(circle)) self.play(FadeOut(circle)) self.triangle = triangle def relabel_start_and_end(self): dx_label, dx_brace = self.dx_label_group x_minus_a = OldTex("(x-a)") x_minus_a.scale(0.7) x_minus_a.move_to(dx_label) labels = VGroup() arrows = VGroup() for vect, tex in (LEFT, "a"), (RIGHT, "x"): point = self.rect.get_corner(DOWN+vect) label = OldTex(tex) label.next_to(point, DOWN+vect) label.shift(LARGE_BUFF*vect) arrow = Arrow( label.get_corner(UP-vect), point, buff = SMALL_BUFF, tip_length = 0.2, color = WHITE ) labels.add(label) arrows.add(arrow) for label, arrow in zip(labels, arrows): self.play( Write(label), ShowCreation(arrow) ) self.wait() self.wait() self.play(ReplacementTransform( dx_label, x_minus_a )) self.wait() self.x_minus_a = x_minus_a def compute_triangle_area(self): triangle = self.triangle.copy() tex_scale_factor = 0.7 base_line = Line(*[ triangle.get_corner(DOWN+vect) for vect in (LEFT, RIGHT) ]) base_line.set_color(RED) base_label = OldTexText("Base = ", "$(x-a)$") base_label.scale(tex_scale_factor) base_label.next_to(base_line, DOWN+RIGHT, MED_LARGE_BUFF) base_label.shift(SMALL_BUFF*UP) base_term = base_label[1].copy() base_arrow = Arrow( base_label.get_left(), base_line.get_center(), buff = SMALL_BUFF, color = base_line.get_color(), tip_length = 0.2 ) height_brace = Brace(triangle, RIGHT, buff = SMALL_BUFF) height_labels = [ OldTex("\\text{Height} = ", s, "(x-a)") for s in [ "(\\text{Slope})", "\\frac{d^2 f_{\\text{area}}}{dx^2}(a)" ] ] for label in height_labels: label.scale(tex_scale_factor) label.next_to(height_brace, RIGHT) height_term = VGroup(*height_labels[1][1:]).copy() self.play( FadeIn(base_label), ShowCreation(base_arrow), ShowCreation(base_line) ) self.wait(2) self.play( GrowFromCenter(height_brace), Write(height_labels[0]) ) self.wait(2) self.play(ReplacementTransform(*height_labels)) self.wait(2) #Show area formula equals_half = OldTex("=\\frac{1}{2}") equals_half.scale(tex_scale_factor) group = VGroup(triangle, equals_half, height_term, base_term) group.generate_target() group.target.arrange(RIGHT, buff = SMALL_BUFF) group.target[-1].next_to( group.target[-2], RIGHT, buff = SMALL_BUFF, align_using_submobjects = True ) group.target[1].shift(0.02*DOWN) group.target.to_corner(UP+RIGHT) exp_2 = OldTex("2").scale(0.8*tex_scale_factor) exp_2.next_to( group.target[-2], UP+RIGHT, buff = 0, align_using_submobjects = True ) equals_half.scale(0.1) equals_half.move_to(triangle) equals_half.set_fill(opacity = 0) self.play( FadeOut(self.deriv_label), MoveToTarget(group, run_time = 2) ) self.wait(2) self.play(Transform( group[-1], exp_2 )) self.wait(2) def walk_through_taylor_terms(self): mini_area, mini_rect, mini_triangle = [ mob.copy() for mob in (self.dark_area, self.rect, self.triangle) ] mini_area.set_fill(BLUE_E, opacity = 1) mini_area.set_height(1) mini_rect.set_height(1) mini_triangle.set_height(0.5) geometric_taylor = VGroup( OldTex("f(x) \\approx "), mini_area, OldTex("+"), mini_rect, OldTex("+"), mini_triangle, ) geometric_taylor.arrange( RIGHT, buff = MED_SMALL_BUFF ) geometric_taylor.to_corner(UP+LEFT) analytic_taylor = OldTex( "f(x) \\approx", "f(a)", "+", "\\frac{df}{dx}(a)(x-a)", "+", "\\frac{1}{2}\\frac{d^2 f}{dx^2}(a)(x-a)^2" ) analytic_taylor.set_color_by_tex("f(a)", BLUE) analytic_taylor.set_color_by_tex("df", YELLOW) analytic_taylor.set_color_by_tex("d^2 f", MAROON_B) analytic_taylor.scale(0.7) analytic_taylor.next_to( geometric_taylor, DOWN, aligned_edge = LEFT ) for part in analytic_taylor: part.add_to_back(BackgroundRectangle(part)) new_func_name = OldTex("f_{\\text{area}}(a)") new_func_name.replace(self.__name__) self.play(FadeIn( geometric_taylor, run_time = 2, lag_ratio = 0.5 )) self.wait() self.play( FadeIn(VGroup(*analytic_taylor[:3])), self.dark_area.set_fill, BLUE_E, 1, Transform(self.__name__, new_func_name) ) self.wait() self.play( self.rect.scale, 0.5, rate_func = there_and_back ) self.play(FadeIn(VGroup(*analytic_taylor[3:5]))) self.wait(2) self.play( self.triangle.scale, 0.5, rate_func = there_and_back ) self.play(FadeIn(VGroup(*analytic_taylor[5:]))) self.wait(3) class EachTermHasMeaning(TeacherStudentsScene): def construct(self): self.get_pi_creatures().scale(0.8).shift(UP) self.teacher_says( "Each term \\\\ has meaning!", target_mode = "hooray", bubble_config = {"height" : 3, "width" : 4} ) self.play_student_changes( *["thinking"]*3, look_at = 4*UP ) self.wait(3) class AskAboutInfiniteSum(TeacherStudentsScene): def construct(self): self.ask_question() self.name_taylor_series() self.be_careful() def ask_question(self): big_rect = Rectangle( width = FRAME_WIDTH, height = FRAME_HEIGHT, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.7, ) randy = self.get_students()[1] series = OldTex( "\\cos(x)", "\\approx", "1 - \\frac{x^2}{2!} + \\frac{x^4}{4!}", " - \\frac{x^6}{6!}", "+\\cdots" ) series.next_to(randy, UP, 2) series.shift_onto_screen() rhs = VGroup(*series[2:]) arrow = Arrow(rhs.get_left(), rhs.get_right()) arrow.next_to(rhs, UP) words = OldTexText("Add infinitely many") words.next_to(arrow, UP) self.teacher_says( "We could call \\\\ it an end here" ) self.play_student_changes(*["erm"]*3) self.wait(3) self.play( RemovePiCreatureBubble(self.teacher), self.get_students()[0].change_mode, "plain", self.get_students()[2].change_mode, "plain", FadeIn(big_rect), randy.change_mode, "pondering" ) crowd = VGroup(*self.get_pi_creatures()) crowd.remove(randy) self.crowd_copy = crowd.copy() self.remove(crowd) self.add(self.crowd_copy, big_rect, randy) self.play(Write(series)) self.play( ShowCreation(arrow), Write(words) ) self.wait(3) self.arrow = arrow self.words = words self.series = series self.randy = randy def name_taylor_series(self): series_def = OldTexText( "Infinite sum $\\Leftrightarrow$ series" ) taylor_series = OldTexText("Taylor series") for mob in series_def, taylor_series: mob.move_to(self.words) brace = Brace(self.series.get_part_by_tex("4!"), DOWN) taylor_polynomial = brace.get_text("Taylor polynomial") self.play(ReplacementTransform( self.words, series_def )) self.wait() self.play( GrowFromCenter(brace), Write(taylor_polynomial) ) self.wait(2) self.play( series_def.scale, 0.7, series_def.to_corner, UP+RIGHT, FadeIn(taylor_series) ) self.play(self.randy.change, "thinking", taylor_series) self.wait() def be_careful(self): self.play(FadeIn(self.teacher)) self.remove(self.crowd_copy[0]) self.teacher_says( "Be careful", bubble_config = { "width" : 3, "height" : 2 }, added_anims = [self.randy.change, "hesitant"] ) self.wait(2) self.play(self.randy.change, "confused", self.series) self.wait(3) class ConvergenceExample(Scene): def construct(self): max_shown_power = 6 max_computed_power = 13 series = OldTex(*list(it.chain(*[ ["\\frac{1}{%d}"%(3**n), "+"] for n in range(1, max_shown_power) ])) + ["\\cdots"]) series_nums = [3**(-n) for n in range(1, max_computed_power)] partial_sums = np.cumsum(series_nums) braces = self.get_partial_sum_braces(series, partial_sums) convergence_words = OldTexText("``Converges'' to $\\frac{1}{2}$") convergence_words.next_to(series, UP, LARGE_BUFF) convergence_words.set_color(YELLOW) rhs = OldTex("= \\frac{1}{2}") rhs.next_to(series, RIGHT) rhs.set_color(BLUE) brace = braces[0] self.add(series, brace) for i, new_brace in enumerate(braces[1:]): self.play(Transform(brace, new_brace)) if i == 4: self.play(FadeIn(convergence_words)) else: self.wait() self.play( FadeOut(brace), Write(rhs) ) self.wait(2) def get_partial_sum_braces(self, series, partial_sums): braces = [ Brace(VGroup(*series[:n])) for n in range(1, len(series)-1, 2) ] last_brace = braces[-1] braces += [ braces[-1].copy().stretch_in_place( 1 + 0.1 + 0.02*(n+1), dim = 0, ).move_to(last_brace, LEFT) for n in range(len(partial_sums) - len(braces)) ] for brace, partial_sum in zip(braces, partial_sums): number = brace.get_text("%.7f"%partial_sum) number.set_color(YELLOW) brace.add(number) return braces class ExpConvergenceExample(ConvergenceExample): def construct(self): e_to_x, series_with_x = x_group = self.get_series("x") x_group.to_edge(UP) e_to_1, series_with_1 = one_group = self.get_series("1") terms = [1./math.factorial(n) for n in range(11)] partial_sums = np.cumsum(terms) braces = self.get_partial_sum_braces(series_with_1, partial_sums) brace = braces[1] for lhs, s in (e_to_x, "x"), (e_to_1, "1"): new_lhs = OldTex("e^%s"%s, "=") new_lhs.move_to(lhs, RIGHT) lhs.target = new_lhs self.add(x_group) self.wait() self.play(ReplacementTransform(x_group.copy(), one_group)) self.play(FadeIn(brace)) self.wait() for new_brace in braces[2:]: self.play(Transform(brace, new_brace)) self.wait() self.wait() self.play(MoveToTarget(e_to_1)) self.wait(2) def get_series(self, arg, n_terms = 5): series = OldTex("1", "+", *list(it.chain(*[ ["\\frac{%s^%d}{%d!}"%(arg, n, n), "+"] for n in range(1, n_terms+1) ])) + ["\\cdots"]) colors = list(CubicAndQuarticApproximations.CONFIG["colors"]) colors += [BLUE_C] for term, color in zip(series[::2], colors): term.set_color(color) lhs = OldTex("e^%s"%arg, "\\rightarrow") lhs.arrange(RIGHT, buff = SMALL_BUFF) group = VGroup(lhs, series) group.arrange(RIGHT, buff = SMALL_BUFF) return group class ExpGraphConvergence(ExpPolynomial, ExpConvergenceExample): CONFIG = { "example_input" : 2, "graph_origin" : 3*DOWN + LEFT, "n_iterations" : 8, "y_max" : 20, "num_graph_anchor_points" : 50, "func" : np.exp, } def construct(self): self.setup_axes() self.add_series() approx_graphs = self.get_approx_graphs() graph = self.get_graph(self.func, color = self.colors[0]) v_line = self.get_vertical_line_to_graph( self.example_input, graph, line_class = DashedLine, color = YELLOW ) dot = Dot(color = YELLOW) dot.to_corner(UP+LEFT) equals = OldTex("=") equals.replace(self.arrow) equals.scale(0.8) brace = self.braces[1] approx_graph = approx_graphs[1] x = self.example_input self.add(graph, self.series) self.wait() self.play(dot.move_to, self.coords_to_point(x, 0)) self.play( dot.move_to, self.input_to_graph_point(x, graph), ShowCreation(v_line) ) self.wait() self.play( GrowFromCenter(brace), ShowCreation(approx_graph) ) self.wait() for new_brace, new_graph in zip(self.braces[2:], approx_graphs[2:]): self.play( Transform(brace, new_brace), Transform(approx_graph, new_graph), Animation(self.series), ) self.wait() self.play(FocusOn(equals)) self.play(Transform(self.arrow, equals)) self.wait(2) def add_series(self): series_group = self.get_series("x") e_to_x, series = series_group series_group.scale(0.8) series_group.to_corner(UP+LEFT) braces = self.get_partial_sum_braces( series, np.zeros(self.n_iterations) ) for brace in braces: brace.remove(brace[-1]) series.add_background_rectangle() self.add(series_group) self.braces = braces self.series = series self.arrow = e_to_x[1] def get_approx_graphs(self): def get_nth_approximation(n): return lambda x : sum([ float(x**k)/math.factorial(k) for k in range(n+1) ]) approx_graphs = [ self.get_graph(get_nth_approximation(n)) for n in range(self.n_iterations) ] colors = it.chain(self.colors, it.repeat(WHITE)) for approx_graph, color in zip(approx_graphs, colors): approx_graph.set_color(color) dot = Dot(color = WHITE) dot.move_to(self.input_to_graph_point( self.example_input, approx_graph )) approx_graph.add(dot) return approx_graphs class SecondExpGraphConvergence(ExpGraphConvergence): CONFIG = { "example_input" : 3, "n_iterations" : 12, } class BoundedRadiusOfConvergence(CubicAndQuarticApproximations): CONFIG = { "num_graph_anchor_points" : 100, } def construct(self): self.setup_axes() func = lambda x : (np.sin(x**2 + x)+0.5)*(np.log(x+1.01)+1)*np.exp(-x) graph = self.get_graph( func, color = self.colors[0], x_min = -0.99, x_max = self.x_max, ) v_line = self.get_vertical_line_to_graph( 0, graph, line_class = DashedLine, color = YELLOW ) dot = Dot(color = YELLOW).move_to(v_line.get_top()) two_graph = self.get_graph(lambda x : 2) outer_v_lines = VGroup(*[ DashedLine( self.coords_to_point(x, -2), self.coords_to_point(x, 2), color = WHITE ) for x in (-1, 1) ]) colors = list(self.colors) + [GREEN, MAROON_B, PINK] approx_graphs = [ self.get_graph( taylor_approximation(func, n), color = color ) for n, color in enumerate(colors) ] approx_graph = approx_graphs[1] self.add(graph, v_line, dot) self.play(ReplacementTransform( VGroup(v_line.copy()), outer_v_lines )) self.play( ShowCreation(approx_graph), Animation(dot) ) self.wait() for new_graph in approx_graphs[2:]: self.play( Transform(approx_graph, new_graph), Animation(dot) ) self.wait() self.wait() class RadiusOfConvergenceForLnX(ExpGraphConvergence): CONFIG = { "x_min" : -1, "x_leftmost_tick" : None, "x_max" : 5, "y_min" : -2, "y_max" : 3, "graph_origin" : DOWN+2*LEFT, "func" : np.log, "num_graph_anchor_points" : 100, "initial_n_iterations" : 7, "n_iterations" : 11, "convergent_example" : 1.5, "divergent_example" : 2.5, } def construct(self): self.add_graph() self.add_series() self.show_bounds() self.show_converging_point() self.show_diverging_point() self.write_divergence() self.write_radius_of_convergence() def add_graph(self): self.setup_axes() self.graph = self.get_graph( self.func, x_min = 0.01 ) self.add(self.graph) def add_series(self): series = OldTex( "\\ln(x) \\rightarrow", "(x-1)", "-", "\\frac{(x-1)^2}{2}", "+", "\\frac{(x-1)^3}{3}", "-", "\\frac{(x-1)^4}{4}", "+", "\\cdots" ) lhs = VGroup(*series[1:]) series.add_background_rectangle() series.scale(0.8) series.to_corner(UP+LEFT) for n in range(4): lhs[2*n].set_color(self.colors[n+1]) self.braces = self.get_partial_sum_braces( lhs, np.zeros(self.n_iterations) ) for brace in self.braces: brace.remove(brace[-1]) self.play(FadeIn( series, run_time = 3, lag_ratio = 0.5 )) self.wait() self.series = series self.foreground_mobjects = [series] def show_bounds(self): dot = Dot(fill_opacity = 0) dot.move_to(self.series) v_lines = [ DashedLine(*[ self.coords_to_point(x, y) for y in (-2, 2) ]) for x in (0, 1, 2) ] outer_v_lines = VGroup(*v_lines[::2]) center_v_line = VGroup(v_lines[1]) input_v_line = Line(*[ self.coords_to_point(self.convergent_example, y) for y in (-4, 3) ]) input_v_line.set_stroke(WHITE, width = 2) self.play( dot.move_to, self.coords_to_point(1, 0), dot.set_fill, YELLOW, 1, ) self.wait() self.play( GrowFromCenter(center_v_line), Animation(dot) ) self.play(Transform(center_v_line, outer_v_lines)) self.foreground_mobjects.append(dot) def show_converging_point(self): approx_graphs = [ self.get_graph( taylor_approximation(self.func, n, 1), color = WHITE ) for n in range(1, self.n_iterations+1) ] colors = it.chain( self.colors[1:], [GREEN, MAROON_B], it.repeat(PINK) ) for graph, color in zip(approx_graphs, colors): graph.set_color(color) for graph in approx_graphs: dot = Dot(color = WHITE) dot.move_to(self.input_to_graph_point( self.convergent_example, graph )) graph.dot = dot graph.add(dot) approx_graph = approx_graphs[0].deepcopy() approx_dot = approx_graph.dot brace = self.braces[0].copy() self.play(*it.chain( list(map(FadeIn, [approx_graph, brace])), list(map(Animation, self.foreground_mobjects)) )) self.wait() new_graphs = approx_graphs[1:self.initial_n_iterations] for new_graph, new_brace in zip(new_graphs, self.braces[1:]): self.play( Transform(approx_graph, new_graph), Transform(brace, new_brace), *list(map(Animation, self.foreground_mobjects)) ) self.wait() approx_graph.remove(approx_dot) self.play( approx_dot.move_to, self.coords_to_point(self.divergent_example, 0), *it.chain( list(map(FadeOut, [approx_graph, brace])), list(map(Animation, self.foreground_mobjects)) ) ) self.wait() self.approx_graphs = approx_graphs self.approx_dot = approx_dot def show_diverging_point(self): for graph in self.approx_graphs: graph.dot.move_to(self.input_to_graph_point( self.divergent_example, graph )) approx_graph = self.approx_graphs[0].deepcopy() brace = self.braces[0].copy() self.play( ReplacementTransform( self.approx_dot, approx_graph.dot ), FadeIn(approx_graph[0]), FadeIn(brace), *list(map(Animation, self.foreground_mobjects)) ) new_graphs = self.approx_graphs[1:self.initial_n_iterations] for new_graph, new_brace in zip(self.approx_graphs[1:], self.braces[1:]): self.play( Transform(approx_graph, new_graph), Transform(brace, new_brace), *list(map(Animation, self.foreground_mobjects)) ) self.wait() self.approx_dot = approx_graph.dot self.approx_graph = approx_graph def write_divergence(self): word = OldTexText("``Diverges''") word.next_to(self.approx_dot, RIGHT, LARGE_BUFF) word.shift(MED_SMALL_BUFF*DOWN) word.add_background_rectangle() arrow = Arrow( word.get_left(), self.approx_dot, buff = SMALL_BUFF, color = WHITE ) self.play( Write(word), ShowCreation(arrow) ) self.wait() new_graphs = self.approx_graphs[self.initial_n_iterations:] for new_graph in new_graphs: self.play( Transform(self.approx_graph, new_graph), *list(map(Animation, self.foreground_mobjects)) ) self.wait() def write_radius_of_convergence(self): line = Line(*[ self.coords_to_point(x, 0) for x in (1, 2) ]) line.set_color(YELLOW) brace = Brace(line, DOWN) words = brace.get_text("``Radius of convergence''") words.add_background_rectangle() self.play( GrowFromCenter(brace), ShowCreation(line) ) self.wait() self.play(Write(words)) self.wait(3) class MoreToBeSaid(TeacherStudentsScene): CONFIG = { "seconds_to_blink" : 4, } def construct(self): words = OldTexText( "Lagrange error bounds, ", "convergence tests, ", "$\\dots$" ) words[0].set_color(BLUE) words[1].set_color(GREEN) words.to_edge(UP) fade_rect = FullScreenFadeRectangle() rect = Rectangle(height = 9, width = 16) rect.set_height(FRAME_Y_RADIUS) rect.to_corner(UP+RIGHT) randy = self.get_students()[1] self.teacher_says( "There's still \\\\ more to learn!", target_mode = "surprised", bubble_config = {"height" : 3, "width" : 4} ) for word in words: self.play(FadeIn(word)) self.wait() self.teacher_says( "About everything", ) self.play_student_changes(*["pondering"]*3) self.wait() self.remove() self.pi_creatures = []##Hack self.play( RemovePiCreatureBubble(self.teacher), FadeOut(words), FadeIn(fade_rect), randy.change, "happy", rect ) self.pi_creatures = [randy] self.play(ShowCreation(rect)) self.wait(4) class Chapter10Thanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "CrypticSwarm", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Karan Bhargava", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Markus Persson", "Joseph John Cox", "Dan Buchoff", "Derek Dai", "Luc Ritchie", "Ahmad Bamieh", "Mark Govea", "Zac Wentzell", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Nils Schneider", "James Thornton", "Mustafa Mahdi", "Jonathan Eppele", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], } class Thumbnail(ExampleApproximationWithSine): CONFIG = { "graph_origin" : DOWN, "x_axis_label" : "", "y_axis_label" : "", "x_axis_width" : 14, "graph_stroke_width" : 8, } def construct(self): self.setup_axes() cos_graph = self.get_graph(np.cos) cos_graph.set_stroke(BLUE, self.graph_stroke_width) quad_graph = self.get_graph(taylor_approximation(np.cos, 2)) quad_graph.set_stroke(GREEN, self.graph_stroke_width) quartic = self.get_graph(taylor_approximation(np.cos, 4)) quartic.set_stroke(PINK, self.graph_stroke_width) self.add(cos_graph, quad_graph, quartic) title = OldTexText("Taylor Series") title.set_width(1.5*FRAME_X_RADIUS) title.add_background_rectangle() title.to_edge(UP) self.add(title)
videos_3b1b/_2017/eoc/chapter7.py
# -*- coding: utf-8 -*- from manim_imports_ext import * class Chapter7OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ " Calculus required ", "continuity", ", and ", "continuity ", "was supposed to require the ", "infinitely little", "; but nobody could discover what the ", "infinitely little", " might be. ", ], "quote_arg_separator" : "", "highlighted_quote_terms" : { "continuity" : BLUE, "infinitely" : GREEN, }, "author" : "Bertrand Russell", } class ThisVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) deriv_videos = VGroup(*series[1:6]) this_video = series[6] integral_videos = VGroup(*series[7:9]) video_groups = [deriv_videos, this_video, integral_videos] braces = list(map(Brace, video_groups)) deriv_brace, this_brace, integral_brace = braces tex_mobs = [ OldTex(*args) for args in [ ("{df ", " \\over \\, ", " dx}"), ("\\lim_{h \\to 0}",), ("\\int ", "f(x)", "\\,dx"), ] ] deriv_tex, this_tex, integral_tex = tex_mobs for tex_mob, brace in zip(tex_mobs, braces): tex_mob.set_color_by_tex("f", GREEN) tex_mob.set_color_by_tex("dx", YELLOW) tex_mob.next_to(brace, DOWN) integral_tex.shift(LARGE_BUFF*RIGHT) lim_to_deriv_arrow = Arrow(this_tex, deriv_tex, color = WHITE) self.add(series) for index in 0, 2: videos = video_groups[index] brace = braces[index] tex_mob = tex_mobs[index] self.play(ApplyWave( videos, direction = DOWN, )) self.play( GrowFromCenter(brace), Write(tex_mob, run_time = 2) ) self.play( this_video.set_color, YELLOW, GrowFromCenter(this_brace), self.get_teacher().change_mode, "raise_right_hand", self.get_teacher().look_at, this_video ) self.play(Write(this_tex)) self.wait(2) self.play(self.get_teacher().change_mode, "sassy") self.wait(2) class LimitJustMeansApproach(PiCreatureScene): CONFIG = { "dx_color" : GREEN, "max_num_zeros" : 7, } def construct(self): limit_expression = self.get_limit_expression() limit_expression.shift(2*LEFT) limit_expression.to_edge(UP) evaluated_expressions = self.get_evaluated_expressions() evaluated_expressions.next_to(limit_expression, DOWN, buff = LARGE_BUFF) brace = Brace(evaluated_expressions[0][-1], DOWN) question = OldTexText("What does this ``approach''?") question.next_to(brace, DOWN) point = VectorizedPoint(limit_expression.get_right()) expression = VGroup( limit_expression[1].copy(), point, point.copy() ) self.add(limit_expression) self.change_mode("raise_right_hand") for next_expression in evaluated_expressions: next_expression.move_to(evaluated_expressions[0], RIGHT) self.play( Transform( expression, next_expression, lag_ratio = 0.5, ), self.pi_creature.look_at, next_expression[-1] ) if brace not in self.get_mobjects(): self.play( GrowFromCenter(brace), Write(question) ) self.wait(0.5) self.wait(2) def create_pi_creature(self): self.pi_creature = Mortimer().flip() self.pi_creature.to_corner(DOWN+LEFT) return self.pi_creature def get_limit_expression(self): lim = OldTex("\\lim_", "{dx", " \\to 0}") lim.set_color_by_tex("dx", self.dx_color) ratio = self.get_expression("dx") ratio.next_to(lim, RIGHT) limit_expression = VGroup(lim, ratio) return limit_expression def get_evaluated_expressions(self): result = VGroup() for num_zeros in range(1, self.max_num_zeros+1): dx_str = "0." + "0"*num_zeros + "1" expression = self.get_expression(dx_str) dx = float(dx_str) ratio = ((2+dx)**3-2**3)/dx ratio_mob = OldTex("%.6f\\dots"%ratio) group = VGroup(expression, OldTex("="), ratio_mob) group.arrange(RIGHT) result.add(group) return result def get_expression(self, dx): result = OldTex( "{(2 + ", str(dx), ")^3 - 2^3 \\over", str(dx) ) result.set_color_by_tex(dx, self.dx_color) return result class Goals(Scene): def construct(self): goals = [ OldTexText("Goal %d:"%d, s) for d, s in [ (1, "Formal definition of derivatives"), (2, "$(\\epsilon, \\delta)$ definition of a limit"), (3, "L'Hôpital's rule"), ] ] for goal in goals: goal.scale(1.3) goal.shift(3*DOWN).to_edge(LEFT) curr_goal = goals[0] self.play(FadeIn(curr_goal)) self.wait(2) for goal in goals[1:]: self.play(Transform(curr_goal, goal)) self.wait(2) class RefreshOnDerivativeDefinition(GraphScene): CONFIG = { "start_x" : 2, "start_dx" : 0.7, "df_color" : YELLOW, "dx_color" : GREEN, "secant_line_color" : MAROON_B, } def construct(self): self.setup_axes() def func(x): u = 0.3*x - 1.5 return -u**3 + 5*u + 7 graph = self.get_graph(func) graph_label = self.get_graph_label(graph) start_x_v_line, nudged_x_v_line = [ self.get_vertical_line_to_graph( self.start_x + nudge, graph, line_class = DashedLine, color = RED ) for nudge in (0, self.start_dx) ] nudged_x_v_line.save_state() ss_group = self.get_secant_slope_group( self.start_x, graph, dx = self.start_dx, dx_label = "dx", df_label = "df", df_line_color = self.df_color, dx_line_color = self.dx_color, secant_line_color = self.secant_line_color, ) derivative = OldTex( "{df", "\\over \\,", "dx}", "(", str(self.start_x), ")" ) derivative.set_color_by_tex("df", self.df_color) derivative.set_color_by_tex("dx", self.dx_color) derivative.set_color_by_tex(str(self.start_x), RED) df = derivative.get_part_by_tex("df") dx = derivative.get_part_by_tex("dx") input_x = derivative.get_part_by_tex(str(self.start_x)) derivative.move_to(self.coords_to_point(7, 4)) derivative.save_state() deriv_brace = Brace(derivative) dx_to_0 = OldTex("dx", "\\to 0") dx_to_0.set_color_by_tex("dx", self.dx_color) dx_to_0.next_to(deriv_brace, DOWN) #Introduce graph self.play(ShowCreation(graph)) self.play(Write(graph_label, run_time = 1)) self.play(Write(derivative)) self.wait() input_copy = input_x.copy() self.play( input_copy.next_to, self.coords_to_point(self.start_x, 0), DOWN ) self.play(ShowCreation(start_x_v_line)) self.wait() #ss_group_development self.play( ShowCreation(ss_group.dx_line), ShowCreation(ss_group.dx_label), ) self.wait() self.play(ShowCreation(ss_group.df_line)) self.play(Write(ss_group.df_label)) self.wait(2) self.play( ReplacementTransform(ss_group.dx_label.copy(), dx), ReplacementTransform(ss_group.df_label.copy(), df), run_time = 2 ) self.play(ShowCreation(ss_group.secant_line)) self.wait() #Let dx approach 0 self.play( GrowFromCenter(deriv_brace), Write(dx_to_0), ) self.animate_secant_slope_group_change( ss_group, target_dx = 0.01, run_time = 5, ) self.wait() #Write out fuller limit new_deriv = OldTex( "{f", "(", str(self.start_x), "+", "dx", ")", "-", "f", "(", str(self.start_x), ")", "\\over \\,", "dx" ) new_deriv.set_color_by_tex("dx", self.dx_color) new_deriv.set_color_by_tex("f", self.df_color) new_deriv.set_color_by_tex(str(self.start_x), RED) deriv_to_new_deriv = dict([ ( VGroup(derivative.get_part_by_tex(s)), VGroup(*new_deriv.get_parts_by_tex(s)) ) for s in ["f", "over", "dx", "(", str(self.start_x), ")"] ]) covered_new_deriv_parts = list(it.chain(*list(deriv_to_new_deriv.values()))) uncovered_new_deriv_parts = [part for part in new_deriv if part not in covered_new_deriv_parts] new_deriv.move_to(derivative) new_brace = Brace(new_deriv, DOWN) self.animate_secant_slope_group_change( ss_group, target_dx = self.start_dx, run_time = 2 ) self.play(ShowCreation(nudged_x_v_line)) self.wait() self.play(*[ ReplacementTransform(*pair, run_time = 2) for pair in list(deriv_to_new_deriv.items()) ]+[ Transform(deriv_brace, new_brace), dx_to_0.next_to, new_brace, DOWN ]) self.play(Write(VGroup(*uncovered_new_deriv_parts), run_time = 2)) self.wait() #Introduce limit notation lim = OldTex("\\lim").scale(1.3) dx_to_0.generate_target() dx_to_0.target.scale(0.7) dx_to_0.target.next_to(lim, DOWN, buff = SMALL_BUFF) lim_group = VGroup(lim, dx_to_0.target) lim_group.move_to(new_deriv, LEFT) self.play( ReplacementTransform(deriv_brace, lim), MoveToTarget(dx_to_0), new_deriv.next_to, lim_group, RIGHT, run_time = 2 ) for sf, color in (1.2, YELLOW), (1/1.2, WHITE): self.play( lim.scale, sf, lim.set_color, color, lag_ratio = 0.5 ) self.wait(2) self.animate_secant_slope_group_change( ss_group, target_dx = 0.01, run_time = 5, added_anims = [ Transform(nudged_x_v_line, start_x_v_line, run_time = 5) ] ) self.wait(2) #Record attributes for DiscussLowercaseDs below digest_locals(self) class RantOpenAndClose(Scene): def construct(self): opening, closing = [ OldTexText( start, "Rant on infinitesimals", "$>$", arg_separator = "" ) for start in ("$<$", "$<$/") ] self.play(FadeIn(opening)) self.wait(2) self.play(Transform(opening, closing)) self.wait(2) class DiscussLowercaseDs(RefreshOnDerivativeDefinition, PiCreatureScene, ZoomedScene): CONFIG = { "zoomed_canvas_corner" : UP+LEFT } def construct(self): self.skip_superclass_anims() self.replace_dx_terms() self.compare_rhs_and_lhs() self.h_is_finite() def skip_superclass_anims(self): self.remove(self.pi_creature) self.force_skipping() RefreshOnDerivativeDefinition.construct(self) self.revert_to_original_skipping_status() self.animate_secant_slope_group_change( self.ss_group, target_dx = self.start_dx, added_anims = [ self.nudged_x_v_line.restore, Animation(self.ss_group.df_line) ], run_time = 1 ) everything = self.get_top_level_mobjects() everything.remove(self.derivative) self.play(*[ ApplyMethod(mob.shift, 2.5*LEFT) for mob in everything ] + [ FadeIn(self.pi_creature) ]) def replace_dx_terms(self): dx_list = [self.dx_to_0[0]] dx_list += self.new_deriv.get_parts_by_tex("dx") mover = dx_list[0] mover_scale_val = 1.5 mover.initial_right = mover.get_right() self.play( mover.scale, mover_scale_val, mover.next_to, self.pi_creature.get_corner(UP+LEFT), UP, MED_SMALL_BUFF, self.pi_creature.change_mode, "sassy", path_arc = np.pi/2, ) self.blink() self.wait() for tex in "\\Delta x", "h": dx_list_replacement = [ OldTex( tex ).set_color(self.dx_color).move_to(dx, DOWN) for dx in dx_list ] self.play( Transform( VGroup(*dx_list), VGroup(*dx_list_replacement), ), self.pi_creature.change_mode, "raise_right_hand" ) self.wait() self.play( mover.scale, 0.9, mover.move_to, mover.initial_right, RIGHT, self.pi_creature.change_mode, "happy", ) self.play( self.dx_to_0.next_to, self.lim, DOWN, SMALL_BUFF, ) self.wait() def compare_rhs_and_lhs(self): self.derivative.restore() lhs = self.derivative equals = OldTex("=") rhs = VGroup(self.lim, self.dx_to_0, self.new_deriv) rhs.generate_target() rhs.target.next_to(self.pi_creature, UP, MED_LARGE_BUFF) rhs.target.to_edge(RIGHT) equals.next_to(rhs.target, LEFT) lhs.next_to(equals, LEFT) d_circles = VGroup(*[ Circle(color = BLUE_B).replace( lhs.get_part_by_tex(tex)[0], stretch = True, ).scale(1.5).rotate(-np.pi/12) for tex in ("df", "dx") ]) d_words = OldTexText(""" Limit idea is built in """) d_words.next_to(d_circles, DOWN) d_words.set_color(d_circles[0].get_color()) lhs_rect, rhs_rect = rects = [ Rectangle(color = GREEN_B).replace( mob, stretch = True ) for mob in (lhs, rhs.target) ] for rect in rects: rect.stretch_to_fit_width(rect.get_width()+2*MED_SMALL_BUFF) rect.stretch_to_fit_height(rect.get_height()+2*MED_SMALL_BUFF) formal_definition_words = OldTexText(""" Formal derivative definition """) formal_definition_words.set_width(rhs_rect.get_width()) formal_definition_words.next_to(rhs_rect, UP) formal_definition_words.set_color(rhs_rect.get_color()) formal_definition_words.add_background_rectangle() df = VGroup(lhs.get_part_by_tex("df")) df_target = VGroup(*self.new_deriv.get_parts_by_tex("f")) self.play( MoveToTarget(rhs), Write(lhs), Write(equals), ) self.play( ShowCreation(d_circles, run_time = 2), self.pi_creature.change_mode, "pondering" ) self.play(Write(d_words)) self.animate_secant_slope_group_change( self.ss_group, target_dx = 0.01, added_anims = [ Transform( self.nudged_x_v_line, self.start_x_v_line, run_time = 3 ) ] ) self.change_mode("thinking") self.wait(2) self.play( ShowCreation(lhs_rect), FadeOut(d_circles), FadeOut(d_words), ) self.wait(2) self.play( ReplacementTransform(lhs_rect, rhs_rect), self.pi_creature.change_mode, "raise_right_hand" ) self.wait(2) self.play(ReplacementTransform( df.copy(), df_target, path_arc = -np.pi/2, run_time = 2 )) self.wait(2) self.play(Indicate( VGroup(*rhs[:2]), run_time = 2 )) self.wait() self.play(Write(formal_definition_words)) self.play( self.pi_creature.change_mode, "happy", self.pi_creature.look_at, formal_definition_words ) self.wait(2) lhs.add_background_rectangle() self.add(rhs_rect, rhs) self.definition_group = VGroup( lhs, equals, rhs_rect, rhs, formal_definition_words ) self.lhs, self.rhs, self.rhs_rect = lhs, rhs, rhs_rect def h_is_finite(self): self.play( FadeOut(self.graph_label), self.definition_group.center, self.definition_group.to_corner, UP+RIGHT, self.pi_creature.change_mode, "sassy", self.pi_creature.look_at, 4*UP ) self.wait() words = OldTexText("No ``infinitely small''") words.next_to( self.definition_group, DOWN, buff = LARGE_BUFF, ) arrow = Arrow(words.get_top(), self.rhs_rect.get_bottom()) arrow.set_color(WHITE) h_group = VGroup( self.rhs[1].get_part_by_tex("dx"), *self.rhs[2].get_parts_by_tex("dx") ) moving_h = h_group[0] moving_h.original_center = moving_h.get_center() dx_group = VGroup() for h in h_group: dx = OldTex("dx") dx.set_color(h.get_color()) dx.replace(h, dim_to_match = 1) dx_group.add(dx) moving_dx = dx_group[0] self.play(Write(words), ShowCreation(arrow)) self.wait(2) self.play( moving_h.next_to, self.pi_creature.get_corner(UP+RIGHT), UP, self.pi_creature.change_mode, "raise_left_hand", ) self.wait() moving_dx.move_to(moving_h) h_group.save_state() self.play(Transform( h_group, dx_group, path_arc = np.pi, )) self.wait(2) self.play(h_group.restore, path_arc = np.pi) self.play( moving_h.move_to, moving_h.original_center, self.pi_creature.change_mode, "plain" ) self.wait() #Zoom in self.activate_zooming() lil_rect = self.little_rectangle lil_rect.move_to(self.ss_group) lil_rect.scale(3) lil_rect.save_state() self.wait() self.add(self.rhs) self.play( lil_rect.set_width, self.ss_group.dx_line.get_width()*4, run_time = 4 ) self.wait() dx = self.ss_group.dx_label dx.save_state() h = OldTex("h") h.set_color(dx.get_color()) h.replace(dx, dim_to_match = 1) self.play(Transform(dx, h, path_arc = np.pi)) self.play(Indicate(dx)) self.wait() self.play(dx.restore, path_arc = np.pi) self.play(lil_rect.restore, run_time = 4) self.wait() self.disactivate_zooming() self.wait() #Last approaching reference for target_dx in 3, 0.01, -2, 0.01: self.animate_secant_slope_group_change( self.ss_group, target_dx = target_dx, run_time = 4, ) self.wait() class OtherViewsOfDx(TeacherStudentsScene): def construct(self): definition = OldTex( "{df", "\\over \\,", "dx}", "(", "2", ")", "=", "\\lim", "_{h", "\\to", "0}", "{f", "(", "2", "+", "h", ")", "-", "f", "(", "2", ")", "\\over \\,", "h}" ) tex_to_color = { "df" : YELLOW, "f" : YELLOW, "dx" : GREEN, "h" : GREEN, "2" : RED } for tex, color in list(tex_to_color.items()): definition.set_color_by_tex(tex, color) definition.scale(0.8) definition.to_corner(UP+LEFT) dx_group = VGroup(*definition.get_parts_by_tex("dx")) h_group = VGroup(*definition.get_parts_by_tex("h")) self.add(definition) statements = [ OldTexText(*args) for args in [ ("Why the new \\\\ variable", "$h$", "?"), ("$dx$", "is more $\\dots$ contentious."), ("$dx$", "is infinitely small"), ("$dx$", "is nothing more \\\\ than a symbol"), ] ] for statement in statements: statement.h, statement.dx = [ VGroup(*statement.get_parts_by_tex( tex, substring = False )).set_color(GREEN) for tex in ("$h$", "$dx$") ] #Question self.student_says( statements[0], index = 1, target_mode = "confused" ) self.play(ReplacementTransform( statements[0].h.copy(), h_group, run_time = 2, lag_ratio = 0.5, )) self.wait() #Teacher answer self.teacher_says( statements[1], target_mode = "hesitant", bubble_creation_class = FadeIn, ) self.play(ReplacementTransform( statements[1].dx.copy(), dx_group, run_time = 2, )) self.wait() #First alternate view moving_dx = dx_group.copy() bubble_intro = PiCreatureBubbleIntroduction( self.get_students()[2], statements[2], target_mode = "hooray", bubble_creation_class = FadeIn, ) bubble_intro.update(1) dx_movement = Transform( moving_dx, statements[2].dx, run_time = 2 ) bubble_intro.update(0) self.play( bubble_intro, dx_movement, RemovePiCreatureBubble(self.get_teacher()), ) self.play(self.get_teacher().change_mode, "erm") self.wait() #Next alternate view bubble_intro = PiCreatureBubbleIntroduction( self.get_students()[0], statements[3], target_mode = "maybe", look_at = 3*UP, bubble_creation_class = FadeIn, ) bubble_intro.update(1) dx_movement = Transform( moving_dx, statements[3].dx, run_time = 2 ) bubble_intro.update(0) last_bubble = self.get_students()[2].bubble self.play( bubble_intro, dx_movement, FadeOut(last_bubble), FadeOut(last_bubble.content), *it.chain(*[ [ pi.change_mode, "pondering", pi.look_at, bubble_intro.mobject ] for pi in self.get_students()[1:] ]) ) self.wait(3) class GoalsListed(Scene): def construct(self): goals = VGroup(*[ OldTexText("Goal %d: %s"%(d, s)) for d, s in zip(it.count(1), [ "Formal definition of a derivative", "$(\\epsilon, \\delta)$ definition of limits", "L'Hôpital's rule", ]) ]) goals.arrange( DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) for goal in goals: self.play(FadeIn(goal)) self.wait() for i, goal in enumerate(goals): anims = [goal.set_color, YELLOW] if i > 0: anims += [goals[i-1].set_color, WHITE] self.play(*anims) self.wait() class GraphLimitExpression(GraphScene): CONFIG = { "start_x" : 2, "h_color" : GREEN, "f_color" : YELLOW, "two_color" : RED, "graph_origin" : 3*DOWN+LEFT, "x_min" : -8, "x_max" : 5, "x_axis_label" : "$h$", "x_labeled_nums" : list(range(-8, 6, 2)), "y_min" : 0, "y_max" : 20, "y_tick_frequency" : 1, "y_labeled_nums" : list(range(5, 25, 5)), "y_axis_label" : "", "big_delta" : 0.7, "small_delta" : 0.01, } def construct(self): self.func = lambda h : 3*(2**2) + 3*2*h + h**2 self.setup_axes() self.introduce_function() self.emphasize_non_definedness_at_0() self.draw_limit_point_hole() self.show_limit() self.skeptic_asks() self.show_epsilon_delta_intuition() def introduce_function(self): expression = OldTex( "{(", "2", "+", "h", ")", "^3", "-", "(", "2", ")", "^3", "\\over \\,", "h}", arg_separator = "", ) limit = OldTex("\\lim", "_{h", "\\to 0}") derivative = OldTex( "{d(x^3)", "\\over \\,", "dx}", "(", "2", ")" ) tex_to_color = { "h" : self.h_color, "dx" : self.h_color, "2" : self.two_color } for tex_mob in expression, limit, derivative: for tex, color in list(tex_to_color.items()): tex_mob.set_color_by_tex(tex, color) tex_mob.next_to(ORIGIN, RIGHT, LARGE_BUFF) tex_mob.to_edge(UP) expression.save_state() expression.generate_target() expression.target.next_to(limit, RIGHT) brace = Brace(VGroup(limit, expression.target)) derivative.next_to(brace, DOWN) indices = [0, 6, 11, 13] funcs = [ lambda h : (2+h)**3, lambda h : (2+h)**3 - 2**3, self.func ] graph = None for i, j, func in zip(indices, indices[1:], funcs): anims = [FadeIn( VGroup(*expression[i:j]), lag_ratio = 0.5, )] new_graph = self.get_graph(func, color = BLUE) if graph is None: graph = new_graph anims.append(FadeIn(graph)) else: anims.append(Transform(graph, new_graph)) self.play(*anims) self.wait() self.wait() self.play( MoveToTarget(expression), FadeIn(limit, lag_ratio = 0.5), GrowFromCenter(brace) ) self.play(Write(derivative)) self.wait(2) self.play( expression.restore, *list(map(FadeOut, [derivative, brace, limit])) ) self.wait() colored_graph = graph.copy().set_color(YELLOW) self.play(ShowCreation(colored_graph)) self.wait() self.play(ShowCreation(graph)) self.remove(colored_graph) self.wait() self.expression = expression self.limit = limit self.graph = graph def emphasize_non_definedness_at_0(self): expression = self.expression dot = Dot(self.graph_origin, color = GREEN) h_equals_0 = OldTex("h", "=", "0", "?") h_equals_0.next_to(self.graph_origin, UP+RIGHT, LARGE_BUFF) for tex in "h", "0": h_equals_0.set_color_by_tex(tex, GREEN) arrow = Arrow(h_equals_0.get_left(), self.graph_origin) arrow.set_color(WHITE) new_expression = expression.deepcopy() h_group = VGroup(*new_expression.get_parts_by_tex("h")) for h in h_group: zero = OldTex("0") zero.set_color(h.get_color()) zero.replace(h, dim_to_match = 1) Transform(h, zero).update(1) rhs = OldTex("=", "{\\, 0\\,", "\\over \\,", "0\\,}") rhs.set_color_by_tex("0", GREEN) rhs.next_to(new_expression, RIGHT) equation = VGroup(new_expression, rhs) equation.next_to(expression, DOWN, buff = LARGE_BUFF) ud_brace = Brace(VGroup(*rhs[1:]), DOWN) undefined = OldTexText("Undefined") undefined.next_to(ud_brace, DOWN) undefined.to_edge(RIGHT) self.play(Write(h_equals_0, run_time = 2)) self.play(*list(map(ShowCreation, [arrow, dot]))) self.wait() self.play(ReplacementTransform( expression.copy(), new_expression )) self.wait() self.play(Write(rhs)) self.wait() self.play( GrowFromCenter(ud_brace), Write(undefined) ) self.wait(2) self.point_to_zero_group = VGroup( h_equals_0, arrow, dot ) self.plug_in_zero_group = VGroup( new_expression, rhs, ud_brace, undefined ) def draw_limit_point_hole(self): dx = 0.07 color = self.graph.get_color() circle = Circle( radius = dx, stroke_color = color, fill_color = BLACK, fill_opacity = 1, ) circle.move_to(self.coords_to_point(0, 12)) colored_circle = circle.copy() colored_circle.set_stroke(YELLOW) colored_circle.set_fill(opacity = 0) self.play(GrowFromCenter(circle)) self.wait() self.play(ShowCreation(colored_circle)) self.play(ShowCreation( circle.copy().set_fill(opacity = 0), remover = True )) self.remove(colored_circle) self.play( circle.scale, 0.3, run_time = 2, rate_func = wiggle ) self.wait() self.limit_point_hole = circle def show_limit(self): dot = self.point_to_zero_group[-1] ed_group = self.get_epsilon_delta_group(self.big_delta) left_v_line, right_v_line = ed_group.delta_lines bottom_h_line, top_h_line = ed_group.epsilon_lines ed_group.delta_lines.save_state() ed_group.epsilon_lines.save_state() brace = Brace(ed_group.input_range, UP) brace_text = brace.get_text("Inputs around 0", buff = SMALL_BUFF) brace_text.add_background_rectangle() brace_text.shift(RIGHT) limit_point_hole_copy = self.limit_point_hole.copy() limit_point_hole_copy.set_stroke(YELLOW) h_zero_hole = limit_point_hole_copy.copy() h_zero_hole.move_to(self.graph_origin) ed_group.input_range.add(h_zero_hole) ed_group.output_range.add(limit_point_hole_copy) #Show range around 0 self.play( FadeOut(self.plug_in_zero_group), FadeOut(VGroup(*self.point_to_zero_group[:-1])), ) self.play( GrowFromCenter(brace), Write(brace_text), ReplacementTransform(dot, ed_group.input_range), ) self.add(h_zero_hole) self.wait() self.play( ReplacementTransform( ed_group.input_range.copy(), ed_group.output_range, run_time = 2 ), ) self.remove(self.limit_point_hole) #Show approaching self.play(*list(map(FadeOut, [brace, brace_text]))) for v_line, h_line in (right_v_line, top_h_line), (left_v_line, bottom_h_line): self.play( ShowCreation(v_line), ShowCreation(h_line) ) self.wait() self.play( v_line.move_to, self.coords_to_point(0, 0), DOWN, h_line.move_to, self.coords_to_point(0, self.func(0)), run_time = 3 ) self.play( VGroup(h_line, v_line).set_stroke, GREY, 2, ) self.wait() #Write limit limit = self.limit limit.next_to(self.expression, LEFT) equals, twelve = rhs = OldTex("=", "12") rhs.next_to(self.expression, RIGHT) twelve_copy = twelve.copy() limit_group = VGroup(limit, rhs) self.play(Write(limit_group)) self.wait() self.play(twelve_copy.next_to, top_h_line, RIGHT) self.wait() self.twelve_copy = twelve_copy self.rhs = rhs self.ed_group = ed_group self.input_range_brace_group = VGroup(brace, brace_text) def skeptic_asks(self): randy = Randolph() randy.scale(0.9) randy.to_edge(DOWN) self.play(FadeIn(randy)) self.play(PiCreatureSays( randy, """ What \\emph{exactly} do you mean by ``approach'' """, bubble_config = { "height" : 3, "width" : 5, "fill_opacity" : 1, "direction" : LEFT, }, target_mode = "sassy" )) self.remove(self.twelve_copy) self.play(randy.look, OUT) self.play(Blink(randy)) self.wait() self.play(RemovePiCreatureBubble( randy, target_mode = "pondering", look_at = self.limit_point_hole )) self.play( self.ed_group.delta_lines.restore, self.ed_group.epsilon_lines.restore, Animation(randy), rate_func = there_and_back, run_time = 5, ) self.play(Blink(randy)) self.play(FadeOut(randy)) def show_epsilon_delta_intuition(self): self.play( FadeOut(self.ed_group.epsilon_lines), FadeIn(self.input_range_brace_group) ) self.ed_group.epsilon_lines.restore() self.wait() self.play( self.ed_group.delta_lines.restore, Animation(self.input_range_brace_group), run_time = 2 ) self.play(FadeOut(self.input_range_brace_group)) self.play( ReplacementTransform( self.ed_group.input_range.copy(), self.ed_group.output_range, run_time = 2 ) ) self.wait() self.play(*list(map(GrowFromCenter, self.ed_group.epsilon_lines))) self.play(*[ ApplyMethod( line.copy().set_stroke(GREY, 2).move_to, self.coords_to_point(0, self.func(0)), run_time = 3, rate_func = there_and_back, remover = True, ) for line in self.ed_group.epsilon_lines ]) self.wait() holes = VGroup( self.ed_group.input_range.submobjects.pop(), self.ed_group.output_range.submobjects.pop(), ) holes.save_state() self.animate_epsilon_delta_group_change( self.ed_group, target_delta = self.small_delta, run_time = 8, rate_func = lambda t : smooth(t, 2), added_anims = [ ApplyMethod( hole.scale, 0.5, run_time = 8 ) for hole in holes ] ) self.wait() self.holes = holes ######### def get_epsilon_delta_group( self, delta, limit_x = 0, dashed_line_stroke_width = 3, dashed_line_length = FRAME_HEIGHT, input_range_color = YELLOW, input_range_stroke_width = 6, ): kwargs = dict(locals()) result = VGroup() kwargs.pop("self") result.delta = kwargs.pop("delta") result.limit_x = kwargs.pop("limit_x") result.kwargs = kwargs dashed_line = DashedLine( ORIGIN, dashed_line_length*RIGHT, stroke_width = dashed_line_stroke_width ) x_values = [limit_x-delta, limit_x+delta] x_axis_points = [self.coords_to_point(x, 0) for x in x_values] result.delta_lines = VGroup(*[ dashed_line.copy().rotate(np.pi/2).move_to( point, DOWN ) for point in x_axis_points ]) if self.func(limit_x) < 0: result.delta_lines.rotate( np.pi, RIGHT, about_point = result.delta_lines.get_bottom() ) basically_zero = 0.00001 result.input_range, result.output_range = [ VGroup(*[ self.get_graph( func, color = input_range_color, x_min = x_min, x_max = x_max, ) for x_min, x_max in [ (limit_x-delta, limit_x-basically_zero), (limit_x+basically_zero, limit_x+delta), ] ]).set_stroke(width = input_range_stroke_width) for func in ((lambda h : 0), self.func) ] result.epsilon_lines = VGroup(*[ dashed_line.copy().move_to( self.coords_to_point(limit_x, 0)[0]*RIGHT+\ result.output_range.get_edge_center(vect)[1]*UP ) for vect in (DOWN, UP) ]) result.digest_mobject_attrs() return result def animate_epsilon_delta_group_change( self, epsilon_delta_group, target_delta, **kwargs ): added_anims = kwargs.get("added_anims", []) limit_x = epsilon_delta_group.limit_x start_delta = epsilon_delta_group.delta ed_group_kwargs = epsilon_delta_group.kwargs def update_ed_group(ed_group, alpha): delta = interpolate(start_delta, target_delta, alpha) new_group = self.get_epsilon_delta_group( delta, limit_x = limit_x, **ed_group_kwargs ) Transform(ed_group, new_group).update(1) return ed_group self.play( UpdateFromAlphaFunc( epsilon_delta_group, update_ed_group, **kwargs ), *added_anims ) class LimitCounterExample(GraphLimitExpression): CONFIG = { "x_min" : -8, "x_max" : 8, "x_labeled_nums" : list(range(-8, 10, 2)), "x_axis_width" : FRAME_WIDTH - LARGE_BUFF, "y_min" : -4, "y_max" : 4, "y_labeled_nums" : list(range(-2, 4, 1)), "y_axis_height" : FRAME_HEIGHT+2*LARGE_BUFF, "graph_origin" : DOWN, "graph_color" : BLUE, "hole_radius" : 0.075, "smaller_hole_radius" : 0.04, "big_delta" : 1.5, "small_delta" : 0.05, } def construct(self): self.add_func() self.setup_axes() self.draw_graph() self.approach_zero() self.write_limit_not_defined() self.show_epsilon_delta_intuition() def add_func(self): def func(h): square = 0.25*h**2 if h < 0: return -square + 1 else: return square + 2 self.func = func def draw_graph(self): epsilon = 0.1 left_graph, right_graph = [ self.get_graph( self.func, color = self.graph_color, x_min = x_min, x_max = x_max, ) for x_min, x_max in [ (self.x_min, -epsilon), (epsilon, self.x_max), ] ] left_hole = self.get_hole(0, 1, color = self.graph_color) right_hole = self.get_hole(0, 2, color = self.graph_color) graph = VGroup( left_graph, left_hole, right_hole, right_graph ) self.play(ShowCreation(graph, run_time = 5)) self.wait() self.play(ReplacementTransform( left_hole.copy().set_stroke(YELLOW), right_hole )) self.wait() self.graph = graph self.graph_holes = VGroup(left_hole, right_hole) def approach_zero(self): ed_group = self.get_epsilon_delta_group(self.big_delta) left_v_line, right_v_line = ed_group.delta_lines bottom_h_line, top_h_line = ed_group.epsilon_lines ed_group.delta_lines.save_state() ed_group.epsilon_lines.save_state() right_lines = VGroup(right_v_line, top_h_line) left_lines = VGroup(left_v_line, bottom_h_line) basically_zero = 0.00001 def update_lines(lines, alpha): v_line, h_line = lines sign = 1 if v_line is right_v_line else -1 x_val = interpolate(sign*self.big_delta, sign*basically_zero, alpha) v_line.move_to(self.coords_to_point(x_val, 0), DOWN) h_line.move_to(self.coords_to_point(0, self.func(x_val))) return lines for lines in right_lines, left_lines: self.play(*list(map(ShowCreation, lines))) self.play(UpdateFromAlphaFunc( lines, update_lines, run_time = 3 )) self.play(lines.set_stroke, GREY, 3) self.wait() self.ed_group = ed_group def write_limit_not_defined(self): limit = OldTex( "\\lim", "_{h", "\\to 0}", "f(", "h", ")" ) limit.set_color_by_tex("h", GREEN) limit.move_to(self.coords_to_point(2, 1.5)) words = OldTexText("is not defined") words.set_color(RED) words.next_to(limit, RIGHT, align_using_submobjects = True) limit_group = VGroup(limit, words) self.play(Write(limit)) self.wait() self.play(Write(words)) self.wait() self.play(limit_group.to_corner, UP+LEFT) self.wait() def show_epsilon_delta_intuition(self): ed_group = self.ed_group self.play( ed_group.delta_lines.restore, ed_group.epsilon_lines.restore, ) self.play(ShowCreation(ed_group.input_range)) self.wait() self.play(ReplacementTransform( ed_group.input_range.copy(), ed_group.output_range, run_time = 2 )) self.graph.remove(*self.graph_holes) self.remove(*self.graph_holes) self.wait() self.animate_epsilon_delta_group_change( ed_group, target_delta = self.small_delta, run_time = 6 ) self.hole_radius = self.smaller_hole_radius brace = Brace(self.ed_group.epsilon_lines, RIGHT, buff = SMALL_BUFF) brace_text = brace.get_text("Can't get \\\\ smaller", buff = SMALL_BUFF) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() run_time_rate_func_pairs = [ (3, lambda t : 1 - there_and_back(t)), (1, lambda t : 1 - 0.2*there_and_back(3*t % 1)), (1, lambda t : 1 - 0.2*there_and_back(5*t % 1)), ] for run_time, rate_func in run_time_rate_func_pairs: self.animate_epsilon_delta_group_change( ed_group, target_delta = self.small_delta, run_time = run_time, rate_func = rate_func, ) self.wait() ##### def get_epsilon_delta_group(self, delta, **kwargs): ed_group = GraphLimitExpression.get_epsilon_delta_group(self, delta, **kwargs) color = ed_group.kwargs["input_range_color"] radius = min(delta/2, self.hole_radius) pairs = [ (ed_group.input_range[0], (0, 0)), (ed_group.input_range[1], (0, 0)), (ed_group.output_range[0], (0, 1)), (ed_group.output_range[1], (0, 2)), ] for mob, coords in pairs: mob.add(self.get_hole( *coords, color = color, radius = radius )) return ed_group def get_hole(self, *coords, **kwargs): color = kwargs.get("color", BLUE) radius = kwargs.get("radius", self.hole_radius) return Circle( radius = radius, stroke_color = color, fill_color = BLACK, fill_opacity = 1, ).move_to(self.coords_to_point(*coords)) class PrefaceToEpsilonDeltaDefinition(TeacherStudentsScene): def construct(self): title = OldTex("(\\epsilon, \\delta) \\text{ definition}") title.next_to(self.get_teacher().get_corner(UP+LEFT), UP) title.save_state() title.shift(DOWN) title.set_fill(opacity = 0) self.play( title.restore, self.get_teacher().change_mode, "raise_right_hand", ) self.play_student_changes(*["confused"]*3) self.wait() self.student_says( "Isn't that pretty \\\\ technical?", target_mode = "guilty", added_anims = [ title.to_edge, UP, self.get_teacher().change_mode, "plain", self.get_teacher().look_at, self.get_students()[1].eyes ] ) self.look_at(self.get_teacher().eyes, self.get_students()) self.wait() self.teacher_says("", bubble_config = {"stroke_width" : 0}) self.play_student_changes( *["pondering"]*3, look_at = UP+LEFT, added_anims = [self.get_teacher().look_at, UP+LEFT] ) self.wait(3) words = OldTexText( "It's a glimpse of\\\\", "real analysis" ) words.set_color_by_tex("real", YELLOW) self.teacher_says( words, bubble_config = {"height" : 3, "width" : 6} ) self.play_student_changes(*["happy"]*3) self.wait(6) class EpsilonDeltaExample(GraphLimitExpression, ZoomedScene): CONFIG = { "epsilon_list" : [2, 1, 0.5], "zoomed_canvas_corner" : DOWN+RIGHT, } def construct(self): self.delta_list = [ epsilon/6.0 for epsilon in self.epsilon_list ] self.skip_superclass_anims() self.introduce_epsilon() self.match_epsilon() self.zoom_in() self.introduce_delta() self.smaller_epsilon() def skip_superclass_anims(self): self.force_skipping() GraphLimitExpression.construct(self) self.animate_epsilon_delta_group_change( self.ed_group, target_delta = self.big_delta, ) self.holes.restore() self.add(self.holes) self.revert_to_original_skipping_status() def introduce_epsilon(self): epsilon_group, small_epsilon_group = list(map( self.get_epsilon_group, self.epsilon_list[:2] )) twelve_line = epsilon_group.limit_line twelve = self.rhs[-1] twelve_copy = twelve.copy() twelve_copy.next_to(twelve_line) distance = OldTexText("Distance") distance.next_to(epsilon_group.labels, DOWN, LARGE_BUFF) distance.to_edge(RIGHT) arrows = VGroup(*[ Arrow(distance.get_top(), label.get_right()) for label in epsilon_group.labels ]) self.play(ShowCreation(twelve_line)) self.play(Write(twelve_copy)) self.play(ReplacementTransform(twelve_copy, twelve)) self.wait() self.play(*it.chain( [ ReplacementTransform(twelve_line.copy(), line) for line in epsilon_group.epsilon_lines ], list(map(GrowFromCenter, epsilon_group.braces)), )) self.play(*list(map(Write, epsilon_group.labels))) self.play( Write(distance), ShowCreation(arrows) ) self.wait() self.play(*list(map(FadeOut, [distance, arrows]))) self.play(Transform( epsilon_group, small_epsilon_group, run_time = 2 )) self.wait() self.epsilon_group = epsilon_group def match_epsilon(self): self.animate_epsilon_delta_group_change( self.ed_group, target_delta = self.delta_list[1], run_time = 2, added_anims = [ ApplyMethod( hole.scale, 0.25, run_time = 2 ) for hole in self.holes ] ) self.ed_group.delta = self.delta_list[1] self.ed_group.input_range.make_jagged() self.wait() def zoom_in(self): self.ed_group.input_range.make_jagged() self.activate_zooming() lil_rect = self.little_rectangle lil_rect.move_to(self.graph_origin) lil_rect.scale(self.zoom_factor) self.add(self.holes) self.wait() self.play(lil_rect.scale, 1./self.zoom_factor) self.wait() def introduce_delta(self): delta_group = self.get_delta_group(self.delta_list[1]) self.play(*list(map(GrowFromCenter, delta_group.braces))) self.play(*list(map(Write, delta_group.labels))) self.wait() self.play( ReplacementTransform( self.ed_group.input_range.copy(), self.ed_group.output_range, run_time = 2 ), Animation(self.holes), ) self.play(ApplyWave( VGroup(self.ed_group.output_range, self.holes[1]), direction = RIGHT )) self.wait(2) self.delta_group = delta_group def smaller_epsilon(self): new_epsilon = self.epsilon_list[-1] new_delta = self.delta_list[-1] self.play(Transform( self.epsilon_group, self.get_epsilon_group(new_epsilon) )) self.wait() self.animate_epsilon_delta_group_change( self.ed_group, target_delta = new_delta, added_anims = [ Transform( self.delta_group, self.get_delta_group(new_delta) ) ] + [ ApplyMethod(hole.scale, 0.5) for hole in self.holes ] ) self.ed_group.input_range.make_jagged() self.wait(2) ## def get_epsilon_group(self, epsilon, limit_value = 12): result = VGroup() line_length = FRAME_HEIGHT lines = [ Line( ORIGIN, line_length*RIGHT, ).move_to(self.coords_to_point(0, limit_value+nudge)) for nudge in (0, -epsilon, epsilon) ] result.limit_line = lines[0] result.limit_line.set_stroke(RED, width = 3) result.epsilon_lines = VGroup(*lines[1:]) result.epsilon_lines.set_stroke(MAROON_B, width = 2) brace = Brace(Line(ORIGIN, 0.5*UP), RIGHT) result.braces = VGroup(*[ brace.copy().set_height( group.get_height() ).next_to(group, RIGHT, SMALL_BUFF) for i in (1, 2) for group in [VGroup(lines[0], lines[i])] ]) result.labels = VGroup(*[ brace.get_text("\\Big $\\epsilon$", buff = SMALL_BUFF) for brace in result.braces ]) for label, brace in zip(result.labels, result.braces): label.set_height(min( label.get_height(), 0.8*brace.get_height() )) result.digest_mobject_attrs() return result def get_delta_group(self, delta): result = VGroup() brace = Brace(Line(ORIGIN, RIGHT), DOWN) brace.set_width( (self.coords_to_point(delta, 0)-self.graph_origin)[0] ) result.braces = VGroup(*[ brace.copy().move_to(self.coords_to_point(x, 0)) for x in (-delta/2, delta/2) ]) result.braces.shift(self.holes[0].get_height()*DOWN) result.labels = VGroup(*[ OldTex("\\delta").scale( 1./self.zoom_factor ) for brace in result.braces ]) for label, brace in zip(result.labels, result.braces): label.next_to( brace, DOWN, buff = SMALL_BUFF/self.zoom_factor ) result.digest_mobject_attrs() return result class EpsilonDeltaCounterExample(LimitCounterExample, EpsilonDeltaExample): def construct(self): self.hole_radius = 0.04 self.add_func() self.setup_axes() self.draw_graph() self.introduce_epsilon() self.introduce_epsilon_delta_group() self.move_epsilon_group_up_and_down() def introduce_epsilon(self): epsilon_group = self.get_epsilon_group(0.4, 1.5) rhs = OldTex("=0.4") label = epsilon_group.labels[1] rhs.next_to(label, RIGHT) epsilon_group.add(rhs) self.play(ShowCreation(epsilon_group.limit_line)) self.play(*it.chain( [ ReplacementTransform( epsilon_group.limit_line.copy(), line ) for line in epsilon_group.epsilon_lines ], list(map(GrowFromCenter, epsilon_group.braces)) )) self.play(*list(map(Write, epsilon_group.labels))) self.play(Write(rhs)) self.wait() self.epsilon_group = epsilon_group def introduce_epsilon_delta_group(self): ed_group = self.get_epsilon_delta_group(self.big_delta) self.play(*list(map(ShowCreation, ed_group.delta_lines))) self.play(ShowCreation(ed_group.input_range)) self.play(ReplacementTransform( ed_group.input_range.copy(), ed_group.output_range, run_time = 2 )) self.remove(self.graph_holes) self.play(*list(map(GrowFromCenter, ed_group.epsilon_lines))) self.wait(2) self.animate_epsilon_delta_group_change( ed_group, target_delta = self.small_delta, run_time = 3 ) ed_group.delta = self.small_delta self.wait() self.ed_group = ed_group def move_epsilon_group_up_and_down(self): vects = [ self.coords_to_point(0, 2) - self.coords_to_point(0, 1.5), self.coords_to_point(0, 1) - self.coords_to_point(0, 2), self.coords_to_point(0, 1.5) - self.coords_to_point(0, 1), ] for vect in vects: self.play(self.epsilon_group.shift, vect) self.wait() self.shake_ed_group() self.wait() ## def shake_ed_group(self): self.animate_epsilon_delta_group_change( self.ed_group, target_delta = self.big_delta, rate_func = lambda t : 0.2*there_and_back(2*t%1) ) class TheoryHeavy(TeacherStudentsScene): def construct(self): lhs = OldTex( "{df", "\\over \\,", "dx}", "(", "x", ")" ) equals = OldTex("=") rhs = OldTex( "\\lim", "_{h", "\\to 0}", "{f", "(", "x", "+", "h", ")", "-", "f", "(", "x", ")", "\\over \\,", "h}" ) derivative = VGroup(lhs, equals, rhs) derivative.arrange(RIGHT) for tex_mob in derivative: tex_mob.set_color_by_tex("x", RED) tex_mob.set_color_by_tex("h", GREEN) tex_mob.set_color_by_tex("dx", GREEN) tex_mob.set_color_by_tex("f", YELLOW) derivative.next_to(self.get_pi_creatures(), UP, buff = MED_LARGE_BUFF) lim = rhs.get_part_by_tex("lim") epsilon_delta = OldTex("(\\epsilon, \\delta)") epsilon_delta.next_to(lim, UP, buff = 1.5*LARGE_BUFF) arrow = Arrow(epsilon_delta, lim, color = WHITE) self.student_says( "Too much theory!", target_mode = "angry", content_introduction_kwargs = {"run_time" : 2}, ) self.wait() student = self.get_students()[1] Scene.play(self, Write(lhs), FadeOut(student.bubble), FadeOut(student.bubble.content), *[ ApplyFunction( lambda pi : pi.change_mode("pondering").look_at(epsilon_delta), pi ) for pi in self.get_pi_creatures() ] ) student.bubble = None part_tex_pairs = [ ("df", "f"), ("over", "+"), ("over", "-"), ("over", "to"), ("over", "over"), ("dx", "h"), ("(", "("), ("x", "x"), (")", ")"), ] self.play(Write(equals), Write(lim), *[ ReplacementTransform( VGroup(*lhs.get_parts_by_tex(t1)).copy(), VGroup(*rhs.get_parts_by_tex(t2)), run_time = 2, rate_func = squish_rate_func(smooth, alpha, alpha+0.5) ) for (t1, t2), alpha in zip( part_tex_pairs, np.linspace(0, 0.5, len(part_tex_pairs)) ) ]) self.wait(2) self.play( Write(epsilon_delta), ShowCreation(arrow) ) self.wait(3) derivative.add(epsilon_delta, arrow) self.student_says( "How do you \\\\ compute limits?", index = 2, added_anims = [ derivative.scale, 0.8, derivative.to_corner, UP+LEFT ] ) self.play(self.get_teacher().change_mode, "happy") self.wait(2) class LHopitalExample(LimitCounterExample, PiCreatureScene, ZoomedScene, ReconfigurableScene): CONFIG = { "graph_origin" : ORIGIN, "x_axis_width" : FRAME_WIDTH, "x_min" : -5, "x_max" : 5, "x_labeled_nums" : list(range(-6, 8, 2)), "x_axis_label" : "$x$", "y_axis_height" : FRAME_HEIGHT, "y_min" : -3.1, "y_max" : 3.1, "y_bottom_tick" : -4, "y_labeled_nums" : list(range(-2, 4, 2)), "y_axis_label" : "", "x_color" : RED, "hole_radius" : 0.07, "big_delta" : 0.5, "small_delta" : 0.01, "dx" : 0.06, "dx_color" : WHITE, "tex_scale_value" : 0.9, "sin_color" : GREEN, "parabola_color" : YELLOW, "zoomed_canvas_corner" : DOWN+LEFT, "zoom_factor" : 10, "zoomed_canvas_frame_shape" : (5, 5), "zoomed_canvas_corner_buff" : MED_SMALL_BUFF, "zoomed_rect_center_coords" : (1 + 0.1, -0.03), } def construct(self): self.setup_axes() self.introduce_function() self.show_non_definedness_at_one() self.plug_in_value_close_to_one() self.ask_about_systematic_process() self.show_graph_of_numerator_and_denominator() self.zoom_in_to_trouble_point() self.talk_through_sizes_of_nudges() self.show_final_ratio() self.show_final_height() def setup(self): PiCreatureScene.setup(self) ZoomedScene.setup(self) ReconfigurableScene.setup(self) self.remove(*self.get_pi_creatures()) def setup_axes(self): GraphScene.setup_axes(self) self.x_axis_label_mob.set_color(self.x_color) def introduce_function(self): graph = self.get_graph(self.func) colored_graph = graph.copy().set_color(YELLOW) func_label = self.get_func_label() func_label.next_to(ORIGIN, RIGHT, buff = LARGE_BUFF) func_label.to_edge(UP) x_copy = self.x_axis_label_mob.copy() self.play( Write(func_label), Transform( x_copy, VGroup(*func_label.get_parts_by_tex("x")), remover = True ) ) self.play(ShowCreation( graph, run_time = 3, rate_func=linear )) self.wait(4) ## Overly oscillation self.play(ShowCreation(colored_graph, run_time = 2)) self.wait() self.play(ShowCreation(graph, run_time = 2)) self.remove(colored_graph) self.wait() self.graph = graph self.func_label = func_label def show_non_definedness_at_one(self): morty = self.get_primary_pi_creature() words = OldTex("\\text{Try }", "x", "=1") words.set_color_by_tex("x", self.x_color, substring = False) v_line, alt_v_line = [ self.get_vertical_line_to_graph( x, self.graph, line_class = DashedLine, color = self.x_color ) for x in (1, -1) ] hole, alt_hole = [ self.get_hole(x, self.func(x)) for x in (1, -1) ] ed_group = self.get_epsilon_delta_group( self.big_delta, limit_x = 1, ) func_1 = self.get_func_label("1") func_1.next_to(self.func_label, DOWN, buff = MED_LARGE_BUFF) rhs = OldTex("\\Rightarrow \\frac{0}{0}") rhs.next_to(func_1, RIGHT) func_1_group = VGroup(func_1, *rhs) func_1_group.add_to_back(BackgroundRectangle(func_1_group)) lim = OldTex("\\lim", "_{x", "\\to 1}") lim.set_color_by_tex("x", self.x_color) lim.move_to(self.func_label, LEFT) self.func_label.generate_target() self.func_label.target.next_to(lim, RIGHT) equals_q = OldTex("=", "???") equals_q.next_to(self.func_label.target, RIGHT) self.play(FadeIn(morty)) self.play(PiCreatureSays(morty, words)) self.play( Blink(morty), ShowCreation(v_line) ) self.play( RemovePiCreatureBubble( morty, target_mode = "pondering", look_at = func_1 ), ReplacementTransform( self.func_label.copy(), func_1 ) ) self.wait(2) self.play(Write(VGroup(*rhs[:-1]))) self.wait() self.play(Write(rhs[-1])) self.wait() self.play(GrowFromCenter(hole)) self.wait() self.play(ShowCreation(alt_v_line)) self.play(GrowFromCenter(alt_hole)) self.wait() alt_group = VGroup(alt_v_line, alt_hole) self.play(alt_group.set_stroke, GREY, 2) self.play(FocusOn(hole)) self.wait() self.play(GrowFromCenter(ed_group.input_range)) self.play( ReplacementTransform( ed_group.input_range.copy(), ed_group.output_range ), *list(map(ShowCreation, ed_group.delta_lines)) ) self.play(*list(map(GrowFromCenter, ed_group.epsilon_lines))) self.play(morty.change_mode, "thinking") self.animate_epsilon_delta_group_change( ed_group, target_delta = self.small_delta, run_time = 4 ) self.wait() self.play( Write(lim), MoveToTarget(self.func_label), Write(equals_q), morty.change_mode, "confused", morty.look_at, lim ) self.wait(2) self.play( func_1_group.to_corner, UP+LEFT, *list(map(FadeOut, [morty, ed_group])) ) self.wait() self.lim_group = VGroup(lim, self.func_label, equals_q) for part in self.lim_group: part.add_background_rectangle() self.func_1_group = func_1_group self.v_line = v_line def plug_in_value_close_to_one(self): num = 1.00001 result = self.func(num) label = self.get_func_label(num) label.add_background_rectangle() rhs = OldTex("= %.4f\\dots"%result) rhs.next_to(label, RIGHT) approx_group = VGroup(label, rhs) approx_group.set_width(FRAME_X_RADIUS-2*MED_LARGE_BUFF) approx_group.next_to(ORIGIN, UP, buff = MED_LARGE_BUFF) approx_group.to_edge(RIGHT) self.play(ReplacementTransform( self.func_label.copy(), label )) self.wait() self.play(Write(rhs)) self.wait() self.approx_group = approx_group def ask_about_systematic_process(self): morty = self.pi_creature morty.change_mode("plain") self.func_1_group.save_state() to_fade = VGroup( *self.x_axis.numbers[:len(self.x_axis.numbers)/2] ) self.play( FadeIn(morty), FadeOut(to_fade) ) self.x_axis.remove(*to_fade) self.pi_creature_says( morty, "Is there a \\\\ better way?", bubble_config = { "height" : 3, "width" : 4, }, ) self.wait(2) self.play( RemovePiCreatureBubble( morty, target_mode = "raise_left_hand", look_at = self.func_1_group ), self.func_1_group.scale, self.tex_scale_value, self.func_1_group.move_to, morty.get_corner(UP+LEFT), DOWN+LEFT, self.func_1_group.shift, MED_LARGE_BUFF*UP, ) self.wait(2) self.play( morty.change_mode, "raise_right_hand", morty.look, UP+RIGHT, FadeOut(self.approx_group), self.func_1_group.restore, self.lim_group.next_to, morty.get_corner(UP+RIGHT), RIGHT, ) self.wait(2) self.play( FadeOut(self.func_1_group), self.lim_group.scale, self.tex_scale_value, self.lim_group.to_corner, UP+LEFT, # self.lim_group.next_to, ORIGIN, UP, MED_LARGE_BUFF, # self.lim_group.to_edge, LEFT, morty.change_mode, "plain" ) self.wait() self.play(FadeOut(morty)) def show_graph_of_numerator_and_denominator(self): sine_graph = self.get_graph( lambda x : np.sin(np.pi*x), color = self.sin_color ) sine_label = self.get_graph_label( sine_graph, "\\sin(\\pi x)", x_val = 4.5, direction = UP ) parabola = self.get_graph( lambda x : x**2 - 1, color = self.parabola_color ) parabola_label = self.get_graph_label( parabola, "x^2 - 1" ) fader = VGroup(*[ Rectangle( width = FRAME_WIDTH, height = FRAME_HEIGHT, stroke_width = 0, fill_opacity = 0.75, fill_color = BLACK, ).next_to(self.coords_to_point(1, 0), vect, MED_LARGE_BUFF) for vect in (LEFT, RIGHT) ]) self.play( ShowCreation(sine_graph, run_time = 2), Animation(self.lim_group) ) self.play(FadeIn(sine_label)) self.wait() self.play(ShowCreation(parabola, run_time = 2)) self.play(FadeIn(parabola_label)) self.wait() self.play(FadeIn(fader, run_time = 2)) self.wait() self.play(FadeOut(fader)) self.sine_graph = sine_graph self.sine_label = sine_label self.parabola = parabola self.parabola_label = parabola_label def zoom_in_to_trouble_point(self): self.activate_zooming() lil_rect = self.little_rectangle lil_rect.scale(self.zoom_factor) lil_rect.move_to(self.coords_to_point( *self.zoomed_rect_center_coords )) self.wait() self.play(lil_rect.scale, 1./self.zoom_factor) self.wait() def talk_through_sizes_of_nudges(self): arrow_tip_length = 0.15/self.zoom_factor zoom_tex_scale_factor = min( 0.75/self.zoom_factor, 1.5*self.dx ) dx_arrow = Arrow( self.coords_to_point(1, 0), self.coords_to_point(1+self.dx, 0), tip_length = arrow_tip_length, color = WHITE, ) dx_label = OldTex("dx") dx_label.scale(zoom_tex_scale_factor) dx_label.next_to(dx_arrow, UP, buff = SMALL_BUFF/self.zoom_factor) d_sine_arrow, d_parabola_arrow = [ Arrow( self.coords_to_point(1+self.dx, 0), self.coords_to_point( 1+self.dx, graph.underlying_function(1+self.dx) ), tip_length = arrow_tip_length, color = graph.get_color() ) for graph in (self.sine_graph, self.parabola) ] tex_arrow_pairs = [ [("d\\big(", "\\sin(", "\\pi", "x", ")", "\\big)"), d_sine_arrow], [("d\\big(", "x", "^2", "-1", "\\big)"), d_parabola_arrow], [("\\cos(", "\\pi", "x", ")", "\\pi ", "\\, dx"), d_sine_arrow], [("2", "x", "\\, dx"), d_parabola_arrow], ] d_labels = [] for tex_args, arrow in tex_arrow_pairs: label = OldTex(*tex_args) label.set_color_by_tex("x", self.x_color) label.set_color_by_tex("dx", self.dx_color) label.scale(zoom_tex_scale_factor) label.next_to(arrow, RIGHT, buff = SMALL_BUFF/self.zoom_factor) d_labels.append(label) d_sine_label, d_parabola_label, cos_dx, two_x_dx = d_labels #Show dx self.play(ShowCreation(dx_arrow)) self.play(Write(dx_label)) self.wait() #Show d_sine bump point = VectorizedPoint(self.coords_to_point(1, 0)) self.play(ReplacementTransform(point, d_sine_arrow)) self.wait() self.play(ReplacementTransform( VGroup(dx_label[1].copy()), d_sine_label, run_time = 2 )) self.wait(2) self.play( d_sine_label.shift, d_sine_label.get_height()*UP ) tex_pair_lists = [ [ ("sin", "cos"), ("pi", "pi"), ("x", "x"), (")", ")"), ], [ ("pi", "\\pi "), #Space there is important, though hacky ], [ ("d\\big(", "dx"), ("\\big)", "dx"), ] ] for tex_pairs in tex_pair_lists: self.play(*[ ReplacementTransform( d_sine_label.get_part_by_tex(t1).copy(), cos_dx.get_part_by_tex(t2) ) for t1, t2 in tex_pairs ]) self.wait() self.play(FadeOut(d_sine_label)) self.wait() #Substitute x = 1 self.substitute_x_equals_1(cos_dx, zoom_tex_scale_factor) #Proportionality constant cos_pi = VGroup(*cos_dx[:-1]) cos = VGroup(*cos_dx[:-2]) brace = Brace(Line(LEFT, RIGHT), UP) brace.set_width(cos_pi.get_width()) brace.move_to(cos_pi.get_top(), DOWN) brace_text = OldTexText( """ \\begin{flushleft} Proportionality constant \\end{flushleft} """ ) brace_text.scale(0.9*zoom_tex_scale_factor) brace_text.add_background_rectangle() brace_text.next_to(brace, UP, SMALL_BUFF/self.zoom_factor, LEFT) neg_one = OldTex("-", "1") neg_one.add_background_rectangle() neg_one.scale(zoom_tex_scale_factor) self.play(GrowFromCenter(brace)) self.play(Write(brace_text)) self.wait(2) self.play( brace.set_width, cos.get_width(), brace.next_to, cos, UP, SMALL_BUFF/self.zoom_factor, FadeOut(brace_text) ) neg_one.next_to(brace, UP, SMALL_BUFF/self.zoom_factor) self.play(Write(neg_one)) self.wait() self.play(FadeOut(cos)) neg = neg_one.get_part_by_tex("-").copy() self.play(neg.next_to, cos_dx[-2], LEFT, SMALL_BUFF/self.zoom_factor) self.play(*list(map(FadeOut, [neg_one, brace]))) neg_pi_dx = VGroup(neg, *cos_dx[-2:]) self.play( neg_pi_dx.next_to, d_sine_arrow, RIGHT, SMALL_BUFF/self.zoom_factor ) self.wait() #Show d_parabola bump point = VectorizedPoint(self.coords_to_point(1, 0)) self.play(ReplacementTransform(point, d_parabola_arrow)) self.play(ReplacementTransform( VGroup(dx_label[1].copy()), d_parabola_label, run_time = 2 )) self.wait(2) self.play( d_parabola_label.shift, d_parabola_label.get_height()*UP ) tex_pair_lists = [ [ ("2", "2"), ("x", "x"), ], [ ("d\\big(", "dx"), ("\\big)", "dx"), ] ] for tex_pairs in tex_pair_lists: self.play(*[ ReplacementTransform( d_parabola_label.get_part_by_tex(t1).copy(), two_x_dx.get_part_by_tex(t2) ) for t1, t2 in tex_pairs ]) self.wait() self.play(FadeOut(d_parabola_label)) self.wait() #Substitute x = 1 self.substitute_x_equals_1(two_x_dx, zoom_tex_scale_factor) def substitute_x_equals_1(self, tex_mob, zoom_tex_scale_factor): x = tex_mob.get_part_by_tex("x") equation = OldTex("x", "=", "1") eq_x, equals, one = equation equation.scale(zoom_tex_scale_factor) equation.next_to( x, UP, buff = MED_SMALL_BUFF/self.zoom_factor, aligned_edge = LEFT ) equation.set_color_by_tex("x", self.x_color) equation.set_color_by_tex("1", self.x_color) dot_one = OldTex("\\cdot", "1") dot_one.scale(zoom_tex_scale_factor) dot_one.set_color(self.x_color) dot_one.move_to(x, DOWN+LEFT) self.play(x.move_to, eq_x) self.wait() self.play( ReplacementTransform(x.copy(), eq_x), Transform(x, one), Write(equals) ) self.wait() self.play(Transform(x, dot_one)) self.wait() self.play(*list(map(FadeOut, [eq_x, equals]))) self.wait() def show_final_ratio(self): lim, ratio, equals_q = self.lim_group self.remove(self.lim_group) self.add(*self.lim_group) numerator = VGroup(*ratio[1][:3]) denominator = VGroup(*ratio[1][-2:]) rhs = OldTex( "\\approx", "{-\\pi", "\\, dx", "\\over \\,", "2", "\\, dx}" ) rhs.add_background_rectangle() rhs.move_to(equals_q, LEFT) equals = OldTex("=") approx = rhs.get_part_by_tex("approx") equals.move_to(approx) dxs = VGroup(*rhs.get_parts_by_tex("dx")) circles = VGroup(*[ Circle(color = GREEN).replace(dx).scale(1.3) for dx in dxs ]) #Show numerator and denominator self.play(FocusOn(ratio)) for mob in numerator, denominator: self.play(ApplyWave( mob, direction = UP+RIGHT, amplitude = 0.1 )) self.wait() self.play(ReplacementTransform(equals_q, rhs)) self.wait() #Cancel dx's self.play(*list(map(ShowCreation, circles)), run_time = 2) self.wait() self.play(dxs.fade, 0.75, FadeOut(circles)) self.wait() #Shrink dx self.transition_to_alt_config( transformation_kwargs = {"run_time" : 2}, dx = self.dx/10 ) self.wait() self.play(Transform(approx, equals)) self.play(Indicate(approx)) self.wait() self.final_ratio = rhs def show_final_height(self): brace = Brace(self.v_line, LEFT) height = brace.get_text("$\\dfrac{-\\pi}{2}$") height.add_background_rectangle() self.disactivate_zooming() self.play(*list(map(FadeOut, [ self.sine_graph, self.sine_label, self.parabola, self.parabola_label, ])) + [ Animation(self.final_ratio) ]) self.play(GrowFromCenter(brace)) self.play(Write(height)) self.wait(2) ## def create_pi_creature(self): self.pi_creature = Mortimer().flip().to_corner(DOWN+LEFT) return self.pi_creature def func(self, x): if abs(x) != 1: return np.sin(x*np.pi) / (x**2 - 1) else: return np.pi*np.cos(x*np.pi) / (2*x) def get_func_label(self, argument = "x"): in_tex = "{%s}"%str(argument) result = OldTex( "{\\sin(\\pi ", in_tex, ")", " \\over \\,", in_tex, "^2 - 1}" ) result.set_color_by_tex(in_tex, self.x_color) return result def get_epsilon_delta_group(self, delta, **kwargs): ed_group = GraphLimitExpression.get_epsilon_delta_group(self, delta, **kwargs) color = ed_group.kwargs["input_range_color"] radius = min(delta/2, self.hole_radius) pairs = [ # (ed_group.input_range[0], (1, 0)), (ed_group.input_range[1], (1, 0)), # (ed_group.output_range[0], (1, self.func(1))), (ed_group.output_range[1], (1, self.func(1))), ] for mob, coords in pairs: mob.add(self.get_hole( *coords, color = color, radius = radius )) return ed_group class DerivativeLimitReciprocity(Scene): def construct(self): arrow = Arrow(LEFT, RIGHT, color = WHITE) lim = OldTex("\\lim", "_{h", "\\to 0}") lim.set_color_by_tex("h", GREEN) lim.next_to(arrow, LEFT) deriv = OldTex("{df", "\\over\\,", "dx}") deriv.set_color_by_tex("dx", GREEN) deriv.set_color_by_tex("df", YELLOW) deriv.next_to(arrow, RIGHT) self.play(FadeIn(lim, lag_ratio = 0.5)) self.play(ShowCreation(arrow)) self.play(FadeIn(deriv, lag_ratio = 0.5)) self.wait() self.play(Rotate(arrow, np.pi, run_time = 2)) self.wait() class GeneralLHoptial(LHopitalExample): CONFIG = { "f_color" : BLUE, "g_color" : YELLOW, "a_value" : 2.5, "zoomed_rect_center_coords" : (2.55, 0), "zoom_factor" : 15, "image_height" : 3, } def construct(self): self.setup_axes() self.add_graphs() self.zoom_in() self.show_limit_in_symbols() self.show_tiny_nudge() self.show_derivative_ratio() self.show_example() self.show_bernoulli_and_lHopital() def add_graphs(self): f_graph = self.get_graph(self.f, self.f_color) f_label = self.get_graph_label( f_graph, "f(x)", x_val = 3, direction = RIGHT ) g_graph = ParametricCurve( lambda y : self.coords_to_point(np.exp(y)+self.a_value-1, y), t_min = self.y_min, t_max = self.y_max, color = self.g_color ) g_graph.underlying_function = self.g g_label = self.get_graph_label( g_graph, "g(x)", x_val = 4, direction = UP ) a_dot = Dot(self.coords_to_point(self.a_value, 0)) a_label = OldTex("x = a") a_label.next_to(a_dot, UP, LARGE_BUFF) a_arrow = Arrow(a_label.get_bottom(), a_dot, buff = SMALL_BUFF) VGroup(a_dot, a_label, a_arrow).set_color(self.x_color) self.play(ShowCreation(f_graph), Write(f_label)) self.play(ShowCreation(g_graph), Write(g_label)) self.wait() self.play( Write(a_label), ShowCreation(a_arrow), ShowCreation(a_dot), ) self.wait() self.play(*list(map(FadeOut, [a_label, a_arrow]))) self.a_dot = a_dot self.f_graph = f_graph self.f_label = f_label self.g_graph = g_graph self.g_label = g_label def zoom_in(self): self.activate_zooming() lil_rect = self.little_rectangle lil_rect.scale(self.zoom_factor) lil_rect.move_to(self.coords_to_point( *self.zoomed_rect_center_coords )) self.wait() self.play( lil_rect.scale, 1./self.zoom_factor, self.a_dot.scale, 1./self.zoom_factor, run_time = 3, ) self.wait() def show_limit_in_symbols(self): frac_a = self.get_frac("a", self.x_color) frac_x = self.get_frac("x") lim = OldTex("\\lim", "_{x", "\\to", "a}") lim.set_color_by_tex("a", self.x_color) equals_zero_over_zero = OldTex( "=", "{\\, 0 \\,", "\\over \\,", "0 \\,}" ) equals_q = OldTex(*"=???") frac_x.next_to(lim, RIGHT, SMALL_BUFF) VGroup(lim, frac_x).to_corner(UP+LEFT) frac_a.move_to(frac_x) equals_zero_over_zero.next_to(frac_a, RIGHT) equals_q.next_to(frac_a, RIGHT) self.play( ReplacementTransform( VGroup(*self.f_label).copy(), VGroup(frac_a.numerator) ), ReplacementTransform( VGroup(*self.g_label).copy(), VGroup(frac_a.denominator) ), Write(frac_a.over), run_time = 2 ) self.wait() self.play(Write(equals_zero_over_zero)) self.wait(2) self.play( ReplacementTransform( VGroup(*frac_a.get_parts_by_tex("a")), VGroup(lim.get_part_by_tex("a")) ) ) self.play(Write(VGroup(*lim[:-1]))) self.play(ReplacementTransform( VGroup(*lim.get_parts_by_tex("x")).copy(), VGroup(*frac_x.get_parts_by_tex("x")) )) self.play(ReplacementTransform( equals_zero_over_zero, equals_q )) self.wait() self.remove(frac_a) self.add(frac_x) self.frac_x = frac_x self.remove(equals_q) self.add(*equals_q) self.equals_q = equals_q def show_tiny_nudge(self): arrow_tip_length = 0.15/self.zoom_factor zoom_tex_scale_factor = min( 0.75/self.zoom_factor, 1.5*self.dx ) z_small_buff = SMALL_BUFF/self.zoom_factor dx_arrow = Arrow( self.coords_to_point(self.a_value, 0), self.coords_to_point(self.a_value+self.dx, 0), tip_length = arrow_tip_length, color = WHITE, ) dx_label = OldTex("dx") dx_label.scale(zoom_tex_scale_factor) dx_label.next_to(dx_arrow, UP, buff = z_small_buff) dx_label.shift(z_small_buff*RIGHT) df_arrow, dg_arrow = [ Arrow( self.coords_to_point(self.a_value+self.dx, 0), self.coords_to_point( self.a_value+self.dx, graph.underlying_function(self.a_value+self.dx) ), tip_length = arrow_tip_length, color = graph.get_color() ) for graph in (self.f_graph, self.g_graph) ] v_labels = [] for char, arrow in ("f", df_arrow), ("g", dg_arrow): label = OldTex( "\\frac{d%s}{dx}"%char, "(", "a", ")", "\\,dx" ) label.scale(zoom_tex_scale_factor) label.set_color_by_tex("a", self.x_color) label.set_color_by_tex("frac", arrow.get_color()) label.next_to(arrow, RIGHT, z_small_buff) v_labels.append(label) df_label, dg_label = v_labels self.play(ShowCreation(dx_arrow)) self.play(Write(dx_label)) self.play(Indicate(dx_label)) self.wait(2) self.play(ShowCreation(df_arrow)) self.play(Write(df_label)) self.wait() self.play(ShowCreation(dg_arrow)) self.play(Write(dg_label)) self.wait() def show_derivative_ratio(self): q_marks = VGroup(*self.equals_q[1:]) deriv_ratio = OldTex( "{ \\frac{df}{dx}", "(", "a", ")", "\\,dx", "\\over \\,", "\\frac{dg}{dx}", "(", "a", ")", "\\,dx}", ) deriv_ratio.set_color_by_tex("a", self.x_color) deriv_ratio.set_color_by_tex("df", self.f_color) deriv_ratio.set_color_by_tex("dg", self.g_color) deriv_ratio.move_to(q_marks, LEFT) dxs = VGroup(*deriv_ratio.get_parts_by_tex("\\,dx")) circles = VGroup(*[ Circle(color = GREEN).replace(dx).scale(1.3) for dx in dxs ]) self.play(FadeOut(q_marks)) self.play(Write(deriv_ratio)) self.wait(2) self.play(FadeIn(circles)) self.wait() self.play(FadeOut(circles), dxs.fade, 0.75) self.wait(2) self.transition_to_alt_config( transformation_kwargs = {"run_time" : 2}, dx = self.dx/10, ) self.wait() def show_example(self): lhs = OldTex( "\\lim", "_{x \\to", "0}", "{\\sin(", "x", ")", "\\over \\,", "x}", ) rhs = OldTex( "=", "{\\cos(", "0", ")", "\\over \\,", "1}", "=", "1" ) rhs.next_to(lhs, RIGHT) equation = VGroup(lhs, rhs) equation.to_corner(UP+RIGHT) for part in equation: part.set_color_by_tex("0", self.x_color) brace = Brace(lhs, DOWN) brace_text = brace.get_text("Looks like 0/0") brace_text.add_background_rectangle() name = OldTexText( "``", "L'Hôpital's", " rule", "''", arg_separator = "" ) name.shift(FRAME_X_RADIUS*RIGHT/2) name.to_edge(UP) self.play(Write(lhs)) self.wait() self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play(Write(rhs[0]), ReplacementTransform( VGroup(*lhs[3:6]).copy(), VGroup(*rhs[1:4]) )) self.wait() self.play(ReplacementTransform( VGroup(*lhs[6:8]).copy(), VGroup(*rhs[4:6]), )) self.wait() self.play(Write(VGroup(*rhs[6:]))) self.wait(2) ##Slide away example = VGroup(lhs, rhs, brace, brace_text) self.play( example.scale, 0.7, example.to_corner, DOWN+RIGHT, SMALL_BUFF, path_arc = 7*np.pi/6, ) self.play(Write(name)) self.wait(2) self.rule_name = name def show_bernoulli_and_lHopital(self): lhopital_name = self.rule_name.get_part_by_tex("L'Hôpital's") strike = Line( lhopital_name.get_left(), lhopital_name.get_right(), color = RED ) bernoulli_name = OldTexText("Bernoulli's") bernoulli_name.next_to(lhopital_name, DOWN) bernoulli_image = ImageMobject("Johann_Bernoulli2") lhopital_image = ImageMobject("Guillaume_de_L'Hopital") for image in bernoulli_image, lhopital_image: image.set_height(self.image_height) image.to_edge(UP) arrow = Arrow(ORIGIN, DOWN, buff = 0, color = GREEN) arrow.next_to(lhopital_image, DOWN, buff = SMALL_BUFF) dollars = VGroup(*[Tex("\\$") for x in range(5)]) for dollar, alpha in zip(dollars, np.linspace(0, 1, len(dollars))): angle = alpha*np.pi dollar.move_to(np.sin(angle)*RIGHT + np.cos(angle)*UP) dollars.set_color(GREEN) dollars.next_to(arrow, RIGHT, MED_LARGE_BUFF) dollars[0].set_fill(opacity = 0) dollars.save_state() self.play(ShowCreation(strike)) self.play( Write(bernoulli_name), FadeIn(bernoulli_image) ) self.wait() self.play( FadeIn(lhopital_image), bernoulli_image.next_to, arrow, DOWN, SMALL_BUFF, ShowCreation(arrow), FadeIn(dollars) ) for x in range(10): dollars.restore() self.play(*[ Transform(*pair) for pair in zip(dollars, dollars[1:]) ] + [ FadeOut(dollars[-1]) ]) #### def f(self, x): return -0.1*(x-self.a_value)*x*(x+4.5) def g(self, x): return np.log(x-self.a_value+1) def get_frac(self, input_tex, color = WHITE): result = OldTex( "{f", "(", input_tex, ")", "\\over \\,", "g", "(", input_tex, ")}" ) result.set_color_by_tex("f", self.f_color) result.set_color_by_tex("g", self.g_color) result.set_color_by_tex(input_tex, color) result.numerator = VGroup(*result[:4]) result.denominator = VGroup(*result[-4:]) result.over = result.get_part_by_tex("over") return result class CannotUseLHopital(TeacherStudentsScene): def construct(self): deriv = OldTex( "{d(e^x)", "\\over \\,", "dx}", "(", "x", ")", "=", "\\lim", "_{h", "\\to 0}", "{e^{", "x", "+", "h}", "-", "e^", "x", "\\over \\,", "h}" ) deriv.to_edge(UP) deriv.set_color_by_tex("x", RED) deriv.set_color_by_tex("dx", GREEN) deriv.set_color_by_tex("h", GREEN) deriv.set_color_by_tex("e^", YELLOW) self.play( Write(deriv), *it.chain(*[ [pi.change_mode, "pondering", pi.look_at, deriv] for pi in self.get_pi_creatures() ]) ) self.wait() self.student_says( "Use L'Hôpital's rule!", target_mode = "hooray" ) self.wait() answer = OldTex( "\\text{That requires knowing }", "{d(e^x)", "\\over \\,", "dx}" ) answer.set_color_by_tex("e^", YELLOW) answer.set_color_by_tex("dx", GREEN) self.teacher_says( answer, bubble_config = {"height" : 2.5}, target_mode = "hesitant" ) self.play_student_changes(*["confused"]*3) self.wait(3) class NextVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) next_video = series[7] brace = Brace(next_video, DOWN) integral = OldTex("\\int", "f(x)", "dx") ftc = OldTex( "F(b)", "-", "F(a)", "=", "\\int_a^b", "{dF", "\\over \\,", "dx}", "(x)", "dx" ) for tex_mob in integral, ftc: tex_mob.set_color_by_tex("dx", GREEN) tex_mob.set_color_by_tex("f", YELLOW) tex_mob.set_color_by_tex("F", YELLOW) tex_mob.next_to(brace, DOWN) self.add(series) self.play( GrowFromCenter(brace), next_video.set_color, YELLOW, self.get_teacher().change_mode, "raise_right_hand", self.get_teacher().look_at, next_video ) self.play(Write(integral)) self.wait(2) self.play(*[ ReplacementTransform( VGroup(*integral.get_parts_by_tex(p1)), VGroup(*ftc.get_parts_by_tex(p2)), run_time = 2, path_arc = np.pi/2, rate_func = squish_rate_func(smooth, alpha, alpha+0.5) ) for alpha, (p1, p2) in zip(np.linspace(0, 0.5, 3), [ ("int", "int"), ("f", "F"), ("dx", "dx"), ]) ]+[ Write(VGroup(*ftc.get_parts_by_tex(part))) for part in ("-", "=", "over", "(x)") ]) self.play_student_changes(*["pondering"]*3) self.wait(3) class Chapter7PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Meshal Alshammari", "CrypticSwarm ", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Nathan Pellegrin", "Karan Bhargava", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Justin Helps", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Daan Smedinga", "Jonathan Eppele", "Albert Nguyen", "Nils Schneider", "Mustafa Mahdi", "Mathew Bramson", "Guido Gambardella", "Jerry Ling", "Mark Govea", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", "Felipe Diniz", ] } class Thumbnail(Scene): def construct(self): lim = OldTex("\\lim", "_{h", "\\to 0}") lim.set_color_by_tex("h", GREEN) lim.set_height(5) self.add(lim)
videos_3b1b/_2017/eoc/chapter5.py
from manim_imports_ext import * from _2017.eoc.chapter4 import ThreeLinesChainRule class ExpFootnoteOpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "Who has not been amazed to learn that the function", "$y = e^x$,", "like a phoenix rising again from its own", "ashes, is its own derivative?", ], "highlighted_quote_terms" : { "$y = e^x$" : MAROON_B }, "author" : "Francois le Lionnais" } class LastVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) last_video = series[2] last_video.save_state() this_video = series[3] known_formulas = VGroup(*list(map(Tex, [ "\\frac{d(x^n)}{dx} = nx^{n-1}", "\\frac{d(\\sin(x))}{dx} = \\cos(x)", ]))) known_formulas.arrange( DOWN, buff = MED_LARGE_BUFF, ) known_formulas.set_height(2.5) exp_question = OldTex("2^x", ", 7^x, ", "e^x", " ???") last_video_brace = Brace(last_video) known_formulas.next_to(last_video_brace, DOWN) known_formulas.shift(MED_LARGE_BUFF*LEFT) last_video_brace.save_state() last_video_brace.shift(3*LEFT) last_video_brace.set_fill(opacity = 0) self.add(series) self.play( last_video_brace.restore, last_video.set_color, YELLOW, self.get_teacher().change_mode, "raise_right_hand", ) self.play(Write(known_formulas)) self.wait() self.student_says( exp_question, index = 1, added_anims = [self.get_teacher().change_mode, "pondering"] ) self.wait(3) e_to_x = exp_question.get_part_by_tex("e^x") self.play( self.teacher.change_mode, "raise_right_hand", e_to_x.scale, 1.5, e_to_x.set_color, YELLOW, e_to_x.next_to, self.teacher.get_corner(UP+LEFT), UP ) self.wait(2) class PopulationSizeGraphVsPopulationMassGraph(Scene): def construct(self): pass class DoublingPopulation(PiCreatureScene): CONFIG = { "time_color" : YELLOW, "pi_creature_grid_dimensions" : (8, 8), "pi_creature_grid_height" : 6, } def construct(self): self.remove(self.get_pi_creatures()) self.introduce_expression() self.introduce_pi_creatures() self.count_through_days() self.ask_about_dM_dt() self.growth_per_day() self.relate_growth_rate_to_pop_size() def introduce_expression(self): f_x = OldTex("f(x)", "=", "2^x") f_t = OldTex("f(t)", "=", "2^t") P_t = OldTex("P(t)", "=", "2^t") M_t = OldTex("M(t)", "=", "2^t") functions = VGroup(f_x, f_t, P_t, M_t) for function in functions: function.scale(1.2) function.to_corner(UP+LEFT) for function in functions[1:]: for i, j in (0, 2), (2, 1): function[i][j].set_color(self.time_color) t_expression = OldTex("t", "=", "\\text{Time (in days)}") t_expression.to_corner(UP+RIGHT) t_expression[0].set_color(self.time_color) pop_brace, mass_brace = [ Brace(function[0], DOWN) for function in (P_t, M_t) ] for brace, word in (pop_brace, "size"), (mass_brace, "mass"): text = brace.get_text("Population %s"%word) text.to_edge(LEFT) brace.text = text self.play(Write(f_x)) self.wait() self.play( Transform(f_x, f_t), FadeIn( t_expression, run_time = 2, lag_ratio = 0.5 ) ) self.play(Transform(f_x, P_t)) self.play( GrowFromCenter(pop_brace), Write(pop_brace.text, run_time = 2) ) self.wait(2) self.function = f_x self.pop_brace = pop_brace self.t_expression = t_expression self.mass_function = M_t self.mass_brace = mass_brace def introduce_pi_creatures(self): creatures = self.get_pi_creatures() total_num_days = self.get_num_days() num_start_days = 4 self.reset() for x in range(num_start_days): self.let_one_day_pass() self.wait() self.play( Transform(self.function, self.mass_function), Transform(self.pop_brace, self.mass_brace), Transform(self.pop_brace.text, self.mass_brace.text), ) self.wait() for x in range(total_num_days-num_start_days): self.let_one_day_pass() self.wait() self.joint_blink(shuffle = False) self.wait() def count_through_days(self): self.reset() brace = self.get_population_size_descriptor() days_to_let_pass = 3 self.play(GrowFromCenter(brace)) self.wait() for x in range(days_to_let_pass): self.let_one_day_pass() new_brace = self.get_population_size_descriptor() self.play(Transform(brace, new_brace)) self.wait() self.population_size_descriptor = brace def ask_about_dM_dt(self): dM_dt_question = OldTex("{dM", "\\over dt}", "=", "???") dM, dt, equals, q_marks = dM_dt_question dM_dt_question.next_to(self.function, DOWN, buff = LARGE_BUFF) dM_dt_question.to_edge(LEFT) self.play( FadeOut(self.pop_brace), FadeOut(self.pop_brace.text), Write(dM_dt_question) ) self.wait(3) for mob in dM, dt: self.play(Indicate(mob)) self.wait() self.dM_dt_question = dM_dt_question def growth_per_day(self): day_to_day, frac = self.get_from_day_to_day_label() self.play( FadeOut(self.dM_dt_question), FadeOut(self.population_size_descriptor), FadeIn(day_to_day) ) rect = self.let_day_pass_and_highlight_new_creatures(frac) for x in range(2): new_day_to_day, new_frac = self.get_from_day_to_day_label() self.play(*list(map(FadeOut, [rect, frac]))) frac = new_frac self.play(Transform(day_to_day, new_day_to_day)) rect = self.let_day_pass_and_highlight_new_creatures(frac) self.play(*list(map(FadeOut, [rect, frac, day_to_day]))) def let_day_pass_and_highlight_new_creatures(self, frac): num_new_creatures = 2**self.get_curr_day() self.let_one_day_pass() new_creatures = VGroup( *self.get_on_screen_pi_creatures()[-num_new_creatures:] ) rect = Rectangle( color = GREEN, fill_color = BLUE, fill_opacity = 0.3, ) rect.replace(new_creatures, stretch = True) rect.stretch_to_fit_height(rect.get_height()+MED_SMALL_BUFF) rect.stretch_to_fit_width(rect.get_width()+MED_SMALL_BUFF) self.play(DrawBorderThenFill(rect)) self.play(Write(frac)) self.wait() return rect def relate_growth_rate_to_pop_size(self): false_deriv = OldTex( "{d(2^t) ", "\\over dt}", "= 2^t" ) difference_eq = OldTex( "{ {2^{t+1} - 2^t} \\over", "1}", "= 2^t" ) real_deriv = OldTex( "{ {2^{t+dt} - 2^t} \\over", "dt}", "= \\, ???" ) VGroup( false_deriv[0][3], false_deriv[2][-1], difference_eq[0][1], difference_eq[0][-2], difference_eq[2][-1], difference_eq[2][-1], real_deriv[0][1], real_deriv[0][-2], ).set_color(YELLOW) VGroup( difference_eq[0][3], difference_eq[1][-1], real_deriv[0][3], real_deriv[0][4], real_deriv[1][-2], real_deriv[1][-1], ).set_color(GREEN) expressions = [false_deriv, difference_eq, real_deriv] text_arg_list = [ ("Tempting", "...",), ("Rate of change", "\\\\ over one full day"), ("Rate of change", "\\\\ in a small time"), ] for expression, text_args in zip(expressions, text_arg_list): expression.next_to( self.function, DOWN, buff = LARGE_BUFF, aligned_edge = LEFT, ) expression.brace = Brace(expression, DOWN) expression.brace_text = expression.brace.get_text(*text_args) time = self.t_expression[-1] new_time = OldTex("3") new_time.move_to(time, LEFT) fading_creatures = VGroup(*self.get_on_screen_pi_creatures()[8:]) self.play(*list(map(FadeIn, [ false_deriv, false_deriv.brace, false_deriv.brace_text ]))) self.wait() self.play( Transform(time, new_time), FadeOut(fading_creatures) ) self.wait() for x in range(3): self.let_one_day_pass(run_time = 2) self.wait(2) for expression in difference_eq, real_deriv: expression.brace_text[1].set_color(GREEN) self.play( Transform(false_deriv, expression), Transform(false_deriv.brace, expression.brace), Transform(false_deriv.brace_text, expression.brace_text), ) self.wait(3) self.reset() for x in range(self.get_num_days()): self.let_one_day_pass() self.wait() rect = Rectangle(color = YELLOW) rect.replace(real_deriv) rect.stretch_to_fit_width(rect.get_width()+MED_SMALL_BUFF) rect.stretch_to_fit_height(rect.get_height()+MED_SMALL_BUFF) self.play(*list(map(FadeOut, [ false_deriv.brace, false_deriv.brace_text ]))) self.play(ShowCreation(rect)) self.play(*[ ApplyFunction( lambda pi : pi.change_mode("pondering").look_at(real_deriv), pi, run_time = 2, rate_func = squish_rate_func(smooth, a, a+0.5) ) for pi in self.get_pi_creatures() for a in [0.5*random.random()] ]) self.wait(3) ########### def create_pi_creatures(self): width, height = self.pi_creature_grid_dimensions creature_array = VGroup(*[ VGroup(*[ PiCreature(mode = "plain") for y in range(height) ]).arrange(UP, buff = MED_LARGE_BUFF) for x in range(width) ]).arrange(RIGHT, buff = MED_LARGE_BUFF) creatures = VGroup(*it.chain(*creature_array)) creatures.set_height(self.pi_creature_grid_height) creatures.to_corner(DOWN+RIGHT) colors = color_gradient([BLUE, GREEN, GREY_BROWN], len(creatures)) random.shuffle(colors) for creature, color in zip(creatures, colors): creature.set_color(color) return creatures def reset(self): time = self.t_expression[-1] faders = [time] + list(self.get_on_screen_pi_creatures()) new_time = OldTex("0") new_time.next_to(self.t_expression[-2], RIGHT) first_creature = self.get_pi_creatures()[0] self.play(*list(map(FadeOut, faders))) self.play(*list(map(FadeIn, [first_creature, new_time]))) self.t_expression.submobjects[-1] = new_time def let_one_day_pass(self, run_time = 2): all_creatures = self.get_pi_creatures() on_screen_creatures = self.get_on_screen_pi_creatures() low_i = len(on_screen_creatures) high_i = min(2*low_i, len(all_creatures)) new_creatures = VGroup(*all_creatures[low_i:high_i]) to_children_anims = [] growing_anims = [] for old_pi, pi in zip(on_screen_creatures, new_creatures): pi.save_state() child = pi.copy() child.scale(0.25, about_point = child.get_bottom()) child.eyes.scale(1.5, about_point = child.eyes.get_bottom()) pi.move_to(old_pi) pi.set_fill(opacity = 0) index = list(new_creatures).index(pi) prop = float(index)/len(new_creatures) alpha = np.clip(len(new_creatures)/8.0, 0, 0.5) rate_func = squish_rate_func( smooth, alpha*prop, alpha*prop+(1-alpha) ) to_child_anim = Transform(pi, child, rate_func = rate_func) to_child_anim.update(1) growing_anim = ApplyMethod(pi.restore, rate_func = rate_func) to_child_anim.update(0) to_children_anims.append(to_child_anim) growing_anims.append(growing_anim) time = self.t_expression[-1] total_new_creatures = len(on_screen_creatures) + len(new_creatures) new_time = OldTex(str(int(np.log2(total_new_creatures)))) new_time.move_to(time, LEFT) growing_anims.append(Transform(time, new_time)) self.play(*to_children_anims, run_time = run_time/2.0) self.play(*growing_anims, run_time = run_time/2.0) def get_num_pi_creatures_on_screen(self): mobjects = self.get_mobjects() return sum([ pi in mobjects for pi in self.get_pi_creatures() ]) def get_population_size_descriptor(self): on_screen_creatures = self.get_on_screen_pi_creatures() brace = Brace(on_screen_creatures, LEFT) n = len(on_screen_creatures) label = brace.get_text( "$2^%d$"%int(np.log2(n)), "$=%d$"%n, ) brace.add(label) return brace def get_num_days(self): x, y = self.pi_creature_grid_dimensions return int(np.log2(x*y)) def get_curr_day(self): return int(np.log2(len(self.get_on_screen_pi_creatures()))) def get_from_day_to_day_label(self): curr_day = self.get_curr_day() top_words = OldTexText( "From day", str(curr_day), "to", str(curr_day+1), ":" ) top_words.set_width(4) top_words.next_to( self.function, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT, ) top_words[1].set_color(GREEN) bottom_words = OldTex( str(2**curr_day), "\\text{ creatures}", "\\over {1 \\text{ day}}" ) bottom_words[0].set_color(GREEN) bottom_words.next_to(top_words, DOWN, buff = MED_LARGE_BUFF) return top_words, bottom_words class GraphOfTwoToT(GraphScene): CONFIG = { "x_axis_label" : "$t$", "y_axis_label" : "$M$", "x_labeled_nums" : list(range(1, 7)), "y_labeled_nums" : list(range(8, 40, 8)), "x_max" : 6, "y_min" : 0, "y_max" : 32, "y_tick_frequency" : 2, "graph_origin" : 2.5*DOWN + 5*LEFT, } def construct(self): self.setup_axes() example_t = 3 graph = self.get_graph(lambda t : 2**t, color = BLUE_C) self.graph = graph graph_label = self.get_graph_label( graph, "M(t) = 2^t", direction = LEFT, ) label_group = self.get_label_group(example_t) v_line, brace, height_label, ss_group, slope_label = label_group self.animate_secant_slope_group_change( ss_group, target_dx = 1, run_time = 0 ) self.remove(ss_group) #Draw graph and revert to tangent self.play(ShowCreation(graph)) self.play(Write(graph_label)) self.wait() self.play(Write(ss_group)) self.wait() for target_dx in 0.01, 1, 0.01: self.animate_secant_slope_group_change( ss_group, target_dx = target_dx ) self.wait() #Mark up with values self.play(ShowCreation(v_line)) self.play( GrowFromCenter(brace), Write(height_label, run_time = 1) ) self.wait() self.play( FadeIn( slope_label, run_time = 4, lag_ratio = 0.5 ), ReplacementTransform( height_label.copy(), slope_label.get_part_by_tex("2^") ) ) self.wait() #Vary value threes = VGroup(height_label[1], slope_label[2][1]) ts = VGroup(*[ OldTex("t").set_color(YELLOW).scale(0.75).move_to(three) for three in threes ]) self.play(Transform(threes, ts)) alt_example_t = example_t+1 def update_label_group(group, alpha): t = interpolate(example_t, alt_example_t, alpha) new_group = self.get_label_group(t) Transform(group, new_group).update(1) for t, three in zip(ts, threes): t.move_to(three) Transform(threes, ts).update(1) return group self.play(UpdateFromAlphaFunc( label_group, update_label_group, run_time = 3, )) self.play(UpdateFromAlphaFunc( label_group, update_label_group, run_time = 3, rate_func = lambda t : 1 - 1.5*smooth(t) )) def get_label_group(self, t): graph = self.graph v_line = self.get_vertical_line_to_graph( t, graph, color = YELLOW, ) brace = Brace(v_line, RIGHT) height_label = brace.get_text("$2^%d$"%t) ss_group = self.get_secant_slope_group( t, graph, dx = 0.01, df_label = "dM", dx_label = "dt", dx_line_color = GREEN, secant_line_color = RED, ) slope_label = OldTex( "\\text{Slope}", "=", "2^%d"%t, "(%.7f\\dots)"%np.log(2) ) slope_label.next_to( ss_group.secant_line.point_from_proportion(0.65), DOWN+RIGHT, buff = 0 ) slope_label.set_color_by_tex("Slope", RED) return VGroup( v_line, brace, height_label, ss_group, slope_label ) class SimpleGraphOfTwoToT(GraphOfTwoToT): CONFIG = { "x_axis_label" : "", "y_axis_label" : "", } def construct(self): self.setup_axes() func = lambda t : 2**t graph = self.get_graph(func) line_pairs = VGroup() for x in 1, 2, 3, 4, 5: point = self.coords_to_point(x, func(x)) x_axis_point = self.coords_to_point(x, 0) y_axis_point = self.coords_to_point(0, func(x)) line_pairs.add(VGroup( DashedLine(x_axis_point, point), DashedLine(y_axis_point, point), )) self.play(ShowCreation(graph, run_time = 2)) for pair in line_pairs: self.play(ShowCreation(pair)) self.wait() class FakeDiagram(TeacherStudentsScene): def construct(self): gs = GraphScene(skip_animations = True) gs.setup_axes() background_graph, foreground_graph = graphs = VGroup(*[ gs.get_graph( lambda t : np.log(2)*2**t, x_min = -8, x_max = 2 + dx ) for dx in (0.25, 0) ]) for graph in graphs: end_point = graph.get_points()[-1] axis_point = end_point[0]*RIGHT + gs.graph_origin[1]*UP for alpha in np.linspace(0, 1, 20): point = interpolate(axis_point, graph.get_points()[0], alpha) graph.add_line_to(point) graph.set_stroke(width = 1) graph.set_fill(opacity = 1) graph.set_color(BLUE_D) background_graph.set_color(YELLOW) background_graph.set_stroke(width = 0.5) graphs.next_to(self.teacher, UP+LEFT, LARGE_BUFF) two_to_t = OldTex("2^t") two_to_t.next_to( foreground_graph.get_corner(DOWN+RIGHT), UP+LEFT ) corner_line = Line(*[ graph.get_corner(DOWN+RIGHT) for graph in graphs ]) dt_brace = Brace(corner_line, DOWN, buff = SMALL_BUFF) dt = dt_brace.get_text("$dt$") side_brace = Brace(graphs, RIGHT, buff = SMALL_BUFF) deriv = side_brace.get_text("$\\frac{d(2^t)}{dt}$") circle = Circle(color = RED) circle.replace(deriv, stretch = True) circle.scale(1.5) words = OldTexText("Not a real explanation") words.to_edge(UP) arrow = Arrow(words.get_bottom(), two_to_t.get_corner(UP+LEFT)) arrow.set_color(WHITE) diagram = VGroup( graphs, two_to_t, dt_brace, dt, side_brace, deriv, circle, words, arrow ) self.play(self.teacher.change_mode, "raise_right_hand") self.play( Animation(VectorizedPoint(graphs.get_right())), DrawBorderThenFill(foreground_graph), Write(two_to_t) ) self.wait() self.play( ReplacementTransform( foreground_graph.copy(), background_graph, ), Animation(foreground_graph), Animation(two_to_t), GrowFromCenter(dt_brace), Write(dt) ) self.play(GrowFromCenter(side_brace)) self.play(Write(deriv, run_time = 2)) self.wait() self.play( ShowCreation(circle), self.teacher.change_mode, "hooray" ) self.play_student_changes(*["confused"]*3) self.play( Write(words), ShowCreation(arrow), self.teacher.change_mode, "shruggie" ) self.wait(3) self.play( FadeOut(diagram), *[ ApplyMethod(pi.change_mode, "plain") for pi in self.get_pi_creatures() ] ) self.teacher_says( "More numerical \\\\ than visual..." ) self.wait(2) self.diagram = diagram class AnalyzeExponentRatio(PiCreatureScene): CONFIG = { "base" : 2, "base_str" : "2", } def construct(self): base_str = self.base_str func_def = OldTex("M(", "t", ")", "= ", "%s^"%base_str, "t") func_def.to_corner(UP+LEFT) self.add(func_def) ratio = OldTex( "{ {%s^"%base_str, "{t", "+", "dt}", "-", "%s^"%base_str, "t}", "\\over \\,", "dt}" ) ratio.shift(UP+LEFT) lhs = OldTex("{dM", "\\over \\,", "dt}", "(", "t", ")", "=") lhs.next_to(ratio, LEFT) two_to_t_plus_dt = VGroup(*ratio[:4]) two_to_t = VGroup(*ratio[5:7]) two_to_t_two_to_dt = OldTex( "%s^"%base_str, "t", "%s^"%base_str, "{dt}" ) two_to_t_two_to_dt.move_to(two_to_t_plus_dt, DOWN+LEFT) exp_prop_brace = Brace(two_to_t_two_to_dt, UP) one = OldTex("1") one.move_to(ratio[5], DOWN) lp, rp = parens = OldTex("()") parens.stretch(1.3, 1) parens.set_height(ratio.get_height()) lp.next_to(ratio, LEFT, buff = 0) rp.next_to(ratio, RIGHT, buff = 0) extracted_two_to_t = OldTex("%s^"%base_str, "t") extracted_two_to_t.next_to(lp, LEFT, buff = SMALL_BUFF) expressions = [ ratio, two_to_t_two_to_dt, extracted_two_to_t, lhs, func_def ] for expression in expressions: expression.set_color_by_tex("t", YELLOW) expression.set_color_by_tex("dt", GREEN) #Apply exponential property self.play( Write(ratio), Write(lhs), self.pi_creature.change_mode, "raise_right_hand" ) self.wait(2) self.play( two_to_t_plus_dt.next_to, exp_prop_brace, UP, self.pi_creature.change_mode, "pondering" ) self.play( ReplacementTransform( two_to_t_plus_dt.copy(), two_to_t_two_to_dt, run_time = 2, path_arc = np.pi, ), FadeIn(exp_prop_brace) ) self.wait(2) #Talk about exponential property add_exp_rect, mult_rect = rects = [ Rectangle( stroke_color = BLUE, stroke_width = 2, ).replace(mob).scale(1.1) for mob in [ VGroup(*two_to_t_plus_dt[1:]), two_to_t_two_to_dt ] ] words = VGroup(*[ OldTexText(s, " ideas") for s in ("Additive", "Multiplicative") ]) words[0].move_to(words[1], LEFT) words.set_color(BLUE) words.next_to(two_to_t_plus_dt, RIGHT, buff = 1.5*LARGE_BUFF) arrows = VGroup(*[ Arrow(word.get_left(), rect, color = words.get_color()) for word, rect in zip(words, rects) ]) self.play(ShowCreation(add_exp_rect)) self.wait() self.play(ReplacementTransform( add_exp_rect.copy(), mult_rect )) self.wait() self.change_mode("happy") self.play(Write(words[0], run_time = 2)) self.play(ShowCreation(arrows[0])) self.wait() self.play( Transform(*words), Transform(*arrows), ) self.wait(2) self.play(*list(map(FadeOut, [ words[0], arrows[0], add_exp_rect, mult_rect, two_to_t_plus_dt, exp_prop_brace, ]))) #Factor out 2^t self.play(*[ FadeIn( mob, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1) ) for mob in (one, lp, rp) ] + [ ReplacementTransform( mob, extracted_two_to_t, path_arc = np.pi/2, run_time = 2, ) for mob in (two_to_t, VGroup(*two_to_t_two_to_dt[:2])) ] + [ lhs.next_to, extracted_two_to_t, LEFT ]) self.change_mode("pondering") shifter = VGroup(ratio[4], one, *two_to_t_two_to_dt[2:]) stretcher = VGroup(lp, ratio[7], rp) self.play( shifter.next_to, ratio[7], UP, stretcher.stretch_in_place, 0.9, 0 ) self.wait(2) #Ask about dt -> 0 brace = Brace(VGroup(extracted_two_to_t, ratio), DOWN) alt_brace = Brace(parens, DOWN) dt_to_zero = OldTex("dt", "\\to 0") dt_to_zero.set_color_by_tex("dt", GREEN) dt_to_zero.next_to(brace, DOWN) self.play(GrowFromCenter(brace)) self.play(Write(dt_to_zero)) self.wait(2) #Who cares randy = Randolph() randy.scale(0.7) randy.to_edge(DOWN) self.play( FadeIn(randy), self.pi_creature.change_mode, "plain", ) self.play(PiCreatureSays( randy, "Who cares?", bubble_config = {"direction" : LEFT}, target_mode = "angry", )) self.wait(2) self.play( RemovePiCreatureBubble(randy), FadeOut(randy), self.pi_creature.change_mode, "hooray", self.pi_creature.look_at, parens ) self.play( Transform(brace, alt_brace), dt_to_zero.next_to, alt_brace, DOWN ) self.wait() #Highlight separation rects = [ Rectangle( stroke_color = color, stroke_width = 2, ).replace(mob, stretch = True).scale(1.1) for mob, color in [ (VGroup(parens, dt_to_zero), GREEN), (extracted_two_to_t, YELLOW), ] ] self.play(ShowCreation(rects[0])) self.wait(2) self.play(ReplacementTransform(rects[0].copy(), rects[1])) self.change_mode("happy") self.wait() self.play(*list(map(FadeOut, rects))) #Plug in specific values static_constant = self.try_specific_dt_values() constant = static_constant.copy() #Replace with actual constant limit_term = VGroup( brace, dt_to_zero, ratio[4], one, rects[0], *ratio[7:]+two_to_t_two_to_dt[2:] ) self.play(FadeIn(rects[0])) self.play(limit_term.to_corner, DOWN+LEFT) self.play( lp.stretch, 0.5, 1, lp.stretch, 0.8, 0, lp.next_to, extracted_two_to_t[0], RIGHT, rp.stretch, 0.5, 1, rp.stretch, 0.8, 0, rp.next_to, lp, RIGHT, SMALL_BUFF, rp.shift, constant.get_width()*RIGHT, constant.next_to, extracted_two_to_t[0], RIGHT, MED_LARGE_BUFF ) self.wait() self.change_mode("confused") self.wait() #Indicate distinction between dt group and t group again for mob in limit_term, extracted_two_to_t: self.play(FocusOn(mob)) self.play(Indicate(mob)) self.wait() #hold_final_value derivative = VGroup( lhs, extracted_two_to_t, parens, constant ) func_def_rhs = VGroup(*func_def[-2:]).copy() func_lp, func_rp = func_parens = OldTex("()") func_parens.set_fill(opacity = 0) func_lp.next_to(func_def_rhs[0], LEFT, buff = 0) func_rp.next_to(func_lp, RIGHT, buff = func_def_rhs.get_width()) func_def_rhs.add(func_parens) M = lhs[0][1] self.play( FadeOut(M), func_def_rhs.move_to, M, LEFT, func_def_rhs.set_fill, None, 1, ) lhs[0].submobjects[1] = func_def_rhs self.wait() self.play( derivative.next_to, self.pi_creature, UP, derivative.to_edge, RIGHT, self.pi_creature.change_mode, "raise_right_hand" ) self.wait(2) for mob in extracted_two_to_t, constant: self.play(Indicate(mob)) self.wait() self.wait(2) def try_specific_dt_values(self): expressions = [] for num_zeros in [1, 2, 4, 7]: dt_str = "0." + num_zeros*"0" + "1" dt_num = float(dt_str) output_num = (self.base**dt_num - 1) / dt_num output_str = "%.7f\\dots"%output_num expression = OldTex( "{%s^"%self.base_str, "{%s}"%dt_str, "-1", "\\over \\,", "%s}"%dt_str, "=", output_str ) expression.set_color_by_tex(dt_str, GREEN) expression.set_color_by_tex(output_str, BLUE) expression.to_corner(UP+RIGHT) expressions.append(expression) curr_expression = expressions[0] self.play( Write(curr_expression), self.pi_creature.change_mode, "pondering" ) self.wait(2) for expression in expressions[1:]: self.play(Transform(curr_expression, expression)) self.wait(2) return curr_expression[-1] class ExponentRatioWithThree(AnalyzeExponentRatio): CONFIG = { "base" : 3, "base_str" : "3", } class ExponentRatioWithSeven(AnalyzeExponentRatio): CONFIG = { "base" : 7, "base_str" : "7", } class ExponentRatioWithEight(AnalyzeExponentRatio): CONFIG = { "base" : 8, "base_str" : "8", } class ExponentRatioWithE(AnalyzeExponentRatio): CONFIG = { "base" : np.exp(1), "base_str" : "e", } class CompareTwoConstantToEightConstant(PiCreatureScene): def construct(self): two_deriv, eight_deriv = derivs = VGroup(*[ self.get_derivative_expression(base) for base in (2, 8) ]) derivs.arrange( DOWN, buff = 1.5, aligned_edge = LEFT ) derivs.to_edge(LEFT, LARGE_BUFF).shift(UP) arrow = Arrow(*[deriv[-2] for deriv in derivs]) times_three = OldTex("\\times 3") times_three.next_to(arrow, RIGHT) why = OldTexText("Why?") why.next_to(self.pi_creature, UP, MED_LARGE_BUFF) self.add(eight_deriv) self.wait() self.play(ReplacementTransform( eight_deriv.copy(), two_deriv )) self.wait() self.play(ShowCreation(arrow)) self.play( Write(times_three), self.pi_creature.change_mode, "thinking" ) self.wait(3) self.play( Animation(derivs), Write(why), self.pi_creature.change, "confused", derivs ) self.wait() for deriv in derivs: for index in -5, -2: self.play(Indicate(deriv[index])) self.wait() self.wait(2) def get_derivative_expression(self, base): base_str = str(base) const_str = "%.4f\\dots"%np.log(base) result = OldTex( "{d(", base_str, "^t", ")", "\\over", "dt}", "=", base_str, "^t", "(", const_str, ")" ) tex_color_paris = [ ("t", YELLOW), ("dt", GREEN), (const_str, BLUE) ] for tex, color in tex_color_paris: result.set_color_by_tex(tex, color) return result def create_pi_creature(self): self.pi_creature = Randolph().flip() self.pi_creature.to_edge(DOWN).shift(3*RIGHT) return self.pi_creature class AskAboutConstantOne(TeacherStudentsScene): def construct(self): note = OldTex( "{ d(a^", "t", ")", "\\over \\,", "dt}", "=", "a^", "t", "(\\text{Some constant})" ) note.set_color_by_tex("t", YELLOW) note.set_color_by_tex("dt", GREEN) note.set_color_by_tex("constant", BLUE) note.to_corner(UP+LEFT) self.add(note) self.student_says( "Is there a base where\\\\", "that constant is 1?" ) self.play_student_changes( "pondering", "raise_right_hand", "thinking", # look_at = self.get_students()[1].bubble ) self.wait(2) self.play(FadeOut(note[-1], run_time = 3)) self.wait() self.teacher_says( "There is!\\\\", "$e = 2.71828\\dots$", target_mode = "hooray" ) self.play_student_changes(*["confused"]*3) self.wait(3) class WhyPi(PiCreatureScene): def construct(self): circle = Circle(radius = 1, color = MAROON_B) circle.rotate(np.pi/2) circle.to_edge(UP) ghost_circle = circle.copy() ghost_circle.set_stroke(width = 1) diam = Line(circle.get_left(), circle.get_right()) diam.set_color(YELLOW) one = OldTex("1") one.next_to(diam, UP) circum = diam.copy() circum.set_color(circle.get_color()) circum.scale(np.pi) circum.next_to(circle, DOWN, LARGE_BUFF) circum.insert_n_curves(circle.get_num_curves()-2) circum.make_jagged() pi = OldTex("\\pi") pi.next_to(circum, UP) why = OldTexText("Why?") why.next_to(self.pi_creature, UP, MED_LARGE_BUFF) self.add(ghost_circle, circle, diam, one) self.wait() self.play(Transform(circle, circum, run_time = 2)) self.play( Write(pi), Write(why), self.pi_creature.change_mode, "confused", ) self.wait(3) ####### def create_pi_creature(self): self.pi_creature = Randolph() self.pi_creature.to_corner(DOWN+LEFT) return self.pi_creature class GraphOfExp(GraphScene): CONFIG = { "x_min" : -3, "x_max" : 3, "x_tick_frequency" : 1, "x_axis_label" : "t", "x_labeled_nums" : list(range(-3, 4)), "x_axis_width" : 11, "graph_origin" : 2*DOWN + LEFT, "example_inputs" : [1, 2], "small_dx" : 0.01, } def construct(self): self.setup_axes() self.show_slopes() def show_slopes(self): graph = self.get_graph(np.exp) graph_label = self.get_graph_label( graph, "e^t", direction = LEFT ) graph_label.shift(MED_SMALL_BUFF*LEFT) start_input, target_input = self.example_inputs ss_group = self.get_secant_slope_group( start_input, graph, dx = self.small_dx, dx_label = "dt", df_label = "d(e^t)", secant_line_color = YELLOW, ) v_lines = [ self.get_vertical_line_to_graph( x, graph, color = WHITE, ) for x in self.example_inputs ] height_labels = [ OldTex("e^%d"%x).next_to(vl, RIGHT, SMALL_BUFF) for vl, x in zip(v_lines, self.example_inputs) ] slope_labels = [ OldTexText( "Slope = $e^%d$"%x ).next_to(vl.get_top(), UP+RIGHT).shift(0.7*RIGHT/x) for vl, x in zip(v_lines, self.example_inputs) ] self.play( ShowCreation(graph, run_time = 2), Write( graph_label, rate_func = squish_rate_func(smooth, 0.5, 1), ) ) self.wait() self.play(*list(map(ShowCreation, ss_group))) self.play(Write(slope_labels[0])) self.play(ShowCreation(v_lines[0])) self.play(Write(height_labels[0])) self.wait(2) self.animate_secant_slope_group_change( ss_group, target_x = target_input, run_time = 2, added_anims = [ Transform( *pair, path_arc = np.pi/6, run_time = 2 ) for pair in [ slope_labels, v_lines, height_labels, ] ] ) self.wait(2) self.graph = graph self.ss_group = ss_group class Chapter4Wrapper(Scene): def construct(self): title = OldTexText("Chapter 4 chain rule intuition") title.to_edge(UP) rect = Rectangle(width = 16, height = 9) rect.set_height(1.5*FRAME_Y_RADIUS) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait(3) class ApplyChainRule(TeacherStudentsScene): def construct(self): deriv_equation = OldTex( "{d(", "e^", "{3", "t}", ")", "\\over", "dt}", "=", "3", "e^", "{3", "t}", ) deriv_equation.next_to(self.teacher, UP+LEFT) deriv_equation.shift(UP) deriv_equation.set_color_by_tex("3", BLUE) deriv = VGroup(*deriv_equation[:7]) exponent = VGroup(*deriv_equation[-2:]) circle = Circle(color = YELLOW) circle.replace(exponent, stretch = True) circle.scale(1.5) self.teacher_says("Think of the \\\\ chain rule") self.play_student_changes(*["pondering"]*3) self.play( Write(deriv), RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand" ), ) self.wait(2) self.play(*[ Transform( *deriv_equation.get_parts_by_tex( tex, substring = False ).copy()[:2], path_arc = -np.pi, run_time = 2 ) for tex in ("e^", "{3", "t}") ] + [ Write(deriv_equation.get_part_by_tex("=")) ]) self.play(self.teacher.change_mode, "happy") self.wait() self.play(ShowCreation(circle)) self.play(Transform( *deriv_equation.get_parts_by_tex("3").copy()[-1:-3:-1] )) self.play(FadeOut(circle)) self.wait(3) class ChainRuleIntuition(ThreeLinesChainRule): CONFIG = { "line_configs" : [ { "func" : lambda t : t, "func_label" : "t", "triangle_color" : WHITE, "center_y" : 3, "x_min" : 0, "x_max" : 3, "numbers_to_show" : list(range(4)), "numbers_with_elongated_ticks" : list(range(4)), "tick_frequency" : 1, }, { "func" : lambda t : 3*t, "func_label" : "3t", "triangle_color" : GREEN, "center_y" : 0.5, "x_min" : 0, "x_max" : 3, "numbers_to_show" : list(range(0, 4)), "numbers_with_elongated_ticks" : list(range(4)), "tick_frequency" : 1, }, { "func" : lambda t : np.exp(3*t), "func_label" : "e^{3t}", "triangle_color" : BLUE, "center_y" : -2, "x_min" : 0, "x_max" : 10, "numbers_to_show" : list(range(0, 11, 3)), "numbers_with_elongated_ticks" : list(range(11)), "tick_frequency" : 1, }, ], "example_x" : 0.4, "start_x" : 0.4, "max_x" : 0.6, "min_x" : 0.2, } def construct(self): self.introduce_line_group() self.nudge_x() def nudge_x(self): lines, labels = self.line_group def get_value_points(): return [ label[0].get_bottom() for label in labels ] starts = get_value_points() self.animate_x_change(self.example_x + self.dx, run_time = 0) ends = get_value_points() self.animate_x_change(self.example_x, run_time = 0) nudge_lines = VGroup() braces = VGroup() numbers = VGroup() for start, end, line, label, config in zip(starts, ends, lines, labels, self.line_configs): color = label[0].get_color() nudge_line = Line(start, end) nudge_line.set_stroke(color, width = 6) brace = Brace(nudge_line, DOWN, buff = SMALL_BUFF) brace.set_color(color) func_label = config["func_label"] if len(func_label) == 1: text = "$d%s$"%func_label else: text = "$d(%s)$"%func_label brace.text = brace.get_text(text, buff = SMALL_BUFF) brace.text.set_color(color) brace.add(brace.text) line.add(nudge_line) nudge_lines.add(nudge_line) braces.add(brace) numbers.add(line.numbers) line.remove(*line.numbers) dt_brace, d3t_brace, dexp3t_brace = braces self.play(*list(map(FadeIn, [nudge_lines, braces]))) self.wait() for count in range(3): for dx in self.dx, 0: self.animate_x_change( self.example_x + dx, run_time = 2 ) self.wait() class WhyNaturalLogOf2ShowsUp(TeacherStudentsScene): def construct(self): self.add_e_to_the_three_t() self.show_e_to_log_2() def add_e_to_the_three_t(self): exp_c = self.get_exp_C("c") exp_c.next_to(self.teacher, UP+LEFT) self.play( FadeIn( exp_c, run_time = 2, lag_ratio = 0.5 ), self.teacher.change, "raise_right_hand" ) self.wait() self.look_at(4*LEFT + UP) self.wait(3) self.exp_c = exp_c def show_e_to_log_2(self): equation = OldTex( "2", "^t", "= e^", "{\\ln(2)", "t}" ) equation.move_to(self.exp_c) t_group = equation.get_parts_by_tex("t") non_t_group = VGroup(*equation) non_t_group.remove(*t_group) log_words = OldTexText("``$e$ to the ", "\\emph{what}", "equals 2?''") log_words.set_color_by_tex("what", BLUE) log_words.next_to(equation, UP+LEFT) log_words_arrow = Arrow( log_words.get_right(), equation.get_part_by_tex("ln(2)").get_corner(UP+LEFT), color = BLUE, ) derivative = OldTex( "\\ln(2)", "2", "^t", "=", "\\ln(2)", "e^", "{\\ln(2)", "t}" ) derivative.move_to(equation) for tex_mob in equation, derivative: tex_mob.set_color_by_tex("ln(2)", BLUE) tex_mob.set_color_by_tex("t", YELLOW) derivative_arrow = Arrow(1.5*UP, ORIGIN, buff = 0) derivative_arrow.set_color(WHITE) derivative_arrow.next_to( derivative.get_parts_by_tex("="), UP ) derivative_symbol = OldTexText("Derivative") derivative_symbol.next_to(derivative_arrow, RIGHT) self.play( Write(non_t_group), self.exp_c.next_to, equation, LEFT, 2*LARGE_BUFF, self.exp_c.to_edge, UP, ) self.play_student_changes("confused", "sassy", "erm") self.play( Write(log_words), ShowCreation( log_words_arrow, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1) ) ) self.play_student_changes( *["pondering"]*3, look_at = log_words ) self.wait(2) t_group.save_state() t_group.shift(UP) t_group.set_fill(opacity = 0) self.play( ApplyMethod( t_group.restore, run_time = 2, lag_ratio = 0.5, ), self.teacher.change_mode, "speaking" ) self.wait(2) self.play(FocusOn(self.exp_c)) self.play(Indicate(self.exp_c, scale_factor = 1.05)) self.wait(2) self.play( equation.next_to, derivative_arrow, UP, equation.shift, MED_SMALL_BUFF*RIGHT, FadeOut(VGroup(log_words, log_words_arrow)), self.teacher.change_mode, "raise_right_hand", ) self.play( ShowCreation(derivative_arrow), Write(derivative_symbol), Write(derivative) ) self.wait(3) self.play(self.teacher.change_mode, "happy") self.wait(2) student = self.get_students()[1] ln = derivative.get_part_by_tex("ln(2)").copy() rhs = OldTex("=%s"%self.get_log_str(2)) self.play( ln.next_to, student, UP+LEFT, MED_LARGE_BUFF, student.change_mode, "raise_left_hand", ) rhs.next_to(ln, RIGHT) self.play(Write(rhs)) self.wait(2) ###### def get_exp_C(self, C): C_str = str(C) result = OldTex( "{d(", "e^", "{%s"%C_str, "t}", ")", "\\over", "dt}", "=", C_str, "e^", "{%s"%C_str, "t}", ) result.set_color_by_tex(C_str, BLUE) result.C_str = C_str return result def get_a_to_t(self, a): a_str = str(a) log_str = self.get_log_str(a) result = OldTex( "{d(", a_str, "^t", ")", "\\over", "dt}", "=", log_str, a_str, "^t" ) result.set_color_by_tex(log_str, BLUE) return result def get_log_str(self, a): return "%.4f\\dots"%np.log(float(a)) class CompareWaysToWriteExponentials(GraphScene): CONFIG = { "y_max" : 50, "y_tick_frequency" : 5, "x_max" : 7, } def construct(self): self.setup_axes() bases = list(range(2, 7)) graphs = [ self.get_graph(lambda t : base**t, color = GREEN) for base in bases ] graph = graphs[0] a_to_t = OldTex("a^t") a_to_t.move_to(self.coords_to_point(6, 45)) cross = OldTex("\\times") cross.set_color(RED) cross.replace(a_to_t, stretch = True) e_to_ct = OldTex("e^", "{c", "t}") e_to_ct.set_color_by_tex("c", BLUE) e_to_ct.scale(1.5) e_to_ct.next_to(a_to_t, DOWN) equations = VGroup() for base in bases: log_str = "%.4f\\dots"%np.log(base) equation = OldTex( str(base), "^t", "=", "e^", "{(%s)"%log_str, "t}", ) equation.set_color_by_tex(log_str, BLUE) equation.scale(1.2) equations.add(equation) equation = equations[0] equations.next_to(e_to_ct, DOWN, LARGE_BUFF, LEFT) self.play( ShowCreation(graph), Write( a_to_t, rate_func = squish_rate_func(smooth, 0.5, 1) ), run_time = 2 ) self.play(Write(cross, run_time = 2)) self.play(Write(e_to_ct, run_time = 2)) self.wait(2) self.play(Write(equation)) self.wait(2) for new_graph, new_equation in zip(graphs, equations)[1:]: self.play( Transform(graph, new_graph), Transform(equation, new_equation) ) self.wait(2) self.wait() class ManyExponentialForms(TeacherStudentsScene): def construct(self): lhs = OldTex("2", "^t") rhs_list = [ OldTex("=", "%s^"%tex, "{(%.5f\\dots)"%log, "t}") for tex, log in [ ("e", np.log(2)), ("\\pi", np.log(2)/np.log(np.pi)), ("42", np.log(2)/np.log(42)), ] ] group = VGroup(lhs, *rhs_list) group.arrange(RIGHT) group.set_width(FRAME_WIDTH - LARGE_BUFF) group.next_to(self.get_pi_creatures(), UP, 2*LARGE_BUFF) for part in group: part.set_color_by_tex("t", YELLOW) const = part.get_part_by_tex("dots") if const: const.set_color(BLUE) brace = Brace(const, UP) log = brace.get_text( "$\\log_{%s}(2)$"%part[1].get_tex()[:-1] ) log.set_color(BLUE) part.add(brace, log) exp = VGroup(*rhs_list[0][1:4]) rect = BackgroundRectangle(group) self.add(lhs, rhs_list[0]) self.wait() for rhs in rhs_list[1:]: self.play(FadeIn( rhs, run_time = 2, lag_ratio = 0.5, )) self.wait(2) self.wait() self.play( FadeIn(rect), exp.next_to, self.teacher, UP+LEFT, self.teacher.change, "raise_right_hand", ) self.play(*[ ApplyFunction( lambda m : m.shift(SMALL_BUFF*UP).set_color(RED), part, run_time = 2, rate_func = squish_rate_func(there_and_back, a, a+0.3) ) for part, a in zip(exp[1], np.linspace(0, 0.7, len(exp[1]))) ]) self.play_student_changes( *["pondering"]*3, look_at = exp ) self.wait(3) class TooManySymbols(TeacherStudentsScene): def construct(self): self.student_says( "Too symbol heavy!", target_mode = "pleading" ) self.play(self.teacher.change_mode, "guilty") self.wait(3) class TemperatureOverTimeOfWarmWater(GraphScene): CONFIG = { "x_min" : 0, "x_axis_label" : "$t$", "y_axis_label" : "Temperature", "T_room" : 4, "include_solution" : False, } def construct(self): self.setup_axes() graph = self.get_graph( lambda t : 3*np.exp(-0.3*t) + self.T_room, color = RED ) h_line = DashedLine(*[ self.coords_to_point(x, self.T_room) for x in (self.x_min, self.x_max) ]) T_room_label = OldTex("T_{\\text{room}}") T_room_label.next_to(h_line, LEFT) ode = OldTex( "\\frac{d\\Delta T}{dt} = -k \\Delta T" ) ode.to_corner(UP+RIGHT) solution = OldTex( "\\Delta T(", "t", ") = e", "^{-k", "t}" ) solution.next_to(ode, DOWN, MED_LARGE_BUFF) solution.set_color_by_tex("t", YELLOW) solution.set_color_by_tex("Delta", WHITE) delta_T_brace = Brace(graph, RIGHT) delta_T_label = OldTex("\\Delta T") delta_T_group = VGroup(delta_T_brace, delta_T_label) def update_delta_T_group(group): brace, label = group v_line = Line( graph.get_points()[-1], graph.get_points()[-1][0]*RIGHT + h_line.get_center()[1]*UP ) brace.set_height(v_line.get_height()) brace.next_to(v_line, RIGHT, SMALL_BUFF) label.set_height(min( label.get_height(), brace.get_height() )) label.next_to(brace, RIGHT, SMALL_BUFF) self.add(ode) self.play( Write(T_room_label), ShowCreation(h_line, run_time = 2) ) if self.include_solution: self.play(Write(solution)) graph_growth = ShowCreation(graph, rate_func=linear) delta_T_group_update = UpdateFromFunc( delta_T_group, update_delta_T_group ) self.play( GrowFromCenter(delta_T_brace), Write(delta_T_label), ) self.play(graph_growth, delta_T_group_update, run_time = 15) self.wait(2) class TemperatureOverTimeOfWarmWaterWithSolution(TemperatureOverTimeOfWarmWater): CONFIG = { "include_solution" : True } class InvestedMoney(Scene): def construct(self): # cash_str = "\\$\\$\\$" cash_str = "M" equation = OldTex( "{d", cash_str, "\\over", "dt}", "=", "(1 + r)", cash_str ) equation.set_color_by_tex(cash_str, GREEN) equation.next_to(ORIGIN, LEFT) equation.to_edge(UP) arrow = Arrow(LEFT, RIGHT, color = WHITE) arrow.next_to(equation) solution = OldTex( cash_str, "(", "t", ")", "=", "e^", "{(1+r)", "t}" ) solution.set_color_by_tex("t", YELLOW) solution.set_color_by_tex(cash_str, GREEN) solution.next_to(arrow, RIGHT) cash = OldTex("\\$") cash_pile = VGroup(*[ cash.copy().shift( x*(1+MED_SMALL_BUFF)*cash.get_width()*RIGHT +\ y*(1+MED_SMALL_BUFF)*cash.get_height()*UP ) for x in range(40) for y in range(8) ]) cash_pile.set_color(GREEN) cash_pile.center() cash_pile.shift(DOWN) anims = [] cash_size = len(cash_pile) run_time = 10 const = np.log(cash_size)/run_time for i, cash in enumerate(cash_pile): start_time = np.log(i+1)/const prop = start_time/run_time rate_func = squish_rate_func( smooth, np.clip(prop-0.5/run_time, 0, 1), np.clip(prop+0.5/run_time, 0, 1), ) anims.append(GrowFromCenter( cash, rate_func = rate_func, )) self.add(equation) self.play(*anims, run_time = run_time) self.wait() self.play(ShowCreation(arrow)) self.play(Write(solution, run_time = 2)) self.wait() self.play(FadeOut(cash_pile)) self.play(*anims, run_time = run_time) self.wait() class NaturalLog(Scene): def construct(self): expressions = VGroup(*list(map(self.get_expression, [2, 3, 7]))) expressions.arrange(DOWN, buff = MED_SMALL_BUFF) expressions.to_edge(LEFT) self.play(FadeIn( expressions, run_time = 3, lag_ratio = 0.5 )) self.wait() self.play( expressions.set_fill, None, 1, run_time = 2, lag_ratio = 0.5 ) self.wait() for i in 0, 2, 1: self.show_natural_loggedness(expressions[i]) def show_natural_loggedness(self, expression): base, constant = expression[1], expression[-3] log_constant, exp_constant = constant.copy(), constant.copy() log_base, exp_base = base.copy(), base.copy() log_equals, exp_equals = list(map(Tex, "==")) ln = OldTex("\\ln(2)") log_base.move_to(ln[-2]) ln.remove(ln[-2]) log_equals.next_to(ln, LEFT) log_constant.next_to(log_equals, LEFT) log_expression = VGroup( ln, log_constant, log_equals, log_base ) e = OldTex("e") exp_constant.scale(0.7) exp_constant.next_to(e, UP+RIGHT, buff = 0) exp_base.next_to(exp_equals, RIGHT) VGroup(exp_base, exp_equals).next_to( VGroup(e, exp_constant), RIGHT, aligned_edge = DOWN ) exp_expression = VGroup( e, exp_constant, exp_equals, exp_base ) for group, vect in (log_expression, UP), (exp_expression, DOWN): group.to_edge(RIGHT) group.shift(vect) self.play( ReplacementTransform(base.copy(), log_base), ReplacementTransform(constant.copy(), log_constant), run_time = 2 ) self.play(Write(ln), Write(log_equals)) self.wait() self.play( ReplacementTransform( log_expression.copy(), exp_expression, run_time = 2, ) ) self.wait(2) ln_a = expression[-1] self.play( FadeOut(expression[-2]), FadeOut(constant), ln_a.move_to, constant, LEFT, ln_a.set_color, BLUE ) self.wait() self.play(*list(map(FadeOut, [log_expression, exp_expression]))) self.wait() def get_expression(self, base): expression = OldTex( "{d(", "%d^"%base, "t", ")", "\\over \\,", "dt}", "=", "%d^"%base, "t", "(%.4f\\dots)"%np.log(base), ) expression.set_color_by_tex("t", YELLOW) expression.set_color_by_tex("dt", GREEN) expression.set_color_by_tex("\\dots", BLUE) brace = Brace(expression.get_part_by_tex("\\dots"), UP) brace_text = brace.get_text("$\\ln(%d)$"%base) for mob in brace, brace_text: mob.set_fill(opacity = 0) expression.add(brace, brace_text) return expression class NextVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) this_video = series[3] next_video = series[4] brace = Brace(this_video, DOWN) this_video.save_state() this_video.set_color(YELLOW) this_tex = OldTex( "{d(", "a^t", ") \\over dt} = ", "a^t", "\\ln(a)" ) this_tex[1][1].set_color(YELLOW) this_tex[3][1].set_color(YELLOW) this_tex.next_to(brace, DOWN) next_tex = VGroup(*list(map(TexText, [ "Chain rule", "Product rule", "$\\vdots$" ]))) next_tex.arrange(DOWN) next_tex.next_to(brace, DOWN) next_tex.shift( next_video.get_center()[0]*RIGHT\ -next_tex.get_center()[0]*RIGHT ) self.add(series, brace, *this_tex[:3]) self.play_student_changes( "confused", "pondering", "erm", look_at = this_tex ) self.play(ReplacementTransform( this_tex[1].copy(), this_tex[3] )) self.wait() self.play( Write(this_tex[4]), ReplacementTransform( this_tex[3][0].copy(), this_tex[4][3], path_arc = np.pi, remover = True ) ) self.wait(2) self.play(this_tex.replace, this_video) self.play( brace.next_to, next_video, DOWN, this_video.restore, Animation(this_tex), next_video.set_color, YELLOW, Write(next_tex), self.get_teacher().change_mode, "raise_right_hand" ) self.play_student_changes( *["pondering"]*3, look_at = next_tex ) self.wait(3) class ExpPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Meshal Alshammari", "CrypticSwarm ", "Kathryn Schmiedicke", "Nathan Pellegrin", "Karan Bhargava", "Justin Helps", "Ankit Agarwal", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Justin Helps", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Mustafa Mahdi", "Daan Smedinga", "Jonathan Eppele", "Albert Nguyen", "Nils Schneider", "Mustafa Mahdi", "Mathew Bramson", "Guido Gambardella", "Jerry Ling", "Mark Govea", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } class Thumbnail(GraphOfTwoToT): CONFIG = { "x_axis_label" : "", "y_axis_label" : "", "x_labeled_nums" : None, "y_labeled_nums" : None, "y_max" : 32, "y_tick_frequency" : 4, "graph_origin" : 3*DOWN + 5*LEFT, "x_axis_width" : 12, } def construct(self): derivative = OldTex( "\\frac{d(a^t)}{dt} =", "a^t \\ln(a)" ) derivative[0][3].set_color(YELLOW) derivative[1][1].set_color(YELLOW) derivative[0][2].set_color(BLUE) derivative[1][0].set_color(BLUE) derivative[1][5].set_color(BLUE) derivative.scale(2) derivative.add_background_rectangle() derivative.to_corner(DOWN+RIGHT, buff = MED_SMALL_BUFF) # brace = Brace(Line(LEFT, RIGHT), UP) # brace.set_width(derivative[1].get_width()) # brace.next_to(derivative[1], UP) # question = OldTexText("Why?") # question.scale(2.5) # question.next_to(brace, UP) # randy = Randolph() # randy.scale(1.3) # randy.next_to(ORIGIN, LEFT).to_edge(DOWN) # randy.change_mode("pondering") question = OldTexText("What is $e\\,$?") e = question[-2] e.scale(1.2, about_point = e.get_bottom()) e.set_color(BLUE) question.scale(3) question.add_background_rectangle() question.to_edge(UP) # randy.look_at(question) self.setup_axes() graph = self.get_graph(np.exp) graph.set_stroke(YELLOW, 8) self.add(graph, question, derivative)
videos_3b1b/_2017/eoc/footnote.py
import scipy import math from manim_imports_ext import * from _2017.eoc.eoc.chapter1 import Car, MoveCar from _2017.eoc.eoc.chapter10 import derivative #revert_to_original_skipping_status ######## class Introduce(TeacherStudentsScene): def construct(self): words = OldTexText("Next up is \\\\", "Taylor series") words.set_color_by_tex("Taylor", BLUE) derivs = VGroup(*[ OldTex( "{d", "^%d"%n, "f \\over dx", "^%d}"%n ).set_color_by_tex(str(n), YELLOW) for n in range(2, 5) ]) derivs.next_to(self.teacher, UP, LARGE_BUFF) second_deriv = derivs[0] second_deriv.save_state() card_dot = Dot(radius = SMALL_BUFF) screen_rect = ScreenRectangle(height = 4) screen_rect.move_to(3*UP, UP) self.teacher_says(words, run_time = 2) taylor_series = words.get_part_by_tex("Taylor").copy() self.play_student_changes(*["happy"]*3) self.play( RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand" ), taylor_series.next_to, screen_rect.copy(), UP, ShowCreation(screen_rect) ) card_dot.move_to(taylor_series) card_dot.generate_target() card_dot.target.set_fill(opacity = 0) card_dot.target.to_edge(RIGHT, buff = MED_SMALL_BUFF) arrow = Arrow( taylor_series, card_dot.target, buff = MED_SMALL_BUFF, color = WHITE ) self.play(FadeIn(second_deriv)) self.wait(2) self.play(Transform(second_deriv, derivs[1])) self.wait(2) self.play(MoveToTarget(card_dot)) self.play(ShowCreation(arrow)) self.wait() self.play(Transform(second_deriv, derivs[2])) self.play_student_changes(*["erm"]*3) self.wait() self.play(second_deriv.restore) self.wait(2) class SecondDerivativeGraphically(GraphScene): CONFIG = { "x1" : 0, "x2" : 4, "x3" : 8, "y" : 4, "deriv_color" : YELLOW, "second_deriv_color" : GREEN, } def construct(self): self.force_skipping() self.setup_axes() self.draw_f() self.show_derivative() self.write_second_derivative() self.show_curvature() self.revert_to_original_skipping_status() self.contrast_big_and_small_concavity() def draw_f(self): def func(x): return 0.1*(x-self.x1)*(x-self.x2)*(x-self.x3) + self.y graph = self.get_graph(func) graph_label = self.get_graph_label(graph, "f(x)") self.play( ShowCreation(graph, run_time = 2), Write( graph_label, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1) ) ) self.wait() self.graph = graph self.graph_label = graph_label def show_derivative(self): deriv = OldTex("\\frac{df}{dx}") deriv.next_to(self.graph_label, DOWN, MED_LARGE_BUFF) deriv.set_color(self.deriv_color) ss_group = self.get_secant_slope_group( 1, self.graph, dx = 0.01, secant_line_color = self.deriv_color ) self.play( Write(deriv), *list(map(ShowCreation, ss_group)) ) self.animate_secant_slope_group_change( ss_group, target_x = self.x3, run_time = 5 ) self.wait() self.animate_secant_slope_group_change( ss_group, target_x = self.x2, run_time = 3 ) self.wait() self.ss_group = ss_group self.deriv = deriv def write_second_derivative(self): second_deriv = OldTex("\\frac{d^2 f}{dx^2}") second_deriv.next_to(self.deriv, DOWN, MED_LARGE_BUFF) second_deriv.set_color(self.second_deriv_color) points = [ self.input_to_graph_point(x, self.graph) for x in (self.x2, self.x3) ] words = OldTexText("Change to \\\\ slope") words.next_to( center_of_mass(points), UP, 1.5*LARGE_BUFF ) arrows = [ Arrow(words.get_bottom(), p, color = WHITE) for p in points ] self.play(Write(second_deriv)) self.wait() self.play( Write(words), ShowCreation( arrows[0], rate_func = squish_rate_func(smooth, 0.5, 1) ), run_time = 2 ) self.animate_secant_slope_group_change( self.ss_group, target_x = self.x3, run_time = 3, added_anims = [ Transform( *arrows, run_time = 3, path_arc = 0.75*np.pi ), ] ) self.play(FadeOut(arrows[0])) self.animate_secant_slope_group_change( self.ss_group, target_x = self.x2, run_time = 3, ) self.second_deriv_words = words self.second_deriv = second_deriv def show_curvature(self): positive_curve, negative_curve = [ self.get_graph( self.graph.underlying_function, x_min = x_min, x_max = x_max, color = color, ).set_stroke(width = 6) for x_min, x_max, color in [ (self.x2, self.x3, PINK), (self.x1, self.x2, RED), ] ] dot = Dot() def get_dot_update_func(curve): def update_dot(dot): dot.move_to(curve.get_points()[-1]) return dot return update_dot self.play( ShowCreation(positive_curve, run_time = 3), UpdateFromFunc(dot, get_dot_update_func(positive_curve)) ) self.play(FadeOut(dot)) self.wait() self.animate_secant_slope_group_change( self.ss_group, target_x = self.x3, run_time = 4, added_anims = [Animation(positive_curve)] ) self.play(*list(map(FadeOut, [self.ss_group, positive_curve]))) self.animate_secant_slope_group_change( self.ss_group, target_x = self.x1, run_time = 0 ) self.play(FadeIn(self.ss_group)) self.play( ShowCreation(negative_curve, run_time = 3), UpdateFromFunc(dot, get_dot_update_func(negative_curve)) ) self.play(FadeOut(dot)) self.animate_secant_slope_group_change( self.ss_group, target_x = self.x2, run_time = 4, added_anims = [Animation(negative_curve)] ) self.wait(2) self.play(*list(map(FadeOut, [ self.graph, self.ss_group, negative_curve, self.second_deriv_words ]))) def contrast_big_and_small_concavity(self): colors = color_gradient([GREEN, WHITE], 3) x0, y0 = 4, 2 graphs = [ self.get_graph(func, color = color) for color, func in zip(colors, [ lambda x : 5*(x - x0)**2 + y0, lambda x : 0.2*(x - x0)**2 + y0, lambda x : (x-x0) + y0, ]) ] arg_rhs_list = [ OldTex("(", str(x0), ")", "=", str(rhs)) for rhs in (10, 0.4, 0) ] for graph, arg_rhs in zip(graphs, arg_rhs_list): graph.ss_group = self.get_secant_slope_group( x0-1, graph, dx = 0.001, secant_line_color = YELLOW ) arg_rhs.move_to(self.second_deriv.get_center(), LEFT) graph.arg_rhs = arg_rhs graph = graphs[0] v_line = DashedLine(*[ self.coords_to_point(x0, 0), self.coords_to_point(x0, y0), ]) input_label = OldTex(str(x0)) input_label.next_to(v_line, DOWN) self.play(ShowCreation(graph, run_time = 2)) self.play( Write(input_label), ShowCreation(v_line) ) self.play( ReplacementTransform( input_label.copy(), graph.arg_rhs.get_part_by_tex(str(x0)) ), self.second_deriv.next_to, graph.arg_rhs.copy(), LEFT, SMALL_BUFF, Write(VGroup(*[ submob for submob in graph.arg_rhs if submob is not graph.arg_rhs.get_part_by_tex(str(x0)) ])) ) self.wait() self.play(FadeIn(graph.ss_group)) self.animate_secant_slope_group_change( graph.ss_group, target_x = x0 + 1, run_time = 3, ) self.play(FadeOut(graph.ss_group)) self.wait() for new_graph in graphs[1:]: self.play(Transform(graph, new_graph)) self.play(Transform( graph.arg_rhs, new_graph.arg_rhs, )) self.play(FadeIn(new_graph.ss_group)) self.animate_secant_slope_group_change( new_graph.ss_group, target_x = x0 + 1, run_time = 3, ) self.play(FadeOut(new_graph.ss_group)) class IntroduceNotation(TeacherStudentsScene): def construct(self): clunky_deriv = OldTex( "{d", "\\big(", "{df", "\\over", "dx}", "\\big)", "\\over", "dx }" ) over_index = clunky_deriv.index_of_part( clunky_deriv.get_parts_by_tex("\\over")[1] ) numerator = VGroup(*clunky_deriv[:over_index]) denominator = VGroup(*clunky_deriv[over_index+1:]) rp = clunky_deriv.get_part_by_tex("(") lp = clunky_deriv.get_part_by_tex(")") dfs, overs, dxs = list(map(clunky_deriv.get_parts_by_tex, [ "df", "over", "dx" ])) df_over_dx = VGroup(dfs[0], overs[0], dxs[0]) d = clunky_deriv.get_part_by_tex("d") d_over_dx = VGroup(d, overs[1], dxs[1]) d2f_over_dx2 = OldTex("{d^2 f", "\\over", "dx", "^2}") d2f_over_dx2.set_color_by_tex("dx", YELLOW) for mob in clunky_deriv, d2f_over_dx2: mob.next_to(self.teacher, UP+LEFT) for mob in numerator, denominator: circle = Circle(color = YELLOW) circle.replace(mob, stretch = True) circle.scale(1.3) mob.circle = circle dx_to_zero = OldTex("dx \\to 0") dx_to_zero.set_color(YELLOW) dx_to_zero.next_to(clunky_deriv, UP+LEFT) self.student_says( "What's that notation?", target_mode = "raise_left_hand" ) self.play_student_changes("confused", "raise_left_hand", "confused") self.play( FadeIn( clunky_deriv, run_time = 2, lag_ratio = 0.5 ), RemovePiCreatureBubble(self.get_students()[1]), self.teacher.change_mode, "raise_right_hand" ) self.wait() self.play(ShowCreation(numerator.circle)) self.wait() self.play(ReplacementTransform( numerator.circle, denominator.circle, )) self.wait() self.play( FadeOut(denominator.circle), Write(dx_to_zero), dxs.set_color, YELLOW ) self.wait() self.play( FadeOut(dx_to_zero), *[ApplyMethod(pi.change, "plain") for pi in self.get_pi_creatures()] ) self.play( df_over_dx.scale, dxs[1].get_height()/dxs[0].get_height(), df_over_dx.move_to, d_over_dx, RIGHT, FadeOut(VGroup(lp, rp)), d_over_dx.shift, 0.8*LEFT + 0.05*UP, ) self.wait() self.play(*[ ReplacementTransform( group, VGroup(d2f_over_dx2.get_part_by_tex(tex)) ) for group, tex in [ (VGroup(d, dfs[0]), "d^2"), (overs, "over"), (dxs, "dx"), (VGroup(dxs[1].copy()), "^2}"), ] ]) self.wait(2) self.student_says( "How does one... \\\\ read that?", index = 0, ) self.play(self.teacher.change, "happy") self.wait(2) class HowToReadNotation(GraphScene, ReconfigurableScene): CONFIG = { "x_max" : 5, "dx" : 0.4, "x" : 2, "graph_origin" : 2.5*DOWN + 5*LEFT, } def setup(self): for base in self.__class__.__bases__: base.setup(self) def construct(self): self.force_skipping() self.add_graph() self.take_two_steps() self.change_step_size() self.show_dfs() self.show_ddf() self.revert_to_original_skipping_status() self.show_proportionality_to_dx_squared() return self.write_second_derivative() def add_graph(self): self.setup_axes() graph = self.get_graph(lambda x : x**2) graph_label = self.get_graph_label( graph, "f(x)", direction = LEFT, x_val = 3.3 ) self.add(graph, graph_label) self.graph = graph def take_two_steps(self): v_lines = [ self.get_vertical_line_to_graph( self.x + i*self.dx, self.graph, line_class = DashedLine, color = WHITE ) for i in range(3) ] braces = [ Brace(VGroup(*v_lines[i:i+2]), buff = 0) for i in range(2) ] for brace in braces: brace.dx = OldTex("dx") max_width = 0.7*brace.get_width() if brace.dx.get_width() > max_width: brace.dx.set_width(max_width) brace.dx.next_to(brace, DOWN, SMALL_BUFF) self.play(ShowCreation(v_lines[0])) self.wait() for brace, line in zip(braces, v_lines[1:]): self.play( ReplacementTransform( VectorizedPoint(brace.get_corner(UP+LEFT)), brace, ), Write(brace.dx, run_time = 1), ) self.play(ShowCreation(line)) self.wait() self.v_lines = v_lines self.braces = braces def change_step_size(self): self.transition_to_alt_config(dx = 0.6) self.transition_to_alt_config(dx = 0.01, run_time = 3) def show_dfs(self): dx_lines = VGroup() df_lines = VGroup() df_dx_groups = VGroup() df_labels = VGroup() for i, v_line1, v_line2 in zip(it.count(1), self.v_lines, self.v_lines[1:]): dx_line = Line( v_line1.get_bottom(), v_line2.get_bottom(), color = GREEN ) dx_line.move_to(v_line1.get_top(), LEFT) dx_lines.add(dx_line) df_line = Line( dx_line.get_right(), v_line2.get_top(), color = YELLOW ) df_lines.add(df_line) df_label = OldTex("df_%d"%i) df_label.set_color(YELLOW) df_label.scale(0.8) df_label.next_to(df_line.get_center(), UP+LEFT, MED_LARGE_BUFF) df_arrow = Arrow( df_label.get_bottom(), df_line.get_center(), buff = SMALL_BUFF, ) df_line.label = df_label df_line.arrow = df_arrow df_labels.add(df_label) df_dx_groups.add(VGroup(df_line, dx_line)) for brace, dx_line, df_line in zip(self.braces, dx_lines, df_lines): self.play( VGroup(brace, brace.dx).next_to, dx_line, DOWN, SMALL_BUFF, FadeIn(dx_line), ) self.play(ShowCreation(df_line)) self.play( ShowCreation(df_line.arrow), Write(df_line.label) ) self.wait(2) self.df_dx_groups = df_dx_groups self.df_labels = df_labels def show_ddf(self): df_dx_groups = self.df_dx_groups.copy() df_dx_groups.generate_target() df_dx_groups.target.arrange( RIGHT, buff = MED_LARGE_BUFF, aligned_edge = DOWN ) df_dx_groups.target.next_to( self.df_dx_groups, RIGHT, buff = 3, aligned_edge = DOWN ) df_labels = self.df_labels.copy() df_labels.generate_target() h_lines = VGroup() for group, label in zip(df_dx_groups.target, df_labels.target): label.next_to(group.get_right(), LEFT, SMALL_BUFF) width = df_dx_groups.target.get_width() + MED_SMALL_BUFF h_line = DashedLine(ORIGIN, width*RIGHT) h_line.move_to( group.get_corner(UP+RIGHT)[1]*UP + \ df_dx_groups.target.get_right()[0]*RIGHT, RIGHT ) h_lines.add(h_line) max_height = 0.8*group.get_height() if label.get_height() > max_height: label.set_height(max_height) ddf_brace = Brace(h_lines, LEFT, buff = SMALL_BUFF) ddf = ddf_brace.get_tex("d(df)", buff = SMALL_BUFF) ddf.scale( df_labels[0].get_height()/ddf.get_height(), about_point = ddf.get_right() ) ddf.set_color(MAROON_B) self.play( *list(map(MoveToTarget, [df_dx_groups, df_labels])), run_time = 2 ) self.play(ShowCreation(h_lines, run_time = 2)) self.play(GrowFromCenter(ddf_brace)) self.play(Write(ddf)) self.wait(2) self.ddf = ddf def show_proportionality_to_dx_squared(self): ddf = self.ddf.copy() ddf.generate_target() ddf.target.next_to(self.ddf, UP, LARGE_BUFF) rhs = OldTex( "\\approx", "(\\text{Some constant})", "(dx)^2" ) rhs.scale(0.8) rhs.next_to(ddf.target, RIGHT) example_dx = OldTex( "dx = 0.01 \\Rightarrow (dx)^2 = 0.0001" ) example_dx.scale(0.8) example_dx.to_corner(UP+RIGHT) self.play(MoveToTarget(ddf)) self.play(Write(rhs)) self.wait() self.play(Write(example_dx)) self.wait(2) self.play(FadeOut(example_dx)) self.ddf = ddf self.dx_squared = rhs.get_part_by_tex("dx") def write_second_derivative(self): ddf_over_dx_squared = OldTex( "{d(df)", "\\over", "(dx)^2}" ) ddf_over_dx_squared.scale(0.8) ddf_over_dx_squared.move_to(self.ddf, RIGHT) ddf_over_dx_squared.set_color_by_tex("df", self.ddf.get_color()) parens = VGroup( ddf_over_dx_squared[0][1], ddf_over_dx_squared[0][4], ddf_over_dx_squared[2][0], ddf_over_dx_squared[2][3], ) right_shifter = ddf_over_dx_squared[0][0] left_shifter = ddf_over_dx_squared[2][4] exp_two = OldTex("2") exp_two.set_color(self.ddf.get_color()) exp_two.scale(0.5) exp_two.move_to(right_shifter.get_corner(UP+RIGHT), LEFT) exp_two.shift(MED_SMALL_BUFF*RIGHT) pre_exp_two = VGroup(ddf_over_dx_squared[0][2]) self.play( Write(ddf_over_dx_squared.get_part_by_tex("over")), *[ ReplacementTransform( mob, ddf_over_dx_squared.get_part_by_tex(tex), path_arc = -np.pi/2, ) for mob, tex in [(self.ddf, "df"), (self.dx_squared, "dx")] ] ) self.wait(2) self.play(FadeOut(parens)) self.play( left_shifter.shift, 0.2*LEFT, right_shifter.shift, 0.2*RIGHT, ReplacementTransform(pre_exp_two, exp_two), ddf_over_dx_squared.get_part_by_tex("over").scale, 0.8 ) self.wait(2) class Footnote(Scene): def construct(self): self.add(OldTexText(""" Interestingly, there is a notion in math called the ``exterior derivative'' which treats this ``d'' as having a more independent meaning, though it's less related to the intuitions I've introduced in this series. """, alignment = "")) class TrajectoryGraphScene(GraphScene): CONFIG = { "x_min" : 0, "x_max" : 10, "x_axis_label" : "t", "y_axis_label" : "s", # "func" : lambda x : 10*smooth(x/10.0), "func" : lambda t : 10*bezier([0, 0, 0, 1, 1, 1])(t/10.0), "color" : BLUE, } def construct(self): self.setup_axes() self.graph = self.get_graph( self.func, color = self.color ) self.add(self.graph) class SecondDerivativeAsAcceleration(Scene): CONFIG = { "car_run_time" : 6, } def construct(self): self.init_car_and_line() self.introduce_acceleration() self.show_functions() def init_car_and_line(self): line = Line(5.5*LEFT, 4.5*RIGHT) line.shift(2*DOWN) car = Car() car.move_to(line.get_left()) self.add(line, car) self.car = car self.start_car_copy = car.copy() self.line = line def introduce_acceleration(self): a_words = OldTex( "{d^2 s \\over dt^2}(t)", "\\Leftrightarrow", "\\text{Acceleration}" ) a_words.set_color_by_tex("d^2 s", MAROON_B) a_words.set_color_by_tex("Acceleration", YELLOW) a_words.to_corner(UP+RIGHT ) self.add(a_words) self.show_car_movement() self.wait() self.a_words = a_words def show_functions(self): def get_deriv(n): return lambda x : derivative( s_scene.graph.underlying_function, x, n ) s_scene = TrajectoryGraphScene() v_scene = TrajectoryGraphScene( func = get_deriv(1), color = GREEN, y_max = 4, y_axis_label = "v", ) a_scene = TrajectoryGraphScene( func = get_deriv(2), color = MAROON_B, y_axis_label = "a", y_min = -2, y_max = 2, ) j_scene = TrajectoryGraphScene( func = get_deriv(3), color = PINK, y_axis_label = "j", y_min = -2, y_max = 2, ) s_graph, v_graph, a_graph, j_graph = graphs = [ VGroup(*scene.get_top_level_mobjects()) for scene in (s_scene, v_scene, a_scene, j_scene) ] for i, graph in enumerate(graphs): graph.set_height(FRAME_Y_RADIUS) graph.to_corner(UP+LEFT) graph.shift(i*DOWN/2.0) s_words = OldTex( "s(t)", "\\Leftrightarrow", "\\text{Displacement}" ) s_words.set_color_by_tex("s(t)", s_scene.graph.get_color()) v_words = OldTex( "\\frac{ds}{dt}(t)", "\\Leftrightarrow", "\\text{Velocity}" ) v_words.set_color_by_tex("ds", v_scene.graph.get_color()) j_words = OldTex( "\\frac{d^3 s}{dt^3}(t)", "\\Leftrightarrow", "\\text{Jerk}" ) j_words.set_color_by_tex("d^3", j_scene.graph.get_color()) self.a_words.generate_target() words_group = VGroup(s_words, v_words, self.a_words.target, j_words) words_group.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) words_group.to_corner(UP+RIGHT) j_graph.scale(0.3).next_to(j_words, LEFT) positive_rect = Rectangle() positive_rect.set_stroke(width = 0) positive_rect.set_fill(GREEN, 0.5) positive_rect.replace( Line( a_scene.coords_to_point(0, -1), a_scene.coords_to_point(5, 1), ), stretch = True ) negative_rect = Rectangle() negative_rect.set_stroke(width = 0) negative_rect.set_fill(RED, 0.5) negative_rect.replace( Line( a_scene.coords_to_point(5, 1), a_scene.coords_to_point(10, -1), ), stretch = True ) self.show_car_movement( MoveToTarget(self.a_words), FadeIn(s_words), FadeIn(s_graph), ) self.play( s_graph.scale, 0.3, s_graph.next_to, s_words, LEFT ) self.play(*list(map(FadeIn, [v_graph, v_words])) ) self.wait(2) self.play( v_graph.scale, 0.3, v_graph.next_to, v_words, LEFT ) self.wait(2) self.play( Indicate(self.a_words), FadeIn(a_graph), ) self.wait() self.play(FadeIn(positive_rect)) for x in range(2): self.show_car_movement( run_time = 3, rate_func = lambda t : smooth(t/2.0) ) self.wait() self.play(FadeIn(negative_rect)) self.wait() self.play(MoveCar( self.car, self.line.get_end(), run_time = 3, rate_func = lambda t : 2*smooth((t+1)/2.0) - 1 )) self.wait() self.play( a_graph.scale, 0.3, a_graph.next_to, self.a_words, LEFT, *list(map(FadeOut, [positive_rect, negative_rect])) ) self.play( FadeOut(self.car), FadeIn(j_words), FadeIn(j_graph), self.line.scale, 0.5, self.line.get_left(), self.line.shift, LEFT, ) self.car.scale(0.5) self.car.move_to(self.line.get_start()) self.play(FadeIn(self.car)) self.show_car_movement() self.wait(2) ########## def show_car_movement(self, *added_anims, **kwargs): distance = get_norm( self.car.get_center() - self.start_car_copy.get_center() ) if distance > 1: self.play(FadeOut(self.car)) self.car.move_to(self.line.get_left()) self.play(FadeIn(self.car)) kwargs["run_time"] = kwargs.get("run_time", self.car_run_time) self.play( MoveCar(self.car, self.line.get_right(), **kwargs), *added_anims ) class NextVideo(Scene): def construct(self): title = OldTexText("Chapter 10: Taylor series") title.to_edge(UP) rect = ScreenRectangle(height = 6) rect.next_to(title, DOWN) self.add(rect) self.play(Write(title)) self.wait() class Thumbnail(SecondDerivativeGraphically): CONFIG = { "graph_origin" : 5*LEFT + 3*DOWN, "x_axis_label" : "", "y_axis_label" : "", } def construct(self): self.setup_axes() self.force_skipping() self.draw_f() self.remove(self.graph_label) self.graph.set_stroke(GREEN, width = 8) tex = OldTex("{d^n f", "\\over", "dx^n}") tex.set_color_by_tex("d^n", YELLOW) tex.set_color_by_tex("dx", BLUE) tex.set_height(4) tex.to_edge(UP) self.add(tex)
videos_3b1b/_2017/eoc/chapter1.py
from manim_imports_ext import * from _2017.eoc.chapter2 import Car, MoveCar class Eoc1Thumbnail(GraphScene): CONFIG = { } def construct(self): title = OldTexText( "The Essence of\\\\Calculus", tex_to_color_map={ "\\emph{you}": YELLOW, }, ) subtitle = OldTexText("Chapter 1") subtitle.match_width(title) subtitle.scale(0.75) subtitle.next_to(title, DOWN) # title.add(subtitle) title.set_width(FRAME_WIDTH - 2) title.to_edge(UP) title.set_stroke(BLACK, 8, background=True) # answer = OldTexText("...yes") # answer.to_edge(DOWN) axes = Axes( x_range=(-1, 5), y_range=(-1, 5), y_axis_config={ "include_tip": False, }, x_axis_config={ "unit_size": 2, }, ) axes.set_width(FRAME_WIDTH - 1) axes.center().to_edge(DOWN) axes.shift(DOWN) self.x_axis = axes.x_axis self.y_axis = axes.y_axis self.axes = axes graph = self.get_graph(self.func) rects = self.get_riemann_rectangles( graph, x_min=0, x_max=4, dx=0.2, ) rects.set_submobject_colors_by_gradient(BLUE, GREEN) rects.set_opacity(1) rects.set_stroke(BLACK, 1) self.add(axes) self.add(graph) self.add(rects) # self.add(title) # self.add(answer) def func(slef, x): return 0.35 * ((x - 2)**3 - 2 * (x - 2) + 6) class CircleScene(PiCreatureScene): CONFIG = { "radius" : 1.5, "stroke_color" : WHITE, "fill_color" : BLUE_E, "fill_opacity" : 0.75, "radial_line_color" : MAROON_B, "outer_ring_color" : GREEN_E, "ring_colors" : [BLUE, GREEN], "dR" : 0.1, "dR_color" : YELLOW, "unwrapped_tip" : ORIGIN, "include_pi_creature" : False, "circle_corner" : UP+LEFT, } def setup(self): PiCreatureScene.setup(self) self.circle = Circle( radius = self.radius, stroke_color = self.stroke_color, fill_color = self.fill_color, fill_opacity = self.fill_opacity, ) self.circle.to_corner(self.circle_corner, buff = MED_LARGE_BUFF) self.radius_line = Line( self.circle.get_center(), self.circle.get_right(), color = self.radial_line_color ) self.radius_brace = Brace(self.radius_line, buff = SMALL_BUFF) self.radius_label = self.radius_brace.get_text("$R$", buff = SMALL_BUFF) self.radius_group = VGroup( self.radius_line, self.radius_brace, self.radius_label ) self.add(self.circle, *self.radius_group) if not self.include_pi_creature: self.remove(self.get_primary_pi_creature()) def introduce_circle(self, added_anims = []): self.remove(self.circle) self.play( ShowCreation(self.radius_line), GrowFromCenter(self.radius_brace), Write(self.radius_label), ) self.circle.set_fill(opacity = 0) self.play( Rotate( self.radius_line, 2*np.pi-0.001, about_point = self.circle.get_center(), ), ShowCreation(self.circle), *added_anims, run_time = 2 ) self.play( self.circle.set_fill, self.fill_color, self.fill_opacity, Animation(self.radius_line), Animation(self.radius_brace), Animation(self.radius_label), ) def increase_radius(self, numerical_dr = True, run_time = 2): radius_mobs = VGroup( self.radius_line, self.radius_brace, self.radius_label ) nudge_line = Line( self.radius_line.get_right(), self.radius_line.get_right() + self.dR*RIGHT, color = self.dR_color ) nudge_arrow = Arrow( nudge_line.get_center() + 0.5*RIGHT+DOWN, nudge_line.get_center(), color = YELLOW, buff = SMALL_BUFF, tip_length = 0.2, ) if numerical_dr: nudge_label = OldTex("%.01f"%self.dR) else: nudge_label = OldTex("dr") nudge_label.set_color(self.dR_color) nudge_label.scale(0.75) nudge_label.next_to(nudge_arrow.get_start(), DOWN) radius_mobs.add(nudge_line, nudge_arrow, nudge_label) outer_ring = self.get_outer_ring() self.play( FadeIn(outer_ring), ShowCreation(nudge_line), ShowCreation(nudge_arrow), Write(nudge_label), run_time = run_time/2. ) self.wait(run_time/2.) self.nudge_line = nudge_line self.nudge_arrow = nudge_arrow self.nudge_label = nudge_label self.outer_ring = outer_ring return outer_ring def get_ring(self, radius, dR, color = GREEN): ring = Circle(radius = radius + dR).center() inner_ring = Circle(radius = radius) inner_ring.rotate(np.pi, RIGHT) ring.append_vectorized_mobject(inner_ring) ring.set_stroke(width = 0) ring.set_fill(color) ring.move_to(self.circle) ring.R = radius ring.dR = dR return ring def get_rings(self, **kwargs): dR = kwargs.get("dR", self.dR) colors = kwargs.get("colors", self.ring_colors) radii = np.arange(0, self.radius, dR) colors = color_gradient(colors, len(radii)) rings = VGroup(*[ self.get_ring(radius, dR = dR, color = color) for radius, color in zip(radii, colors) ]) return rings def get_outer_ring(self): return self.get_ring( radius = self.radius, dR = self.dR, color = self.outer_ring_color ) def unwrap_ring(self, ring, **kwargs): self.unwrap_rings(ring, **kwargs) def unwrap_rings(self, *rings, **kwargs): added_anims = kwargs.get("added_anims", []) rings = VGroup(*rings) unwrapped = VGroup(*[ self.get_unwrapped(ring, **kwargs) for ring in rings ]) self.play( rings.rotate, np.pi/2, rings.next_to, unwrapped.get_bottom(), UP, run_time = 2, path_arc = np.pi/2, ) self.play( Transform(rings, unwrapped, run_time = 3), *added_anims ) def get_unwrapped(self, ring, to_edge = LEFT, **kwargs): R = ring.R R_plus_dr = ring.R + ring.dR n_anchors = ring.get_num_curves() result = VMobject() result.set_points_as_corners([ interpolate(np.pi*R_plus_dr*LEFT, np.pi*R_plus_dr*RIGHT, a) for a in np.linspace(0, 1, n_anchors/2) ]+[ interpolate(np.pi*R*RIGHT+ring.dR*UP, np.pi*R*LEFT+ring.dR*UP, a) for a in np.linspace(0, 1, n_anchors/2) ]) result.set_style_data( stroke_color = ring.get_stroke_color(), stroke_width = ring.get_stroke_width(), fill_color = ring.get_fill_color(), fill_opacity = ring.get_fill_opacity(), ) result.move_to(self.unwrapped_tip, aligned_edge = DOWN) result.shift(R_plus_dr*DOWN) if to_edge is not None: result.to_edge(to_edge) return result def create_pi_creature(self): self.pi_creature = Randolph(color = BLUE_C) self.pi_creature.to_corner(DOWN+LEFT) return self.pi_creature ############# class Chapter1OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ """The art of doing mathematics is finding that """, "special case", """that contains all the germs of generality.""" ], "quote_arg_separator" : " ", "highlighted_quote_terms" : { "special case" : BLUE }, "author" : "David Hilbert", } class Introduction(TeacherStudentsScene): def construct(self): self.show_series() self.show_many_facts() self.invent_calculus() def show_series(self): series = VideoSeries() series.to_edge(UP) this_video = series[0] this_video.set_color(YELLOW) this_video.save_state() this_video.set_fill(opacity = 0) this_video.center() this_video.set_height(FRAME_HEIGHT) self.this_video = this_video words = OldTexText( "Welcome to \\\\", "Essence of calculus" ) words.set_color_by_tex("Essence of calculus", YELLOW) self.teacher.change_mode("happy") self.play( FadeIn( series, lag_ratio = 0.5, run_time = 2 ), Blink(self.get_teacher()) ) self.teacher_says(words, target_mode = "hooray") self.play_student_changes( *["hooray"]*3, look_at = series[1].get_left(), added_anims = [ ApplyMethod(this_video.restore, run_time = 3), ] ) self.play(*[ ApplyMethod( video.shift, 0.5*video.get_height()*DOWN, run_time = 3, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.3 ) ) for video, alpha in zip(series, np.linspace(0, 0.7, len(series))) ]+[ Animation(self.teacher.bubble), Animation(self.teacher.bubble.content), ]) essence_words = words.get_part_by_tex("Essence").copy() self.play( FadeOut(self.teacher.bubble), FadeOut(self.teacher.bubble.content), essence_words.next_to, series, DOWN, *[ ApplyMethod(pi.change_mode, "pondering") for pi in self.get_pi_creatures() ] ) self.wait(3) self.series = series self.essence_words = essence_words def show_many_facts(self): rules = list(it.starmap(Tex, [ ("{d(", "x", "^2)", "\\over \\,", "dx}", "=", "2", "x"), ( "d(", "f", "g", ")", "=", "f", "dg", "+", "g", "df", ), ( "F(x)", "=", "\\int_0^x", "\\frac{dF}{dg}(t)\\,", "dt" ), ( "f(x)", "=", "\\sum_{n = 0}^\\infty", "f^{(n)}(a)", "\\frac{(x-a)^n}{n!}" ), ])) video_indices = [2, 3, 7, 10] tex_to_color = [ ("x", BLUE), ("f", BLUE), ("df", BLUE), ("g", YELLOW), ("dg", YELLOW), ("f(x)", BLUE), ( "f^{(n)}(a)", BLUE), ] for rule in rules: for tex, color in tex_to_color: rule.set_color_by_tex(tex, color, substring = False) rule.next_to(self.teacher.get_corner(UP+LEFT), UP) rule.shift_onto_screen() index = 1 student = self.get_students()[index] self.play_student_changes( "pondering", "sassy", "pondering", look_at = self.teacher.eyes, added_anims = [ self.teacher.change_mode, "plain" ] ) self.wait(2) self.play( Write(rules[0]), self.teacher.change_mode, "raise_right_hand", ) self.wait() alt_rules_list = list(rules[1:]) + [VectorizedPoint(self.teacher.eyes.get_top())] for last_rule, rule, video_index in zip(rules, alt_rules_list, video_indices): video = self.series[video_index] self.play( last_rule.replace, video, FadeIn(rule), ) self.play(Animation(rule)) self.wait() self.play( self.teacher.change_mode, "happy", self.teacher.look_at, student.eyes ) def invent_calculus(self): student = self.get_students()[1] creatures = self.get_pi_creatures() creatures.remove(student) creature_copies = creatures.copy() self.remove(creatures) self.add(creature_copies) calculus = VGroup(*self.essence_words[-len("calculus"):]) calculus.generate_target() invent = OldTexText("Invent") invent_calculus = VGroup(invent, calculus.target) invent_calculus.arrange(RIGHT, buff = MED_SMALL_BUFF) invent_calculus.next_to(student, UP, 1.5*LARGE_BUFF) invent_calculus.shift(RIGHT) arrow = Arrow(invent_calculus, student) fader = Rectangle( width = FRAME_WIDTH, height = FRAME_HEIGHT, stroke_width = 0, fill_color = BLACK, fill_opacity = 0.5, ) self.play( FadeIn(fader), Animation(student), Animation(calculus) ) self.play( Write(invent), MoveToTarget(calculus), student.change_mode, "erm", student.look_at, calculus ) self.play(ShowCreation(arrow)) self.wait(2) class PreviewFrame(Scene): def construct(self): frame = Rectangle(height = 9, width = 16, color = WHITE) frame.set_height(1.5*FRAME_Y_RADIUS) colors = iter(color_gradient([BLUE, YELLOW], 3)) titles = [ OldTexText("Chapter %d:"%d, s).to_edge(UP).set_color(next(colors)) for d, s in [ (3, "Derivative formulas through geometry"), (4, "Chain rule, product rule, etc."), (7, "Limits"), ] ] title = titles[0] frame.next_to(title, DOWN) self.add(frame, title) self.wait(3) for next_title in titles[1:]: self.play(Transform(title, next_title)) self.wait(3) class ProductRuleDiagram(Scene): def construct(self): df = 0.4 dg = 0.2 rect_kwargs = { "stroke_width" : 0, "fill_color" : BLUE, "fill_opacity" : 0.6, } rect = Rectangle(width = 4, height = 3, **rect_kwargs) rect.shift(DOWN) df_rect = Rectangle( height = rect.get_height(), width = df, **rect_kwargs ) dg_rect = Rectangle( height = dg, width = rect.get_width(), **rect_kwargs ) corner_rect = Rectangle( height = dg, width = df, **rect_kwargs ) d_rects = VGroup(df_rect, dg_rect, corner_rect) for d_rect, direction in zip(d_rects, [RIGHT, DOWN, RIGHT+DOWN]): d_rect.next_to(rect, direction, buff = 0) d_rect.set_fill(YELLOW, 0.75) corner_pairs = [ (DOWN+RIGHT, UP+RIGHT), (DOWN+RIGHT, DOWN+LEFT), (DOWN+RIGHT, DOWN+RIGHT), ] for d_rect, corner_pair in zip(d_rects, corner_pairs): line = Line(*[ rect.get_corner(corner) for corner in corner_pair ]) d_rect.line = d_rect.copy().replace(line, stretch = True) d_rect.line.set_color(d_rect.get_color()) f_brace = Brace(rect, UP) g_brace = Brace(rect, LEFT) df_brace = Brace(df_rect, UP) dg_brace = Brace(dg_rect, LEFT) f_label = f_brace.get_text("$f$") g_label = g_brace.get_text("$g$") df_label = df_brace.get_text("$df$") dg_label = dg_brace.get_text("$dg$") VGroup(f_label, df_label).set_color(GREEN) VGroup(g_label, dg_label).set_color(RED) f_label.generate_target() g_label.generate_target() fg_group = VGroup(f_label.target, g_label.target) fg_group.generate_target() fg_group.target.arrange(RIGHT, buff = SMALL_BUFF) fg_group.target.move_to(rect.get_center()) for mob in df_brace, df_label, dg_brace, dg_label: mob.save_state() mob.scale(0.01, about_point = rect.get_corner( mob.get_center() - rect.get_center() )) self.add(rect) self.play( GrowFromCenter(f_brace), GrowFromCenter(g_brace), Write(f_label), Write(g_label), ) self.play(MoveToTarget(fg_group)) self.play(*[ mob.restore for mob in (df_brace, df_label, dg_brace, dg_label) ] + [ ReplacementTransform(d_rect.line, d_rect) for d_rect in d_rects ]) self.wait() self.play( d_rects.space_out_submobjects, 1.2, MaintainPositionRelativeTo( VGroup(df_brace, df_label), df_rect ), MaintainPositionRelativeTo( VGroup(dg_brace, dg_label), dg_rect ), ) self.wait() deriv = OldTex( "d(", "fg", ")", "=", "f", "\\cdot", "dg", "+", "g", "\\cdot", "df" ) deriv.to_edge(UP) alpha_iter = iter(np.linspace(0, 0.5, 5)) self.play(*[ ApplyMethod( mob.copy().move_to, deriv.get_part_by_tex(tex, substring = False), rate_func = squish_rate_func(smooth, alpha, alpha+0.5) ) for mob, tex in [ (fg_group, "fg"), (f_label, "f"), (dg_label, "dg"), (g_label, "g"), (df_label, "df"), ] for alpha in [next(alpha_iter)] ]+[ Write(VGroup(*it.chain(*[ deriv.get_parts_by_tex(tex, substring = False) for tex in ("d(", ")", "=", "\\cdot", "+") ]))) ], run_time = 3) self.wait() class IntroduceCircle(CircleScene): CONFIG = { "include_pi_creature" : True, "unwrapped_tip" : 2*RIGHT } def construct(self): self.force_skipping() self.introduce_area() self.question_area() self.show_calculus_symbols() def introduce_area(self): area = OldTex("\\text{Area}", "=", "\\pi", "R", "^2") area.next_to(self.pi_creature.get_corner(UP+RIGHT), UP+RIGHT) self.remove(self.circle, self.radius_group) self.play( self.pi_creature.change_mode, "pondering", self.pi_creature.look_at, self.circle ) self.introduce_circle() self.wait() R_copy = self.radius_label.copy() self.play( self.pi_creature.change_mode, "raise_right_hand", self.pi_creature.look_at, area, Transform(R_copy, area.get_part_by_tex("R")) ) self.play(Write(area)) self.remove(R_copy) self.wait() self.area = area def question_area(self): q_marks = OldTex("???") q_marks.next_to(self.pi_creature, UP) rings = VGroup(*reversed(self.get_rings())) unwrapped_rings = VGroup(*[ self.get_unwrapped(ring, to_edge = None) for ring in rings ]) unwrapped_rings.arrange(UP, buff = SMALL_BUFF) unwrapped_rings.move_to(self.unwrapped_tip, UP) ring_anim_kwargs = { "run_time" : 3, "lag_ratio" : 0.5 } self.play( Animation(self.area), Write(q_marks), self.pi_creature.change_mode, "confused", self.pi_creature.look_at, self.area, ) self.wait() self.play( FadeIn(rings, **ring_anim_kwargs), Animation(self.radius_group), FadeOut(q_marks), self.pi_creature.change_mode, "thinking" ) self.wait() self.play( rings.rotate, np.pi/2, rings.move_to, unwrapped_rings.get_top(), Animation(self.radius_group), path_arc = np.pi/2, **ring_anim_kwargs ) self.play( Transform(rings, unwrapped_rings, **ring_anim_kwargs), ) self.wait() def show_calculus_symbols(self): ftc = OldTex( "\\int_0^R", "\\frac{dA}{dr}", "\\,dr", "=", "A(R)" ) ftc.shift(2*UP) self.play( ReplacementTransform( self.area.get_part_by_tex("R").copy(), ftc.get_part_by_tex("int") ), self.pi_creature.change_mode, "plain" ) self.wait() self.play( ReplacementTransform( self.area.get_part_by_tex("Area").copy(), ftc.get_part_by_tex("frac") ), ReplacementTransform( self.area.get_part_by_tex("R").copy(), ftc.get_part_by_tex("\\,dr") ) ) self.wait() self.play(Write(VGroup(*ftc[-2:]))) self.wait(2) class ApproximateOneRing(CircleScene, ReconfigurableScene): CONFIG = { "num_lines" : 24, "ring_index_proportion" : 0.6, "ring_shift_val" : 6*RIGHT, "ring_colors" : [BLUE, GREEN_E], "unwrapped_tip" : 2*RIGHT+0.5*UP, } def setup(self): CircleScene.setup(self) ReconfigurableScene.setup(self) def construct(self): self.force_skipping() self.write_radius_three() self.try_to_understand_area() self.slice_into_rings() self.isolate_one_ring() self.revert_to_original_skipping_status() self.straighten_ring_out() self.force_skipping() self.approximate_as_rectangle() def write_radius_three(self): three = OldTex("3") three.move_to(self.radius_label) self.look_at(self.circle) self.play(Transform( self.radius_label, three, path_arc = np.pi )) self.wait() def try_to_understand_area(self): line_sets = [ VGroup(*[ Line( self.circle.point_from_proportion(alpha), self.circle.point_from_proportion(func(alpha)), ) for alpha in np.linspace(0, 1, self.num_lines) ]) for func in [ lambda alpha : 1-alpha, lambda alpha : (0.5-alpha)%1, lambda alpha : (alpha + 0.4)%1, lambda alpha : (alpha + 0.5)%1, ] ] for lines in line_sets: lines.set_stroke(BLACK, 2) lines = line_sets[0] self.play( ShowCreation( lines, run_time = 2, lag_ratio = 0.5 ), Animation(self.radius_group), self.pi_creature.change_mode, "maybe" ) self.wait(2) for new_lines in line_sets[1:]: self.play( Transform(lines, new_lines), Animation(self.radius_group) ) self.wait() self.wait() self.play(FadeOut(lines), Animation(self.radius_group)) def slice_into_rings(self): rings = self.get_rings() rings.set_stroke(BLACK, 1) self.play( FadeIn( rings, lag_ratio = 0.5, run_time = 3 ), Animation(self.radius_group), self.pi_creature.change_mode, "pondering", self.pi_creature.look_at, self.circle ) self.wait(2) for x in range(2): self.play( Rotate(rings, np.pi, in_place = True, run_time = 2), Animation(self.radius_group), self.pi_creature.change_mode, "happy" ) self.wait(2) self.rings = rings def isolate_one_ring(self): rings = self.rings index = int(self.ring_index_proportion*len(rings)) original_ring = rings[index] ring = original_ring.copy() radius = Line(ORIGIN, ring.R*RIGHT, color = WHITE) radius.rotate(np.pi/4) r_label = OldTex("r") r_label.next_to(radius.get_center(), UP+LEFT, SMALL_BUFF) area_q = OldTexText("Area", "?", arg_separator = "") area_q.set_color(YELLOW) self.play( ring.shift, self.ring_shift_val, original_ring.set_fill, None, 0.25, Animation(self.radius_group), ) VGroup(radius, r_label).shift(ring.get_center()) area_q.next_to(ring, RIGHT) self.play(ShowCreation(radius)) self.play(Write(r_label)) self.wait() self.play(Write(area_q)) self.wait() self.play(*[ ApplyMethod( r.set_fill, YELLOW, rate_func = squish_rate_func(there_and_back, alpha, alpha+0.15), run_time = 3 ) for r, alpha in zip(rings, np.linspace(0, 0.85, len(rings))) ]+[ Animation(self.radius_group) ]) self.wait() self.change_mode("thinking") self.wait() self.original_ring = original_ring self.ring = ring self.ring_radius_group = VGroup(radius, r_label) self.area_q = area_q def straighten_ring_out(self): ring = self.ring.copy() trapezoid = OldTexText("Trapezoid?") rectangle_ish = OldTexText("Rectangle-ish") for text in trapezoid, rectangle_ish: text.next_to( self.pi_creature.get_corner(UP+RIGHT), DOWN+RIGHT, buff = MED_LARGE_BUFF ) self.unwrap_ring(ring, to_edge = RIGHT) self.change_mode("pondering") self.wait() self.play(Write(trapezoid)) self.wait() self.play(trapezoid.shift, DOWN) strike = Line( trapezoid.get_left(), trapezoid.get_right(), stroke_color = RED, stroke_width = 8 ) self.play( Write(rectangle_ish), ShowCreation(strike), self.pi_creature.change_mode, "happy" ) self.wait() self.play(*list(map(FadeOut, [trapezoid, strike]))) self.unwrapped_ring = ring def approximate_as_rectangle(self): top_brace, side_brace = [ Brace( self.unwrapped_ring, vect, buff = SMALL_BUFF, min_num_quads = 2, ) for vect in (UP, LEFT) ] top_brace.scale(self.ring.R/(self.ring.R+self.dR)) side_brace.set_stroke(WHITE, 0.5) width_label = OldTex("2\\pi", "r") width_label.next_to(top_brace, UP, SMALL_BUFF) dr_label = OldTex("dr") q_marks = OldTex("???") concrete_dr = OldTex("=0.1") concrete_dr.submobjects.reverse() for mob in dr_label, q_marks, concrete_dr: mob.next_to(side_brace, LEFT, SMALL_BUFF) dr_label.save_state() alt_side_brace = side_brace.copy() alt_side_brace.move_to(ORIGIN, UP+RIGHT) alt_side_brace.rotate(-np.pi/2) alt_side_brace.shift( self.original_ring.get_boundary_point(RIGHT) ) alt_dr_label = dr_label.copy() alt_dr_label.next_to(alt_side_brace, UP, SMALL_BUFF) approx = OldTex("\\approx") approx.next_to( self.area_q.get_part_by_tex("Area"), RIGHT, align_using_submobjects = True, ) two_pi_r_dr = VGroup(width_label, dr_label).copy() two_pi_r_dr.generate_target() two_pi_r_dr.target.arrange( RIGHT, buff = SMALL_BUFF, aligned_edge = DOWN ) two_pi_r_dr.target.next_to(approx, RIGHT, aligned_edge = DOWN) self.play(GrowFromCenter(top_brace)) self.play( Write(width_label.get_part_by_tex("pi")), ReplacementTransform( self.ring_radius_group[1].copy(), width_label.get_part_by_tex("r") ) ) self.wait() self.play( GrowFromCenter(side_brace), Write(q_marks) ) self.change_mode("confused") self.wait() for num_rings in 20, 7: self.show_alternate_width(num_rings) self.play(ReplacementTransform(q_marks, dr_label)) self.play( ReplacementTransform(side_brace.copy(), alt_side_brace), ReplacementTransform(dr_label.copy(), alt_dr_label), run_time = 2 ) self.wait() self.play( dr_label.next_to, concrete_dr.copy(), LEFT, SMALL_BUFF, DOWN, Write(concrete_dr, run_time = 2), self.pi_creature.change_mode, "pondering" ) self.wait(2) self.play( MoveToTarget(two_pi_r_dr), FadeIn(approx), self.area_q.get_part_by_tex("?").fade, 1, ) self.wait() self.play( FadeOut(concrete_dr), dr_label.restore ) self.show_alternate_width( 40, transformation_kwargs = {"run_time" : 4}, return_to_original_configuration = False, ) self.wait(2) self.look_at(self.circle) self.play( ApplyWave(self.rings, amplitude = 0.1), Animation(self.radius_group), Animation(alt_side_brace), Animation(alt_dr_label), run_time = 3, lag_ratio = 0.5 ) self.wait(2) def show_alternate_width(self, num_rings, **kwargs): self.transition_to_alt_config( dR = self.radius/num_rings, **kwargs ) class MoveForwardWithApproximation(TeacherStudentsScene): def construct(self): self.teacher_says( "Move forward with \\\\", "the", "approximation" ) self.play_student_changes("hesitant", "erm", "sassy") self.wait() words = OldTexText( "It gets better", "\\\\ for smaller ", "$dr$" ) words.set_color_by_tex("dr", BLUE) self.teacher_says(words, target_mode = "shruggie") self.wait(3) class GraphRectangles(CircleScene, GraphScene): CONFIG = { "graph_origin" : 3.25*LEFT+2.5*DOWN, "x_min" : 0, "x_max" : 4, "x_axis_width" : 7, "x_labeled_nums" : list(range(5)), "x_axis_label" : "$r$", "y_min" : 0, "y_max" : 20, "y_tick_frequency" : 2.5, "y_labeled_nums" : list(range(5, 25, 5)), "y_axis_label" : "", "exclude_zero_label" : False, "num_rings_in_ring_sum_start" : 3, "tick_height" : 0.2, } def setup(self): CircleScene.setup(self) GraphScene.setup(self) self.setup_axes() self.remove(self.axes) # self.pi_creature.change_mode("pondering") # self.pi_creature.look_at(self.circle) # self.add(self.pi_creature) three = OldTex("3") three.move_to(self.radius_label) self.radius_label.save_state() Transform(self.radius_label, three).update(1) def construct(self): self.draw_ring_sum() self.draw_r_values() self.unwrap_rings_onto_graph() self.draw_graph() self.point_out_approximation() self.let_dr_approah_zero() self.compute_area_under_graph() self.show_circle_unwrapping() def draw_ring_sum(self): rings = self.get_rings() rings.set_stroke(BLACK, 1) ring_sum, draw_ring_sum_anims = self.get_ring_sum(rings) area_label = OldTex( "\\text{Area}", "\\approx", "2\\pi", "r", "\\,dr" ) area_label.set_color_by_tex("r", YELLOW, substring = False) area_label.next_to(ring_sum, RIGHT, aligned_edge = UP) area = area_label.get_part_by_tex("Area") arrow_start = area.get_corner(DOWN+LEFT) arrows = VGroup(*[ Arrow( arrow_start, ring.target.get_boundary_point( arrow_start - ring.target.get_center() ), color = ring.get_color() ) for ring in rings if ring.target.get_fill_opacity() > 0 ]) self.add(rings, self.radius_group) self.remove(self.circle) self.wait() self.play(*draw_ring_sum_anims) self.play(Write(area_label, run_time = 2)) self.play(ShowCreation(arrows)) self.wait() self.ring_sum = ring_sum area_label.add(arrows) self.area_label = area_label self.rings = rings def draw_r_values(self): values_of_r = OldTexText("Values of ", "$r$") values_of_r.set_color_by_tex("r", YELLOW) values_of_r.next_to( self.x_axis, UP, buff = 2*LARGE_BUFF, aligned_edge = LEFT ) r_ticks = VGroup(*[ Line( self.coords_to_point(r, -self.tick_height), self.coords_to_point(r, self.tick_height), color = YELLOW ) for r in np.arange(0, 3, 0.1) ]) arrows = VGroup(*[ Arrow( values_of_r.get_part_by_tex("r").get_bottom(), tick.get_top(), buff = SMALL_BUFF, color = YELLOW, tip_length = 0.15 ) for tick in (r_ticks[0], r_ticks[-1]) ]) first_tick = r_ticks[0].copy() moving_arrow = arrows[0].copy() index = 2 dr_brace = Brace( VGroup(*r_ticks[index:index+2]), DOWN, buff = SMALL_BUFF ) dr_label = OldTex("dr") dr_label.next_to( dr_brace, DOWN, buff = SMALL_BUFF, aligned_edge = LEFT ) dr_group = VGroup(dr_brace, dr_label) self.play( FadeIn(values_of_r), FadeIn(self.x_axis), ) self.play( ShowCreation(moving_arrow), ShowCreation(first_tick), ) self.play(Indicate(self.rings[0])) self.wait() self.play( Transform(moving_arrow, arrows[-1]), ShowCreation(r_ticks, lag_ratio = 0.5), run_time = 2 ) self.play(Indicate(self.rings[-1])) self.wait() self.play(FadeIn(dr_group)) self.wait() self.play(*list(map(FadeOut, [moving_arrow, values_of_r]))) self.x_axis.add(r_ticks) self.r_ticks = r_ticks self.dr_group = dr_group def unwrap_rings_onto_graph(self): rings = self.rings graph = self.get_graph(lambda r : 2*np.pi*r) flat_graph = self.get_graph(lambda r : 0) rects, flat_rects = [ self.get_riemann_rectangles( g, x_min = 0, x_max = 3, dx = self.dR, start_color = self.rings[0].get_fill_color(), end_color = self.rings[-1].get_fill_color(), ) for g in (graph, flat_graph) ] self.graph, self.flat_rects = graph, flat_rects transformed_rings = VGroup() self.ghost_rings = VGroup() for index, rect, r in zip(it.count(), rects, np.arange(0, 3, 0.1)): proportion = float(index)/len(rects) ring_index = int(len(rings)*proportion**0.6) ring = rings[ring_index] if ring in transformed_rings: ring = ring.copy() transformed_rings.add(ring) if ring.get_fill_opacity() > 0: ghost_ring = ring.copy() ghost_ring.set_fill(opacity = 0.25) self.add(ghost_ring, ring) self.ghost_rings.add(ghost_ring) ring.rect = rect n_anchors = ring.get_num_curves() target = VMobject() target.set_points_as_corners([ interpolate(ORIGIN, DOWN, a) for a in np.linspace(0, 1, n_anchors/2) ]+[ interpolate(DOWN+RIGHT, RIGHT, a) for a in np.linspace(0, 1, n_anchors/2) ]) target.replace(rect, stretch = True) target.stretch_to_fit_height(2*np.pi*r) target.move_to(rect, DOWN) target.set_stroke(BLACK, 1) target.set_fill(ring.get_fill_color(), 1) ring.target = target ring.original_ring = ring.copy() foreground_animations = list(map(Animation, [self.x_axis, self.area_label])) example_ring = transformed_rings[2] self.play( MoveToTarget( example_ring, path_arc = -np.pi/2, run_time = 2 ), Animation(self.x_axis), ) self.wait(2) self.play(*[ MoveToTarget( ring, path_arc = -np.pi/2, run_time = 4, rate_func = squish_rate_func(smooth, alpha, alpha+0.25) ) for ring, alpha in zip( transformed_rings, np.linspace(0, 0.75, len(transformed_rings)) ) ] + foreground_animations) self.wait() ##Demonstrate height of one rect highlighted_ring = transformed_rings[6].copy() original_ring = transformed_rings[6].original_ring original_ring.move_to(highlighted_ring, RIGHT) original_ring.set_fill(opacity = 1) highlighted_ring.save_state() side_brace = Brace(highlighted_ring, RIGHT) height_label = side_brace.get_text("2\\pi", "r") height_label.set_color_by_tex("r", YELLOW) self.play( transformed_rings.set_fill, None, 0.2, Animation(highlighted_ring), *foreground_animations ) self.play( self.dr_group.arrange, DOWN, self.dr_group.next_to, highlighted_ring, DOWN, SMALL_BUFF ) self.wait() self.play( GrowFromCenter(side_brace), Write(height_label) ) self.wait() self.play(Transform(highlighted_ring, original_ring)) self.wait() self.play(highlighted_ring.restore) self.wait() self.play( transformed_rings.set_fill, None, 1, FadeOut(side_brace), FadeOut(height_label), *foreground_animations ) self.remove(highlighted_ring) self.wait() ##Rescale self.play(*[ ApplyMethod( ring.replace, ring.rect, method_kwargs = {"stretch" : True} ) for ring in transformed_rings ] + [ Write(self.y_axis), FadeOut(self.area_label), ] + foreground_animations) self.remove(transformed_rings) self.add(rects) self.wait() self.rects = rects def draw_graph(self): graph_label = self.get_graph_label( self.graph, "2\\pi r", direction = UP+LEFT, x_val = 2.5, buff = SMALL_BUFF ) self.play(ShowCreation(self.graph)) self.play(Write(graph_label)) self.wait() self.play(*[ Transform( rect, flat_rect, run_time = 2, rate_func = squish_rate_func( lambda t : 0.1*there_and_back(t), alpha, alpha+0.5 ), lag_ratio = 0.5 ) for rect, flat_rect, alpha in zip( self.rects, self.flat_rects, np.linspace(0, 0.5, len(self.rects)) ) ] + list(map(Animation, [self.x_axis, self.graph])) ) self.wait(2) def point_out_approximation(self): rect = self.rects[10] rect.generate_target() rect.save_state() approximation = OldTexText("= Approximation") approximation.scale(0.8) group = VGroup(rect.target, approximation) group.arrange(RIGHT) group.to_edge(RIGHT) self.play( MoveToTarget(rect), Write(approximation), ) self.wait(2) self.play( rect.restore, FadeOut(approximation) ) self.wait() def let_dr_approah_zero(self): thinner_rects_list = [ self.get_riemann_rectangles( self.graph, x_min = 0, x_max = 3, dx = 1./(10*2**n), stroke_width = 1./(2**n), start_color = self.rects[0].get_fill_color(), end_color = self.rects[-1].get_fill_color(), ) for n in range(1, 5) ] self.play(*list(map(FadeOut, [self.r_ticks, self.dr_group]))) self.x_axis.remove(self.r_ticks, *self.r_ticks) for new_rects in thinner_rects_list: self.play( Transform( self.rects, new_rects, lag_ratio = 0.5, run_time = 2 ), Animation(self.axes), Animation(self.graph), ) self.wait() self.play(ApplyWave( self.rects, direction = RIGHT, run_time = 2, lag_ratio = 0.5, )) self.wait() def compute_area_under_graph(self): formula, formula_with_R = formulas = [ self.get_area_formula(R) for R in ("3", "R") ] for mob in formulas: mob.to_corner(UP+RIGHT, buff = MED_SMALL_BUFF) brace = Brace(self.rects, RIGHT) height_label = brace.get_text("$2\\pi \\cdot 3$") height_label_with_R = brace.get_text("$2\\pi \\cdot R$") base_line = Line( self.coords_to_point(0, 0), self.coords_to_point(3, 0), color = YELLOW ) fresh_rings = self.get_rings(dR = 0.025) fresh_rings.set_stroke(width = 0) self.radius_label.restore() VGroup( fresh_rings, self.radius_group ).to_corner(UP+LEFT, buff = SMALL_BUFF) self.play(Write(formula.top_line, run_time = 2)) self.play(FocusOn(base_line)) self.play(ShowCreation(base_line)) self.wait() self.play( GrowFromCenter(brace), Write(height_label) ) self.wait() self.play(FocusOn(formula)) self.play(Write(formula.mid_line)) self.wait() self.play(Write(formula.bottom_line)) self.wait(2) self.play(*list(map(FadeOut, [ self.ghost_rings, self.ring_sum.tex_mobs ]))) self.play(*list(map(FadeIn, [fresh_rings, self.radius_group]))) self.wait() self.play( Transform(formula, formula_with_R), Transform(height_label, height_label_with_R), ) self.wait(2) self.fresh_rings = fresh_rings def show_circle_unwrapping(self): rings = self.fresh_rings rings.rotate(np.pi) rings.submobjects.reverse() ghost_rings = rings.copy() ghost_rings.set_fill(opacity = 0.25) self.add(ghost_rings, rings, self.radius_group) unwrapped = VGroup(*[ self.get_unwrapped(ring, to_edge = None) for ring in rings ]) unwrapped.stretch_to_fit_height(1) unwrapped.stretch_to_fit_width(2) unwrapped.move_to(ORIGIN, DOWN) unwrapped.apply_function( lambda p : np.dot(p, np.array([[1, 0, 0], [-1, 1, 0], [0, 0, 1]]) ), maintain_smoothness = False ) unwrapped.rotate(np.pi/2) unwrapped.replace(self.rects, stretch = True) self.play(self.rects.fade, 0.8) self.play( Transform( rings, unwrapped, run_time = 5, lag_ratio = 0.5, ), Animation(self.radius_group) ) self.wait() ##### def get_ring_sum(self, rings): arranged_group = VGroup() tex_mobs = VGroup() for ring in rings: ring.generate_target() ring.target.set_stroke(width = 0) for ring in rings[:self.num_rings_in_ring_sum_start]: plus = OldTex("+") arranged_group.add(ring.target) arranged_group.add(plus) tex_mobs.add(plus) dots = OldTex("\\vdots") plus = OldTex("+") arranged_group.add(dots, plus) tex_mobs.add(dots, plus) last_ring = rings[-1] arranged_group.add(last_ring.target) arranged_group.arrange(DOWN, buff = SMALL_BUFF) arranged_group.set_height(FRAME_HEIGHT-1) arranged_group.to_corner(DOWN+LEFT, buff = MED_SMALL_BUFF) for mob in tex_mobs: mob.scale(0.7) middle_rings = rings[self.num_rings_in_ring_sum_start:-1] alphas = np.linspace(0, 1, len(middle_rings)) for ring, alpha in zip(middle_rings, alphas): ring.target.set_fill(opacity = 0) ring.target.move_to(interpolate( dots.get_left(), last_ring.target.get_center(), alpha )) draw_ring_sum_anims = [Write(tex_mobs)] draw_ring_sum_anims += [ MoveToTarget( ring, run_time = 3, path_arc = -np.pi/3, rate_func = squish_rate_func(smooth, alpha, alpha+0.8) ) for ring, alpha in zip(rings, np.linspace(0, 0.2, len(rings))) ] draw_ring_sum_anims.append(FadeOut(self.radius_group)) ring_sum = VGroup(rings, tex_mobs) ring_sum.rings = VGroup(*[r.target for r in rings]) ring_sum.tex_mobs = tex_mobs return ring_sum, draw_ring_sum_anims def get_area_formula(self, R): formula = OldTex( "\\text{Area}", "&= \\frac{1}{2}", "b", "h", "\\\\ &=", "\\frac{1}{2}", "(%s)"%R, "(2\\pi \\cdot %s)"%R, "\\\\ &=", "\\pi ", "%s"%R, "^2" ) formula.set_color_by_tex("b", GREEN, substring = False) formula.set_color_by_tex("h", RED, substring = False) formula.set_color_by_tex("%s"%R, GREEN) formula.set_color_by_tex("(2\\pi ", RED) formula.set_color_by_tex("(2\\pi ", RED) formula.scale(0.8) formula.top_line = VGroup(*formula[:4]) formula.mid_line = VGroup(*formula[4:8]) formula.bottom_line = VGroup(*formula[8:]) return formula class ThinkLikeAMathematician(TeacherStudentsScene): def construct(self): pi_R_squraed = OldTex("\\pi", "R", "^2") pi_R_squraed.set_color_by_tex("R", YELLOW) pi_R_squraed.move_to(self.get_students(), UP) pi_R_squraed.set_fill(opacity = 0) self.play( pi_R_squraed.shift, 2*UP, pi_R_squraed.set_fill, None, 1 ) self.play_student_changes(*["hooray"]*3) self.wait(2) self.play_student_changes( *["pondering"]*3, look_at = self.teacher.eyes, added_anims = [PiCreatureSays( self.teacher, "But why did \\\\ that work?" )] ) self.play(FadeOut(pi_R_squraed)) self.look_at(2*UP+4*LEFT) self.wait(5) class TwoThingsToNotice(TeacherStudentsScene): def construct(self): words = OldTexText( "Two things to \\\\ note about", "$dr$", ) words.set_color_by_tex("dr", GREEN) self.teacher_says(words, run_time = 1) self.wait(3) class RecapCircleSolution(GraphRectangles, ReconfigurableScene): def setup(self): GraphRectangles.setup(self) ReconfigurableScene.setup(self) def construct(self): self.break_up_circle() self.show_sum() self.dr_indicates_spacing() self.smaller_dr() self.show_riemann_sum() self.limiting_riemann_sum() self.full_precision() def break_up_circle(self): self.remove(self.circle) rings = self.get_rings() rings.set_stroke(BLACK, 1) ring_sum, draw_ring_sum_anims = self.get_ring_sum(rings) hard_problem = OldTexText("Hard problem") down_arrow = OldTex("\\Downarrow") sum_words = OldTexText("Sum of many \\\\ small values") integral_condition = VGroup(hard_problem, down_arrow, sum_words) integral_condition.arrange(DOWN) integral_condition.scale(0.8) integral_condition.to_corner(UP+RIGHT) self.add(rings, self.radius_group) self.play(FadeIn( integral_condition, lag_ratio = 0.5 )) self.wait() self.play(*draw_ring_sum_anims) self.rings = rings self.integral_condition = integral_condition def show_sum(self): visible_rings = [ring for ring in self.rings if ring.get_fill_opacity() > 0] radii = self.dR*np.arange(len(visible_rings)) radii[-1] = 3-self.dR radial_lines = VGroup() for ring in visible_rings: radius_line = Line(ORIGIN, ring.R*RIGHT, color = YELLOW) radius_line.rotate(np.pi/4) radius_line.shift(ring.get_center()) radial_lines.add(radius_line) approximations = VGroup() for ring, radius in zip(visible_rings, radii): label = OldTex( "\\approx", "2\\pi", "(%s)"%str(radius), "(%s)"%str(self.dR) ) label[2].set_color(YELLOW) label[3].set_color(GREEN) label.scale(0.75) label.next_to(ring, RIGHT) approximations.add(label) approximations[-1].shift(UP+0.5*LEFT) area_label = OldTex("2\\pi", "r", "\\, dr") area_label.set_color_by_tex("r", YELLOW) area_label.set_color_by_tex("dr", GREEN) area_label.next_to(approximations, RIGHT, buff = 2*LARGE_BUFF) arrows = VGroup(*[ Arrow( area_label.get_left(), approximation.get_right(), color = WHITE ) for approximation in approximations ]) self.play(Write(area_label)) self.play( ShowCreation(arrows, lag_ratio = 0), FadeIn(radial_lines), *[ ReplacementTransform( area_label.copy(), VGroup(*approximation[1:]) ) for approximation in approximations ] ) self.wait() self.play(Write(VGroup(*[ approximation[0] for approximation in approximations ]))) self.wait() self.area_label = area_label self.area_arrows = arrows self.approximations = approximations def dr_indicates_spacing(self): r_ticks = VGroup(*[ Line( self.coords_to_point(r, -self.tick_height), self.coords_to_point(r, self.tick_height), color = YELLOW ) for r in np.arange(0, 3, self.dR) ]) index = int(0.75*len(r_ticks)) brace_ticks = VGroup(*r_ticks[index:index+2]) dr_brace = Brace(brace_ticks, UP, buff = SMALL_BUFF) dr = self.area_label.get_part_by_tex("dr") dr_copy = dr.copy() circle = Circle().replace(dr) circle.scale(1.3) dr_num = self.approximations[0][-1] self.play(ShowCreation(circle)) self.play(FadeOut(circle)) self.play(ReplacementTransform( dr.copy(), dr_num, run_time = 2, path_arc = np.pi/2, )) self.wait() self.play(FadeIn(self.x_axis)) self.play(Write(r_ticks, run_time = 1)) self.wait() self.play( GrowFromCenter(dr_brace), dr_copy.next_to, dr_brace.copy(), UP ) self.wait() self.r_ticks = r_ticks self.dr_brace_group = VGroup(dr_brace, dr_copy) def smaller_dr(self): self.transition_to_alt_config(dR = 0.05) def show_riemann_sum(self): graph = self.get_graph(lambda r : 2*np.pi*r) graph_label = self.get_graph_label( graph, "2\\pi r", x_val = 2.5, direction = UP+LEFT ) rects = self.get_riemann_rectangles( graph, x_min = 0, x_max = 3, dx = self.dR ) self.play( Write(self.y_axis, run_time = 2), *list(map(FadeOut, [ self.approximations, self.area_label, self.area_arrows, self.dr_brace_group, self.r_ticks, ])) ) self.play( ReplacementTransform( self.rings.copy(), rects, run_time = 2, lag_ratio = 0.5 ), Animation(self.x_axis), ) self.play(ShowCreation(graph)) self.play(Write(graph_label)) self.wait() self.graph = graph self.graph_label = graph_label self.rects = rects def limiting_riemann_sum(self): thinner_rects_list = [ self.get_riemann_rectangles( self.graph, x_min = 0, x_max = 3, dx = 1./(10*2**n), stroke_width = 1./(2**n), start_color = self.rects[0].get_fill_color(), end_color = self.rects[-1].get_fill_color(), ) for n in range(1, 4) ] for new_rects in thinner_rects_list: self.play( Transform( self.rects, new_rects, lag_ratio = 0.5, run_time = 2 ), Animation(self.axes), Animation(self.graph), ) self.wait() def full_precision(self): words = OldTexText("Area under \\\\ a graph") group = VGroup(OldTex("\\Downarrow"), words) group.arrange(DOWN) group.set_color(YELLOW) group.scale(0.8) group.next_to(self.integral_condition, DOWN) arc = Arc(start_angle = 2*np.pi/3, angle = 2*np.pi/3) arc.scale(2) arc.add_tip() arc.add(arc[1].copy().rotate(np.pi, RIGHT)) arc_next_to_group = VGroup( self.integral_condition[0][0], words[0] ) arc.set_height( arc_next_to_group.get_height()-MED_LARGE_BUFF ) arc.next_to(arc_next_to_group, LEFT, SMALL_BUFF) self.play(Write(group)) self.wait() self.play(ShowCreation(arc)) self.wait() class ExampleIntegralProblems(PiCreatureScene, GraphScene): CONFIG = { "dt" : 0.2, "t_max" : 7, "x_max" : 8, "y_axis_height" : 5.5, "x_axis_label" : "$t$", "y_axis_label" : "", "graph_origin" : 3*DOWN + 4.5*LEFT } def construct(self): self.write_integral_condition() self.show_car() self.show_graph() self.let_dt_approach_zero() self.show_confusion() def write_integral_condition(self): words = OldTexText( "Hard problem $\\Rightarrow$ Sum of many small values" ) words.to_edge(UP) self.play( Write(words), self.pi_creature.change_mode, "raise_right_hand" ) self.wait() self.words = words def show_car(self): car = Car() start, end = 3*LEFT+UP, 5*RIGHT+UP car.move_to(start) line = Line(start, end) tick_height = MED_SMALL_BUFF ticks = VGroup(*[ Line( p+tick_height*UP/2, p+tick_height*DOWN/2, color = YELLOW, stroke_width = 2 ) for t in np.arange(0, self.t_max, self.dt) for p in [ line.point_from_proportion(smooth(t/self.t_max)) ] ]) index = int(len(ticks)/2) brace_ticks = VGroup(*ticks[index:index+2]) brace = Brace(brace_ticks, UP) v_dt = OldTex("v(t)", "dt") v_dt.next_to(brace, UP, SMALL_BUFF) v_dt.set_color(YELLOW) v_dt_brace_group = VGroup(brace, v_dt) self.play( FadeIn(car), self.pi_creature.change_mode, "plain" ) self.play( MoveCar(car, end), FadeIn( ticks, lag_ratio=1, rate_func=linear, ), ShowCreation(line), FadeIn( v_dt_brace_group, rate_func = squish_rate_func(smooth, 0.6, 0.8) ), run_time = self.t_max ) self.wait() for mob in v_dt: self.play(Indicate(mob)) self.wait(2) self.v_dt_brace_group = v_dt_brace_group self.line = line self.ticks = ticks self.car = car def show_graph(self): self.setup_axes() self.remove(self.axes) s_graph = self.get_graph( lambda t : 1.8*self.y_max*smooth(t/self.t_max) ) v_graph = self.get_derivative_graph(s_graph) rects = self.get_riemann_rectangles( v_graph, x_min = 0, x_max = self.t_max, dx = self.dt ) rects.set_fill(opacity = 0.5) pre_rects = rects.copy() pre_rects.rotate(-np.pi/2) for index, pre_rect in enumerate(pre_rects): ti1 = len(self.ticks)*index/len(pre_rects) ti2 = min(ti1+1, len(self.ticks)-1) tick_pair = VGroup(self.ticks[ti1], self.ticks[ti2]) pre_rect.stretch_to_fit_width(tick_pair.get_width()) pre_rect.move_to(tick_pair) special_rect = rects[int(0.6*len(rects))] brace = Brace(special_rect, LEFT, buff = 0) v_dt_brace_group_copy = self.v_dt_brace_group.copy() start_brace, (v_t, dt) = v_dt_brace_group_copy self.play( FadeIn( pre_rects, run_time = 2, lag_ratio = 0.5 ), Animation(self.ticks) ) self.play( ReplacementTransform( pre_rects, rects, run_time = 3, lag_ratio = 0.5 ), Animation(self.ticks), Write(self.axes, run_time = 1) ) self.play(ShowCreation(v_graph)) self.change_mode("pondering") self.wait() self.play( v_t.next_to, brace, LEFT, SMALL_BUFF, dt.next_to, special_rect, DOWN, special_rect.set_fill, None, 1, ReplacementTransform(start_brace, brace), ) self.wait(3) self.v_graph = v_graph self.rects = rects self.v_dt_brace_group_copy = v_dt_brace_group_copy def let_dt_approach_zero(self): thinner_rects_list = [ self.get_riemann_rectangles( self.v_graph, x_min = 0, x_max = self.t_max, dx = self.dt/(2**n), stroke_width = 1./(2**n) ) for n in range(1, 4) ] self.play( self.rects.set_fill, None, 1, Animation(self.x_axis), FadeOut(self.v_dt_brace_group_copy), ) self.change_mode("thinking") self.wait() for thinner_rects in thinner_rects_list: self.play( Transform( self.rects, thinner_rects, run_time = 2, lag_ratio = 0.5 ) ) self.wait() def show_confusion(self): randy = Randolph(color = BLUE_C) randy.to_corner(DOWN+LEFT) randy.to_edge(LEFT, buff = MED_SMALL_BUFF) self.play(FadeIn(randy)) self.play( randy.change_mode, "confused", randy.look_at, self.rects ) self.play( self.pi_creature.change_mode, "confused", self.pi_creature.look_at, randy.eyes ) self.play(Blink(randy)) self.wait() class MathematicianPonderingAreaUnderDifferentCurves(PiCreatureScene): def construct(self): self.play( self.pi_creature.change_mode, "raise_left_hand", self.pi_creature.look, UP+LEFT ) self.wait(4) self.play( self.pi_creature.change_mode, "raise_right_hand", self.pi_creature.look, UP+RIGHT ) self.wait(4) self.play( self.pi_creature.change_mode, "pondering", self.pi_creature.look, UP+LEFT ) self.wait(2) def create_pi_creature(self): self.pi_creature = Randolph(color = BLUE_C) self.pi_creature.to_edge(DOWN) return self.pi_creature class AreaUnderParabola(GraphScene): CONFIG = { "x_max" : 4, "x_labeled_nums" : list(range(-1, 5)), "y_min" : 0, "y_max" : 15, "y_tick_frequency" : 2.5, "y_labeled_nums" : list(range(5, 20, 5)), "n_rect_iterations" : 6, "default_right_x" : 3, "func" : lambda x : x**2, "graph_label_tex" : "x^2", "graph_label_x_val" : 3.8, } def construct(self): self.setup_axes() self.show_graph() self.show_area() self.ask_about_area() self.show_confusion() self.show_variable_endpoint() self.name_integral() def show_graph(self): graph = self.get_graph(self.func) graph_label = self.get_graph_label( graph, self.graph_label_tex, direction = LEFT, x_val = self.graph_label_x_val, ) self.play(ShowCreation(graph)) self.play(Write(graph_label)) self.wait() self.graph = graph self.graph_label = graph_label def show_area(self): dx_list = [0.25/(2**n) for n in range(self.n_rect_iterations)] rect_lists = [ self.get_riemann_rectangles( self.graph, x_min = 0, x_max = self.default_right_x, dx = dx, stroke_width = 4*dx, ) for dx in dx_list ] rects = rect_lists[0] foreground_mobjects = [self.axes, self.graph] self.play( DrawBorderThenFill( rects, run_time = 2, rate_func = smooth, lag_ratio = 0.5, ), *list(map(Animation, foreground_mobjects)) ) self.wait() for new_rects in rect_lists[1:]: self.play( Transform( rects, new_rects, lag_ratio = 0.5, ), *list(map(Animation, foreground_mobjects)) ) self.wait() self.rects = rects self.dx = dx_list[-1] self.foreground_mobjects = foreground_mobjects def ask_about_area(self): rects = self.rects question = OldTexText("Area?") question.move_to(rects.get_top(), DOWN) mid_rect = rects[2*len(rects)/3] arrow = Arrow(question.get_bottom(), mid_rect.get_center()) v_lines = VGroup(*[ DashedLine( FRAME_HEIGHT*UP, ORIGIN, color = RED ).move_to(self.coords_to_point(x, 0), DOWN) for x in (0, self.default_right_x) ]) self.play( Write(question), ShowCreation(arrow) ) self.wait() self.play(ShowCreation(v_lines, run_time = 2)) self.wait() self.foreground_mobjects += [question, arrow] self.question = question self.question_arrow = arrow self.v_lines = v_lines def show_confusion(self): morty = Mortimer() morty.to_corner(DOWN+RIGHT) self.play(FadeIn(morty)) self.play( morty.change_mode, "confused", morty.look_at, self.question, ) self.play(morty.look_at, self.rects.get_bottom()) self.play(Blink(morty)) self.play(morty.look_at, self.question) self.wait() self.play(Blink(morty)) self.play(FadeOut(morty)) def show_variable_endpoint(self): triangle = RegularPolygon( n = 3, start_angle = np.pi/2, stroke_width = 0, fill_color = WHITE, fill_opacity = 1, ) triangle.set_height(0.25) triangle.move_to(self.v_lines[1].get_bottom(), UP) x_label = OldTex("x") x_label.next_to(triangle, DOWN) self.right_point_slider = VGroup(triangle, x_label) A_func = OldTex("A(x)") A_func.move_to(self.question, DOWN) self.play(FadeOut(self.x_axis.numbers)) self.x_axis.remove(*self.x_axis.numbers) self.foreground_mobjects.remove(self.axes) self.play(DrawBorderThenFill(self.right_point_slider)) self.move_right_point_to(2) self.wait() self.move_right_point_to(self.default_right_x) self.wait() self.play(ReplacementTransform(self.question, A_func)) self.wait() self.A_func = A_func def name_integral(self): f_tex = "$%s$"%self.graph_label_tex words = OldTexText("``Integral'' of ", f_tex) words.set_color_by_tex(f_tex, self.graph_label.get_color()) brace = Brace(self.A_func, UP) words.next_to(brace, UP) self.play( Write(words), GrowFromCenter(brace) ) self.wait() for x in 4, 2, self.default_right_x: self.move_right_point_to(x, run_time = 2) self.integral_words_group = VGroup(brace, words) #### def move_right_point_to(self, target_x, **kwargs): v_line = self.v_lines[1] slider = self.right_point_slider rects = self.rects curr_x = self.x_axis.point_to_number(v_line.get_bottom()) group = VGroup(rects, v_line, slider) def update_group(group, alpha): rects, v_line, slider = group new_x = interpolate(curr_x, target_x, alpha) new_rects = self.get_riemann_rectangles( self.graph, x_min = 0, x_max = new_x, dx = self.dx*new_x/3.0, stroke_width = rects[0].get_stroke_width(), ) point = self.coords_to_point(new_x, 0) v_line.move_to(point, DOWN) slider.move_to(point, UP) Transform(rects, new_rects).update(1) return VGroup(rects, v_line, slider) self.play( UpdateFromAlphaFunc( group, update_group, **kwargs ), *list(map(Animation, self.foreground_mobjects)) ) class WhoCaresAboutArea(TeacherStudentsScene): def construct(self): point = 2*RIGHT+3*UP self.student_says( "Who cares!?!", target_mode = "angry", ) self.play(self.teacher.change_mode, "guilty") self.wait() self.play( RemovePiCreatureBubble(self.students[1]), self.teacher.change_mode, "raise_right_hand", self.teacher.look_at, point ) self.play_student_changes( *["pondering"]*3, look_at = point, added_anims = [self.teacher.look_at, point] ) self.wait(3) class PlayWithThisIdea(TeacherStudentsScene): def construct(self): self.teacher_says( "Play with", "the", "thought!", target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.wait() equation = OldTex("A(x)", "\\leftrightarrow", "x^2") equation.set_color_by_tex("x^2", BLUE) self.teacher_says(equation, target_mode = "sassy") self.play_student_changes(*["thinking"]*3) self.wait(2) class PlayingTowardsDADX(AreaUnderParabola, ReconfigurableScene): CONFIG = { "n_rect_iterations" : 6, "deriv_dx" : 0.2, "graph_origin" : 2.5*DOWN + 6*LEFT, } def setup(self): AreaUnderParabola.setup(self) ReconfigurableScene.setup(self) def construct(self): self.fast_forward_to_end_of_previous_scene() self.nudge_x() self.describe_sliver() self.shrink_dx() self.write_dA_dx() self.dA_remains_a_mystery() self.write_example_inputs() self.show_dA_dx_in_detail() self.show_smaller_x() def fast_forward_to_end_of_previous_scene(self): self.force_skipping() AreaUnderParabola.construct(self) self.revert_to_original_skipping_status() def nudge_x(self): shadow_rects = self.rects.copy() shadow_rects.set_fill(BLACK, opacity = 0.5) original_v_line = self.v_lines[1].copy() right_v_lines = VGroup(original_v_line, self.v_lines[1]) curr_x = self.x_axis.point_to_number(original_v_line.get_bottom()) self.add(original_v_line) self.foreground_mobjects.append(original_v_line) self.move_right_point_to(curr_x + self.deriv_dx) self.play( FadeIn(shadow_rects), *list(map(Animation, self.foreground_mobjects)) ) self.shadow_rects = shadow_rects self.right_v_lines = right_v_lines def describe_sliver(self): dx_brace = Brace(self.right_v_lines, DOWN, buff = 0) dx_label = dx_brace.get_text("$dx$") dx_group = VGroup(dx_brace, dx_label) dA_rect = Rectangle( width = self.right_v_lines.get_width(), height = self.shadow_rects[-1].get_height(), stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.5, ).move_to(self.right_v_lines, DOWN) dA_label = OldTex("d", "A") dA_label.next_to(dA_rect, RIGHT, MED_LARGE_BUFF, UP) dA_label.set_color(GREEN) dA_arrow = Arrow( dA_label.get_bottom()+MED_SMALL_BUFF*DOWN, dA_rect.get_center(), buff = 0, color = WHITE ) difference_in_area = OldTexText( "d", "ifference in ", "A", "rea", arg_separator = "" ) difference_in_area.set_color_by_tex("d", GREEN) difference_in_area.set_color_by_tex("A", GREEN) difference_in_area.scale(0.7) difference_in_area.next_to(dA_label, UP, MED_SMALL_BUFF, LEFT) side_brace = Brace(dA_rect, LEFT, buff = 0) graph_label_copy = self.graph_label.copy() self.play( FadeOut(self.right_point_slider), FadeIn(dx_group) ) self.play(Indicate(dx_label)) self.wait() self.play(ShowCreation(dA_arrow)) self.wait() self.play(Write(dA_label, run_time = 2)) self.wait() self.play( ReplacementTransform(dA_label[0].copy(), difference_in_area[0]), ReplacementTransform(dA_label[1].copy(), difference_in_area[2]), *list(map(FadeIn, [difference_in_area[1], difference_in_area[3]])) ) self.wait(2) self.play(FadeIn(dA_rect), Animation(dA_arrow)) self.play(GrowFromCenter(side_brace)) self.play( graph_label_copy.set_color, WHITE, graph_label_copy.next_to, side_brace, LEFT, SMALL_BUFF ) self.wait() self.play(Indicate(dx_group)) self.wait() self.play(FadeOut(difference_in_area)) self.dx_group = dx_group self.dA_rect = dA_rect self.dA_label = dA_label self.graph_label_copy = graph_label_copy def shrink_dx(self, **kwargs): self.transition_to_alt_config( deriv_dx = 0.05, transformation_kwargs = {"run_time" : 2}, **kwargs ) def write_dA_dx(self): f_tex = self.graph_label_tex equation = OldTex("dA", "\\approx", f_tex, "dx") equation.to_edge(RIGHT).shift(3*UP) deriv_equation = OldTex( "{dA", "\\over \\,", "dx}", "\\approx", f_tex ) deriv_equation.move_to(equation, UP+LEFT) for tex_mob in equation, deriv_equation: tex_mob.set_color_by_tex( "dA", self.dA_label.get_color() ) dA = VGroup(self.dA_label[0][0], self.dA_label[1][0]) x_squared = self.graph_label_copy dx = self.dx_group[1] self.play(*[ ReplacementTransform( mob.copy(), equation.get_part_by_tex(tex), run_time = 2 ) for mob, tex in [(x_squared, f_tex), (dx, "dx"), (dA, "dA")] ]) self.play(Write(equation.get_part_by_tex("approx"))) self.wait() for tex, mob in (f_tex, x_squared), ("dx", dx): self.play(*list(map(Indicate, [ equation.get_part_by_tex(tex), mob ]))) self.wait(2) self.play(*[ ReplacementTransform( equation.get_part_by_tex(tex), deriv_equation.get_part_by_tex(tex), run_time = 2, ) for tex in ("dA", "approx", f_tex, "dx") ] + [ Write(deriv_equation.get_part_by_tex("over")) ]) self.wait(2) self.shrink_dx(return_to_original_configuration = False) self.wait() self.deriv_equation = deriv_equation def dA_remains_a_mystery(self): randy = Randolph(color = BLUE_C) randy.to_corner(DOWN+LEFT) randy.look_at(self.A_func) A_circle, dA_circle = [ Circle(color = color).replace( mob, stretch = True ).scale(1.5) for mob, color in [(self.A_func, RED), (self.deriv_equation, GREEN)] ] q_marks = OldTex("???") q_marks.next_to(A_circle, UP) self.play( FadeOut(self.integral_words_group), FadeIn(randy) ) self.play( ShowCreation(A_circle), randy.change_mode, "confused" ) self.play(Write(q_marks, run_time = 2)) self.play(Blink(randy)) self.wait() self.play( randy.change_mode, "surprised", randy.look_at, dA_circle, ReplacementTransform(A_circle, dA_circle) ) self.play(Blink(randy)) self.wait() self.play(*list(map(FadeOut, [randy, q_marks, dA_circle]))) def write_example_inputs(self): d = self.default_right_x three = OldTex("x =", "%d"%d) three_plus_dx = OldTex("x = ", "%d.001"%d) labels_lines_vects = list(zip( [three, three_plus_dx], self.right_v_lines, [LEFT, RIGHT] )) for label, line, vect in labels_lines_vects: point = line.get_bottom() label.next_to(point, DOWN+vect, MED_SMALL_BUFF) label.shift(LARGE_BUFF*vect) label.arrow = Arrow( label, point, buff = SMALL_BUFF, color = WHITE, tip_length = 0.15 ) line_copy = line.copy() line_copy.set_color(YELLOW) self.play( FadeIn(label), FadeIn(label.arrow), ShowCreation(line_copy) ) self.play(FadeOut(line_copy)) self.wait() self.three = three self.three_plus_dx = three_plus_dx def show_dA_dx_in_detail(self): d = self.default_right_x expression = OldTex( "{A(", "%d.001"%d, ") ", "-A(", "%d"%d, ")", "\\over \\,", "0.001}", "\\approx", "%d"%d, "^2" ) expression.scale(0.9) expression.next_to( self.deriv_equation, DOWN, MED_LARGE_BUFF ) expression.to_edge(RIGHT) self.play( ReplacementTransform( self.three_plus_dx.get_part_by_tex("%d.001"%d).copy(), expression.get_part_by_tex("%d.001"%d) ), Write(VGroup( expression.get_part_by_tex("A("), expression.get_part_by_tex(")"), )), ) self.wait() self.play( ReplacementTransform( self.three.get_part_by_tex("%d"%d).copy(), expression.get_part_by_tex("%d"%d, substring = False) ), Write(VGroup( expression.get_part_by_tex("-A("), expression.get_parts_by_tex(")")[1], )), ) self.wait(2) self.play( Write(expression.get_part_by_tex("over")), ReplacementTransform( expression.get_part_by_tex("%d.001"%d).copy(), expression.get_part_by_tex("0.001"), ) ) self.wait() self.play( Write(expression.get_part_by_tex("approx")), ReplacementTransform( self.graph_label_copy.copy(), VGroup(*expression[-2:]), run_time = 2 ) ) self.wait() def show_smaller_x(self): self.transition_to_alt_config( default_right_x = 2, deriv_dx = 0.04, transformation_kwargs = {"run_time" : 2} ) class AlternateAreaUnderCurve(PlayingTowardsDADX): CONFIG = { "func" : lambda x : (x-2)**3 - 3*(x-2) + 6, "graph_label_tex" : "f(x)", "deriv_dx" : 0.1, "x_max" : 5, "x_axis_width" : 11, "graph_label_x_val" : 4.5, } def construct(self): #Superclass parts to skip self.force_skipping() self.setup_axes() self.show_graph() self.show_area() self.ask_about_area() self.show_confusion() #Superclass parts to show self.revert_to_original_skipping_status() self.show_variable_endpoint() self.name_integral() self.nudge_x() self.describe_sliver() self.write_dA_dx() #New animations self.approximation_improves_for_smaller_dx() self.name_derivative() def approximation_improves_for_smaller_dx(self): color = YELLOW approx = self.deriv_equation.get_part_by_tex("approx") dx_to_zero_words = OldTexText( "Gets better \\\\ as", "$dx \\to 0$" ) dx_to_zero_words.set_color_by_tex("dx", color) dx_to_zero_words.next_to(approx, DOWN, 1.5*LARGE_BUFF) arrow = Arrow(dx_to_zero_words, approx, color = color) self.play( approx.set_color, color, ShowCreation(arrow), FadeIn(dx_to_zero_words), ) self.wait() self.transition_to_alt_config( deriv_dx = self.deriv_dx/4.0, transformation_kwargs = {"run_time" : 2} ) self.dx_to_zero_words = dx_to_zero_words self.dx_to_zero_words_arrow = arrow def name_derivative(self): deriv_words = OldTexText("``Derivative'' of $A$") deriv_words.scale(0.9) deriv_words.to_edge(UP+RIGHT) moving_group = VGroup( self.deriv_equation, self.dx_to_zero_words, self.dx_to_zero_words_arrow, ) moving_group.generate_target() moving_group.target.next_to(deriv_words, DOWN, LARGE_BUFF) moving_group.target.to_edge(RIGHT) self.play( FadeIn(deriv_words), MoveToTarget(moving_group) ) dA_dx = VGroup(*self.deriv_equation[:3]) box = Rectangle(color = GREEN) box.replace(dA_dx, stretch = True) box.scale(1.3) brace = Brace(box, UP) faders = VGroup( self.dx_to_zero_words[0], self.dx_to_zero_words_arrow ) dx_to_zero = self.dx_to_zero_words[1] self.play(*list(map(FadeIn, [box, brace]))) self.wait() self.play( FadeOut(faders), dx_to_zero.next_to, box, DOWN ) self.wait() ######## def show_smaller_x(self): return def shrink_dx(self, **kwargs): return class NextVideoWrapper(Scene): def construct(self): rect = Rectangle(height = 9, width = 16) rect.set_height(1.5*FRAME_Y_RADIUS) titles = [ OldTexText("Chapter %d:"%d, s) for d, s in [ (2, "The paradox of the derivative"), (3, "Derivative formulas through geometry"), ] ] for title in titles: title.to_edge(UP) rect.next_to(VGroup(*titles), DOWN) self.add(titles[0]) self.play(ShowCreation(rect)) self.wait(3) self.play(Transform(*titles)) self.wait(3) class ProblemSolvingTool(TeacherStudentsScene): def construct(self): self.teacher_says(""" The derivative is a problem-solving tool """) self.wait(3) class FundamentalTheorem(Scene): def construct(self): words = OldTexText(""" Fundamental theorem of calculus """) words.to_edge(UP) arrow = DoubleArrow(LEFT, RIGHT).shift(2*RIGHT) deriv = OldTex( "{dA", "\\over \\,", "dx}", "=", "x^2" ) deriv.set_color_by_tex("dA", GREEN) deriv.next_to(arrow, RIGHT) self.play(ShowCreation(arrow)) self.wait() self.play(Write(deriv)) self.wait() self.play(Write(words)) self.wait() class NextVideos(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) this_video = series[0] this_video.set_color(YELLOW) self.add(series) self.teacher_says( "That's a high-level view" ) self.wait() self.play( RemovePiCreatureBubble( self.teacher, target_mode = "raise_right_hand", look_at = this_video, ), *it.chain(*[ [pi.change_mode, "pondering", pi.look_at, this_video] for pi in self.get_students() ]) ) self.play(*[ ApplyMethod(pi.look_at, series) for pi in self.get_pi_creatures() ]) self.play(*[ ApplyMethod( video.shift, 0.5*video.get_height()*DOWN, run_time = 3, rate_func = squish_rate_func( there_and_back, alpha, alpha+0.3 ) ) for video, alpha in zip(series, np.linspace(0, 0.7, len(series))) ]) self.wait() student = self.get_students()[1] self.remove(student) everything = VGroup(*self.get_top_level_mobjects()) self.add(student) words = OldTexText(""" You could have invented this. """) words.next_to(student, UP, LARGE_BUFF) self.play(self.teacher.change_mode, "plain") self.play( everything.fade, 0.75, student.change_mode, "plain" ) self.play( Write(words), student.look_at, words, ) self.play( student.change_mode, "confused", student.look_at, words ) self.wait(3) self.play(student.change_mode, "thinking") self.wait(4) class Chapter1PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "CrypticSwarm", "Juan Benet", "Yu Jun", "Othman Alikhan", "Markus Persson", "Joseph John Cox", "Luc Ritchie", "Einar Johansen", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ], "patron_scale_val" : 0.9 } class EndScreen(PiCreatureScene): CONFIG = { "seconds_to_blink" : 3, } def construct(self): words = OldTexText("Clicky stuffs") words.scale(1.5) words.next_to(self.pi_creature, UP) words.to_edge(UP) self.play( FadeIn( words, run_time = 2, lag_ratio = 0.5 ), self.pi_creature.change_mode, "hooray" ) self.wait() mode_point_pairs = [ ("raise_left_hand", 5*LEFT+3*UP), ("raise_right_hand", 5*RIGHT+3*UP), ("thinking", 5*LEFT+2*DOWN), ("thinking", 5*RIGHT+2*DOWN), ("thinking", 5*RIGHT+2*DOWN), ("happy", 5*LEFT+3*UP), ("raise_right_hand", 5*RIGHT+3*UP), ] for mode, point in mode_point_pairs: self.play(self.pi_creature.change, mode, point) self.wait() self.wait(3) def create_pi_creature(self): self.pi_creature = Randolph() self.pi_creature.shift(2*DOWN + 1.5*LEFT) return self.pi_creature class Thumbnail(AlternateAreaUnderCurve): CONFIG = { "x_axis_label" : "", "y_axis_label" : "", "graph_origin" : 2.4 * DOWN + 3 * LEFT, } def construct(self): self.setup_axes() self.remove(*self.x_axis.numbers) self.remove(*self.y_axis.numbers) graph = self.get_graph(self.func) rects = self.get_riemann_rectangles( graph, x_min = 0, x_max = 4, dx = 0.25, start_color = BLUE_E, ) words = OldTexText(""" Could \\emph{you} invent calculus? """) words.set_width(9) words.to_edge(UP) self.add(graph, rects, words)
videos_3b1b/_2017/eoc/chapter4.py
from manim_imports_ext import * SINE_COLOR = BLUE X_SQUARED_COLOR = GREEN SUM_COLOR = YELLOW PRODUCT_COLOR = YELLOW class Chapter4OpeningQuote(OpeningQuote): CONFIG = { "quote" : [ "Using the chain rule is like peeling an onion: ", "you have to deal with each layer at a time, and ", "if it is too big you will start crying." ], "author" : "(Anonymous professor)" } class TransitionFromLastVideo(TeacherStudentsScene): def construct(self): simple_rules = VGroup(*list(map(Tex, [ "\\frac{d(x^3)}{dx} = 3x^2", "\\frac{d(\\sin(x))}{dx} = \\cos(x)", "\\frac{d(1/x)}{dx} = -\\frac{1}{x^2}", ]))) combination_rules = VGroup(*[ OldTex("\\frac{d}{dx}\\left(%s\\right)"%tex) for tex in [ "\\sin(x) + x^2", "\\sin(x)(x^2)", "\\sin(x^2)", ] ]) for rules in simple_rules, combination_rules: rules.arrange(buff = LARGE_BUFF) rules.next_to(self.get_teacher(), UP, buff = MED_LARGE_BUFF) rules.to_edge(LEFT) series = VideoSeries() series.to_edge(UP) last_video = series[2] last_video.save_state() this_video = series[3] brace = Brace(last_video) #Simple rules self.add(series) self.play( FadeIn(brace), last_video.set_color, YELLOW ) for rule in simple_rules: self.play( Write(rule, run_time = 2), self.get_teacher().change_mode, "raise_right_hand", *[ ApplyMethod(pi.change_mode, "pondering") for pi in self.get_students() ] ) self.wait() self.wait(2) self.play(simple_rules.replace, last_video) self.play( last_video.restore, Animation(simple_rules), brace.next_to, this_video, DOWN, this_video.set_color, YELLOW ) #Combination rules self.play( Write(combination_rules), *[ ApplyMethod(pi.change_mode, "confused") for pi in self.get_students() ] ) self.wait(2) for rule in combination_rules: interior = VGroup(*rule[5:-1]) added_anims = [] if rule is combination_rules[-1]: inner_func = VGroup(*rule[-4:-2]) self.play(inner_func.shift, 0.5*UP) added_anims = [ inner_func.shift, 0.5*DOWN, inner_func.set_color, YELLOW ] self.play( interior.set_color, YELLOW, *added_anims, lag_ratio = 0.5 ) self.wait() self.wait() #Address subtraction and division subtraction = OldTex("\\sin(x)", "-", "x^2") decomposed_subtraction = OldTex("\\sin(x)", "+(-1)\\cdot", "x^2") pre_division = OldTex("\\frac{\\sin(x)}{x^2}") division = VGroup( VGroup(*pre_division[:6]), VGroup(*pre_division[6:7]), VGroup(*pre_division[7:]), ) pre_decomposed_division = OldTex("\\sin(x)\\cdot\\frac{1}{x^2}") decomposed_division = VGroup( VGroup(*pre_decomposed_division[:6]), VGroup(*pre_decomposed_division[6:9]), VGroup(*pre_decomposed_division[9:]), ) for mob in subtraction, decomposed_subtraction, division, decomposed_division: mob.next_to( VGroup(self.get_teacher(), self.get_students()[-1]), UP, buff = MED_LARGE_BUFF ) top_group = VGroup(series, simple_rules, brace) combination_rules.save_state() self.play( top_group.next_to, FRAME_Y_RADIUS*UP, UP, combination_rules.to_edge, UP, ) pairs = [ (subtraction, decomposed_subtraction), (division, decomposed_division) ] for question, answer in pairs: self.play( Write(question), combination_rules.fade, 0.2, self.get_students()[2].change_mode, "raise_right_hand", self.get_teacher().change_mode, "plain", ) self.wait() answer[1].set_color(GREEN) self.play( Transform(question, answer), self.get_teacher().change_mode, "hooray", self.get_students()[2].change_mode, "plain", ) self.wait() self.play(FadeOut(question)) #Monstrous expression monster = OldTex( "\\Big(", "e^{\\sin(x)} \\cdot", "\\cos\\Big(", "\\frac{1}{x^3}", " + x^3", "\\Big)", "\\Big)^4" ) monster.next_to(self.get_pi_creatures(), UP) parts = [ VGroup(*monster[3][2:]), VGroup(*monster[3][:2]), monster[4], VGroup(monster[2], monster[5]), monster[1], VGroup(monster[0], monster[6]) ] modes = 3*["erm"] + 3*["pleading"] for part, mode in zip(parts, modes): self.play( FadeIn(part, lag_ratio = 0.5), self.get_teacher().change_mode, "raise_right_hand", *[ ApplyMethod(pi.change_mode, mode) for pi in self.get_students() ] ) self.wait() self.play_student_changes(*["happy"]*3) words = list(map(TexText, [ "composition", "product", "composition", "sum", "composition" ])) for word, part in zip(words, reversed(parts)): word.set_color(YELLOW) word.next_to(monster, UP) self.play( FadeIn(word), part.scale, 1.2, part.set_color, YELLOW ) self.wait() self.play(*list(map(FadeOut, [word, part]))) self.play(FadeOut(parts[0])) #Bring back combinations self.play( combination_rules.restore, *[ ApplyMethod(pi_creature.change_mode, "pondering") for pi_creature in self.get_pi_creatures() ] ) self.wait(2) class DampenedSpring(Scene): def construct(self): compact_spring, extended_spring = [ ParametricCurve( lambda t : (t/denom)*RIGHT+np.sin(t)*UP+np.cos(t)*OUT, t_max = 12*np.pi, color = GREY, ).shift(3*LEFT) for denom in (12.0, 2.0) ] for spring in compact_spring, extended_spring: spring.scale(0.5) spring.rotate(np.pi/6, UP) spring.set_color(GREY) spring.shift(-spring.get_points()[0] + 3*LEFT) moving_spring = compact_spring.copy() def update_spring(spring, a): spring.interpolate( compact_spring, extended_spring, 0.5*(np.exp(-4*a)*np.cos(40*a)+1) ) equation = OldTex( "\\text{Length} = 2 + e^{-4t}\\cos(20t)" ) equation.to_edge(UP) self.add(moving_spring, equation) self.play(UpdateFromAlphaFunc( moving_spring, update_spring, run_time = 10, rate_func=linear )) self.wait() class ComingUp(Scene): def construct(self): rect = Rectangle(height = 9, width = 16) rect.set_stroke(WHITE) rect.set_height(FRAME_HEIGHT-2) title = OldTexText("Coming up...") title.to_edge(UP) rect.next_to(title, DOWN) self.play(Write(title)) self.play(ShowCreation(rect)) self.wait() class PreSumRuleDiscussion(Scene): def construct(self): title = OldTexText("Sum rule") title.to_edge(UP) self.add(title) specific = OldTex( "\\frac{d}{dx}(", "\\sin(x)", "+", "x^2", ")", "=", "\\cos(x)", "+", "2x" ) general = OldTex( "\\frac{d}{dx}(", "g(x)", "+", "h(x)", ")", "=", "\\frac{dg}{dx}", "+", "\\frac{dh}{dx}" ) for formula in specific, general: formula[1].set_color(SINE_COLOR) formula[6].set_color(SINE_COLOR) formula[3].set_color(X_SQUARED_COLOR) formula[8].set_color(X_SQUARED_COLOR) VGroup(specific, general).arrange(DOWN, buff = LARGE_BUFF) #Add on rules self.add(specific) for i in 0, 4, 5: self.add(general[i]) self.wait(2) for indices in [(1, 2, 3), (6,), (7, 8)]: self.play(*[ ReplacementTransform( specific[i].copy(), general[i] ) for i in indices ]) self.wait() #Highlight parts for i in 1, 3, -1, 6, 8: if i < 0: self.wait() else: part = specific[i] self.play( part.set_color, YELLOW, part.scale, 1.2, rate_func = there_and_back ) self.wait() class SumRule(GraphScene): CONFIG = { "x_labeled_nums" : [], "y_labeled_nums" : [], "y_axis_label" : "", "x_max" : 4, "x_axis_width" : FRAME_WIDTH, "y_max" : 3, "graph_origin" : 2.5*DOWN + 2.5*LEFT, "graph_label_x_value" : 1.5, "example_input" : 0.5, "example_input_string" : "0.5", "dx" : 0.05, "v_lines_x_min" : -1, "v_lines_x_max" : 2, "graph_scale_factor" : 2, "tex_scale_factor" : 0.8, } def construct(self): self.write_function() self.add_graphs() self.zoom_in_on_graph() self.show_example_stacking() self.show_df() self.expand_derivative() def write_function(self): func_mob = OldTex("f(x)", "=", "\\sin(x)", "+", "x^2") func_mob.scale(self.tex_scale_factor) func_mob.set_color_by_tex("f(x)", SUM_COLOR) func_mob.set_color_by_tex("\\sin(x)", SINE_COLOR) func_mob.set_color_by_tex("x^2", X_SQUARED_COLOR) func_mob.to_corner(UP+LEFT) self.add(func_mob) self.func_mob = func_mob def add_graphs(self): self.setup_axes() sine_graph = self.get_graph(np.sin, color = SINE_COLOR) parabola = self.get_graph(lambda x : x**2, color = X_SQUARED_COLOR) sum_graph = self.get_graph( lambda x : np.sin(x) + x**2, color = SUM_COLOR ) sine_label = self.get_graph_label( sine_graph, "\\sin(x)", x_val = self.graph_label_x_value, direction = UP+RIGHT, buff = 0, ) sine_label.scale(self.tex_scale_factor) parabola_label = self.get_graph_label( parabola, "x^2", x_val = self.graph_label_x_value, ) parabola_label.scale(self.tex_scale_factor) graphs = VGroup(sine_graph, parabola) labels = VGroup(sine_label, parabola_label) for label in labels: label.add_background_rectangle() for graph, label in zip(graphs, labels): self.play( ShowCreation(graph), Write(label) ) self.wait() num_lines = (self.v_lines_x_max-self.v_lines_x_min)/self.dx sine_v_lines, parabox_v_lines = v_line_sets = [ self.get_vertical_lines_to_graph( graph, x_min = self.v_lines_x_min, x_max = self.v_lines_x_max, num_lines = num_lines, stroke_width = 2 ) for graph in graphs ] sine_v_lines.shift(0.02*RIGHT) for v_lines in v_line_sets: self.play(ShowCreation(v_lines), Animation(labels)) self.wait() self.play(*it.chain( [ ApplyMethod(l2.move_to, l1.get_top(), DOWN) for l1, l2, in zip(*v_line_sets) ], [graph.fade for graph in graphs], [Animation(labels)] )) self.wait() self.play(ShowCreation(sum_graph)) self.wait() self.sum_graph = sum_graph self.parabola = parabola self.sine_graph = sine_graph self.graph_labels = labels self.v_line_sets = v_line_sets def zoom_in_on_graph(self): graph_parts = VGroup( self.axes, self.sine_graph, self.parabola, self.sum_graph, *self.v_line_sets ) graph_parts.remove(self.func_mob, *self.graph_labels) graph_parts.generate_target() self.graph_labels.generate_target() for mob in graph_parts, self.graph_labels: mob.target.scale( self.graph_scale_factor, about_point = self.graph_origin, ) for mob in self.graph_labels.target: mob.scale( 1./self.graph_scale_factor, about_point = mob.get_bottom() ) mob.shift_onto_screen() self.play(*list(map(MoveToTarget, [ graph_parts, self.graph_labels ]))) self.wait() def show_example_stacking(self): v_line_sets = self.v_line_sets num_lines = len(v_line_sets[0]) example_v_lines, nudged_v_lines = [ VGroup(*[v_lines[index] for v_lines in v_line_sets]) for index in (num_lines/2, num_lines/2+1) ] for line in nudged_v_lines: line.save_state() sine_lines, parabola_lines = [ VGroup(example_v_lines[i], nudged_v_lines[i]) for i in (0, 1) ] faders = VGroup(*[line for line in it.chain(*v_line_sets) if line not in example_v_lines]) label_groups = [] for line, tex, vect in zip(sine_lines, ["", "+dx"], [LEFT, RIGHT]): dot = Dot(line.get_bottom(), radius = 0.03, color = YELLOW) label = OldTex( "x=" + str(self.example_input) + tex ) label.next_to(dot, DOWN+vect, buff = MED_LARGE_BUFF) arrow = Arrow( label.get_corner(UP-vect), dot, buff = SMALL_BUFF, color = WHITE, tip_length = 0.1 ) label_groups.append(VGroup(label, arrow, dot)) line_tex_direction_triplets = [ (sine_lines[0], "\\sin(0.5)", LEFT), (sine_lines[1], "\\sin(0.5+dx)", RIGHT), (parabola_lines[0], "(0.5)^2", LEFT), (parabola_lines[1], "(0.5+dx)^2", RIGHT), ] for line, tex, direction in line_tex_direction_triplets: line.brace = Brace( line, direction, buff = SMALL_BUFF, min_num_quads = 2, ) line.brace.set_color(line.get_color()) line.brace.add_background_rectangle() line.brace_text = line.brace.get_text("$%s$"%tex) line.brace_text.scale( self.tex_scale_factor, about_point = line.brace_text.get_edge_center(-direction) ) line.brace_text.add_background_rectangle() line.brace_anim = MaintainPositionRelativeTo( VGroup(line.brace, line.brace_text), line ) ##Look at example lines self.play( example_v_lines.set_stroke, None, 4, faders.fade, Animation(self.graph_labels), Write(label_groups[0]), ) for line in example_v_lines: line.save_state() self.wait() self.play( GrowFromCenter(sine_lines[0].brace), Write(sine_lines[0].brace_text), ) self.wait() self.play( sine_lines[0].shift, UP+4*LEFT, sine_lines[0].brace_anim, parabola_lines[0].move_to, sine_lines[0], DOWN ) self.wait() parabola_lines[0].brace_anim.update(1) self.play( GrowFromCenter(parabola_lines[0].brace), Write(parabola_lines[0].brace_text), ) self.wait() self.play(*it.chain(*[ [line.restore, line.brace_anim] for line in example_v_lines ])) ## Nudged_lines self.play( Write(label_groups[1]), *it.chain(*[ [line.restore, line.set_stroke, None, 4] for line in nudged_v_lines ]) ) self.wait() for line in nudged_v_lines: self.play( GrowFromCenter(line.brace), Write(line.brace_text) ) self.wait() self.sine_lines = sine_lines self.parabola_lines = parabola_lines def show_df(self): sine_lines = self.sine_lines parabola_lines = self.parabola_lines df, equals, d_sine, plus, d_x_squared = deriv_mob = OldTex( "df", "=", "d(\\sin(x))", "+", "d(x^2)" ) df.set_color(SUM_COLOR) d_sine.set_color(SINE_COLOR) d_x_squared.set_color(X_SQUARED_COLOR) deriv_mob.scale(self.tex_scale_factor) deriv_mob.next_to( self.func_mob, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) for submob in deriv_mob: submob.add_to_back(BackgroundRectangle(submob)) df_lines = self.show_difference(parabola_lines, df, equals) self.wait() self.play(FadeOut(df_lines)) self.play( parabola_lines[0].shift, (parabola_lines[1].get_bottom()[1]-parabola_lines[0].get_bottom()[1])*UP, parabola_lines[0].brace_anim ) d_sine_lines = self.show_difference(sine_lines, d_sine, plus) d_x_squared_lines = self.show_difference(parabola_lines, d_x_squared, VGroup()) self.wait() self.deriv_mob = deriv_mob self.d_sine_lines = d_sine_lines self.d_x_squared_lines = d_x_squared_lines def show_difference(self, v_lines, target_tex, added_tex): distance = v_lines[1].get_top()[1]-v_lines[0].get_top()[1] h_lines = VGroup(*[ DashedLine(ORIGIN, 2*RIGHT, stroke_width = 3) for x in range(2) ]) h_lines.arrange(DOWN, buff = distance) h_lines.move_to(v_lines[1].get_top(), UP+RIGHT) brace = Brace(h_lines, LEFT) brace_text = target_tex.copy() brace_text.next_to(brace, LEFT) self.play(ShowCreation(h_lines)) self.play(GrowFromCenter(brace), Write(brace_text)) self.wait() self.play( ReplacementTransform(brace_text.copy(), target_tex), Write(added_tex) ) return VGroup(h_lines, brace, brace_text) def expand_derivative(self): expanded_deriv = OldTex( "df", "=", "\\cos(x)", "\\,dx", "+", "2x", "\\,dx" ) expanded_deriv.set_color_by_tex("df", SUM_COLOR) VGroup(*expanded_deriv[2:4]).set_color(SINE_COLOR) VGroup(*expanded_deriv[5:7]).set_color(X_SQUARED_COLOR) expanded_deriv.scale(self.tex_scale_factor) expanded_deriv.next_to( self.deriv_mob, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) background_rect = BackgroundRectangle(expanded_deriv) rearranged_deriv = OldTex( "{df \\over", "dx}", "=", "\\cos(x)", "+", "2x" ) rearranged_deriv[0].set_color(SUM_COLOR) rearranged_deriv[3].set_color(SINE_COLOR) rearranged_deriv[5].set_color(X_SQUARED_COLOR) rearranged_deriv.scale(self.tex_scale_factor) rearranged_deriv.move_to(expanded_deriv, UP+LEFT) deriv_target_indices = [0, 2, 3, 1, 4, 5, 1] self.play( FadeIn( background_rect, rate_func = squish_rate_func(smooth, 0.6, 1) ), Write(expanded_deriv) ) self.wait() tex_group_pairs = [ ("\\cos(0.5)dx", self.d_sine_lines), ("2(0.5)dx", self.d_x_squared_lines), ] def indicate(mob): self.play( mob.set_color, YELLOW, mob.scale, 1.2, rate_func = there_and_back ) for tex, group in tex_group_pairs: old_label = group[-1] new_label = OldTex(tex) pre_dx = VGroup(*new_label[:-2]) dx = VGroup(*new_label[-2:]) new_label.add_background_rectangle() new_label.scale(self.tex_scale_factor) new_label.move_to(old_label, RIGHT) new_label.set_color(old_label.get_color()) self.play(FocusOn(old_label)) indicate(old_label) self.wait() self.play(FadeOut(old_label)) self.play(FadeIn(new_label)) self.wait() indicate(dx) self.wait() indicate(pre_dx) self.wait() self.wait() self.play(*[ Transform( expanded_deriv[i], rearranged_deriv[j], path_arc = -np.pi/2 ) for i, j in enumerate(deriv_target_indices) ]) self.wait() class DiscussProducts(TeacherStudentsScene): def construct(self): wrong_product_rule = OldTex( "\\frac{d(\\sin(x)x^2)}{dx}", "\\ne", "\\left(\\frac{d(\\sin(x))}{dx}\\right)", "\\left(\\frac{d(x^2)}{dx}\\right)", ) not_equals = wrong_product_rule[1] wrong_product_rule[2].set_color(SINE_COLOR) wrong_product_rule[3].set_color(X_SQUARED_COLOR) wrong_product_rule.next_to( self.get_teacher().get_corner(UP+LEFT), UP, buff = MED_LARGE_BUFF ).shift_onto_screen() self.teacher_says( "Products are a bit different", target_mode = "sassy" ) self.wait(2) self.play(RemovePiCreatureBubble( self.get_teacher(), target_mode = "raise_right_hand" )) self.play(Write(wrong_product_rule)) self.play_student_changes( "pondering", "confused", "erm", added_anims = [ not_equals.scale, 1.3, not_equals.set_color, RED ] ) self.wait() self.teacher_says( "Think about the \\\\ underlying meaning", bubble_config = {"height" : 3}, added_anims = [ wrong_product_rule.scale, 0.7, wrong_product_rule.to_corner, UP+LEFT ] ) self.play_student_changes(*["pondering"]*3) self.wait(2) class NotGraphsForProducts(GraphScene): CONFIG = { "y_max" : 25, "x_max" : 7, } def construct(self): self.setup_axes() sine_graph = self.get_graph(np.sin, color = SINE_COLOR) sine_graph.label = self.get_graph_label( sine_graph, "\\sin(x)", x_val = 3*np.pi/2, direction = DOWN ) parabola = self.get_graph( lambda x : x**2, color = X_SQUARED_COLOR ) parabola.label = self.get_graph_label( parabola, "x^2", x_val = 2.5, direction = UP+LEFT, ) product_graph = self.get_graph( lambda x : np.sin(x)*(x**2), color = PRODUCT_COLOR ) product_graph.label = self.get_graph_label( product_graph, "\\sin(x)x^2", x_val = 2.8, direction = UP+RIGHT, buff = 0 ) graphs = [sine_graph, parabola, product_graph] for graph in graphs: self.play( ShowCreation(graph), Write(graph.label, run_time = 2) ) self.wait() everything = VGroup(*[m for m in self.get_mobjects() if not m.is_subpath]) words = OldTexText("Not the best visualization") words.scale(1.5) words.shift(FRAME_Y_RADIUS*UP/2) words.add_background_rectangle() words.set_color(RED) self.play( everything.fade, Write(words) ) self.wait() class ConfusedMorty(Scene): def construct(self): morty = Mortimer() self.add(morty) self.wait() self.play(morty.change_mode, "confused") self.play(Blink(morty)) self.wait(2) class IntroduceProductAsArea(ReconfigurableScene): CONFIG = { "top_func" : np.sin, "top_func_label" : "\\sin(x)", "top_func_nudge_label" : "d(\\sin(x))", "top_func_derivative" : "\\cos(x)", "side_func" : lambda x : x**2, "side_func_label" : "x^2", "side_func_nudge_label" : "d(x^2)", "side_func_derivative" : "2x", "x_unit_to_space_unit" : 3, "box_kwargs" : { "fill_color" : YELLOW, "fill_opacity" : 0.75, "stroke_width" : 1, }, "df_box_kwargs" : { "fill_color" : GREEN, "fill_opacity" : 0.75, "stroke_width" : 0, }, "box_corner_location" : 6*LEFT+2.5*UP, "slider_center" : 3.5*RIGHT+2*DOWN, "slider_width" : 6, "slider_x_max" : 3, "x_slider_handle_height" : 0.25, "slider_handle_color" : BLUE, "default_x" : .75, "dx" : 0.1, "tiny_dx" : 0.01, } def construct(self): self.introduce_box() self.talk_though_sine() self.define_f_of_x() self.nudge_x() self.write_df() self.show_thinner_dx() self.expand_derivative() self.write_derivative_abstractly() self.write_mneumonic() def introduce_box(self): box, labels = self.box_label_group = self.get_box_label_group(self.default_x) self.x_slider = self.get_x_slider(self.default_x) self.play(Write(labels)) self.play(DrawBorderThenFill(box)) self.wait() for mob in self.x_slider: self.play(Write(mob, run_time = 1)) self.wait() for new_x in 0.5, 2, self.default_x: self.animate_x_change( new_x, run_time = 2 ) self.wait() def talk_though_sine(self): x_axis = self.x_slider[0] graph = FunctionGraph( np.sin, x_min = 0, x_max = np.pi, color = SINE_COLOR ) scale_factor = self.x_slider.get_width()/self.slider_x_max graph.scale(scale_factor) graph.move_to(x_axis.number_to_point(0), DOWN+LEFT) label = OldTex("\\sin(x)") label.set_color(SINE_COLOR) label.next_to(graph, UP) y_axis = x_axis.copy() y_axis.remove(*y_axis.numbers) v_line = Line(ORIGIN, UP, color = WHITE, stroke_width = 2) def v_line_update(v_line): x = x_axis.point_to_number(self.x_slider[1].get_top()) v_line.set_height(np.sin(x)*scale_factor) v_line.move_to(x_axis.number_to_point(x), DOWN) v_line_update(v_line) self.play( Rotate(y_axis, np.pi/2, about_point = y_axis.get_left()), Animation(x_axis) ) self.play( ShowCreation(graph), Write(label, run_time = 1) ) self.play(ShowCreation(v_line)) for x, rt in zip([0.25, np.pi/2, 3, self.default_x], [2, 4, 4, 2]): self.animate_x_change( x, run_time = rt, added_anims = [ UpdateFromFunc(v_line, v_line_update) ] ) self.wait() self.play(*it.chain( list(map(FadeOut, [y_axis, graph, label, v_line])), [Animation(x_axis)] )) self.wait() for x in 1, 0.5, self.default_x: self.animate_x_change(x) self.wait() def define_f_of_x(self): f_def = OldTex( "f(x)", "=", self.top_func_label, self.side_func_label, "=", "\\text{Area}" ) f_def.to_corner(UP+RIGHT) f_def[-1].set_color(self.box_kwargs["fill_color"]) box, labels = self.box_label_group self.play(Write(VGroup(*f_def[:-1]))) self.play(Transform( box.copy().set_fill(opacity = 0), f_def[-1], run_time = 1.5, )) self.wait() self.f_def = f_def def nudge_x(self): box, labels = self.box_label_group nudge_label_group = self.get_nudge_label_group() original_dx = self.dx self.dx = self.tiny_dx thin_df_boxes = self.get_df_boxes() self.dx = original_dx df_boxes = self.get_df_boxes() right_box, corner_box, right_box = df_boxes self.play(FocusOn(nudge_label_group)) self.play(*list(map(GrowFromCenter, nudge_label_group))) self.animate_x_change( self.default_x+self.dx, rate_func = there_and_back, run_time = 2, added_anims = [Animation(nudge_label_group)] ) self.wait() self.play( ReplacementTransform(thin_df_boxes, df_boxes), VGroup(*labels[1]).shift, right_box.get_width()*RIGHT, ) self.play( df_boxes.space_out_submobjects, 1.1, df_boxes.move_to, box, UP+LEFT, ) self.wait() self.df_boxes = df_boxes self.df_box_labels = self.get_df_box_labels(df_boxes) self.x_slider.add(nudge_label_group) def get_nudge_label_group(self): line, triangle, x_mob = self.x_slider dx_line = Line(*[ line.number_to_point(self.x_slider.x_val + num) for num in (0, self.dx,) ]) dx_line.set_stroke( self.df_box_kwargs["fill_color"], width = 6 ) brace = Brace(dx_line, UP, buff = SMALL_BUFF) brace.stretch_to_fit_height(0.2) brace.next_to(dx_line, UP, buff = SMALL_BUFF) brace.set_stroke(width = 1) dx = OldTex("dx") dx.scale(0.7) dx.next_to(brace, UP, buff = SMALL_BUFF) dx.set_color(dx_line.get_color()) return VGroup(dx_line, brace, dx) def get_df_boxes(self): box, labels = self.box_label_group alt_box = self.get_box(self.x_slider.x_val + self.dx) h, w = box.get_height(), box.get_width() dh, dw = alt_box.get_height()-h, alt_box.get_width()-w heights_and_widths = [(dh, w), (dh, dw), (h, dw)] vects = [DOWN, DOWN+RIGHT, RIGHT] df_boxes = VGroup(*[ Rectangle( height = height, width = width, **self.df_box_kwargs ).next_to(box, vect, buff = 0) for (height, width), vect in zip( heights_and_widths, vects ) ]) return df_boxes def get_df_box_labels(self, df_boxes): bottom_box, corner_box, right_box = df_boxes result = VGroup() quads = [ (right_box, UP, self.top_func_nudge_label, LEFT), (corner_box, RIGHT, self.side_func_nudge_label, ORIGIN), ] for box, vect, label_tex, aligned_edge in quads: brace = Brace(box, vect) label = OldTex(label_tex) label.next_to( brace, vect, aligned_edge = aligned_edge, buff = SMALL_BUFF ) label.set_color(df_boxes[0].get_color()) result.add(VGroup(brace, label)) return result def write_df(self): deriv = OldTex( "df", "=", self.top_func_label, self.side_func_nudge_label, "+", self.side_func_label, self.top_func_nudge_label, ) deriv.scale(0.9) deriv.next_to(self.f_def, DOWN, buff = LARGE_BUFF) deriv.to_edge(RIGHT) for submob, tex in zip(deriv, deriv.expression_parts): if tex.startswith("d"): submob.set_color(self.df_box_kwargs["fill_color"]) bottom_box_area = VGroup(*deriv[2:4]) right_box_area = VGroup(*deriv[5:7]) bottom_box, corner_box, right_box = self.df_boxes plus = OldTex("+").set_fill(opacity = 0) df_boxes_copy = VGroup( bottom_box.copy(), plus, right_box.copy(), plus.copy(), corner_box.copy(), ) self.deriv = deriv self.df_boxes_copy = df_boxes_copy box, labels = self.box_label_group self.full_box_parts = VGroup(*it.chain( [box], self.df_boxes, labels, self.df_box_labels )) self.play(Write(VGroup(*deriv[:2]))) self.play( df_boxes_copy.arrange, df_boxes_copy.set_fill, None, self.df_box_kwargs["fill_opacity"], df_boxes_copy.next_to, deriv[1] ) deriv.submobjects[4] = df_boxes_copy[1] self.wait() self.set_color_right_boxes() self.set_color_bottom_boxes() self.describe_bottom_box(bottom_box_area) self.describe_right_box(right_box_area) self.ignore_corner() # self.add(deriv) def set_color_boxes_and_label(self, boxes, label): boxes.save_state() label.save_state() self.play(GrowFromCenter(label)) self.play( boxes.set_color, RED, label.set_color, RED, ) self.play( label[1].scale, 1.1, rate_func = there_and_back ) self.play(boxes.restore, label.restore) self.wait() def set_color_right_boxes(self): self.set_color_boxes_and_label( VGroup(*self.df_boxes[1:]), self.df_box_labels[0] ) def set_color_bottom_boxes(self): self.set_color_boxes_and_label( VGroup(*self.df_boxes[:-1]), self.df_box_labels[1] ) def describe_bottom_box(self, bottom_box_area): bottom_box = self.df_boxes[0] bottom_box_copy = self.df_boxes_copy[0] other_box_copies = VGroup(*self.df_boxes_copy[1:]) top_label = self.box_label_group[1][0] right_label = self.df_box_labels[1] faders = VGroup(*[m for m in self.full_box_parts if m not in [bottom_box, top_label, right_label]]) faders.save_state() self.play(faders.fade, 0.8) self.wait() self.play(FocusOn(bottom_box_copy)) self.play( ReplacementTransform(bottom_box_copy, bottom_box_area), other_box_copies.next_to, bottom_box_area, RIGHT ) self.wait() self.play(faders.restore) def describe_right_box(self, right_box_area): right_box = self.df_boxes[2] right_box_copy = self.df_boxes_copy[2] right_box_area.next_to(self.df_boxes_copy[1]) other_box_copies = VGroup(*self.df_boxes_copy[3:]) top_label = self.df_box_labels[0] right_label = self.box_label_group[1][1] faders = VGroup(*[m for m in self.full_box_parts if m not in [right_box, top_label, right_label]]) faders.save_state() self.play(faders.fade, 0.8) self.wait() self.play(FocusOn(right_box_copy)) self.play( ReplacementTransform(right_box_copy, right_box_area), other_box_copies.next_to, right_box_area, DOWN, MED_SMALL_BUFF, RIGHT, ) self.wait() self.play(faders.restore) def ignore_corner(self): corner = self.df_boxes[1] corner.save_state() corner_copy = VGroup(*self.df_boxes_copy[-2:]) words = OldTexText("Ignore") words.set_color(RED) words.next_to(corner_copy, LEFT, buff = LARGE_BUFF) words.shift(MED_SMALL_BUFF*DOWN) arrow = Arrow(words, corner_copy, buff = SMALL_BUFF, color = RED) self.play( corner.set_color, RED, corner_copy.set_color, RED, ) self.wait() self.play(Write(words), ShowCreation(arrow)) self.wait() self.play(*list(map(FadeOut, [words, arrow, corner_copy]))) self.wait() corner_copy.set_color(BLACK) def show_thinner_dx(self): self.transition_to_alt_config(dx = self.tiny_dx) def expand_derivative(self): # self.play( # self.deriv.next_to, self.f_def, DOWN, MED_LARGE_BUFF, # self.deriv.shift_onto_screen # ) # self.wait() expanded_deriv = OldTex( "df", "=", self.top_func_label, self.side_func_derivative, "\\,dx", "+", self.side_func_label, self.top_func_derivative, "\\,dx" ) final_deriv = OldTex( "{df \\over ", "dx}", "=", self.top_func_label, self.side_func_derivative, "+", self.side_func_label, self.top_func_derivative, ) color = self.deriv[0].get_color() for new_deriv in expanded_deriv, final_deriv: for submob, tex in zip(new_deriv, new_deriv.expression_parts): for substr in "df", "dx", self.top_func_derivative, self.side_func_derivative: if substr in tex: submob.set_color(color) new_deriv.scale(0.9) new_deriv.next_to(self.deriv, DOWN, buff = MED_LARGE_BUFF) new_deriv.shift_onto_screen() def indicate(mob): self.play( mob.scale, 1.2, mob.set_color, YELLOW, rate_func = there_and_back ) for index in 6, 3: self.deriv.submobjects.insert( index+1, self.deriv[index].copy() ) non_deriv_indices = list(range(len(expanded_deriv))) for indices in [(3, 4), (7, 8)]: top_part = VGroup() bottom_part = VGroup() for i in indices: non_deriv_indices.remove(i) top_part.add(self.deriv[i].copy()) bottom_part.add(expanded_deriv[i]) self.play(top_part.move_to, bottom_part) self.wait() indicate(top_part) self.wait() self.play(ReplacementTransform(top_part, bottom_part)) self.wait() top_part = VGroup() bottom_part = VGroup() for i in non_deriv_indices: top_part.add(self.deriv[i].copy()) bottom_part.add(expanded_deriv[i]) self.play(ReplacementTransform( top_part, bottom_part )) self.wait() self.play(*[ ReplacementTransform( expanded_deriv[i], final_deriv[j], path_arc = -np.pi/2 ) for i, j in [ (0, 0), (1, 2), (2, 3), (3, 4), (4, 1), (5, 5), (6, 6), (7, 7), (8, 1), ] ]) self.wait() for index in 0, 1, 3, 4, 6, 7: indicate(final_deriv[index]) self.wait() def write_derivative_abstractly(self): self.transition_to_alt_config( return_to_original_configuration = False, top_func_label = "g(x)", top_func_nudge_label = "dg", top_func_derivative = "\\frac{dg}{dx}", side_func_label = "h(x)", side_func_nudge_label = "dh", side_func_derivative = "\\frac{dh}{dx}", ) self.wait() def write_mneumonic(self): morty = Mortimer() morty.scale(0.7) morty.to_edge(DOWN) morty.shift(2*LEFT) words = OldTexText( "``Left ", "d(Right) ", "+", " Right ", "d(Left)", "''", arg_separator = "" ) VGroup(words[1], words[4]).set_color(self.df_boxes[0].get_color()) words.scale(0.7) words.next_to(morty.get_corner(UP+LEFT), UP) words.shift_onto_screen() self.play(FadeIn(morty)) self.play( morty.change_mode, "raise_right_hand", Write(words) ) self.wait() ############### def animate_x_change( self, target_x, box_label_group = None, x_slider = None, **kwargs ): box_label_group = box_label_group or self.box_label_group x_slider = x_slider or self.x_slider kwargs["run_time"] = kwargs.get("run_time", 2) added_anims = kwargs.get("added_anims", []) start_x = x_slider.x_val def update_box_label_group(box_label_group, alpha): new_x = interpolate(start_x, target_x, alpha) new_box_label_group = self.get_box_label_group(new_x) Transform(box_label_group, new_box_label_group).update(1) def update_x_slider(x_slider, alpha): new_x = interpolate(start_x, target_x, alpha) new_x_slider = self.get_x_slider(new_x) Transform(x_slider, new_x_slider).update(1) self.play( UpdateFromAlphaFunc( box_label_group, update_box_label_group ), UpdateFromAlphaFunc( x_slider, update_x_slider ), *added_anims, **kwargs ) x_slider.x_val = target_x def get_x_slider(self, x): numbers = list(range(int(self.slider_x_max) + 1)) line = NumberLine( x_min = 0, x_max = self.slider_x_max, unit_size = float(self.slider_width)/self.slider_x_max, color = GREY, numbers_with_elongated_ticks = numbers, tick_frequency = 0.25, ) line.add_numbers(*numbers) line.numbers.next_to(line, UP, buff = SMALL_BUFF) for number in line.numbers: number.add_background_rectangle() line.move_to(self.slider_center) triangle = RegularPolygon( 3, start_angle = np.pi/2, fill_color = self.slider_handle_color, fill_opacity = 0.8, stroke_width = 0, ) triangle.set_height(self.x_slider_handle_height) triangle.move_to(line.number_to_point(x), UP) x_mob = OldTex("x") x_mob.next_to(triangle, DOWN, buff = SMALL_BUFF) result = VGroup(line, triangle, x_mob) result.x_val = x return result def get_box_label_group(self, x): box = self.get_box(x) labels = self.get_box_labels(box) return VGroup(box, labels) def get_box(self, x): box = Rectangle( width = self.x_unit_to_space_unit * self.top_func(x), height = self.x_unit_to_space_unit * self.side_func(x), **self.box_kwargs ) box.move_to(self.box_corner_location, UP+LEFT) return box def get_box_labels(self, box): result = VGroup() for label_tex, vect in (self.top_func_label, UP), (self.side_func_label, RIGHT): brace = Brace(box, vect, min_num_quads = 5) label = OldTex(label_tex) label.next_to(brace, vect, buff = SMALL_BUFF) result.add(VGroup(brace, label)) return result class WriteDXSquared(Scene): def construct(self): term = OldTex("(...)(dx)^2") term.set_color(RED) self.play(Write(term)) self.wait() class MneumonicExample(TeacherStudentsScene): def construct(self): d, left, right, rp = deriv_q = OldTex( "\\frac{d}{dx}(", "\\sin(x)", "x^2", ")" ) deriv_q.to_edge(UP) words = OldTexText( "Left ", "d(Right) ", "+", " Right ", "d(Left)", arg_separator = "" ) deriv = OldTex("\\sin(x)", "2x", "+", "x^2", "\\cos(x)") for mob in words, deriv: VGroup(mob[1], mob[4]).set_color(GREEN) mob.next_to(deriv_q, DOWN, buff = MED_LARGE_BUFF) deriv.shift(words[2].get_center()-deriv[2].get_center()) self.add(words) self.play( Write(deriv_q), self.get_teacher().change_mode, "raise_right_hand" ) self.play_student_changes(*["pondering"]*3) left_words = VGroup(*words[:2]) left_terms = VGroup(*deriv[:2]) self.play( left_words.next_to, left_terms, DOWN, MED_LARGE_BUFF, RIGHT ) self.play(ReplacementTransform( left_words.copy(), left_terms )) self.wait() self.play(*list(map(Indicate, [left, left_words[0], left_terms[0]]))) self.wait() self.play(*list(map(Indicate, [right, left_words[1], left_terms[1]]))) self.wait() right_words = VGroup(*words[2:]) right_terms = VGroup(*deriv[2:]) self.play( right_words.next_to, right_terms, DOWN, MED_LARGE_BUFF, LEFT ) self.play(ReplacementTransform( right_words.copy(), right_terms )) self.wait() self.play(*list(map(Indicate, [right, right_words[1], right_terms[1]]))) self.wait() self.play(*list(map(Indicate, [left, right_words[2], right_terms[2]]))) self.wait(3) self.play(self.get_teacher().change_mode, "shruggie") self.wait() self.play_student_changes(*["confused"]*3) self.wait(3) class ConstantMultiplication(TeacherStudentsScene): def construct(self): question = OldTexText("What about $\\dfrac{d}{dx}(2\\sin(x))$?") answer = OldTexText("2\\cos(x)") self.teacher_says(question) self.wait() self.student_says( answer, target_mode = "hooray", added_anims = [question.copy().to_edge, UP] ) self.play(self.get_teacher().change_mode, "happy") self.play_student_changes("pondering", "hooray", "pondering") self.wait(3) class ConstantMultiplicationFigure(IntroduceProductAsArea): CONFIG = { "side_func" : lambda x : 1, "side_func_label" : "\\text{Constant}", "side_func_nudge_label" : "", "side_func_derivative" : "", "x_unit_to_space_unit" : 3, "default_x" : 0.5, "dx" : 0.1 } def construct(self): self.box_label_group = self.get_box_label_group(self.default_x) self.x_slider = self.get_x_slider(self.default_x) # df_boxes = self.get_df_boxes() # df_box_labels = self.get_df_box_labels(df_boxes) self.add(self.box_label_group, self.x_slider) self.nudge_x() class ShoveXSquaredInSine(Scene): def construct(self): title = OldTexText("Function composition") title.to_edge(UP) sine = OldTex("g(", "x", ")", "=", "\\sin(", "x", ")") sine.set_color(SINE_COLOR) x_squared = OldTex("h(x)", "=", "x^2") x_squared.set_color(X_SQUARED_COLOR) group = VGroup(sine, x_squared) group.arrange(buff = LARGE_BUFF) group.shift(UP) composition = OldTex( "g(", "h(x)", ")", "=", "\\sin(", "x^2", ")" ) for i in 0, 2, 4, 6: composition[i].set_color(SINE_COLOR) for i in 1, 5: composition[i].set_color(X_SQUARED_COLOR) composition.next_to(group, DOWN, buff = LARGE_BUFF) brace = Brace(VGroup(*composition[-3:]), DOWN) deriv_q = brace.get_text("Derivative?") self.add(group) self.play(Write(title)) self.wait() triplets = [ [sine, (0, 2), (0, 2)], [x_squared, (0,), (1,)], [sine, (3, 4, 6), (3, 4, 6)], [x_squared, (2,), (5,)] ] for premob, pre_indices, comp_indicies in triplets: self.play(*[ ReplacementTransform( premob[i].copy(), composition[j] ) for i, j in zip(pre_indices, comp_indicies) ]) self.wait() self.wait() self.play( GrowFromCenter(brace), Write(deriv_q) ) self.wait() class ThreeLinesChainRule(ReconfigurableScene): CONFIG = { "start_x" : 0.5, "max_x" : 1, "min_x" : 0, "top_x" : 3, "example_x" : 1.5, "dx" : 0.1, "line_configs" : [ { "func" : lambda x : x, "func_label" : "x", "triangle_color" : WHITE, "center_y" : 3, "x_min" : 0, "x_max" : 3, "numbers_to_show" : list(range(4)), "numbers_with_elongated_ticks" : list(range(4)), "tick_frequency" : 0.25, }, { "func" : lambda x : x**2, "func_label" : "x^2", "triangle_color" : X_SQUARED_COLOR, "center_y" : 0.5, "x_min" : 0, "x_max" : 10, "numbers_to_show" : list(range(0, 11)), "numbers_with_elongated_ticks" : list(range(0, 11, 1)), "tick_frequency" : 0.25, }, { "func" : lambda x : np.sin(x**2), "func_label" : "\\sin(x^2)", "triangle_color" : SINE_COLOR, "center_y" : -2, "x_min" : -2, "x_max" : 2, "numbers_to_show" : list(range(-2, 3)), "numbers_with_elongated_ticks" : list(range(-2, 3)), "tick_frequency" : 0.25, }, ], "line_width" : 8, "triangle_height" : 0.25, } def construct(self): self.introduce_line_group() self.draw_function_arrows() self.talk_through_movement() self.nudge_x() self.give_example_of_meaning() def introduce_line_group(self): self.line_group = self.get_line_group(self.start_x) lines, labels = self.line_group for line in lines: self.play(Write(line, run_time = 2)) self.wait() last_label = labels[0].copy() last_label.to_corner(UP+LEFT) last_label.set_fill(opacity = 0) for label in labels: self.play(ReplacementTransform( last_label.copy(), label )) self.wait() last_label = label for x in self.max_x, self.min_x, self.start_x: self.animate_x_change(x, run_time = 1) self.wait() def draw_function_arrows(self): lines, line_labels = self.line_group labels = VGroup(*[ OldTex("(\\dots)^2").set_color(X_SQUARED_COLOR), OldTex("\\sin(\\dots)").set_color(SINE_COLOR) ]) arrows = VGroup() for lines_subset, label in zip([lines[:2], lines[1:]], labels): arrow = Arc(start_angle = np.pi/3, angle = -2*np.pi/3) arrow.add_tip() arrow.set_color(label.get_color()) arrow.next_to(VGroup(*lines_subset)) arrows.add(arrow) label.next_to(arrow, RIGHT) self.play( ShowCreation(arrow), Write(label) ) self.wait() self.arrows = arrows self.arrow_labels = labels def talk_through_movement(self): lines, labels = self.line_group self.animate_x_change(self.top_x, run_time = 4) self.wait() for label in labels[0], labels[1]: oval = Circle(color = YELLOW) oval.replace(label, stretch = True) oval.scale(2.5) oval.move_to(label.get_bottom()) self.play(ShowCreation(oval)) self.wait() self.play(FadeOut(oval)) sine_text = OldTex("\\sin(9) \\approx 0.412") sine_text.move_to(labels[-1][-1]) sine_text.to_edge(DOWN) sine_arrow = Arrow( sine_text.get_top(), labels[-1][0].get_bottom(), buff = SMALL_BUFF, ) self.play( FadeIn(sine_text), ShowCreation(sine_arrow) ) self.wait(2) self.play(*list(map(FadeOut, [sine_text, sine_arrow]))) self.animate_x_change(self.example_x, run_time = 3) def nudge_x(self): lines, labels = self.line_group def get_value_points(): return [ label[0].get_bottom() for label in labels ] starts = get_value_points() self.animate_x_change(self.example_x + self.dx, run_time = 0) ends = get_value_points() self.animate_x_change(self.example_x, run_time = 0) nudge_lines = VGroup() braces = VGroup() numbers = VGroup() for start, end, line, label, config in zip(starts, ends, lines, labels, self.line_configs): color = label[0].get_color() nudge_line = Line(start, end) nudge_line.set_stroke(color, width = 6) brace = Brace(nudge_line, DOWN, buff = SMALL_BUFF) brace.set_color(color) func_label = config["func_label"] if len(func_label) == 1: text = "$d%s$"%func_label else: text = "$d(%s)$"%func_label brace.text = brace.get_text(text, buff = SMALL_BUFF) brace.text.set_color(color) brace.add(brace.text) line.add(nudge_line) nudge_lines.add(nudge_line) braces.add(brace) numbers.add(line.numbers) line.remove(*line.numbers) dx_brace, dx_squared_brace, dsine_brace = braces x_value = str(self.example_x) x_value_label = OldTex("=%s"%x_value) x_value_label.next_to(labels[0][1], RIGHT) dx_squared_value = OldTex( "= 2x\\,dx ", "\\\\ = 2(%s)dx"%x_value ) dx_squared_value.shift( dx_squared_brace.text.get_right()+MED_SMALL_BUFF*RIGHT - \ dx_squared_value[0].get_left() ) dsine_value = OldTexText( "$=\\cos(%s)$"%self.line_configs[1]["func_label"], dx_squared_brace.text.get_tex() ) dsine_value.next_to(dsine_brace.text) less_than_zero = OldTex("<0") less_than_zero.next_to(dsine_brace.text) all_x_squared_relevant_labels = VGroup( dx_squared_brace, dsine_brace, labels[1], labels[2], dsine_value, ) all_x_squared_relevant_labels.save_state() self.play(FadeOut(numbers)) self.animate_x_change( self.example_x + self.dx, run_time = 1, added_anims = it.chain( [GrowFromCenter(dx_brace)], list(map(ShowCreation, nudge_lines)) ) ) self.animate_x_change(self.example_x) self.wait() self.play(Write(x_value_label)) self.wait() self.play(FocusOn(dx_squared_brace)) self.play(Write(dx_squared_brace)) self.wiggle_by_dx() self.wait() for part in dx_squared_value: self.play(Write(part)) self.wait() self.play(FadeOut(dx_squared_value)) self.wait() #Needs to be part of everything for the reconfiguraiton dsine_brace.set_fill(opacity = 0) dsine_value.set_fill(opacity = 0) self.add(dsine_brace, dsine_value) self.replace_x_squared_with_h() self.wait() self.play(dsine_brace.set_fill, None, 1) self.discuss_dsine_sign(less_than_zero) self.wait() dsine_value.set_fill(opacity = 1) self.play(Write(dsine_value)) self.wait() self.play( all_x_squared_relevant_labels.restore, lag_ratio = 0.5, run_time = 3, ) self.__dict__.update(self.__class__.CONFIG) self.wait() for mob in dsine_value: self.play(Indicate(mob)) self.wait() two_x_dx = dx_squared_value[0] dx_squared = dsine_value[1] two_x_dx_copy = VGroup(*two_x_dx[1:]).copy() self.play(FocusOn(two_x_dx)) self.play(Write(two_x_dx)) self.play( two_x_dx_copy.move_to, dx_squared, LEFT, dx_squared.next_to, dx_squared, UP, run_time = 2 ) self.play(FadeOut(dx_squared)) for sublist in two_x_dx_copy[:2], two_x_dx_copy[2:]: self.play(Indicate(VGroup(*sublist))) self.wait() self.wait(2) self.final_derivative = dsine_value def discuss_dsine_sign(self, less_than_zero): self.wiggle_by_dx() self.wait() for x in self.example_x+self.dx, self.example_x: self.animate_x_change(x, run_time = 2) self.wait() if less_than_zero not in self.get_mobjects(): self.play(Write(less_than_zero)) else: self.play(FadeOut(less_than_zero)) def replace_x_squared_with_h(self): new_config = copy.deepcopy(self.__class__.CONFIG) new_config["line_configs"][1]["func_label"] = "h" new_config["line_configs"][2]["func_label"] = "\\sin(h)" self.transition_to_alt_config( return_to_original_configuration = False, **new_config ) def give_example_of_meaning(self): words = OldTexText("For example,") expression = OldTex("\\cos(1.5^2)\\cdot 2(1.5)\\,dx") group = VGroup(words, expression) group.arrange(DOWN, aligned_edge = LEFT) group.scale(0.8) group.to_edge(RIGHT) arrow = Arrow(group.get_bottom(), self.final_derivative[0].get_top()) self.play(*list(map(FadeOut, [self.arrows, self.arrow_labels]))) self.play(FadeIn(group)) self.play(ShowCreation(arrow)) self.wait() self.wiggle_by_dx() self.wait() ######## def wiggle_by_dx(self, **kwargs): kwargs["run_time"] = kwargs.get("run_time", 1) kwargs["rate_func"] = kwargs.get("rate_func", there_and_back) target_x = self.line_group.x_val + self.dx self.animate_x_change(target_x, **kwargs) def animate_x_change(self, target_x, **kwargs): #Assume fixed lines, only update labels kwargs["run_time"] = kwargs.get("run_time", 2) added_anims = kwargs.get("added_anims", []) start_x = self.line_group.x_val def update(line_group, alpha): lines, labels = line_group new_x = interpolate(start_x, target_x, alpha) for line, label, config in zip(lines, labels, self.line_configs): new_label = self.get_line_label( line, new_x, **config ) Transform(label, new_label).update(1) line_group.x_val = new_x self.play( UpdateFromAlphaFunc(self.line_group, update), *added_anims, **kwargs ) def get_line_group(self, x): group = VGroup() group.lines, group.labels = VGroup(), VGroup() for line_config in self.line_configs: number_line = self.get_number_line(**line_config) label = self.get_line_label(number_line, x, **line_config) group.lines.add(number_line) group.labels.add(label) group.add(group.lines, group.labels) group.x_val = x return group def get_number_line( self, center_y, **number_line_config ): number_line = NumberLine(color = GREY, **number_line_config) number_line.stretch_to_fit_width(self.line_width) number_line.add_numbers() number_line.shift(center_y*UP) number_line.to_edge(LEFT, buff = LARGE_BUFF) return number_line def get_line_label( self, number_line, x, func, func_label, triangle_color, **spillover_kwargs ): triangle = RegularPolygon( n=3, start_angle = -np.pi/2, fill_color = triangle_color, fill_opacity = 0.75, stroke_width = 0, ) triangle.set_height(self.triangle_height) triangle.move_to( number_line.number_to_point(func(x)), DOWN ) label_mob = OldTex(func_label) label_mob.next_to(triangle, UP, buff = SMALL_BUFF, aligned_edge = LEFT) return VGroup(triangle, label_mob) class GeneralizeChainRule(Scene): def construct(self): example = OldTex( "\\frac{d}{dx}", "\\sin(", "x^2", ")", "=", "\\cos(", "x^2", ")", "\\,2x", ) general = OldTex( "\\frac{d}{dx}", "g(", "h(x)", ")", "=", "{dg \\over ", " dh}", "(", "h(x)", ")", "{dh \\over", " dx}", "(x)" ) example.to_edge(UP, buff = LARGE_BUFF) example.shift(RIGHT) general.next_to(example, DOWN, buff = 1.5*LARGE_BUFF) for mob in example, general: mob.set_color(SINE_COLOR) mob[0].set_color(WHITE) for tex in "x^2", "2x", "(x)", "{dh", " dx}": mob.set_color_by_tex(tex, X_SQUARED_COLOR, substring = True) example_outer = VGroup(*example[1:4]) example_inner = example[2] d_example_outer = VGroup(*example[5:8]) d_example_inner = example[6] d_example_d_inner = example[8] general_outer = VGroup(*general[1:4]) general_inner = general[2] d_general_outer = VGroup(*general[5:10]) d_general_inner = general[8] d_general_d_inner = VGroup(*general[10:13]) example_outer_brace = Brace(example_outer) example_inner_brace = Brace(example_inner, UP, buff = SMALL_BUFF) d_example_outer_brace = Brace(d_example_outer) d_example_inner_brace = Brace(d_example_inner, buff = SMALL_BUFF) d_example_d_inner_brace = Brace(d_example_d_inner, UP, buff = SMALL_BUFF) general_outer_brace = Brace(general_outer) general_inner_brace = Brace(general_inner, UP, buff = SMALL_BUFF) d_general_outer_brace = Brace(d_general_outer) d_general_inner_brace = Brace(d_general_inner, buff = SMALL_BUFF) d_general_d_inner_brace = Brace(d_general_d_inner, UP, buff = SMALL_BUFF) for brace in example_outer_brace, general_outer_brace: brace.text = brace.get_text("Outer") for brace in example_inner_brace, general_inner_brace: brace.text = brace.get_text("Inner") for brace in d_example_outer_brace, d_general_outer_brace: brace.text = brace.get_text("d(Outer)") brace.text.shift(SMALL_BUFF*LEFT) for brace in d_example_d_inner_brace, d_general_d_inner_brace: brace.text = brace.get_text("d(Inner)", buff = SMALL_BUFF) #d(out)d(in) for example self.add(example) braces = VGroup( example_outer_brace, example_inner_brace, d_example_outer_brace ) for brace in braces: self.play(GrowFromCenter(brace)) self.play(Write(brace.text, run_time = 1)) self.wait() self.wait() self.play(*it.chain(*[ [mob.scale, 1.2, mob.set_color, YELLOW] for mob in (example_inner, d_example_inner) ]), rate_func = there_and_back) self.play(Transform( example_inner.copy(), d_example_inner, path_arc = -np.pi/2, remover = True )) self.wait() self.play( GrowFromCenter(d_example_d_inner_brace), Write(d_example_d_inner_brace.text) ) self.play(Transform( VGroup(*reversed(example_inner.copy())), d_example_d_inner, path_arc = -np.pi/2, run_time = 2, remover = True )) self.wait() #Generalize self.play(*list(map(FadeIn, general[:5]))) self.wait() self.play( Transform(example_outer_brace, general_outer_brace), Transform(example_outer_brace.text, general_outer_brace.text), Transform(example_inner_brace, general_inner_brace), Transform(example_inner_brace.text, general_inner_brace.text), ) self.wait() self.play( Transform(d_example_outer_brace, d_general_outer_brace), Transform(d_example_outer_brace.text, d_general_outer_brace.text), ) self.play(Write(d_general_outer)) self.wait(2) self.play( Transform(d_example_d_inner_brace, d_general_d_inner_brace), Transform(d_example_d_inner_brace.text, d_general_d_inner_brace.text), ) self.play(Write(d_general_d_inner)) self.wait(2) #Name chain rule name = OldTexText("``Chain rule''") name.scale(1.2) name.set_color(YELLOW) name.to_corner(UP+LEFT) self.play(Write(name)) self.wait() #Point out dh bottom morty = Mortimer().flip() morty.to_corner(DOWN+LEFT) d_general_outer_copy = d_general_outer.copy() morty.set_fill(opacity = 0) self.play( morty.set_fill, None, 1, morty.change_mode, "raise_left_hand", morty.look, UP+LEFT, d_general_outer_copy.next_to, morty.get_corner(UP+LEFT), UP, MED_LARGE_BUFF, d_general_outer_copy.shift_onto_screen ) self.wait() circle = Circle(color = YELLOW) circle.replace(d_general_outer_copy[1]) circle.scale(1.4) self.play(ShowCreation(circle)) self.play(Blink(morty)) self.wait() inner = d_general_outer_copy[3] self.play( morty.change_mode, "hooray", morty.look_at, inner, inner.shift, UP ) self.play(inner.shift, DOWN) self.wait() self.play(morty.change_mode, "pondering") self.play(Blink(morty)) self.wait() self.play(*list(map(FadeOut, [ d_general_outer_copy, inner, circle ]))) #Show cancelation braces = [ d_example_d_inner_brace, d_example_outer_brace, example_inner_brace, example_outer_brace, ] texts = [brace.text for brace in braces] self.play(*list(map(FadeOut, braces+texts))) to_collapse = VGroup(VGroup(*general[7:10]), general[12]) dg_dh = VGroup(*general[5:7]) dh_dx = VGroup(*general[10:12]) to_collapse.generate_target() points = VGroup(*list(map(VectorizedPoint, [m.get_left() for m in to_collapse] ))) self.play( Transform(to_collapse, points), dh_dx.next_to, dg_dh, morty.look_at, dg_dh, ) self.wait() for mob in list(dg_dh)+list(dh_dx): circle = Circle(color = YELLOW) circle.replace(mob) circle.scale(1.3) self.play(ShowCreation(circle)) self.wait() self.play(FadeOut(circle)) strikes = VGroup() for dh in dg_dh[1], dh_dx[0]: strike = OldTex("/") strike.stretch(2, dim = 0) strike.rotate(-np.pi/12) strike.move_to(dh) strike.set_color(RED) strikes.add(strike) self.play(Write(strikes)) self.play(morty.change_mode, "hooray") equals_dg_dx = OldTex("= \\frac{dg}{dx}") equals_dg_dx.next_to(dh_dx) self.play(Write(equals_dg_dx)) self.play(Blink(morty)) self.wait(2) ##More than a notational trick self.play( PiCreatureSays(morty, """ This is more than a notational trick """), VGroup( dg_dh, dh_dx, equals_dg_dx, strikes, *general[:5] ).shift, DOWN, FadeOut(example) ) self.wait() self.play(Blink(morty)) self.wait() class WatchingVideo(PiCreatureScene): def construct(self): laptop = Laptop() laptop.scale(2) laptop.to_corner(UP+RIGHT) randy = self.get_primary_pi_creature() randy.move_to(laptop, DOWN+LEFT) randy.shift(MED_SMALL_BUFF*UP) randy.look_at(laptop.screen) formulas = VGroup(*[ OldTex("\\frac{d}{dx}\\left( %s \\right)"%s) for s in [ "e^x \\sin(x)", "\\sin(x) \\cdot \\frac{1}{\\cos(x)}", "\\cos(3x)^2", "e^x(x^2 + 3x + 2)", ] ]) formulas.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) formulas.next_to(randy, LEFT, buff = MED_LARGE_BUFF) formulas.shift_onto_screen() self.add(randy, laptop) self.wait() self.play(randy.change_mode, "erm") self.play(Blink(randy)) self.wait() self.play(randy.change_mode, "maybe") self.wait() self.play(Blink(randy)) for formula in formulas: self.play( Write(formula, run_time = 2), randy.change_mode, "thinking" ) self.wait() def create_pi_creatures(self): return [Randolph().shift(DOWN+RIGHT)] class NextVideo(TeacherStudentsScene): def construct(self): series = VideoSeries() series.to_edge(UP) next_video = series[4] pre_expression = OldTex( "x", "^2", "+", "y", "^2", "=", "1" ) d_expression = OldTex( "2", "x", "\\,dx", "+", "2", "y", "\\,dy", "=", "0" ) expression_to_d_expression_indices = [ 1, 0, 0, 2, 4, 3, 3, 5, 6 ] expression = VGroup() for i, j in enumerate(expression_to_d_expression_indices): submob = pre_expression[j].copy() if d_expression.expression_parts[i] == "2": two = OldTex("2") two.replace(submob) expression.add(two) else: expression.add(submob) for mob in expression, d_expression: mob.scale(1.2) mob.next_to( self.get_teacher().get_corner(UP+LEFT), UP, buff = MED_LARGE_BUFF ) mob.shift_onto_screen() axes = Axes(x_min = -3, x_max = 3, color = GREY) axes.add(Circle(color = YELLOW)) line = Line(np.sqrt(2)*UP, np.sqrt(2)*RIGHT) line.scale(1.5) axes.add(line) axes.scale(0.5) axes.next_to(d_expression, LEFT) self.add(series) self.play( next_video.shift, 0.5*DOWN, next_video.set_color, YELLOW, self.get_teacher().change_mode, "raise_right_hand" ) self.wait() self.play( Write(expression), *[ ApplyMethod(pi.change_mode, "pondering") for pi in self.get_students() ] ) self.play(FadeIn(axes)) self.wait() self.remove(expression) self.play(Transform(expression, d_expression, path_arc = np.pi/2)) self.wait() self.play( Rotate( line, np.pi/4, about_point = axes.get_center(), rate_func = wiggle, run_time = 3 ) ) self.wait(2) class Chapter4Thanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Ali Yahya", "Meshal Alshammari", "CrypticSwarm ", "Ankit Agarwal", "Yu Jun", "Shelby Doolittle", "Dave Nicponski", "Damion Kistler", "Juan Benet", "Othman Alikhan", "Justin Helps", "Markus Persson", "Dan Buchoff", "Derek Dai", "Joseph John Cox", "Luc Ritchie", "Nils Schneider", "Mathew Bramson", "Guido Gambardella", "Jerry Ling", "Mark Govea", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ], "patron_group_size" : 8, } class Thumbnail(IntroduceProductAsArea): CONFIG = { "default_x" : 0.8, "dx" : 0.05 } def construct(self): self.x_slider = self.get_x_slider(self.default_x) blg = self.box_label_group = self.get_box_label_group( self.default_x ) df_boxes = self.get_df_boxes() df_boxes.space_out_submobjects(1.1) df_boxes.move_to(blg[0], UP+LEFT) blg[1][1].next_to(df_boxes[-1], RIGHT) df_box_labels = self.get_df_box_labels(df_boxes) blg.add(df_boxes, df_box_labels) blg.set_height(FRAME_HEIGHT-2*MED_LARGE_BUFF) blg.center() self.add(blg)
videos_3b1b/_2017/eoc/old_chapter1.py
from manim_imports_ext import * #### Warning, scenes here not updated based on most recent GraphScene changes ####### class CircleScene(PiCreatureScene): CONFIG = { "radius" : 1.5, "stroke_color" : WHITE, "fill_color" : BLUE_E, "fill_opacity" : 0.5, "radial_line_color" : MAROON_B, "outer_ring_color" : GREEN_E, "dR" : 0.1, "dR_color" : YELLOW, "unwrapped_tip" : ORIGIN, "include_pi_creature" : False, "circle_corner" : UP+LEFT } def setup(self): self.circle = Circle( radius = self.radius, stroke_color = self.stroke_color, fill_color = self.fill_color, fill_opacity = self.fill_opacity, ) self.circle.to_corner(self.circle_corner, buff = MED_LARGE_BUFF) self.radius_line = Line( self.circle.get_center(), self.circle.get_right(), color = self.radial_line_color ) self.radius_brace = Brace(self.radius_line, buff = SMALL_BUFF) self.radius_label = self.radius_brace.get_text("$R$", buff = SMALL_BUFF) self.add( self.circle, self.radius_line, self.radius_brace, self.radius_label ) self.pi_creature = self.create_pi_creature() if self.include_pi_creature: self.add(self.pi_creature) else: self.pi_creature.set_fill(opacity = 0) def create_pi_creature(self): return Mortimer().to_corner(DOWN+RIGHT) def introduce_circle(self, added_anims = []): self.remove(self.circle) self.play( ShowCreation(self.radius_line), GrowFromCenter(self.radius_brace), Write(self.radius_label), ) self.circle.set_fill(opacity = 0) self.play( Rotate( self.radius_line, 2*np.pi-0.001, about_point = self.circle.get_center(), ), ShowCreation(self.circle), *added_anims, run_time = 2 ) self.play( self.circle.set_fill, self.fill_color, self.fill_opacity, Animation(self.radius_line), Animation(self.radius_brace), Animation(self.radius_label), ) def increase_radius(self, numerical_dr = True, run_time = 2): radius_mobs = VGroup( self.radius_line, self.radius_brace, self.radius_label ) nudge_line = Line( self.radius_line.get_right(), self.radius_line.get_right() + self.dR*RIGHT, color = self.dR_color ) nudge_arrow = Arrow( nudge_line.get_center() + 0.5*RIGHT+DOWN, nudge_line.get_center(), color = YELLOW, buff = SMALL_BUFF, tip_length = 0.2, ) if numerical_dr: nudge_label = OldTex("%.01f"%self.dR) else: nudge_label = OldTex("dr") nudge_label.set_color(self.dR_color) nudge_label.scale(0.75) nudge_label.next_to(nudge_arrow.get_start(), DOWN) radius_mobs.add(nudge_line, nudge_arrow, nudge_label) outer_ring = self.get_outer_ring() self.play( FadeIn(outer_ring), ShowCreation(nudge_line), ShowCreation(nudge_arrow), Write(nudge_label), run_time = run_time/2. ) self.wait(run_time/2.) self.nudge_line = nudge_line self.nudge_arrow = nudge_arrow self.nudge_label = nudge_label self.outer_ring = outer_ring return outer_ring def get_ring(self, radius, dR, color = GREEN): ring = Circle(radius = radius + dR).center() inner_ring = Circle(radius = radius) inner_ring.rotate(np.pi, RIGHT) ring.append_vectorized_mobject(inner_ring) ring.set_stroke(width = 0) ring.set_fill(color) ring.move_to(self.circle) ring.R = radius ring.dR = dR return ring def get_outer_ring(self): return self.get_ring( radius = self.radius, dR = self.dR, color = self.outer_ring_color ) def unwrap_ring(self, ring, **kwargs): self.unwrap_rings(ring, **kwargs) def unwrap_rings(self, *rings, **kwargs): added_anims = kwargs.get("added_anims", []) rings = VGroup(*rings) unwrapped = VGroup(*[ self.get_unwrapped(ring, **kwargs) for ring in rings ]) self.play( rings.rotate, np.pi/2, rings.next_to, unwrapped.get_bottom(), UP, run_time = 2, path_arc = np.pi/2 ) self.play( Transform(rings, unwrapped, run_time = 3), *added_anims ) def get_unwrapped(self, ring, to_edge = LEFT, **kwargs): R = ring.R R_plus_dr = ring.R + ring.dR n_anchors = ring.get_num_curves() result = VMobject() result.set_points_as_corners([ interpolate(np.pi*R_plus_dr*LEFT, np.pi*R_plus_dr*RIGHT, a) for a in np.linspace(0, 1, n_anchors/2) ]+[ interpolate(np.pi*R*RIGHT+ring.dR*UP, np.pi*R*LEFT+ring.dR*UP, a) for a in np.linspace(0, 1, n_anchors/2) ]) result.set_style_data( stroke_color = ring.get_stroke_color(), stroke_width = ring.get_stroke_width(), fill_color = ring.get_fill_color(), fill_opacity = ring.get_fill_opacity(), ) result.move_to(self.unwrapped_tip, aligned_edge = DOWN) result.shift(R_plus_dr*DOWN) result.to_edge(to_edge) return result ###################### class PatronsOnly(Scene): def construct(self): morty = Mortimer() morty.shift(2*DOWN) title = OldTexText(""" This is a draft for patrons only """) title.set_color(RED) title.scale(2) title.to_edge(UP) self.add(morty) self.play( Write(title), morty.change_mode, "wave_1" ) self.play(Blink(morty)) self.play( morty.change_mode, "pondering", morty.look_at, title ) self.play(Blink(morty)) self.wait() class Introduction(TeacherStudentsScene): def construct(self): self.show_series() self.look_to_center() self.go_through_students() self.zoom_in_on_first() def show_series(self): series = VideoSeries() series.to_edge(UP) this_video = series[0] this_video.set_color(YELLOW) this_video.save_state() this_video.set_fill(opacity = 0) this_video.center() this_video.set_height(FRAME_HEIGHT) self.this_video = this_video words = OldTexText( "Welcome to \\\\", "Essence of calculus" ) words.set_color_by_tex("Essence of calculus", YELLOW) self.remove(self.teacher) self.teacher.change_mode("happy") self.add(self.teacher) self.play( FadeIn( series, lag_ratio = 0.5, run_time = 2 ), Blink(self.get_teacher()) ) self.teacher_says(words, target_mode = "hooray") self.play( ApplyMethod(this_video.restore, run_time = 3), *[ ApplyFunction( lambda p : p.change_mode("hooray").look_at(series[1]), pi ) for pi in self.get_pi_creatures() ] ) def homotopy(x, y, z, t): alpha = (0.7*x + FRAME_X_RADIUS)/(FRAME_WIDTH) beta = squish_rate_func(smooth, alpha-0.15, alpha+0.15)(t) return (x, y - 0.3*np.sin(np.pi*beta), z) self.play( Homotopy( homotopy, series, apply_function_kwargs = {"maintain_smoothness" : False}, ), *[ ApplyMethod(pi.look_at, series[-1]) for pi in self.get_pi_creatures() ], run_time = 5 ) self.play( FadeOut(self.teacher.bubble), FadeOut(self.teacher.bubble.content), *[ ApplyMethod(pi.change_mode, "happy") for pi in self.get_pi_creatures() ] ) def look_to_center(self): anims = [] for pi in self.get_pi_creatures(): anims += [ pi.change_mode, "pondering", pi.look_at, 2*UP ] self.play(*anims) self.random_blink(6) self.play(*[ ApplyMethod(pi.change_mode, "happy") for pi in self.get_pi_creatures() ]) def go_through_students(self): pi1, pi2, pi3 = self.get_students() for pi in pi1, pi2, pi3: pi.save_state() bubble = pi1.get_bubble(width = 5) bubble.set_fill(BLACK, opacity = 1) remembered_symbols = VGroup( OldTex("\\int_0^1 \\frac{1}{1-x^2}\\,dx").shift(UP+LEFT), OldTex("\\frac{d}{dx} e^x = e^x").shift(DOWN+RIGHT), ) cant_wait = OldTexText("I literally \\\\ can't wait") big_derivative = OldTex(""" \\frac{d}{dx} \\left( \\sin(x^2)2^{\\sqrt{x}} \\right) """) self.play( pi1.change_mode, "confused", pi1.look_at, bubble.get_right(), ShowCreation(bubble), pi2.fade, pi3.fade, ) bubble.add_content(remembered_symbols) self.play(Write(remembered_symbols)) self.play(ApplyMethod( remembered_symbols.fade, 0.7, lag_ratio = 0.5, run_time = 3 )) self.play( pi1.restore, pi1.fade, pi2.restore, pi2.change_mode, "hooray", pi2.look_at, bubble.get_right(), bubble.pin_to, pi2, FadeOut(remembered_symbols), ) bubble.add_content(cant_wait) self.play(Write(cant_wait, run_time = 2)) self.play(Blink(pi2)) self.play( pi2.restore, pi2.fade, pi3.restore, pi3.change_mode, "pleading", pi3.look_at, bubble.get_right(), bubble.pin_to, pi3, FadeOut(cant_wait) ) bubble.add_content(big_derivative) self.play(Write(big_derivative)) self.play(Blink(pi3)) self.wait() def zoom_in_on_first(self): this_video = self.this_video self.remove(this_video) this_video.generate_target() this_video.target.set_height(FRAME_HEIGHT) this_video.target.center() this_video.target.set_fill(opacity = 0) everything = VGroup(*self.get_mobjects()) self.play( FadeOut(everything), MoveToTarget(this_video, run_time = 2) ) class IntroduceCircle(Scene): def construct(self): circle = Circle(radius = 3, color = WHITE) circle.to_edge(LEFT) radius = Line(circle.get_center(), circle.get_right()) radius.set_color(MAROON_B) R = OldTex("R").next_to(radius, UP) area, circumference = words = VGroup(*list(map(TexText, [ "Area =", "Circumference =" ]))) area.set_color(BLUE) circumference.set_color(YELLOW) words.arrange(DOWN, aligned_edge = LEFT) words.next_to(circle, RIGHT) words.to_edge(UP) pi_R, pre_squared = OldTex("\\pi R", "{}^2") squared = OldTex("2").replace(pre_squared) area_form = VGroup(pi_R, squared) area_form.next_to(area, RIGHT) two, pi_R = OldTex("2", "\\pi R") circum_form = VGroup(pi_R, two) circum_form.next_to(circumference, RIGHT) derivative = OldTex( "\\frac{d}{dR}", "\\pi R^2", "=", "2\\pi R" ) integral = OldTex( "\\int_0^R", "2\\pi r", "\\, dR = ", "\\pi R^2" ) up_down_arrow = OldTex("\\Updownarrow") calc_stuffs = VGroup(derivative, up_down_arrow, integral) calc_stuffs.arrange(DOWN) calc_stuffs.next_to(words, DOWN, buff = LARGE_BUFF, aligned_edge = LEFT) brace = Brace(calc_stuffs, RIGHT) to_be_explained = brace.get_text("To be \\\\ explained") VGroup(brace, to_be_explained).set_color(GREEN) self.play(ShowCreation(radius), Write(R)) self.play( Rotate(radius, 2*np.pi, about_point = circle.get_center()), ShowCreation(circle) ) self.play( FadeIn(area), Write(area_form), circle.set_fill, area.get_color(), 0.5, Animation(radius), Animation(R), ) self.wait() self.play( circle.set_stroke, circumference.get_color(), FadeIn(circumference), Animation(radius), Animation(R), ) self.play(Transform( area_form.copy(), circum_form, path_arc = -np.pi/2, run_time = 3 )) self.wait() self.play( area_form.copy().replace, derivative[1], circum_form.copy().replace, derivative[3], Write(derivative[0]), Write(derivative[2]), run_time = 1 ) self.wait() self.play( area_form.copy().replace, integral[3], Transform(circum_form.copy(), integral[1]), Write(integral[0]), Write(integral[2]), run_time = 1 ) self.wait() self.play(Write(up_down_arrow)) self.wait() self.play( GrowFromCenter(brace), Write(to_be_explained) ) self.wait() class HeartOfCalculus(GraphScene): CONFIG = { "x_labeled_nums" : [], "y_labeled_nums" : [], } def construct(self): self.setup_axes() self.graph_function(lambda x : 3*np.sin(x/2) + x) rect_sets = [ self.get_riemann_rectangles( 0, self.x_max, 1./(2**n), stroke_width = 1./(n+1) ) for n in range(6) ] rects = rect_sets.pop(0) rects.save_state() rects.stretch_to_fit_height(0) rects.shift( (self.graph_origin[1] - rects.get_center()[1])*UP ) self.play( rects.restore, lag_ratio = 0.5, run_time = 3 ) while rect_sets: self.play( Transform(rects, rect_sets.pop(0)), run_time = 2 ) class PragmatismToArt(Scene): def construct(self): morty = Mortimer() morty.to_corner(DOWN+RIGHT) morty.shift(LEFT) pragmatism = OldTexText("Pragmatism") art = OldTexText("Art") pragmatism.move_to(morty.get_corner(UP+LEFT), aligned_edge = DOWN) art.move_to(morty.get_corner(UP+RIGHT), aligned_edge = DOWN) art.shift(0.2*(LEFT+UP)) circle1 = Circle( radius = 2, fill_opacity = 1, fill_color = BLUE_E, stroke_width = 0, ) circle2 = Circle( radius = 2, stroke_color = YELLOW ) arrow = DoubleArrow(LEFT, RIGHT, color = WHITE) circle_group = VGroup(circle1, arrow, circle2) circle_group.arrange() circle_group.to_corner(UP+LEFT) circle2.save_state() circle2.move_to(circle1) q_marks = OldTexText("???").next_to(arrow, UP) self.play( morty.change_mode, "raise_right_hand", morty.look_at, pragmatism, Write(pragmatism, run_time = 1), ) self.play(Blink(morty)) self.play( morty.change_mode, "raise_left_hand", morty.look_at, art, Transform( VectorizedPoint(morty.get_corner(UP+RIGHT)), art ), pragmatism.fade, 0.7, pragmatism.rotate, np.pi/4, pragmatism.shift, DOWN+LEFT ) self.play(Blink(morty)) self.play( GrowFromCenter(circle1), morty.look_at, circle1 ) self.play(ShowCreation(circle2)) self.play( ShowCreation(arrow), Write(q_marks), circle2.restore ) self.play(Blink(morty)) class IntroduceTinyChangeInArea(CircleScene): CONFIG = { "include_pi_creature" : True, } def construct(self): new_area_form, minus, area_form = expression = OldTex( "\\pi (R + 0.1)^2", "-", "\\pi R^2" ) VGroup(*new_area_form[4:7]).set_color(self.dR_color) expression_brace = Brace(expression, UP) change_in_area = expression_brace.get_text("Change in area") change_in_area.set_color(self.outer_ring_color) area_brace = Brace(area_form) area_word = area_brace.get_text("Area") area_word.set_color(BLUE) new_area_brace = Brace(new_area_form) new_area_word = new_area_brace.get_text("New area") group = VGroup( expression, expression_brace, change_in_area, area_brace, area_word, new_area_brace, new_area_word ) group.to_edge(UP).shift(RIGHT) group.save_state() area_group = VGroup(area_form, area_brace, area_word) area_group.save_state() area_group.next_to(self.circle, RIGHT, buff = LARGE_BUFF) self.introduce_circle( added_anims = [self.pi_creature.change_mode, "speaking"] ) self.play(Write(area_group)) self.change_mode("happy") outer_ring = self.increase_radius() self.wait() self.play( area_group.restore, GrowFromCenter(expression_brace), Write(new_area_form), Write(minus), Write(change_in_area), self.pi_creature.change_mode, "confused", ) self.play( Write(new_area_word), GrowFromCenter(new_area_brace) ) self.wait(2) self.play( group.fade, 0.7, self.pi_creature.change_mode, "happy" ) self.wait() self.play( outer_ring.set_color, YELLOW, Animation(self.nudge_arrow), Animation(self.nudge_line), rate_func = there_and_back ) self.show_unwrapping(outer_ring) self.play(group.restore) self.work_out_expression(group) self.second_unwrapping(outer_ring) insignificant = OldTexText("Insignificant") insignificant.set_color(self.dR_color) insignificant.move_to(self.error_words) self.play(Transform(self.error_words, insignificant)) self.wait() big_rect = Rectangle( width = FRAME_WIDTH, height = FRAME_HEIGHT, fill_color = BLACK, fill_opacity = 0.85, stroke_width = 0, ) self.play( FadeIn(big_rect), area_form.set_color, BLUE, self.two_pi_R.set_color, GREEN, self.pi_creature.change_mode, "happy" ) def show_unwrapping(self, outer_ring): almost_rect = outer_ring.copy() self.unwrap_ring( almost_rect, added_anims = [self.pi_creature.change_mode, "pondering"] ) circum_brace = Brace(almost_rect, UP).scale(0.95) dR_brace = OldTex("\\}") dR_brace.stretch(0.5, 1) dR_brace.next_to(almost_rect, RIGHT) two_pi_R = circum_brace.get_text("$2\\pi R$") dR = OldTex("$0.1$").scale(0.7).next_to(dR_brace, RIGHT) dR.set_color(self.dR_color) two_pi_R.generate_target() dR.generate_target() lp, rp = OldTex("()") change_in_area = OldTexText( "Change in area $\\approx$" ) final_area = VGroup( change_in_area, two_pi_R.target, lp, dR.target.scale(1./0.7), rp ) final_area.arrange(RIGHT, buff = SMALL_BUFF) final_area.next_to(almost_rect, DOWN, buff = MED_LARGE_BUFF) final_area.set_color(GREEN_A) final_area[3].set_color(self.dR_color) change_in_area.shift(0.1*LEFT) self.play( GrowFromCenter(circum_brace), Write(two_pi_R) ) self.wait() self.play( GrowFromCenter(dR_brace), Write(dR) ) self.wait() self.play( MoveToTarget(two_pi_R.copy()), MoveToTarget(dR.copy()), Write(change_in_area, run_time = 1), Write(lp), Write(rp), ) self.remove(*self.get_mobjects_from_last_animation()) self.add(final_area) self.play( self.pi_creature.change_mode, "happy", self.pi_creature.look_at, final_area ) self.wait() group = VGroup( almost_rect, final_area, two_pi_R, dR, circum_brace, dR_brace ) self.play(group.fade) def work_out_expression(self, expression_group): exp, exp_brace, title, area_brace, area_word, new_area_brace, new_area_word = expression_group new_area_form, minus, area_form = exp expanded = OldTex( "\\pi R^2", "+", "2\\pi R (0.1)", "+", "\\pi (0.1)^2", "-", "\\pi R^2", ) pi_R_squared, plus, two_pi_R_dR, plus2, pi_dR_squared, minus2, pi_R_squared2 = expanded for subset in two_pi_R_dR[4:7], pi_dR_squared[2:5]: VGroup(*subset).set_color(self.dR_color) expanded.next_to(new_area_form, DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) expanded.shift(LEFT/2.) faders = [area_brace, area_word, new_area_brace, new_area_word] self.play(*list(map(FadeOut, faders))) trips = [ ([0, 2, 8], pi_R_squared, plus), ([8, 0, 2, 1, 4, 5, 6, 7], two_pi_R_dR, plus2), ([0, 1, 4, 5, 6, 7, 8], pi_dR_squared, VGroup()), ] to_remove = [] for subset, target, writer in trips: starter = VGroup( *np.array(list(new_area_form.copy()))[subset] ) self.play( Transform(starter, target, run_time = 2), Write(writer) ) to_remove += self.get_mobjects_from_last_animation() self.wait() self.play( Transform(minus.copy(), minus2), Transform(area_form.copy(), pi_R_squared2), ) to_remove += self.get_mobjects_from_last_animation() self.remove(*to_remove) self.add(self.pi_creature, *expanded) self.wait(2) self.play(*[ ApplyMethod(mob.set_color, RED) for mob in (pi_R_squared, pi_R_squared2) ]) self.wait() self.play(*[ ApplyMethod(mob.fade, 0.7) for mob in (plus, pi_R_squared, pi_R_squared2, minus2) ]) self.wait() approx_brace = Brace(two_pi_R_dR) error_brace = Brace(pi_dR_squared, buff = SMALL_BUFF) error_words = error_brace.get_text("Error", buff = SMALL_BUFF) error_words.set_color(RED) self.error_words = error_words self.play( GrowFromCenter(approx_brace), self.pi_creature.change_mode, "hooray" ) self.wait() self.play( GrowFromCenter(error_brace), Write(error_words), self.pi_creature.change_mode, "confused" ) self.wait() self.two_pi_R = VGroup(*two_pi_R_dR[:3]) def second_unwrapping(self, outer_ring): almost_rect = outer_ring.copy() rect = Rectangle( width = 2*np.pi*self.radius, height = self.dR, fill_color = self.outer_ring_color, fill_opacity = 1, stroke_width = 0, ) self.play( almost_rect.set_color, YELLOW, self.pi_creature.change_mode, "pondering" ) self.unwrap_ring(almost_rect) self.wait() rect.move_to(almost_rect) self.play(FadeIn(rect)) self.wait() def create_pi_creature(self): morty = Mortimer() morty.scale(0.7) morty.to_corner(DOWN+RIGHT) return morty class CleanUpABit(TeacherStudentsScene): def construct(self): self.teacher_says(""" Let's clean that up a bit """) self.random_blink(2) class BuildToDADR(CircleScene): CONFIG = { "include_pi_creature" : True, } def construct(self): self.outer_ring = self.increase_radius() self.write_initial_terms() self.show_fractions() self.transition_to_dR() self.elaborate_on_d() self.not_infinitely_small() def create_pi_creature(self): morty = Mortimer() morty.flip() morty.to_corner(DOWN+LEFT) return morty def write_initial_terms(self): change = OldTexText("Change in area") change.set_color(GREEN_B) equals, two_pi_R, dR, plus, pi, dR2, squared = rhs = OldTex( "=", "2 \\pi R", "(0.1)", "+", "\\pi", "(0.1)", "^2" ) VGroup(dR, dR2).set_color(self.dR_color) change.next_to(self.circle, buff = LARGE_BUFF) rhs.next_to(change) circum_brace = Brace(two_pi_R, UP) circum_text = circum_brace.get_text("Circumference") error_brace = Brace(VGroup(pi, squared), UP) error_text = error_brace.get_text("Error") error_text.set_color(RED) self.play( Write(change, run_time = 1), self.pi_creature.change_mode, "pondering", ) self.wait() self.play(*it.chain( list(map(Write, [equals, two_pi_R, dR])), list(map(FadeIn, [circum_text, circum_brace])) )) self.wait() self.play(*it.chain( list(map(Write, [plus, pi, dR2, squared])), list(map(FadeIn, [error_brace, error_text])) )) self.wait(2) self.change = change self.circum_term = VGroup(two_pi_R, dR) self.circum_term.label = VGroup(circum_brace, circum_text) self.error_term = VGroup(pi, dR2, squared) self.error_term.label = VGroup(error_brace, error_text) self.equals = equals self.plus = plus def show_fractions(self): terms = [self.change, self.circum_term, self.error_term] for term in terms: term.frac_line = OldTex("\\frac{\\quad}{\\quad}") term.frac_line.stretch_to_fit_width(term.get_width()) term.frac_line.next_to(term, DOWN, buff = SMALL_BUFF) term.denom = OldTex("(0.1)") term.denom.next_to(term.frac_line, DOWN, buff = SMALL_BUFF) term.denom.set_color(self.dR_color) term.denom.save_state() term.denom.replace(self.nudge_label) self.equals.generate_target() self.equals.target.next_to(self.change.frac_line, RIGHT) self.plus.generate_target() self.plus.target.next_to(self.circum_term.frac_line, RIGHT) self.play(*it.chain( [Write(term.frac_line) for term in terms], list(map(MoveToTarget, [self.equals, self.plus])) )) self.play(*[term.denom.restore for term in terms]) self.wait(2) self.play( self.outer_ring.set_color, YELLOW, rate_func = there_and_back ) self.play( self.nudge_label.scale, 2, rate_func = there_and_back ) self.wait(2) canceleres = VGroup(self.circum_term[1], self.circum_term.denom) self.play(canceleres.set_color, RED) self.play(FadeOut(canceleres)) self.remove(self.circum_term) self.play( self.circum_term[0].move_to, self.circum_term.frac_line, LEFT, self.circum_term[0].shift, 0.1*UP, FadeOut(self.circum_term.frac_line), MaintainPositionRelativeTo( self.circum_term.label, self.circum_term[0] ) ) self.circum_term = self.circum_term[0] self.wait(2) self.play( FadeOut(self.error_term[-1]), FadeOut(self.error_term.denom) ) self.error_term.remove(self.error_term[-1]) self.play( self.error_term.move_to, self.error_term.frac_line, self.error_term.shift, 0.3*LEFT + 0.15*UP, FadeOut(self.error_term.frac_line), self.plus.shift, 0.7*LEFT + 0.1*UP, MaintainPositionRelativeTo( self.error_term.label, self.error_term ) ) self.wait() def transition_to_dR(self): dRs = VGroup( self.nudge_label, self.change.denom, self.error_term[1], ) error_brace, error_text = self.error_term.label for s, width in ("(0.01)", 0.05), ("(0.001)", 0.03), ("dR", 0.03): new_dRs = VGroup(*[ OldTex(s).move_to(mob, LEFT) for mob in dRs ]) new_dRs.set_color(self.dR_color) new_outer_ring = self.get_ring(self.radius, width) new_nudge_line = self.nudge_line.copy() new_nudge_line.set_width(width) new_nudge_line.move_to(self.nudge_line, LEFT) error_brace.target = error_brace.copy() error_brace.target.stretch_to_fit_width( VGroup(self.error_term[0], new_dRs[-1]).get_width() ) error_brace.target.move_to(error_brace, LEFT) self.play( MoveToTarget(error_brace), Transform(self.outer_ring, new_outer_ring), Transform(self.nudge_line, new_nudge_line), *[ Transform(*pair) for pair in zip(dRs, new_dRs) ] ) self.wait() if s == "(0.001)": self.plus.generate_target() self.plus.target.next_to(self.circum_term) self.error_term.generate_target() self.error_term.target.next_to(self.plus.target) error_brace.target = Brace(self.error_term.target) error_text.target = error_brace.target.get_text("Truly tiny") error_text.target.set_color(error_text.get_color()) self.play(*list(map(MoveToTarget, [ error_brace, error_text, self.plus, self.error_term ]))) self.wait() difference_text = OldTexText( "``Tiny " , "d", "ifference in ", "$R$", "''", arg_separator = "" ) difference_text.set_color_by_tex("d", self.dR_color) difference_text.next_to(self.pi_creature, UP+RIGHT) difference_arrow = Arrow(difference_text, self.change.denom) self.play( Write(difference_text, run_time = 2), ShowCreation(difference_arrow), self.pi_creature.change_mode, "speaking" ) self.wait() dA = OldTex("dA") dA.set_color(self.change.get_color()) frac_line = self.change.frac_line frac_line.generate_target() frac_line.target.stretch_to_fit_width(dA.get_width()) frac_line.target.next_to(self.equals, LEFT) dA.next_to(frac_line.target, UP, 2*SMALL_BUFF) self.change.denom.generate_target() self.change.denom.target.next_to(frac_line.target, DOWN, 2*SMALL_BUFF) A = OldTex("A").replace(difference_text[3]) difference_arrow.target = Arrow(difference_text, dA.get_left()) self.play( Transform(self.change, dA), MoveToTarget(frac_line), MoveToTarget(self.change.denom), Transform(difference_text[3], A), difference_text[1].set_color, dA.get_color(), MoveToTarget(difference_arrow), ) self.wait(2) self.play(*list(map(FadeOut, [difference_text, difference_arrow]))) def elaborate_on_d(self): arc = Arc(-np.pi, start_angle = -np.pi/2) arc.set_height( self.change.get_center()[1]-self.change.denom.get_center()[1] ) arc.next_to(self.change.frac_line, LEFT) arc.add_tip() self.play( ShowCreation(arc), self.pi_creature.change_mode, "sassy" ) self.wait() self.play(self.pi_creature.shrug) self.play(FadeOut(arc)) self.wait() d = OldTexText("``$d$''") arrow = OldTex("\\Rightarrow") arrow.next_to(d) ignore_error = OldTexText("Ignore error") d_group = VGroup(d, arrow, ignore_error) d_group.arrange() d_group.next_to( self.pi_creature.get_corner(UP+RIGHT), buff = LARGE_BUFF ) error_group = VGroup( self.plus, self.error_term, self.error_term.label ) self.play( Write(d), self.pi_creature.change_mode, "speaking" ) self.play(*list(map(Write, [arrow, ignore_error]))) self.play(error_group.fade, 0.8) self.wait(2) equality_brace = Brace(VGroup(self.change.denom, self.circum_term)) equal_word = equality_brace.get_text("Equality") VGroup(equality_brace, equal_word).set_color(BLUE) self.play( GrowFromCenter(equality_brace), Write(equal_word, run_time = 1) ) self.wait(2) self.play(*list(map(FadeOut, [equality_brace, equal_word]))) less_wrong_philosophy = OldTexText("``Less wrong'' philosophy") less_wrong_philosophy.move_to(ignore_error, LEFT) self.play(Transform(ignore_error, less_wrong_philosophy)) self.wait() big_dR = 0.3 big_outer_ring = self.get_ring(self.radius, big_dR) big_nudge_line = self.nudge_line.copy() big_nudge_line.stretch_to_fit_width(big_dR) big_nudge_line.move_to(self.nudge_line, LEFT) new_nudge_arrow = Arrow(self.nudge_label, big_nudge_line, buff = SMALL_BUFF) self.outer_ring.save_state() self.nudge_line.save_state() self.nudge_arrow.save_state() self.play( Transform(self.outer_ring, big_outer_ring), Transform(self.nudge_line, big_nudge_line), Transform(self.nudge_arrow, new_nudge_arrow), ) self.play( *[ mob.restore for mob in [ self.outer_ring, self.nudge_line, self.nudge_arrow, ] ], rate_func=linear, run_time = 7 ) self.play(self.pi_creature.change_mode, "hooray") self.less_wrong_philosophy = VGroup( d, arrow, ignore_error ) def not_infinitely_small(self): randy = Randolph().flip() randy.scale(0.7) randy.to_corner(DOWN+RIGHT) bubble = SpeechBubble() bubble.write("$dR$ is infinitely small") bubble.resize_to_content() bubble.stretch(0.7, 1) bubble.pin_to(randy) bubble.set_fill(BLACK, opacity = 1) bubble.add_content(bubble.content) self.play(FadeIn(randy)) self.play( randy.change_mode, "speaking", ShowCreation(bubble), Write(bubble.content), self.pi_creature.change_mode, "confused" ) self.wait() to_infs = [self.change, self.change.denom, self.nudge_label] for mob in to_infs: mob.save_state() mob.inf = OldTex("1/\\infty") mob.inf.set_color(mob.get_color()) mob.inf.move_to(mob) self.play(*[ Transform(mob, mob.inf) for mob in to_infs ]) self.wait() self.play(self.pi_creature.change_mode, "pleading") self.wait() self.play(*it.chain( [mob.restore for mob in to_infs], list(map(FadeOut, [bubble, bubble.content])), [randy.change_mode, "erm"], [self.pi_creature.change_mode, "happy"], )) for n in range(7): target = OldTex("0.%s1"%("0"*n)) target.set_color(self.nudge_label.get_color()) target.move_to(self.nudge_label, LEFT) self.outer_ring.target = self.get_ring(self.radius, 0.1/(n+1)) self.nudge_line.get_center = self.nudge_line.get_left self.play( Transform(self.nudge_label, target), MoveToTarget(self.outer_ring), self.nudge_line.stretch_to_fit_width, 0.1/(n+1) ) self.wait() bubble.write("Wrong!") bubble.resize_to_content() bubble.stretch(0.7, 1) bubble.pin_to(randy) bubble.add_content(bubble.content) self.play( FadeIn(bubble), Write(bubble.content, run_time = 1), randy.change_mode, "angry", ) self.play(randy.set_color, RED) self.play(self.pi_creature.change_mode, "guilty") self.wait() new_bubble = self.pi_creature.get_bubble(SpeechBubble) new_bubble.set_fill(BLACK, opacity = 0.8) new_bubble.write("But it gets \\\\ less wrong!") new_bubble.resize_to_content() new_bubble.pin_to(self.pi_creature) self.play( FadeOut(bubble), FadeOut(bubble.content), ShowCreation(new_bubble), Write(new_bubble.content), randy.change_mode, "erm", randy.set_color, BLUE_E, self.pi_creature.change_mode, "shruggie" ) self.wait(2) class NameDerivative(IntroduceTinyChangeInArea): def construct(self): self.increase_radius(run_time = 0) self.change_nudge_label() self.name_derivative_for_cricle() self.interpret_geometrically() self.show_limiting_process() self.reference_approximation() self.emphasize_equality() def change_nudge_label(self): new_label = OldTex("dR") new_label.move_to(self.nudge_label) new_label.to_edge(UP) new_label.set_color(self.nudge_label.get_color()) new_arrow = Arrow(new_label, self.nudge_line) self.remove(self.nudge_label, self.nudge_arrow) self.nudge_label = new_label self.nudge_arrow = new_arrow self.add(self.nudge_label, self.nudge_arrow) self.wait() def name_derivative_for_cricle(self): dA_dR, equals, d_formula_dR, equals2, two_pi_R = dArea_fom = OldTex( "\\frac{dA}{dR}", "=", "\\frac{d(\\pi R^2)}{dR}", "=", "2\\pi R" ) dArea_fom.to_edge(UP, buff = MED_LARGE_BUFF).shift(RIGHT) dA, frac_line, dR = VGroup(*dA_dR[:2]), dA_dR[2], VGroup(*dA_dR[3:]) dA.set_color(GREEN_B) dR.set_color(self.dR_color) VGroup(*d_formula_dR[7:]).set_color(self.dR_color) dA_dR_circle = Circle() dA_dR_circle.replace(dA_dR, stretch = True) dA_dR_circle.scale(1.5) dA_dR_circle.set_color(BLUE) words = OldTexText( "``Derivative'' of $A$\\\\", "with respect to $R$" ) words.next_to(dA_dR_circle, DOWN, buff = 1.5*LARGE_BUFF) words.shift(0.5*LEFT) arrow = Arrow(words, dA_dR_circle) arrow.set_color(dA_dR_circle.get_color()) self.play(Transform(self.outer_ring.copy(), dA, run_time = 2)) self.play( Transform(self.nudge_line.copy(), dR, run_time = 2), Write(frac_line) ) self.wait() self.play( ShowCreation(dA_dR_circle), ShowCreation(arrow), Write(words) ) self.wait() self.play(Write(VGroup(equals, d_formula_dR))) self.wait() self.play(Write(VGroup(equals2, two_pi_R))) self.wait() self.dArea_fom = dArea_fom self.words = words self.two_pi_R = two_pi_R def interpret_geometrically(self): target_formula = OldTex( "\\frac{d \\quad}{dR} = " ) VGroup(*target_formula[2:4]).set_color(self.dR_color) target_formula.scale(1.3) target_formula.next_to(self.dArea_fom, DOWN) target_formula.shift(2*RIGHT + 0.5*DOWN) area_form = VGroup(*self.dArea_fom[2][2:5]).copy() area_form.set_color(BLUE_D) circum_form = self.dArea_fom[-1] circle_width = 1 area_circle = self.circle.copy() area_circle.set_stroke(width = 0) area_circle.generate_target() area_circle.target.set_width(circle_width) area_circle.target.next_to(target_formula[0], RIGHT, buff = 0) area_circle.target.set_color(BLUE_D) circum_circle = self.circle.copy() circum_circle.set_fill(opacity = 0) circum_circle.generate_target() circum_circle.target.set_width(circle_width) circum_circle.target.next_to(target_formula) self.play( Write(target_formula), MoveToTarget(area_circle), MoveToTarget( circum_circle, run_time = 2, rate_func = squish_rate_func(smooth, 0.5, 1) ), self.pi_creature.change_mode, "hooray" ) self.wait() self.play(Transform(area_circle.copy(), area_form)) self.remove(area_form) self.play(Transform(circum_circle.copy(), circum_form)) self.change_mode("happy") def show_limiting_process(self): big_dR = 0.3 small_dR = 0.01 big_ring = self.get_ring(self.radius, big_dR) small_ring = self.get_ring(self.radius, small_dR) big_nudge_line = self.nudge_line.copy().set_width(big_dR) small_nudge_line = self.nudge_line.copy().set_width(small_dR) for line in big_nudge_line, small_nudge_line: line.move_to(self.nudge_line, LEFT) new_nudge_arrow = Arrow(self.nudge_label, big_nudge_line) small_nudge_arrow = Arrow(self.nudge_label, small_nudge_line) ring_group = VGroup(self.outer_ring, self.nudge_line, self.nudge_arrow) ring_group.save_state() big_group = VGroup(big_ring, big_nudge_line, new_nudge_arrow) small_group = VGroup(small_ring, small_nudge_line, small_nudge_arrow) fracs = VGroup() sample_dRs = [0.3, 0.1, 0.01] for dR in sample_dRs: dA = 2*np.pi*dR + np.pi*(dR**2) frac = OldTex("\\frac{%.3f}{%.2f}"%(dA, dR)) VGroup(*frac[:5]).set_color(self.outer_ring.get_color()) VGroup(*frac[6:]).set_color(self.dR_color) fracs.add(frac) fracs.add(OldTex("\\cdots \\rightarrow")) fracs.add(OldTex("???")) fracs[-1].set_color_by_gradient(self.dR_color, self.outer_ring.get_color()) fracs.arrange(RIGHT, buff = MED_LARGE_BUFF) fracs.to_corner(DOWN+LEFT) arrows = VGroup() for frac in fracs[:len(sample_dRs)] + [fracs[-1]]: arrow = Arrow(self.words.get_bottom(), frac.get_top()) arrow.set_color(WHITE) if frac is fracs[-1]: check = OldTex("\\checkmark") check.set_color(GREEN) check.next_to(arrow.get_center(), UP+RIGHT, SMALL_BUFF) arrow.add(check) else: cross = OldTex("\\times") cross.set_color(RED) cross.move_to(arrow.get_center()) cross.set_stroke(RED, width = 5) arrow.add(cross) arrows.add(arrow) self.play( Transform(ring_group, big_group), self.pi_creature.change_mode, "sassy" ) for n, frac in enumerate(fracs): anims = [FadeIn(frac)] num_fracs = len(sample_dRs) if n < num_fracs: anims.append(ShowCreation(arrows[n])) anims.append(Transform( ring_group, small_group, rate_func = lambda t : t*(1./(num_fracs-n)), run_time = 2 )) elif n > num_fracs: anims.append(ShowCreation(arrows[-1])) self.play(*anims) self.wait(2) self.play( FadeOut(arrows), ring_group.restore, self.pi_creature.change_mode, "happy", ) self.wait() def reference_approximation(self): ring_copy = self.outer_ring.copy() self.unwrap_ring(ring_copy) self.wait() self.last_mover = ring_copy def emphasize_equality(self): equals = self.dArea_fom[-2] self.play(Transform(self.last_mover, equals)) self.remove(self.last_mover) self.play( equals.scale, 1.5, equals.set_color, GREEN, rate_func = there_and_back, run_time = 2 ) self.play( self.two_pi_R.set_stroke, YELLOW, 3, rate_func = there_and_back, run_time = 2 ) self.wait() new_words = OldTexText( "Systematically\\\\", "ignore error" ) new_words.move_to(self.words) self.play(Transform(self.words, new_words)) self.wait() class DerivativeAsTangentLine(ZoomedScene): CONFIG = { "zoomed_canvas_frame_shape" : (4, 4), "zoom_factor" : 10, "R_min" : 0, "R_max" : 2.5, "R_to_zoom_in_on" : 2, "little_rect_nudge" : 0.075*(UP+RIGHT), } def construct(self): self.setup_axes() self.show_zoomed_in_steps() self.show_tangent_lines() self.state_commonality() def setup_axes(self): x_axis = NumberLine( x_min = -0.25, x_max = 4, unit_size = 2, tick_frequency = 0.25, leftmost_tick = -0.25, numbers_with_elongated_ticks = [0, 1, 2, 3, 4], color = GREY ) x_axis.shift(2.5*DOWN) x_axis.shift(4*LEFT) x_axis.add_numbers(1, 2, 3, 4) x_label = OldTex("R") x_label.next_to(x_axis, RIGHT+UP, buff = SMALL_BUFF) self.x_axis_label = x_label y_axis = NumberLine( x_min = -2, x_max = 20, unit_size = 0.3, tick_frequency = 2.5, leftmost_tick = 0, longer_tick_multiple = -2, numbers_with_elongated_ticks = [0, 5, 10, 15, 20], color = GREY ) y_axis.shift(x_axis.number_to_point(0)-y_axis.number_to_point(0)) y_axis.rotate(np.pi/2, about_point = y_axis.number_to_point(0)) y_axis.add_numbers(5, 10, 15, 20) y_axis.numbers.shift(0.4*UP+0.5*LEFT) y_label = OldTex("A") y_label.next_to(y_axis.get_top(), RIGHT, buff = MED_LARGE_BUFF) def func(alpha): R = interpolate(self.R_min, self.R_max, alpha) x = x_axis.number_to_point(R)[0] output = np.pi*(R**2) y = y_axis.number_to_point(output)[1] return x*RIGHT + y*UP graph = ParametricCurve(func, color = BLUE) graph_label = OldTex("A(R) = \\pi R^2") graph_label.set_color(BLUE) graph_label.next_to( graph.point_from_proportion(2), LEFT ) self.play(Write(VGroup(x_axis, y_axis))) self.play(ShowCreation(graph)) self.play(Write(graph_label)) self.play(Write(VGroup(x_label, y_label))) self.wait() self.x_axis, self.y_axis = x_axis, y_axis self.graph = graph self.graph_label = graph_label def graph_point(self, R): alpha = (R - self.R_min)/(self.R_max - self.R_min) return self.graph.point_from_proportion(alpha) def angle_of_tangent(self, R, dR = 0.01): vect = self.graph_point(R + dR) - self.graph_point(R) return angle_of_vector(vect) def show_zoomed_in_steps(self): R = self.R_to_zoom_in_on dR = 0.05 graph_point = self.graph_point(R) nudged_point = self.graph_point(R+dR) interim_point = nudged_point[0]*RIGHT + graph_point[1]*UP self.activate_zooming() dot = Dot(color = YELLOW) dot.scale(0.1) dot.move_to(graph_point) self.play(*list(map(FadeIn, [ self.little_rectangle, self.big_rectangle ]))) self.play( self.little_rectangle.move_to, graph_point+self.little_rect_nudge ) self.play(FadeIn(dot)) dR_line = Line(graph_point, interim_point) dR_line.set_color(YELLOW) dA_line = Line(interim_point, nudged_point) dA_line.set_color(GREEN) tiny_buff = SMALL_BUFF/self.zoom_factor for line, vect, char in (dR_line, DOWN, "R"), (dA_line, RIGHT, "A"): line.brace = Brace(Line(LEFT, RIGHT)) line.brace.scale(1./self.zoom_factor) line.brace.stretch_to_fit_width(line.get_length()) line.brace.rotate(line.get_angle()) line.brace.next_to(line, vect, buff = tiny_buff) line.text = OldTex("d%s"%char) line.text.scale(1./self.zoom_factor) line.text.set_color(line.get_color()) line.text.next_to(line.brace, vect, buff = tiny_buff) self.play(ShowCreation(line)) self.play(Write(VGroup(line.brace, line.text))) self.wait() deriv_is_slope = OldTex( "\\frac{dA}{dR} =", "\\text{Slope}" ) self.slope_word = deriv_is_slope[1] VGroup(*deriv_is_slope[0][:2]).set_color(GREEN) VGroup(*deriv_is_slope[0][3:5]).set_color(YELLOW) deriv_is_slope.next_to(self.y_axis, RIGHT) deriv_is_slope.shift(UP) self.play(Write(deriv_is_slope)) self.wait() ### Whoa boy, this aint' gonna be pretty self.dot = dot self.small_step_group = VGroup( dR_line, dR_line.brace, dR_line.text, dA_line, dA_line.brace, dA_line.text, ) def update_small_step_group(group): R = self.x_axis.point_to_number(dot.get_center()) graph_point = self.graph_point(R) nudged_point = self.graph_point(R+dR) interim_point = nudged_point[0]*RIGHT + graph_point[1]*UP dR_line.put_start_and_end_on(graph_point, interim_point) dA_line.put_start_and_end_on(interim_point, nudged_point) dR_line.brace.stretch_to_fit_width(dR_line.get_width()) dR_line.brace.next_to(dR_line, DOWN, buff = tiny_buff) dR_line.text.next_to(dR_line.brace, DOWN, buff = tiny_buff) dA_line.brace.stretch_to_fit_height(dA_line.get_height()) dA_line.brace.next_to(dA_line, RIGHT, buff = tiny_buff) dA_line.text.next_to(dA_line.brace, RIGHT, buff = tiny_buff) self.update_small_step_group = update_small_step_group def show_tangent_lines(self): R = self.R_to_zoom_in_on line = Line(LEFT, RIGHT).scale(FRAME_Y_RADIUS) line.set_color(MAROON_B) line.rotate(self.angle_of_tangent(R)) line.move_to(self.graph_point(R)) x_axis_y = self.x_axis.number_to_point(0)[1] two_pi_R = OldTex("= 2\\pi R") two_pi_R.next_to(self.slope_word, DOWN, aligned_edge = RIGHT) two_pi_R.shift(0.5*LEFT) def line_update_func(line): R = self.x_axis.point_to_number(self.dot.get_center()) line.rotate( self.angle_of_tangent(R) - line.get_angle() ) line.move_to(self.dot) def update_little_rect(rect): R = self.x_axis.point_to_number(self.dot.get_center()) rect.move_to(self.graph_point(R) + self.little_rect_nudge) self.play(ShowCreation(line)) self.wait() self.note_R_value_of_point() alphas = np.arange(0, 1, 0.01) graph_points = list(map(self.graph.point_from_proportion, alphas)) curr_graph_point = self.graph_point(R) self.last_alpha = alphas[np.argmin([ get_norm(point - curr_graph_point) for point in graph_points ])] def shift_everything_to_alpha(alpha, run_time = 3): self.play( MoveAlongPath( self.dot, self.graph, rate_func = lambda t : interpolate(self.last_alpha, alpha, smooth(t)) ), UpdateFromFunc(line, line_update_func), UpdateFromFunc(self.small_step_group, self.update_small_step_group), UpdateFromFunc(self.little_rectangle, update_little_rect), run_time = run_time ) self.last_alpha = alpha for alpha in 0.95, 0.2: shift_everything_to_alpha(alpha) self.wait() self.play(Write(two_pi_R)) self.wait() shift_everything_to_alpha(0.8, 4) self.wait() def note_R_value_of_point(self): R = self.R_to_zoom_in_on point = self.graph_point(R) R_axis_point = point[0]*RIGHT + 2.5*DOWN dashed_line = DashedLine(point, R_axis_point, color = RED) dot = Dot(R_axis_point, color = RED) arrow = Arrow( self.x_axis_label.get_left(), dot, buff = SMALL_BUFF ) self.play(ShowCreation(dashed_line)) self.play(ShowCreation(dot)) self.play(ShowCreation(arrow)) self.play(dot.scale, 2, rate_func = there_and_back) self.wait() self.play(*list(map(FadeOut, [dashed_line, dot, arrow]))) def state_commonality(self): morty = Mortimer() morty.scale(0.7) morty.to_edge(DOWN).shift(2*RIGHT) bubble = morty.get_bubble(SpeechBubble, height = 2) bubble.set_fill(BLACK, opacity = 0.8) bubble.shift(0.5*DOWN) bubble.write("This is the standard view") self.play(FadeIn(morty)) self.play( ShowCreation(bubble), Write(bubble.content), morty.change_mode, "surprised" ) self.play(Blink(morty)) self.wait() new_words = OldTexText("Which is...fine...") new_words.move_to(bubble.content, RIGHT) self.play( bubble.stretch_to_fit_width, 5, bubble.shift, RIGHT, Transform(bubble.content, new_words), morty.change_mode, "hesitant" ) self.play(Blink(morty)) self.wait() class SimpleConfusedPi(Scene): def construct(self): randy = Randolph() confused = Randolph(mode = "confused") for pi in randy, confused: pi.flip() pi.look(UP+LEFT) pi.scale(2) pi.rotate(np.pi/2) self.play(Transform(randy, confused)) self.wait() class TangentLinesAreNotEverything(TeacherStudentsScene): def construct(self): self.teacher_says(""" Tangent lines are just one way to visualize derivatives """) self.play_student_changes("raise_left_hand", "pondering", "erm") self.random_blink(3) class OnToIntegrals(TeacherStudentsScene): def construct(self): self.teacher_says("On to integrals!", target_mode = "hooray") self.play_student_changes(*["happy"]*3) self.random_blink(3) class IntroduceConcentricRings(CircleScene): CONFIG = { "radius" : 2.5, "special_ring_index" : 10, "include_pi_creature" : True, } def construct(self): self.build_up_rings() self.add_up_areas() self.unwrap_special_ring() self.write_integral() self.ask_about_approx() def create_pi_creature(self): morty = Mortimer() morty.scale(0.7) morty.to_corner(DOWN+RIGHT) return morty def build_up_rings(self): self.circle.set_fill(opacity = 0) rings = VGroup(*[ self.get_ring(r, self.dR) for r in np.arange(0, self.radius, self.dR) ]) rings.set_color_by_gradient(BLUE_E, GREEN_E) rings.set_stroke(BLACK, width = 1) outermost_ring = rings[-1] dr_line = Line( rings[-2].get_top(), rings[-1].get_top(), color = YELLOW ) dr_text = OldTex("dr") dr_text.move_to(self.circle.get_corner(UP+RIGHT)) dr_text.shift(LEFT) dr_text.set_color(YELLOW) dr_arrow = Arrow(dr_text, dr_line, buff = SMALL_BUFF) self.dr_group = VGroup(dr_text, dr_arrow, dr_line) foreground_group = VGroup(self.radius_brace, self.radius_label, self.radius_line) self.play( FadeIn(outermost_ring), Animation(foreground_group) ) self.play( Write(dr_text), ShowCreation(dr_arrow), ShowCreation(dr_line) ) foreground_group.add(dr_line, dr_arrow, dr_text) self.change_mode("pondering") self.wait() self.play( FadeIn( VGroup(*rings[:-1]), lag_ratio=1, run_time = 5 ), Animation(foreground_group) ) self.wait() self.foreground_group = foreground_group self.rings = rings def add_up_areas(self): start_rings = VGroup(*self.rings[:4]) moving_rings = start_rings.copy() moving_rings.generate_target() moving_rings.target.set_stroke(width = 0) plusses = VGroup(*[Tex("+") for ring in moving_rings]) area_sum = VGroup(*it.chain(*list(zip( [ring for ring in moving_rings.target], plusses )))) dots_equals_area = OldTex("\\dots", "=", "\\pi R^2") area_sum.add(*dots_equals_area) area_sum.arrange() area_sum.to_edge(RIGHT) area_sum.to_edge(UP, buff = MED_SMALL_BUFF) dots_equals_area[-1].shift(0.1*UP) self.area_sum_rhs = dots_equals_area[-1] # start_rings.set_fill(opacity = 0.3) self.play( MoveToTarget( moving_rings, lag_ratio = 0.5, ), Write( VGroup(plusses, dots_equals_area), rate_func = squish_rate_func(smooth, 0.5, 1) ), Animation(self.foreground_group), run_time = 5, ) self.wait() self.area_sum = area_sum def unwrap_special_ring(self): rings = self.rings foreground_group = self.foreground_group special_ring = rings[self.special_ring_index] special_ring.save_state() radius = (special_ring.get_width()-2*self.dR)/2. radial_line = Line(ORIGIN, radius*RIGHT) radial_line.rotate(np.pi/4) radial_line.shift(self.circle.get_center()) radial_line.set_color(YELLOW) r_label = OldTex("r") r_label.next_to(radial_line.get_center(), UP+LEFT, buff = SMALL_BUFF) rings.generate_target() rings.save_state() rings.target.set_fill(opacity = 0.3) rings.target.set_stroke(BLACK) rings.target[self.special_ring_index].set_fill(opacity = 1) self.play( MoveToTarget(rings), Animation(foreground_group) ) self.play(ShowCreation(radial_line)) self.play(Write(r_label)) self.foreground_group.add(radial_line, r_label) self.wait() self.unwrap_ring(special_ring, to_edge = RIGHT) brace = Brace(special_ring, UP) brace.stretch_in_place(0.9, 0) two_pi_r = brace.get_text("$2\\pi r$") left_brace = OldTex("\\{") left_brace.stretch_to_fit_height(1.5*self.dR) left_brace.next_to(special_ring, LEFT, buff = SMALL_BUFF) dr = OldTex("dr") dr.next_to(left_brace, LEFT, buff = SMALL_BUFF) self.play( GrowFromCenter(brace), Write(two_pi_r) ) self.play(GrowFromCenter(left_brace), Write(dr)) self.wait() think_concrete = OldTexText("Think $dr = 0.1$") think_concrete.next_to(dr, DOWN+LEFT, buff = LARGE_BUFF) arrow = Arrow(think_concrete.get_top(), dr) self.play( Write(think_concrete), ShowCreation(arrow), self.pi_creature.change_mode, "speaking" ) self.wait() less_wrong = OldTexText(""" Approximations get less wrong """) less_wrong.next_to(self.pi_creature, LEFT, aligned_edge = UP) self.play(Write(less_wrong)) self.wait() self.special_ring = special_ring self.radial_line = radial_line self.r_label = r_label self.to_fade = VGroup( brace, left_brace, two_pi_r, dr, think_concrete, arrow, less_wrong ) self.two_pi_r = two_pi_r.copy() self.dr = dr.copy() def write_integral(self): brace = Brace(self.area_sum) formula_q = brace.get_text("Nice formula?") int_sym, R, zero = def_int = OldTex("\\int", "_0", "^R") self.two_pi_r.generate_target() self.dr.generate_target() equals_pi_R_squared = OldTex("= \\pi R^2") integral_expression = VGroup( def_int, self.two_pi_r.target, self.dr.target, equals_pi_R_squared ) integral_expression.arrange() integral_expression.next_to(brace, DOWN) self.integral_expression = VGroup(*integral_expression[:-1]) self.play( GrowFromCenter(brace), Write(formula_q), self.pi_creature.change_mode, "pondering" ) self.wait(2) last = VMobject() last.save_state() for ring in self.rings: ring.save_state() target = ring.copy() target.set_fill(opacity = 1) self.play( last.restore, Transform(ring, target), Animation(self.foreground_group), run_time = 0.5 ) last = ring self.play(last.restore) self.wait() ghost = self.rings.copy() for mob in self.area_sum_rhs, self.two_pi_r: ghost.set_fill(opacity = 0.1) self.play(Transform(ghost, mob)) self.wait() self.remove(ghost) self.wait() self.play(FadeOut(formula_q)) self.play(Write(int_sym)) self.wait() self.rings.generate_target() self.rings.target.set_fill(opacity = 1) self.play( MoveToTarget(self.rings, rate_func = there_and_back), Animation(self.foreground_group) ) self.wait() self.grow_and_shrink_r_line(zero, R) self.wait() self.play( MoveToTarget(self.two_pi_r), MoveToTarget(self.dr), run_time = 2 ) self.wait() self.play( FadeOut(self.to_fade), ApplyMethod(self.rings.restore, run_time = 2), Animation(self.foreground_group) ) self.wait() self.play(Write(equals_pi_R_squared)) self.wait() self.equals = equals_pi_R_squared[0] self.integral_terms = VGroup( self.integral_expression[1], self.integral_expression[2], self.int_lower_bound, self.int_upper_bound, VGroup(*equals_pi_R_squared[1:]) ) def grow_and_shrink_r_line(self, zero_target, R_target): self.radial_line.get_center = self.circle.get_center self.radial_line.save_state() self.radial_line.generate_target() self.radial_line.target.scale( 0.1 / self.radial_line.get_length() ) self.r_label.generate_target() self.r_label.save_state() equals_0 = OldTex("=0") r_equals_0 = VGroup(self.r_label.target, equals_0) r_equals_0.arrange(buff = SMALL_BUFF) r_equals_0.next_to(self.radial_line.target, UP+LEFT, buff = SMALL_BUFF) self.play( MoveToTarget(self.radial_line), MoveToTarget(self.r_label), GrowFromCenter(equals_0) ) self.play(equals_0[-1].copy().replace, zero_target) self.remove(self.get_mobjects_from_last_animation()[0]) self.add(zero_target) self.wait() self.radial_line.target.scale( self.radius/self.radial_line.get_length() ) equals_0.target = OldTex("=R") equals_0.target.next_to( self.radial_line.target.get_center_of_mass(), UP+LEFT, buff = SMALL_BUFF ) self.r_label.target.next_to(equals_0.target, LEFT, buff = SMALL_BUFF) self.play( MoveToTarget(self.radial_line), MoveToTarget(self.r_label), MoveToTarget(equals_0) ) self.play(equals_0[-1].copy().replace, R_target) self.remove(self.get_mobjects_from_last_animation()[0]) self.add(R_target) self.wait() self.play( self.radial_line.restore, self.r_label.restore, FadeOut(equals_0) ) self.int_lower_bound, self.int_upper_bound = zero_target, R_target def ask_about_approx(self): approx = OldTex("\\approx").replace(self.equals) self.equals.save_state() question = OldTexText( "Should this be\\\\", "an approximation?" ) question.next_to(approx, DOWN, buff = 1.3*LARGE_BUFF) arrow = Arrow(question, approx, buff = MED_SMALL_BUFF) approach_words = OldTexText("Consider\\\\", "$dr \\to 0$") approach_words.move_to(question, RIGHT) int_brace = Brace(self.integral_expression) integral_word = int_brace.get_text("``Integral''") self.play( Transform(self.equals, approx), Write(question), ShowCreation(arrow), self.pi_creature.change_mode, "confused" ) self.wait(2) self.play(*[ ApplyMethod(ring.set_stroke, ring.get_color(), width = 1) for ring in self.rings ] + [ FadeOut(self.dr_group), Animation(self.foreground_group) ]) self.wait() self.play( Transform(question, approach_words), Transform(arrow, Arrow(approach_words, approx)), self.equals.restore, self.pi_creature.change_mode, "happy" ) self.wait(2) self.play( self.integral_expression.set_color_by_gradient, BLUE, GREEN, GrowFromCenter(int_brace), Write(integral_word) ) self.wait() for term in self.integral_terms: term.save_state() self.play(term.set_color, YELLOW) self.play(term.restore) self.wait(3) class AskAboutGeneralCircles(TeacherStudentsScene): def construct(self): self.student_says(""" What about integrals beyond this circle example? """) self.play_student_changes("confused") self.random_blink(2) self.teacher_says( "All in due time", ) self.play_student_changes(*["happy"]*3) self.random_blink(2) class GraphIntegral(GraphScene): CONFIG = { "x_min" : -0.25, "x_max" : 4, "x_tick_frequency" : 0.25, "x_leftmost_tick" : -0.25, "x_labeled_nums" : list(range(1, 5)), "x_axis_label" : "r", "y_min" : -2, "y_max" : 25, "y_tick_frequency" : 2.5, "y_bottom_tick" : 0, "y_labeled_nums" : list(range(5, 30, 5)), "y_axis_label" : "", "dr" : 0.125, "R" : 3.5, } def construct(self): self.func = lambda r : 2*np.pi*r integral = OldTex("\\int_0^R 2\\pi r \\, dr") integral.to_edge(UP).shift(LEFT) self.little_r = integral[5] self.play(Write(integral)) self.wait() self.setup_axes() self.show_horizontal_axis() self.add_rectangles() self.thinner_rectangles() self.ask_about_area() def show_horizontal_axis(self): arrows = [ Arrow(self.little_r, self.coords_to_point(*coords)) for coords in ((0, 0), (self.x_max, 0)) ] moving_arrow = arrows[0].copy() self.play( ShowCreation(moving_arrow), self.little_r.set_color, YELLOW ) for arrow in reversed(arrows): self.play(Transform(moving_arrow, arrow, run_time = 4)) self.play( FadeOut(moving_arrow), self.little_r.set_color, WHITE ) def add_rectangles(self): tick_height = 0.2 special_tick_index = 12 ticks = VGroup(*[ Line(UP, DOWN).move_to(self.coords_to_point(x, 0)) for x in np.arange(0, self.R+self.dr, self.dr) ]) ticks.stretch_to_fit_height(tick_height) ticks.set_color(YELLOW) R_label = OldTex("R") R_label.next_to(self.coords_to_point(self.R, 0), DOWN) values_words = OldTexText("Values of $r$") values_words.shift(UP) arrows = VGroup(*[ Arrow( values_words.get_bottom(), tick.get_center(), tip_length = 0.15 ) for tick in ticks ]) dr_brace = Brace( VGroup(*ticks[special_tick_index:special_tick_index+2]), buff = SMALL_BUFF ) dr_text = dr_brace.get_text("$dr$", buff = SMALL_BUFF) # dr_text.set_color(YELLOW) rectangles = self.get_rectangles(self.dr) special_rect = rectangles[special_tick_index] left_brace = Brace(special_rect, LEFT) height_label = left_brace.get_text("$2\\pi r$") self.play( ShowCreation(ticks, lag_ratio = 0.5), Write(R_label) ) self.play( Write(values_words), ShowCreation(arrows) ) self.wait() self.play( GrowFromCenter(dr_brace), Write(dr_text) ) self.wait() rectangles.save_state() rectangles.stretch_to_fit_height(0) rectangles.move_to(self.graph_origin, DOWN+LEFT) self.play(*list(map(FadeOut, [arrows, values_words]))) self.play( rectangles.restore, Animation(ticks), run_time = 2 ) self.wait() self.play(*[ ApplyMethod(rect.fade, 0.7) for rect in rectangles if rect is not special_rect ] + [Animation(ticks)]) self.play( GrowFromCenter(left_brace), Write(height_label) ) self.wait() graph = self.graph_function( lambda r : 2*np.pi*r, animate = False ) graph_label = self.label_graph( self.graph, "f(r) = 2\\pi r", proportion = 0.5, direction = LEFT, animate = False ) self.play( rectangles.restore, Animation(ticks), FadeOut(left_brace), Transform(height_label, graph_label), ShowCreation(graph) ) self.wait(3) self.play(*list(map(FadeOut, [ticks, dr_brace, dr_text]))) self.rectangles = rectangles def thinner_rectangles(self): for x in range(2, 8): new_rects = self.get_rectangles( dr = self.dr/x, stroke_width = 1./x ) self.play(Transform(self.rectangles, new_rects)) self.wait() def ask_about_area(self): question = OldTexText("What's this \\\\ area") question.to_edge(RIGHT).shift(2*UP) arrow = Arrow( question.get_bottom(), self.rectangles, buff = SMALL_BUFF ) self.play( Write(question), ShowCreation(arrow) ) self.wait() def get_rectangles(self, dr, stroke_width = 1): return self.get_riemann_rectangles( 0, self.R, dr, stroke_width = stroke_width ) class MoreOnThisLater(TeacherStudentsScene): def construct(self): self.teacher_says(""" More details on integrals later """) self.play_student_changes( "raise_right_hand", "raise_left_hand", "raise_left_hand", ) self.random_blink(2) self.teacher_says(""" This is just a preview """) self.random_blink(2) class FundamentalTheorem(CircleScene): CONFIG = { "circle_corner" : ORIGIN, "radius" : 1.5, "area_color" : BLUE, "circum_color" : WHITE, "unwrapped_tip" : 2.5*UP, "include_pi_creature" : False } def setup(self): CircleScene.setup(self) group = VGroup( self.circle, self.radius_line, self.radius_brace, self.radius_label ) self.remove(*group) group.shift(DOWN) self.foreground_group = VGroup( self.radius_line, self.radius_brace, self.radius_label, ) def create_pi_creature(self): morty = Mortimer() morty.scale(0.7) morty.to_corner(DOWN+RIGHT) return morty def construct(self): self.add_derivative_terms() self.add_integral_terms() self.think_about_it() self.bring_in_circle() self.show_outer_ring() self.show_all_rings() self.emphasize_oposites() def add_derivative_terms(self): symbolic = OldTex( "\\frac{d(\\pi R^2)}{dR} =", "2\\pi R" ) VGroup(*symbolic[0][2:5]).set_color(self.area_color) VGroup(*symbolic[0][7:9]).set_color(self.dR_color) symbolic[1].set_color(self.circum_color) geometric = OldTex("\\frac{d \\quad}{dR}=") VGroup(*geometric[2:4]).set_color(self.dR_color) radius = geometric[0].get_height() area_circle = Circle( stroke_width = 0, fill_color = self.area_color, fill_opacity = 0.5, radius = radius ) area_circle.next_to(geometric[0], buff = SMALL_BUFF) circum_circle = Circle( color = self.circum_color, radius = radius ) circum_circle.next_to(geometric, RIGHT) geometric.add(area_circle, circum_circle) self.derivative_terms = VGroup(symbolic, geometric) self.derivative_terms.arrange( DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) self.derivative_terms.next_to(ORIGIN, LEFT, buff = LARGE_BUFF) self.play( Write(self.derivative_terms), self.pi_creature.change_mode, "hooray" ) self.wait() def add_integral_terms(self): symbolic = OldTex( "\\int_0^R", "2\\pi r", "\\cdot", "dr", "=", "\\pi R^2" ) symbolic.set_color_by_tex("2\\pi r", self.circum_color) symbolic.set_color_by_tex("dr", self.dR_color) symbolic.set_color_by_tex("\\pi R^2", self.area_color) geometric = symbolic.copy() area_circle = Circle( radius = geometric[-1].get_width()/2, stroke_width = 0, fill_color = self.area_color, fill_opacity = 0.5 ) area_circle.move_to(geometric[-1]) circum_circle = Circle( radius = geometric[1].get_width()/2, color = self.circum_color ) circum_circle.move_to(geometric[1]) geometric.submobjects[1] = circum_circle geometric.submobjects[-1] = area_circle self.integral_terms = VGroup(symbolic, geometric) self.integral_terms.arrange( DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) self.integral_terms.next_to(ORIGIN, RIGHT, buff = LARGE_BUFF) self.play(Write(self.integral_terms)) self.wait() def think_about_it(self): for mode in "confused", "pondering", "surprised": self.change_mode(mode) self.wait() def bring_in_circle(self): self.play( FadeOut(self.derivative_terms[0]), FadeOut(self.integral_terms[0]), self.derivative_terms[1].to_corner, UP+LEFT, MED_LARGE_BUFF, self.integral_terms[1].to_corner, UP+RIGHT, MED_LARGE_BUFF, self.pi_creature.change_mode, "speaking" ) self.introduce_circle() def show_outer_ring(self): self.increase_radius(numerical_dr = False) self.foreground_group.add(self.nudge_line, self.nudge_arrow) self.wait() ring_copy = self.outer_ring.copy() ring_copy.save_state() self.unwrap_ring(ring_copy, to_edge = LEFT) brace = Brace(ring_copy, UP) brace.stretch_in_place(0.95, 0) deriv = brace.get_text("$\\dfrac{dA}{dR}$") VGroup(*deriv[:2]).set_color(self.outer_ring.get_color()) VGroup(*deriv[-2:]).set_color(self.dR_color) self.play( GrowFromCenter(brace), Write(deriv), self.pi_creature.change_mode, "happy" ) self.to_fade = VGroup(deriv, brace) self.to_restore = ring_copy def show_all_rings(self): rings = VGroup(*[ self.get_ring(radius = r, dR = self.dR) for r in np.arange(0, self.radius, self.dR) ]) rings.set_color_by_gradient(BLUE_E, GREEN_E) rings.save_state() integrand = self.integral_terms[1][1] for ring in rings: Transform(ring, integrand).update(1) self.play( ApplyMethod( rings.restore, lag_ratio = 0.5, run_time = 5 ), Animation(self.foreground_group), ) def emphasize_oposites(self): self.play( FadeOut(self.to_fade), self.to_restore.restore, Animation(self.foreground_group), run_time = 2 ) arrow = DoubleArrow( self.derivative_terms[1], self.integral_terms[1], ) opposites = OldTexText("Opposites") opposites.next_to(arrow, DOWN) self.play( ShowCreation(arrow), Write(opposites) ) self.wait() class NameTheFundamentalTheorem(TeacherStudentsScene): def construct(self): symbols = OldTex( "\\frac{d}{dx} \\int_0^x f(t)dt = f(x)", ) symbols.to_corner(UP+LEFT) brace = Brace(symbols) abstract = brace.get_text("Abstract version") self.add(symbols) self.play( GrowFromCenter(brace), Write(abstract), *[ ApplyMethod(pi.look_at, symbols) for pi in self.get_pi_creatures() ] ) self.play_student_changes("pondering", "confused", "erm") self.random_blink() self.teacher_says(""" This is known as the ``fundamental theorem of calculus'' """, width = 5, height = 5, target_mode = "hooray") self.random_blink(3) self.teacher_says(""" We'll get here in due time. """) self.play_student_changes(*["happy"]*3) self.wait(2) class CalculusInANutshell(CircleScene): CONFIG = { "circle_corner" : ORIGIN, "radius" : 3, } def construct(self): self.clear() self.morph_word() self.show_remainder_of_series() def morph_word(self): calculus = OldTexText("Calculus") calculus.scale(1.5) calculus.to_edge(UP) dR = self.radius/float(len(calculus.split())) rings = VGroup(*[ self.get_ring(rad, 0.95*dR) for rad in np.arange(0, self.radius, dR) ]) for ring in rings: ring.add(ring.copy().rotate(np.pi)) for mob in calculus, rings: mob.set_color_by_gradient(BLUE, GREEN) rings.set_stroke(width = 0) self.play(Write(calculus)) self.wait() self.play(Transform( calculus, rings, lag_ratio = 0.5, run_time = 5 )) self.wait() def show_remainder_of_series(self): series = VideoSeries() first = series[0] first.set_fill(YELLOW) first.save_state() first.center() first.set_height(FRAME_Y_RADIUS*2) first.set_fill(opacity = 0) everything = VGroup(*self.get_mobjects()) everything.generate_target() everything.target.scale(series[1].get_height()/first.get_height()) everything.target.shift(first.saved_state.get_center()) everything.target.set_fill(opacity = 0.1) second = series[1] brace = Brace(second) derivatives = brace.get_text("Derivatives") self.play( MoveToTarget(everything), first.restore, run_time = 2 ) self.play(FadeIn( VGroup(*series[1:]), lag_ratio = 0.5, run_time = 2, )) self.wait() self.play( GrowFromCenter(brace), Write(derivatives) ) self.wait() class Thumbnail(CircleScene): CONFIG = { "radius" : 2, "circle_corner" : ORIGIN } def construct(self): self.clear() title = OldTexText("Essence of \\\\ calculus") title.scale(2) title.to_edge(UP) area_circle = Circle( fill_color = BLUE, fill_opacity = 0.5, stroke_width = 0, ) circum_circle = Circle( color = YELLOW ) deriv_eq = OldTex("\\frac{d \\quad}{dR} = ") int_eq = OldTex("\\int_0^R \\quad = ") target_height = deriv_eq[0].get_height()*2 area_circle.set_height(target_height) circum_circle.set_height(target_height) area_circle.next_to(deriv_eq[0], buff = SMALL_BUFF) circum_circle.next_to(deriv_eq) deriv_eq.add(area_circle.copy(), circum_circle.copy()) area_circle.next_to(int_eq) circum_circle.next_to(int_eq[-1], LEFT) int_eq.add(area_circle, circum_circle) for mob in deriv_eq, int_eq: mob.scale(1.5) arrow = OldTex("\\Leftrightarrow").scale(2) arrow.shift(DOWN) deriv_eq.next_to(arrow, LEFT) int_eq.next_to(arrow, RIGHT) self.add(title, arrow, deriv_eq, int_eq)
videos_3b1b/_2017/dominos/domino_play.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from manim_imports_ext import * class SimpleVelocityGraph(GraphScene): CONFIG = { # "frame_rate" : 4000, # "domino_thickness" : 7.5438, # "domino_spacing" : 8.701314282, "data_files" : [ "data07.txt", "data13.txt", # "data11.txt", ], "colors" : [WHITE, BLUE, YELLOW, GREEN, MAROON_B], "x_axis_label" : "$t$", "y_axis_label" : "$v$", "x_min" : 0, "x_max" : 1.8, "x_tick_frequency" : 0.1, "x_labeled_nums" : np.arange(0, 1.8, 0.2), "y_tick_frequency" : 100, "y_min" : 0, "y_max" : 1000, "y_labeled_nums" : list(range(0, 1000, 200)), "x_axis_width" : 12, "graph_origin" : 2.5*DOWN + 5*LEFT, "trailing_average_length" : 20, "include_domino_thickness" : False, } def construct(self): self.setup_axes() # self.save_all_images() for data_file, color in zip(self.data_files, self.colors): self.init_data(data_file) self.draw_dots(color) self.add_label_to_last_dot( "%s %s %.2f"%( data_file[4:6], "hard" if self.friction == "low" else "felt", self.domino_spacing, ), color ) self.draw_lines(color) def save_all_images(self): indices = list(range(1, 20)) for i1, i2 in it.combinations(indices, 2): to_remove = VGroup() for index in i1, i2: index_str = ("%.2f"%float(0.01*index))[-2:] data_file = "data%s.txt"%index_str self.init_data(data_file) color = WHITE if self.friction == "low" else BLUE self.draw_dots(color) self.add_label_to_last_dot( "%s %s %.2f"%( data_file[4:6], "hard" if self.friction == "low" else "felt", self.domino_spacing, ), color ) self.draw_lines(color) to_remove.add(self.dots, self.lines, self.label) self.save_image("dominos_%d_vs_%d"%(i1, i2)) self.remove(to_remove) def init_data(self, data_file): file_name = os.path.join( os.path.dirname(os.path.realpath(__file__)), "dominos", data_file ) file = open(file_name, "r") frames, notes = [], [] for line in file: line = line.replace(" ", ",") line = line.replace("\n", "") entries = [s for s in line.split(",") if s is not ""] if len(entries) == 0: continue if entries[0] == "framerate": frame_rate = float(entries[1]) elif entries[0] == "domino spacing": domino_spacing = float(entries[1]) elif entries[0] == "domino thickness": domino_thickness = float(entries[1]) elif entries[0] == "friction": self.friction = entries[1] else: try: frames.append(int(entries[0])) except: continue #How to treat? # frames.append(frames[-1] + (frames[-1] - frames[-2])) if len(entries) > 1: notes.append(entries[1]) else: notes.append("") frames = np.array(frames) self.times = (frames - frames[0])/float(frame_rate) delta_times = self.times[1:] - self.times[:-1] if self.include_domino_thickness: distance = domino_spacing+domino_thickness else: distance = domino_spacing self.velocities = distance/delta_times self.notes = notes n = self.trailing_average_length self.velocities = np.array([ np.mean(self.velocities[max(0, i-n):i]) for i in range(len(self.velocities)) ]) self.domino_spacing = domino_spacing self.domino_thickness = domino_thickness def draw_dots(self, color = WHITE): dots = VGroup() for time, v, note in zip(self.times, self.velocities, self.notes): dot = Dot(color = color) dot.scale(0.5) dot.move_to(self.coords_to_point(time, v)) self.add(dot) dots.add(dot) if note == "twist": dot.set_color(RED) self.dots = dots def add_label_to_last_dot(self, label, color = WHITE): dot = self.dots[-1] label = OldTexText(label) label.scale(0.75) label.next_to(dot, UP, buff = MED_SMALL_BUFF) label.set_color(color) label.shift_onto_screen() self.label = label self.add(label) def draw_lines(self, color = WHITE, stroke_width = 2): lines = VGroup() for d1, d2 in zip(self.dots, self.dots[1:]): line = Line(d1.get_center(), d2.get_center()) lines.add(line) lines.set_stroke(color, stroke_width) self.add(lines, self.dots) self.lines = lines ALL_VELOCITIES = { 10 : [ 0.350308642, 0.3861880046, 0.8665243271, 0.9738947062, 0.8087560386, 1.067001275, 0.9059117965, 1.113855622, 0.9088626493, 1.504155436, 1.347926731, 1.274067732, 1.242854491, 1.118319973, 1.177303094, 1.202676006, 0.9965029762, 1.558775605, 1.472405453, 1.357765612, 1.200089606, 1.285810292, 1.138860544, 1.322373618, 1.51230804, 1.148233882, 1.276983219, 1.150601375, 1.492090018, 1.210502531, 1.221097739, 1.141189502, 1.364405053, 1.608189241, 1.223775585, 1.174824561, 1.069045338, 1.468530702, 1.733048654, 1.328670635, 1.118319973, 1.143528005, 1.010945048, 1.430876068, 1.395104167, 1.018324209, 1.405646516, 1.120565596, 1.24562872, 1.65590999, 1.276983219, 1.282854406, 1.338229416, 1.240092593, 0.9982856291, 1.811823593, 1.328670635, 1.167451185, 1.27991208, 1.221097739, 1.022054335, 1.160169785, 1.805960086, 0.9965029762, 1.449458874, 1.603568008, 1.234605457, 1.210502531, 1.192396724, 1.020185862, 1.496090259, 1.322373618, 1.291763117, 1.210502531, 0.9807410662, 1.341446314, 1.391625104, 1.480216622, 1.148233882, 1.125084005, 1.670783433, 1.118319973, 1.174824561, 1.395104167, 1.167451185, 1.182291667, 1.696175279, 1.306889149, 1.430876068, 1.048950501, 1.823665577, 1.24562872, ], 13 : [ 0.2480920273, 0.3532654568, 0.549163523, 0.5979017857, 0.6643353175, 0.8495940117, 1.037573598, 0.897413562, 1.410977665, 0.9180833562, 1.303328143, 0.9324004456, 2.026785714, 0.9721980256, 1.339835934, 1.002770291, 2.3797086, 1.235972684, 1.508900406, 1.239174685, 1.374486864, 1.181040564, 1.144309638, 1.195803571, 1.265400605, 1.223328462, 1.678320802, 1.198800573, 0.7958759211, 1.573425752, 1.046655205, 2.009753902, 1.42782516, 1.289276088, 1.347384306, 1.299786491, 1.06530385, 1.339835934, 1.242393321, 1.053571429, 1.317689886, 1.626943635, 1.112375415, 1.362739113, 0.9110884354, 1.578618576, 1.853959025, 1.504155436, 1.158163265, 1.262061817, 1.060579664, 1.122820255, 1.594404762, 1.27552381, 1.382431874, 1.109794498, 1.303328143, 1.160974341, 1.296264034, 1.092058056, 1.077300515, 1.462756662, 1.317689886, 1.390469269, 1.099589491, 1.649384236, 1.467243646, 1.402702137, 1.092058056, 1.201812635, 1.258740602, 1.321329913, 1.272131459, 1.175236925, 1.181040564, 1.296264034, 1.24562872, 1.358867695, 1.332371667, 1.296264034, 1.217102872, 1.169490045, 1.114968365, 1.528183478, 1.374486864, 1.223328462, 1.324990107, 1.268757105, 1.169490045, 1.578618576, ], 14 : [ 0.4905860806, 0.6236263736, 0.71391258, 0.8436004031, 1.048950501, 0.9585599771, 1.138860544, 1.210940325, 1.27552381, 1.282363079, 1.166637631, 1.242393321, 1.163799096, 1.166637631, 1.42357568, 1.382431874, 1.278934301, 1.390469269, 1.181040564, 1.107225529, 1.08462909, 1.160974341, 1.374486864, 1.382431874, 1.355018211, 1.25543682, 1.192821518, 0.9360497624, 1.449458874, 1.370548506, 1.485470275, 1.471758242, 1.149811126, 1.217102872, 1.152581756, 1.402702137, 1.155365769, 1.141578588, 1.248881015, 1.074879615, 1.453864525, 1.303328143, 1.248881015, 1.169490045, 1.214013778, 1.220207726, 1.310469667, 1.42357568, 1.163799096, 1.220207726, 1.141578588, 1.207882395, 1.104668426, 1.328670635, 1.25543682, 1.239174685, 1.169490045, 1.149811126, 1.000672445, 1.144309638, 1.232787187, 1.268757105, 1.306889149, 1.538011024, 1.355018211, 1.347384306, 1.223328462, 1.149811126, 1.158163265, 1.24562872, 1.485470275, 1.339835934, 1.314069859, 1.235972684, 1.265400605, 1.181040564, 1.638087084, 1.568266979, 1.299786491, 1.278934301, 1.336093376, 1.089570452, 1.004876951, 1.089570452, 1.282363079, 1.449458874, 1.370548506, 1.265400605, 1.143215651, ], 15 : [ 1.087094156, 1.223328462, 1.563141923, 1.394523115, 1.268757105, 1.513675407, 1.436400686, 1.094557045, 0.9761661808, 1.072469571, 1.178131597, 1.366632653, 1.258740602, 1.25543682, 1.285810292, 1.235972684, 1.347384306, 1.239174685, 1.195803571, 1.186901808, 1.141578588, 1.152581756, 1.136155412, 1.102123107, 1.242393321, 1.347384306, 1.278934301, 1.366632653, 1.351190476, 0.9882674144, 1.1898543, 1.351190476, 1.169490045, 1.292760618, 1.638087084, 1.436400686, 1.328670635, 1.242393321, 1.355018211, 1.303328143, 1.186901808, 1.112375415, 1.432100086, 1.1898543, 1.324990107, 1.074879615, 1.214013778, 1.20483987, 1.158163265, 1.112375415, 1.220207726, 1.402702137, 1.268757105, 1.282363079, 1.289276088, 1.292760618, 1.183963932, 1.252150337, 1.42782516, 1.292760618, 1.026440834, 1.268757105, 1.268757105, 1.285810292, 1.347384306, 1.272131459, 1.220207726, 1.296264034, 1.25543682, 1.494754464, 1.347384306, 1.214013778, 1.169490045, 1.147053786, 1.082175178, 1.109794498, 1.382431874, 1.24562872, 1.201812635, 1.328670635, 1.122820255, 1.220207726, 1.192821518, 1.563141923, 1.41935142, 1.336093376, 1.406827731, 1.258740602, 1.186901808, 1.232787187, 1.107225529, ], } # Felt: 8,9,10,11,12,13 # Hardwood 1-7, 14,15 class ContrastTwoGraphs(SimpleVelocityGraph): CONFIG = { "velocities1_index" : 13, "velocities2_index" : 14, "x_min" : -1, "x_max" : 10, "y_min" : -0.25, "y_max" : 2, "x_axis_label" : "", "y_axis_label" : "", "x_labeled_nums" : [], "y_labeled_nums" : [], "y_tick_frequency" : 0.25, "x_tick_frequency" : 12, "moving_average_n" : 20, } def construct(self): self.setup_axes() velocities1 = ALL_VELOCITIES[self.velocities1_index] velocities2 = ALL_VELOCITIES[self.velocities2_index] self.n_data_points = len(velocities1) graph1 = self.get_velocity_graph(velocities1) graph2 = self.get_velocity_graph(velocities2) smoothed_graph1 = self.get_smoothed_velocity_graph(velocities1) smoothed_graph2 = self.get_smoothed_velocity_graph(velocities2) for graph in graph1, smoothed_graph1: self.color_graph(graph) for graph in graph2, smoothed_graph2: self.color_graph(graph, BLUE, RED) for graph in graph1, graph2, smoothed_graph1, smoothed_graph2: graph.axes = self.axes.deepcopy() graph.add_to_back(graph.axes) lower_left = self.axes.get_corner(DOWN+LEFT) self.remove(self.axes) felt = OldTexText("Felt") hardwood = OldTexText("Hardwood") hardwood.set_color(RED) words = VGroup(felt, hardwood) self.force_skipping() #Show jaggediness graph1.scale(0.5).to_edge(UP) graph2.scale(0.5).to_edge(DOWN) felt.next_to(graph1, LEFT, buff = 0.75) hardwood.next_to(graph2, LEFT, buff = 0.75) self.play( ShowCreation(graph1, run_time = 3, rate_func=linear), Write(felt) ) self.play( ShowCreation(graph2, run_time = 4, rate_func=linear), Write(hardwood) ) self.wait() for g, sg in (graph1, smoothed_graph1), (graph2, smoothed_graph2): sg_copy = sg.deepcopy() sg_copy.scale(0.5) sg_copy.shift(g.get_center()) mover = VGroup(*it.chain(*list(zip(g.dots, g.lines)))) target = VGroup(*it.chain(*list(zip(sg_copy.dots, sg_copy.lines)))) for m, t in zip(mover, target): m.target = t self.play(LaggedStartMap( MoveToTarget, mover, rate_func = lambda t : 0.3*wiggle(t), run_time = 3, lag_ratio = 0.2, )) twists = OldTexText("Twists?") variable_distances = OldTexText("Variable distances") for word in twists, variable_distances: word.to_corner(UP+RIGHT) self.play(Write(twists)) self.wait() self.play(ReplacementTransform(twists, variable_distances)) self.wait(3) self.play(FadeOut(variable_distances)) self.revert_to_original_skipping_status() self.play( graph1.scale, 2, graph1.move_to, lower_left, DOWN+LEFT, graph2.scale, 2, graph2.move_to, lower_left, DOWN+LEFT, FadeOut(words) ) self.wait() return #Show moving averages self.play(FadeOut(graph2)) dots = graph1.dots dot1, dot2 = dots[21], dots[41] rect = Rectangle( width = dot2.get_center()[0] - dot1.get_center()[0], height = FRAME_Y_RADIUS - self.x_axis.get_center()[1], stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.5 ) rect.move_to(dot2.get_center(), RIGHT) rect.to_edge(UP, buff = 0) pre_rect = rect.copy() pre_rect.stretch_to_fit_width(0) pre_rect.move_to(rect, RIGHT) arrow = Vector(DOWN) arrow.next_to(dot2, UP, SMALL_BUFF) self.play(GrowArrow(arrow)) self.play( dot2.shift, MED_SMALL_BUFF*UP, dot2.set_color, PINK, rate_func = wiggle ) self.wait() self.play( FadeOut(arrow), ReplacementTransform(pre_rect, rect), ) self.wait() self.play( Transform(graph1, smoothed_graph1, run_time = 2), Animation(rect) ) self.play(FadeOut(rect)) self.wait() self.play(FadeIn(graph2)) self.play(Transform(graph2, smoothed_graph2)) felt.next_to(dot2, UP, MED_LARGE_BUFF) hardwood.next_to(felt, DOWN, LARGE_BUFF) self.play( LaggedStartMap(FadeIn, felt), LaggedStartMap(FadeIn, hardwood), run_time = 1 ) self.wait() #Compare regions dot_group1 = VGroup( *graph1.dots[35:75] + graph2.dots[35:75] ) dot_group2 = VGroup( *graph1.dots[75:] + graph2.dots[75:] ) dot_group3 = VGroup( *graph1.dots[35:] + graph2.dots[35:] ) rect1 = SurroundingRectangle(dot_group1) rect2 = SurroundingRectangle(dot_group2) rect3 = SurroundingRectangle(dot_group3) self.play(ShowCreation(rect1)) for x in range(2): self.play(LaggedStartMap( ApplyMethod, dot_group1, lambda m : (m.scale, 0.5), rate_func = wiggle, lag_ratio = 0.05, run_time = 3, )) self.wait() self.play(ReplacementTransform(rect1, rect2)) for x in range(2): self.play(LaggedStartMap( ApplyMethod, dot_group2, lambda m : (m.scale, 0.5), rate_func = wiggle, lag_ratio = 0.05, run_time = 3, )) self.wait() self.play(ReplacementTransform(rect1, rect3)) for x in range(2): self.play(LaggedStartMap( ApplyMethod, dot_group3, lambda m : (m.scale, 0.5), rate_func = wiggle, lag_ratio = 0.05, run_time = 3, )) self.wait() ### def color_graph(self, graph, color1 = BLUE, color2 = WHITE, n_starts = 20): graph.set_color(color2) VGroup(*graph.dots[:11] + graph.lines[:10]).set_color(color1) def get_smoothed_velocity_graph(self, velocities): n = self.moving_average_n smoothed_vs = np.array([ np.mean(velocities[max(0, i-n):i]) for i in range(len(velocities)) ]) return self.get_velocity_graph(smoothed_vs) def get_velocity_graph(self, velocities): n = len(velocities) dots = VGroup(self.get_dot(1, velocities[0])) lines = VGroup() for x in range(1, n): dots.add(self.get_dot(x+1, velocities[x])) lines.add(Line( dots[-2].get_center(), dots[-1].get_center(), )) graph = VGroup(dots, lines) graph.dots = dots graph.lines = lines return graph def get_dot(self, x, y): dot = Dot(radius = 0.05) dot.move_to(self.coords_to_point( x * float(self.x_max) / self.n_data_points, y )) return dot class ShowAllSteadyStateVelocities(SimpleVelocityGraph): CONFIG = { "x_axis_label" : "\\text{Domino spacing}", "x_min" : 0, "x_max" : 40, "x_axis_width" : 9, "x_tick_frequency" : 5, "x_labeled_nums" : list(range(0, 50, 10)), "y_min" : 0, "y_max" : 400, "y_labeled_nums" : [], # "y_labeled_nums" : range(200, 1400, 200), } def construct(self): self.setup_axes() for index in range(1, 20): index_str = ("%.2f"%float(0.01*index))[-2:] data_file = "data%s.txt"%index_str self.init_data(data_file) color = WHITE if self.friction == "low" else BLUE label = OldTexText( index_str, color = color ) label.scale(0.5) label.set_color(color) dot = Dot(color = color) dot.scale(0.5) dot.move_to(self.coords_to_point( self.domino_spacing, self.velocities[-1] - 400 )) label.next_to( dot, random.choice([LEFT, RIGHT]), SMALL_BUFF ) self.add(dot) self.add(label) print(index_str, self.velocities[-1], self.friction) class Test(Scene): def construct(self): shift_val = 1.5 domino1 = Rectangle( width = 0.5, height = 3, stroke_width = 0, fill_color = GREEN, fill_opacity = 1 ) domino1.shift(LEFT) domino2 = domino1.copy() domino2.set_fill(BLUE_E) domino2.shift(shift_val*RIGHT) spacing = shift_val - domino2.get_width() dominos = VGroup(domino1, domino2) for domino in dominos: line = DashedLine(domino.get_left(), domino.get_right()) dot = Dot(domino.get_center()) domino.add(line, dot) arc1 = Arc( radius = domino1.get_height(), start_angle = np.pi/2, angle = -np.arcsin(spacing / domino1.get_height()) ) arc1.shift(domino1.get_corner(DOWN+RIGHT)) arc2 = Arc( radius = domino1.get_height()/2, start_angle = np.pi/2, angle = -np.arcsin(2*spacing/domino1.get_height()) ) arc2.shift(domino1.get_right()) arc2.set_color(BLUE) arcs = VGroup(arc1, arc2) for arc, vect in zip(arcs, [DOWN+RIGHT, RIGHT]): arc_copy = arc.copy() point = domino1.get_bounding_box_point(vect) arc_copy.add_line_to([point]) arc_copy.set_stroke(width = 0) arc_copy.set_fill( arc.get_stroke_color(), 0.2, ) self.add(arc_copy) domino1_ghost = domino1.copy() domino1_ghost.fade(0.8) self.add(domino1_ghost, dominos, arcs) self.play(Rotate( domino1, angle = arc1.angle, about_point = domino1.get_corner(DOWN+RIGHT), rate_func = there_and_back, run_time = 3, )) self.play(Rotate( domino1, angle = arc2.angle, about_point = domino1.get_right(), rate_func = there_and_back, run_time = 3, )) print(arc1.angle, arc2.angle)
videos_3b1b/_2017/nn/mnist_loader.py
""" mnist_loader ~~~~~~~~~~~~ A library to load the MNIST image data. For details of the data structures that are returned, see the doc strings for ``load_data`` and ``load_data_wrapper``. In practice, ``load_data_wrapper`` is the function usually called by our neural network code. """ #### Libraries # Standard library import pickle import gzip # Third-party libraries import numpy as np def load_data(): """Return the MNIST data as a tuple containing the training data, the validation data, and the test data. The ``training_data`` is returned as a tuple with two entries. The first entry contains the actual training images. This is a numpy ndarray with 50,000 entries. Each entry is, in turn, a numpy ndarray with 784 values, representing the 28 * 28 = 784 pixels in a single MNIST image. The second entry in the ``training_data`` tuple is a numpy ndarray containing 50,000 entries. Those entries are just the digit values (0...9) for the corresponding images contained in the first entry of the tuple. The ``validation_data`` and ``test_data`` are similar, except each contains only 10,000 images. This is a nice data format, but for use in neural networks it's helpful to modify the format of the ``training_data`` a little. That's done in the wrapper function ``load_data_wrapper()``, see below. """ f = gzip.open('/Users/grant/cs/neural-networks-and-deep-learning/data/mnist.pkl.gz', 'rb') u = pickle._Unpickler(f) u.encoding = 'latin1' # p = u.load() # training_data, validation_data, test_data = pickle.load(f) training_data, validation_data, test_data = u.load() f.close() return (training_data, validation_data, test_data) def load_data_wrapper(): """Return a tuple containing ``(training_data, validation_data, test_data)``. Based on ``load_data``, but the format is more convenient for use in our implementation of neural networks. In particular, ``training_data`` is a list containing 50,000 2-tuples ``(x, y)``. ``x`` is a 784-dimensional numpy.ndarray containing the input image. ``y`` is a 10-dimensional numpy.ndarray representing the unit vector corresponding to the correct digit for ``x``. ``validation_data`` and ``test_data`` are lists containing 10,000 2-tuples ``(x, y)``. In each case, ``x`` is a 784-dimensional numpy.ndarry containing the input image, and ``y`` is the corresponding classification, i.e., the digit values (integers) corresponding to ``x``. Obviously, this means we're using slightly different formats for the training data and the validation / test data. These formats turn out to be the most convenient for use in our neural network code.""" tr_d, va_d, te_d = load_data() training_inputs = [np.reshape(x, (784, 1)) for x in tr_d[0]] training_results = [vectorized_result(y) for y in tr_d[1]] training_data = list(zip(training_inputs, training_results)) validation_inputs = [np.reshape(x, (784, 1)) for x in va_d[0]] validation_data = list(zip(validation_inputs, va_d[1])) test_inputs = [np.reshape(x, (784, 1)) for x in te_d[0]] test_data = list(zip(test_inputs, te_d[1])) return (training_data, validation_data, test_data) def vectorized_result(j): """Return a 10-dimensional unit vector with a 1.0 in the jth position and zeroes elsewhere. This is used to convert a digit (0...9) into a corresponding desired output from the neural network.""" e = np.zeros((10, 1)) e[j] = 1.0 return e
videos_3b1b/_2017/nn/part1.py
import sys import os.path import cv2 sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from manim_imports_ext import * import warnings warnings.warn(""" Warning: This file makes use of ContinualAnimation, which has since been deprecated """) from nn.network import * #force_skipping #revert_to_original_skipping_status DEFAULT_GAUSS_BLUR_CONFIG = { "ksize" : (5, 5), "sigmaX" : 10, "sigmaY" : 10, } DEFAULT_CANNY_CONFIG = { "threshold1" : 100, "threshold2" : 200, } def get_edges(image_array): blurred = cv2.GaussianBlur( image_array, **DEFAULT_GAUSS_BLUR_CONFIG ) edges = cv2.Canny( blurred, **DEFAULT_CANNY_CONFIG ) return edges class WrappedImage(Group): CONFIG = { "rect_kwargs" : { "color" : BLUE, "buff" : SMALL_BUFF, } } def __init__(self, image_mobject, **kwargs): Group.__init__(self, **kwargs) rect = SurroundingRectangle( image_mobject, **self.rect_kwargs ) self.add(rect, image_mobject) class PixelsAsSquares(VGroup): CONFIG = { "height" : 2, } def __init__(self, image_mobject, **kwargs): VGroup.__init__(self, **kwargs) for row in image_mobject.pixel_array: for rgba in row: square = Square( stroke_width = 0, fill_opacity = rgba[3]/255.0, fill_color = rgba_to_color(rgba/255.0), ) self.add(square) self.arrange_in_grid( *image_mobject.pixel_array.shape[:2], buff = 0 ) self.replace(image_mobject) class PixelsFromVect(PixelsAsSquares): def __init__(self, vect, **kwargs): PixelsAsSquares.__init__(self, ImageMobject(layer_to_image_array(vect)), **kwargs ) class MNistMobject(WrappedImage): def __init__(self, vect, **kwargs): WrappedImage.__init__(self, ImageMobject(layer_to_image_array(vect)), **kwargs ) class NetworkMobject(VGroup): CONFIG = { "neuron_radius" : 0.15, "neuron_to_neuron_buff" : MED_SMALL_BUFF, "layer_to_layer_buff" : LARGE_BUFF, "neuron_stroke_color" : BLUE, "neuron_stroke_width" : 3, "neuron_fill_color" : GREEN, "edge_color" : GREY_B, "edge_stroke_width" : 2, "edge_propogation_color" : YELLOW, "edge_propogation_time" : 1, "max_shown_neurons" : 16, "brace_for_large_layers" : True, "average_shown_activation_of_large_layer" : True, "include_output_labels" : False, } def __init__(self, neural_network, **kwargs): VGroup.__init__(self, **kwargs) self.neural_network = neural_network self.layer_sizes = neural_network.sizes self.add_neurons() self.add_edges() def add_neurons(self): layers = VGroup(*[ self.get_layer(size) for size in self.layer_sizes ]) layers.arrange(RIGHT, buff = self.layer_to_layer_buff) self.layers = layers self.add(self.layers) if self.include_output_labels: self.add_output_labels() def get_layer(self, size): layer = VGroup() n_neurons = size if n_neurons > self.max_shown_neurons: n_neurons = self.max_shown_neurons neurons = VGroup(*[ Circle( radius = self.neuron_radius, stroke_color = self.neuron_stroke_color, stroke_width = self.neuron_stroke_width, fill_color = self.neuron_fill_color, fill_opacity = 0, ) for x in range(n_neurons) ]) neurons.arrange( DOWN, buff = self.neuron_to_neuron_buff ) for neuron in neurons: neuron.edges_in = VGroup() neuron.edges_out = VGroup() layer.neurons = neurons layer.add(neurons) if size > n_neurons: dots = OldTex("\\vdots") dots.move_to(neurons) VGroup(*neurons[:len(neurons) // 2]).next_to( dots, UP, MED_SMALL_BUFF ) VGroup(*neurons[len(neurons) // 2:]).next_to( dots, DOWN, MED_SMALL_BUFF ) layer.dots = dots layer.add(dots) if self.brace_for_large_layers: brace = Brace(layer, LEFT) brace_label = brace.get_tex(str(size)) layer.brace = brace layer.brace_label = brace_label layer.add(brace, brace_label) return layer def add_edges(self): self.edge_groups = VGroup() for l1, l2 in zip(self.layers[:-1], self.layers[1:]): edge_group = VGroup() for n1, n2 in it.product(l1.neurons, l2.neurons): edge = self.get_edge(n1, n2) edge_group.add(edge) n1.edges_out.add(edge) n2.edges_in.add(edge) self.edge_groups.add(edge_group) self.add_to_back(self.edge_groups) def get_edge(self, neuron1, neuron2): return Line( neuron1.get_center(), neuron2.get_center(), buff = self.neuron_radius, stroke_color = self.edge_color, stroke_width = self.edge_stroke_width, ) def get_active_layer(self, layer_index, activation_vector): layer = self.layers[layer_index].deepcopy() self.activate_layer(layer, activation_vector) return layer def activate_layer(self, layer, activation_vector): n_neurons = len(layer.neurons) av = activation_vector def arr_to_num(arr): return (np.sum(arr > 0.1) / float(len(arr)))**(1./3) if len(av) > n_neurons: if self.average_shown_activation_of_large_layer: indices = np.arange(n_neurons) indices *= int(len(av)/n_neurons) indices = list(indices) indices.append(len(av)) av = np.array([ arr_to_num(av[i1:i2]) for i1, i2 in zip(indices[:-1], indices[1:]) ]) else: av = np.append( av[:n_neurons/2], av[-n_neurons/2:], ) for activation, neuron in zip(av, layer.neurons): neuron.set_fill( color = self.neuron_fill_color, opacity = activation ) return layer def activate_layers(self, input_vector): activations = self.neural_network.get_activation_of_all_layers(input_vector) for activation, layer in zip(activations, self.layers): self.activate_layer(layer, activation) def deactivate_layers(self): all_neurons = VGroup(*it.chain(*[ layer.neurons for layer in self.layers ])) all_neurons.set_fill(opacity = 0) return self def get_edge_propogation_animations(self, index): edge_group_copy = self.edge_groups[index].copy() edge_group_copy.set_stroke( self.edge_propogation_color, width = 1.5*self.edge_stroke_width ) return [ShowCreationThenDestruction( edge_group_copy, run_time = self.edge_propogation_time, lag_ratio = 0.5 )] def add_output_labels(self): self.output_labels = VGroup() for n, neuron in enumerate(self.layers[-1].neurons): label = OldTex(str(n)) label.set_height(0.75*neuron.get_height()) label.move_to(neuron) label.shift(neuron.get_width()*RIGHT) self.output_labels.add(label) self.add(self.output_labels) class MNistNetworkMobject(NetworkMobject): CONFIG = { "neuron_to_neuron_buff" : SMALL_BUFF, "layer_to_layer_buff" : 1.5, "edge_stroke_width" : 1, "include_output_labels" : True, } def __init__(self, **kwargs): network = get_pretrained_network() NetworkMobject.__init__(self, network, **kwargs) class NetworkScene(Scene): CONFIG = { "layer_sizes" : [8, 6, 6, 4], "network_mob_config" : {}, } def setup(self): self.add_network() def add_network(self): self.network = Network(sizes = self.layer_sizes) self.network_mob = NetworkMobject( self.network, **self.network_mob_config ) self.add(self.network_mob) def feed_forward(self, input_vector, false_confidence = False, added_anims = None): if added_anims is None: added_anims = [] activations = self.network.get_activation_of_all_layers( input_vector ) if false_confidence: i = np.argmax(activations[-1]) activations[-1] *= 0 activations[-1][i] = 1.0 for i, activation in enumerate(activations): self.show_activation_of_layer(i, activation, added_anims) added_anims = [] def show_activation_of_layer(self, layer_index, activation_vector, added_anims = None): if added_anims is None: added_anims = [] layer = self.network_mob.layers[layer_index] active_layer = self.network_mob.get_active_layer( layer_index, activation_vector ) anims = [Transform(layer, active_layer)] if layer_index > 0: anims += self.network_mob.get_edge_propogation_animations( layer_index-1 ) anims += added_anims self.play(*anims) def remove_random_edges(self, prop = 0.9): for edge_group in self.network_mob.edge_groups: for edge in list(edge_group): if np.random.random() < prop: edge_group.remove(edge) def make_transparent(image_mob): alpha_vect = np.array( image_mob.pixel_array[:,:,0], dtype = 'uint8' ) image_mob.set_color(WHITE) image_mob.pixel_array[:,:,3] = alpha_vect return image_mob ############################### class ExampleThrees(PiCreatureScene): def construct(self): self.show_initial_three() self.show_alternate_threes() self.resolve_remaining_threes() self.show_alternate_digits() def show_initial_three(self): randy = self.pi_creature self.three_mobs = self.get_three_mobs() three_mob = self.three_mobs[0] three_mob_copy = three_mob[1].copy() three_mob_copy.sort(lambda p : np.dot(p, DOWN+RIGHT)) braces = VGroup(*[Brace(three_mob, v) for v in (LEFT, UP)]) brace_labels = VGroup(*[ brace.get_text("28px") for brace in braces ]) bubble = randy.get_bubble(height = 4, width = 6) three_mob.generate_target() three_mob.target.set_height(1) three_mob.target.next_to(bubble[-1].get_left(), RIGHT, LARGE_BUFF) arrow = Arrow(LEFT, RIGHT, color = BLUE) arrow.next_to(three_mob.target, RIGHT) real_three = OldTex("3") real_three.set_height(0.8) real_three.next_to(arrow, RIGHT) self.play( FadeIn(three_mob[0]), LaggedStartMap(FadeIn, three_mob[1]) ) self.wait() self.play( LaggedStartMap( DrawBorderThenFill, three_mob_copy, run_time = 3, stroke_color = WHITE, remover = True, ), randy.change, "sassy", *it.chain( list(map(GrowFromCenter, braces)), list(map(FadeIn, brace_labels)) ) ) self.wait() self.play( ShowCreation(bubble), MoveToTarget(three_mob), FadeOut(braces), FadeOut(brace_labels), randy.change, "pondering" ) self.play( ShowCreation(arrow), Write(real_three) ) self.wait() self.bubble = bubble self.arrow = arrow self.real_three = real_three def show_alternate_threes(self): randy = self.pi_creature three = self.three_mobs[0] three.generate_target() three.target[0].set_fill(opacity = 0, family = False) for square in three.target[1]: yellow_rgb = color_to_rgb(YELLOW) square_rgb = color_to_rgb(square.get_fill_color()) square.set_fill( rgba_to_color(yellow_rgb*square_rgb), opacity = 0.5 ) alt_threes = VGroup(*self.three_mobs[1:]) alt_threes.arrange(DOWN) alt_threes.set_height(FRAME_HEIGHT - 2) alt_threes.to_edge(RIGHT) for alt_three in alt_threes: self.add(alt_three) self.wait(0.5) self.play( randy.change, "plain", *list(map(FadeOut, [ self.bubble, self.arrow, self.real_three ])) + [MoveToTarget(three)] ) for alt_three in alt_threes[:2]: self.play(three.replace, alt_three) self.wait() for moving_three in three, alt_threes[1]: moving_three.generate_target() moving_three.target.next_to(alt_threes, LEFT, LARGE_BUFF) moving_three.target[0].set_stroke(width = 0) moving_three.target[1].space_out_submobjects(1.5) self.play(MoveToTarget( moving_three, lag_ratio = 0.5 )) self.play( Animation(randy), moving_three.replace, randy.eyes[1], moving_three.scale, 0.7, run_time = 2, lag_ratio = 0.5, ) self.play( Animation(randy), FadeOut(moving_three) ) self.remaining_threes = [alt_threes[0], alt_threes[2]] def resolve_remaining_threes(self): randy = self.pi_creature left_three, right_three = self.remaining_threes equals = OldTex("=") equals.move_to(self.arrow) for three, vect in (left_three, LEFT), (right_three, RIGHT): three.generate_target() three.target.set_height(1) three.target.next_to(equals, vect) self.play( randy.change, "thinking", ShowCreation(self.bubble), MoveToTarget(left_three), MoveToTarget(right_three), Write(equals), ) self.wait() self.equals = equals def show_alternate_digits(self): randy = self.pi_creature cross = Cross(self.equals) cross.stretch_to_fit_height(0.5) three = self.remaining_threes[1] image_map = get_organized_images() arrays = [image_map[k][0] for k in range(8, 4, -1)] alt_mobs = [ WrappedImage( PixelsAsSquares(ImageMobject(layer_to_image_array(arr))), color = GREY_B, buff = 0 ).replace(three) for arr in arrays ] self.play( randy.change, "sassy", Transform(three, alt_mobs[0]), ShowCreation(cross) ) self.wait() for mob in alt_mobs[1:]: self.play(Transform(three, mob)) self.wait() ###### def create_pi_creature(self): return Randolph().to_corner(DOWN+LEFT) def get_three_mobs(self): three_arrays = get_organized_images()[3][:4] three_mobs = VGroup() for three_array in three_arrays: im_mob = ImageMobject( layer_to_image_array(three_array), height = 4, ) pixel_mob = PixelsAsSquares(im_mob) three_mob = WrappedImage( pixel_mob, color = GREY_B, buff = 0 ) three_mobs.add(three_mob) return three_mobs class BrainAndHow(Scene): def construct(self): brain = SVGMobject(file_name = "brain") brain.set_height(2) brain.set_fill(GREY_B) brain_outline = brain.copy() brain_outline.set_fill(opacity = 0) brain_outline.set_stroke(BLUE_B, 3) how = OldTexText("How?!?") how.scale(2) how.next_to(brain, UP) self.add(brain) self.play(Write(how)) for x in range(2): self.play( ShowPassingFlash( brain_outline, time_width = 0.5, run_time = 2 ) ) self.wait() class WriteAProgram(Scene): def construct(self): three_array = get_organized_images()[3][0] im_mob = ImageMobject(layer_to_image_array(three_array)) three = PixelsAsSquares(im_mob) three.sort(lambda p : np.dot(p, DOWN+RIGHT)) three.set_height(6) three.next_to(ORIGIN, LEFT) three_rect = SurroundingRectangle( three, color = BLUE, buff = SMALL_BUFF ) numbers = VGroup() for square in three: rgb = square.fill_rgb num = DecimalNumber( square.fill_rgb[0], num_decimal_places = 1 ) num.set_stroke(width = 1) color = rgba_to_color(1 - (rgb + 0.2)/1.2) num.set_color(color) num.set_width(0.7*square.get_width()) num.move_to(square) numbers.add(num) arrow = Arrow(LEFT, RIGHT, color = BLUE) arrow.next_to(three, RIGHT) choices = VGroup(*[Tex(str(n)) for n in range(10)]) choices.arrange(DOWN) choices.set_height(FRAME_HEIGHT - 1) choices.next_to(arrow, RIGHT) self.play( LaggedStartMap(DrawBorderThenFill, three), ShowCreation(three_rect) ) self.play(Write(numbers)) self.play( ShowCreation(arrow), LaggedStartMap(FadeIn, choices), ) rect = SurroundingRectangle(choices[0], buff = SMALL_BUFF) q_mark = OldTex("?") q_mark.next_to(rect, RIGHT) self.play(ShowCreation(rect)) for n in 8, 1, 5, 3: self.play( rect.move_to, choices[n], MaintainPositionRelativeTo(q_mark, rect) ) self.wait(1) choice = choices[3] choices.remove(choice) choice.add(rect) self.play( choice.scale, 1.5, choice.next_to, arrow, RIGHT, FadeOut(choices), FadeOut(q_mark), ) self.wait(2) class LayOutPlan(TeacherStudentsScene, NetworkScene): def setup(self): TeacherStudentsScene.setup(self) NetworkScene.setup(self) self.remove(self.network_mob) def construct(self): self.force_skipping() self.show_words() self.show_network() self.show_math() self.ask_about_layers() self.show_learning() self.show_videos() def show_words(self): words = VGroup( OldTexText("Machine", "learning").set_color(GREEN), OldTexText("Neural network").set_color(BLUE), ) words.next_to(self.teacher.get_corner(UP+LEFT), UP) words[0].save_state() words[0].shift(DOWN) words[0].fade(1) self.play( words[0].restore, self.teacher.change, "raise_right_hand", self.change_students("pondering", "erm", "sassy") ) self.play( words[0].shift, MED_LARGE_BUFF*UP, FadeIn(words[1]), ) self.play_student_changes( *["pondering"]*3, look_at = words ) self.play(words.to_corner, UP+RIGHT) self.words = words def show_network(self): network_mob = self.network_mob network_mob.next_to(self.students, UP) self.play( ReplacementTransform( VGroup(self.words[1].copy()), network_mob.layers ), self.change_students( *["confused"]*3, lag_ratio = 0 ), self.teacher.change, "plain", run_time = 1 ) self.play(ShowCreation( network_mob.edge_groups, lag_ratio = 0.5, run_time = 2, rate_func=linear, )) in_vect = np.random.random(self.network.sizes[0]) self.feed_forward(in_vect) def show_math(self): equation = OldTex( "\\textbf{a}_{l+1}", "=", "\\sigma(", "W_l", "\\textbf{a}_l", "+", "b_l", ")" ) equation.set_color_by_tex_to_color_map({ "\\textbf{a}" : GREEN, }) equation.move_to(self.network_mob.get_corner(UP+RIGHT)) equation.to_edge(UP) self.play(Write(equation, run_time = 2)) self.wait() self.equation = equation def ask_about_layers(self): self.student_says( "Why the layers?", index = 2, bubble_config = {"direction" : LEFT} ) self.wait() self.play(RemovePiCreatureBubble(self.students[2])) def show_learning(self): word = self.words[0][1].copy() rect = SurroundingRectangle(word, color = YELLOW) self.network_mob.neuron_fill_color = YELLOW layer = self.network_mob.layers[-1] activation = np.zeros(len(layer.neurons)) activation[1] = 1.0 active_layer = self.network_mob.get_active_layer( -1, activation ) word_group = VGroup(word, rect) word_group.generate_target() word_group.target.move_to(self.equation, LEFT) word_group.target[0].set_color(YELLOW) word_group.target[1].set_stroke(width = 0) self.play(ShowCreation(rect)) self.play( Transform(layer, active_layer), FadeOut(self.equation), MoveToTarget(word_group), ) for edge_group in reversed(self.network_mob.edge_groups): edge_group.generate_target() for edge in edge_group.target: edge.set_stroke( YELLOW, width = 4*np.random.random()**2 ) self.play(MoveToTarget(edge_group)) self.wait() self.learning_word = word def show_videos(self): network_mob = self.network_mob learning = self.learning_word structure = OldTexText("Structure") structure.set_color(YELLOW) videos = VGroup(*[ VideoIcon().set_fill(RED) for x in range(2) ]) videos.set_height(1.5) videos.arrange(RIGHT, buff = LARGE_BUFF) videos.next_to(self.students, UP, LARGE_BUFF) network_mob.generate_target() network_mob.target.set_height(0.8*videos[0].get_height()) network_mob.target.move_to(videos[0]) learning.generate_target() learning.target.next_to(videos[1], UP) structure.next_to(videos[0], UP) structure.shift(0.5*SMALL_BUFF*UP) self.revert_to_original_skipping_status() self.play( MoveToTarget(network_mob), MoveToTarget(learning) ) self.play( DrawBorderThenFill(videos[0]), FadeIn(structure), self.change_students(*["pondering"]*3) ) self.wait() self.play(DrawBorderThenFill(videos[1])) self.wait() class PreviewMNistNetwork(NetworkScene): CONFIG = { "n_examples" : 15, "network_mob_config" : {}, } def construct(self): self.remove_random_edges(0.7) #Remove? training_data, validation_data, test_data = load_data_wrapper() for data in test_data[:self.n_examples]: self.feed_in_image(data[0]) def feed_in_image(self, in_vect): image = PixelsFromVect(in_vect) image.next_to(self.network_mob, LEFT, LARGE_BUFF, UP) image.shift_onto_screen() image_rect = SurroundingRectangle(image, color = BLUE) start_neurons = self.network_mob.layers[0].neurons.copy() start_neurons.set_stroke(WHITE, width = 0) start_neurons.set_fill(WHITE, 0) self.play(FadeIn(image), FadeIn(image_rect)) self.feed_forward(in_vect, added_anims = [ self.get_image_to_layer_one_animation(image, start_neurons) ]) n = np.argmax([ neuron.get_fill_opacity() for neuron in self.network_mob.layers[-1].neurons ]) rect = SurroundingRectangle(VGroup( self.network_mob.layers[-1].neurons[n], self.network_mob.output_labels[n], )) self.play(ShowCreation(rect)) self.reset_display(rect, image, image_rect) def reset_display(self, answer_rect, image, image_rect): self.play(FadeOut(answer_rect)) self.play( FadeOut(image), FadeOut(image_rect), self.network_mob.deactivate_layers, ) def get_image_to_layer_one_animation(self, image, start_neurons): image_mover = VGroup(*[ pixel.copy() for pixel in image if pixel.fill_rgb[0] > 0.1 ]) return Transform( image_mover, start_neurons, remover = True, run_time = 1, ) ### def add_network(self): self.network_mob = MNistNetworkMobject(**self.network_mob_config) self.network = self.network_mob.neural_network self.add(self.network_mob) class AlternateNeuralNetworks(PiCreatureScene): def construct(self): morty = self.pi_creature examples = VGroup( VGroup( OldTexText("Convolutional neural network"), OldTexText("Good for image recognition"), ), VGroup( OldTexText("Long short-term memory network"), OldTexText("Good for speech recognition"), ) ) for ex in examples: arrow = Arrow(LEFT, RIGHT, color = BLUE) ex[0].next_to(arrow, LEFT) ex[1].next_to(arrow, RIGHT) ex.submobjects.insert(1, arrow) examples.set_width(FRAME_WIDTH - 1) examples.next_to(morty, UP).to_edge(RIGHT) maybe_words = OldTexText("Maybe future videos?") maybe_words.scale(0.8) maybe_words.next_to(morty, UP) maybe_words.to_edge(RIGHT) maybe_words.set_color(YELLOW) self.play( Write(examples[0], run_time = 2), morty.change, "raise_right_hand" ) self.wait() self.play( examples[0].shift, MED_LARGE_BUFF*UP, FadeIn(examples[1], lag_ratio = 0.5), ) self.wait() self.play( examples.shift, UP, FadeIn(maybe_words), morty.change, "maybe" ) self.wait(2) class PlainVanillaWrapper(Scene): def construct(self): title = OldTexText("Plain vanilla") subtitle = OldTexText("(aka ``multilayer perceptron'')") title.scale(1.5) title.to_edge(UP) subtitle.next_to(title, DOWN) self.add(title) self.wait(2) self.play(Write(subtitle, run_time = 2)) self.wait(2) class NotPerfectAddOn(Scene): def construct(self): words = OldTexText("Not perfect!") words.scale(1.5) arrow = Arrow(UP+RIGHT, DOWN+LEFT, color = RED) words.set_color(RED) arrow.to_corner(DOWN+LEFT) words.next_to(arrow, UP+RIGHT) self.play( Write(words), ShowCreation(arrow), run_time = 1 ) self.wait(2) class MoreAThanI(TeacherStudentsScene): def construct(self): self.teacher_says( "More \\\\ A than I", target_mode = "hesitant" ) self.play_student_changes("sad", "erm", "tired") self.wait(2) class BreakDownName(Scene): def construct(self): self.ask_questions() self.show_neuron() def ask_questions(self): name = OldTexText("Neural", "network") name.to_edge(UP) q1 = OldTexText( "What are \\\\ the ", "neuron", "s?", arg_separator = "" ) q2 = OldTexText("How are \\\\ they connected?") q1.next_to(name[0].get_bottom(), DOWN, buff = LARGE_BUFF) q2.next_to(name[1].get_bottom(), DOWN+RIGHT, buff = LARGE_BUFF) a1 = Arrow(q1.get_top(), name[0].get_bottom()) a2 = Arrow(q2.get_top(), name.get_corner(DOWN+RIGHT)) VGroup(q1, a1).set_color(BLUE) VGroup(q2, a2).set_color(YELLOW) randy = Randolph().to_corner(DOWN+LEFT) brain = SVGMobject(file_name = "brain") brain.set_fill(GREY_B, opacity = 0) brain.replace(randy.eyes, dim_to_match = 1) self.add(name) self.play(randy.change, "pondering") self.play( brain.set_height, 2, brain.shift, 2*UP, brain.set_fill, None, 1, randy.look, UP ) brain_outline = brain.copy() brain_outline.set_fill(opacity = 0) brain_outline.set_stroke(BLUE_B, 3) self.play( ShowPassingFlash( brain_outline, time_width = 0.5, run_time = 2 ) ) self.play(Blink(randy)) self.wait() self.play( Write(q1, run_time = 1), ShowCreation(a1), name[0].set_color, q1.get_color(), ) self.play( Write(q2, run_time = 1), ShowCreation(a2), name[1].set_color, q2.get_color() ) self.wait(2) self.play(*list(map(FadeOut, [ name, randy, brain, q2, a1, a2, q1[0], q1[2] ]))) self.neuron_word = q1[1] def show_neuron(self): neuron_word = OldTexText("Neuron") arrow = OldTex("\\rightarrow") arrow.shift(LEFT) description = OldTexText("Thing that holds a number") neuron_word.set_color(BLUE) neuron_word.next_to(arrow, LEFT) neuron_word.shift(0.5*SMALL_BUFF*UP) description.next_to(arrow, RIGHT) neuron = Circle(radius = 0.35, color = BLUE) neuron.next_to(neuron_word, UP, MED_LARGE_BUFF) num = OldTex("0.2") num.set_width(0.7*neuron.get_width()) num.move_to(neuron) num.save_state() num.move_to(description.get_right()) num.set_fill(opacity = 1) self.play( ReplacementTransform(self.neuron_word, neuron_word), ShowCreation(neuron) ) self.play( ShowCreation(arrow), Write(description, run_time = 1) ) self.wait() self.play( neuron.set_fill, None, 0.2, num.restore ) self.wait() for value in 0.8, 0.4, 0.1, 0.5: mob = OldTex(str(value)) mob.replace(num) self.play( neuron.set_fill, None, value, Transform(num, mob) ) self.wait() class IntroduceEachLayer(PreviewMNistNetwork): CONFIG = { "network_mob_config" : { "neuron_stroke_color" : WHITE, "neuron_stroke_width" : 2, "neuron_fill_color" : WHITE, "average_shown_activation_of_large_layer" : False, "edge_propogation_color" : YELLOW, "edge_propogation_time" : 2, } } def construct(self): self.setup_network_mob() self.break_up_image_as_neurons() self.show_activation_of_one_neuron() self.transform_into_full_network() self.show_output_layer() self.show_hidden_layers() self.show_propogation() def setup_network_mob(self): self.remove(self.network_mob) def break_up_image_as_neurons(self): self.image_map = get_organized_images() image = self.image_map[9][0] image_mob = PixelsFromVect(image) image_mob.set_height(4) image_mob.next_to(ORIGIN, LEFT) rect = SurroundingRectangle(image_mob, color = BLUE) neurons = VGroup() for pixel in image_mob: pixel.set_fill(WHITE, opacity = pixel.fill_rgb[0]) neuron = Circle( color = WHITE, stroke_width = 1, radius = pixel.get_width()/2 ) neuron.move_to(pixel) neuron.set_fill(WHITE, pixel.get_fill_opacity()) neurons.add(neuron) neurons.scale(1.2) neurons.space_out_submobjects(1.3) neurons.to_edge(DOWN) braces = VGroup(*[Brace(neurons, vect) for vect in (LEFT, UP)]) labels = VGroup(*[ brace.get_tex("28", buff = SMALL_BUFF) for brace in braces ]) equation = OldTex("28", "\\times", "28", "=", "784") equation.next_to(neurons, RIGHT, LARGE_BUFF, UP) self.corner_image = MNistMobject(image) self.corner_image.to_corner(UP+LEFT) self.add(image_mob, rect) self.wait() self.play( ReplacementTransform(image_mob, neurons), FadeOut(rect), FadeIn(braces), FadeIn(labels), ) self.wait() self.play( ReplacementTransform(labels[0].copy(), equation[0]), Write(equation[1]), ReplacementTransform(labels[1].copy(), equation[2]), Write(equation[3]), Write(equation[4]), ) self.wait() self.neurons = neurons self.braces = braces self.brace_labels = labels self.num_pixels_equation = equation self.image_vect = image def show_activation_of_one_neuron(self): neurons = self.neurons numbers = VGroup() example_neuron = None example_num = None for neuron in neurons: o = neuron.get_fill_opacity() num = DecimalNumber(o, num_decimal_places = 1) num.set_width(0.7*neuron.get_width()) num.move_to(neuron) if o > 0.8: num.set_fill(BLACK) numbers.add(num) if o > 0.25 and o < 0.75 and example_neuron is None: example_neuron = neuron example_num = num example_neuron.save_state() example_num.save_state() example_neuron.generate_target() example_neuron.target.set_height(1.5) example_neuron.target.next_to(neurons, RIGHT) example_num.target = DecimalNumber( example_neuron.get_fill_opacity() ) example_num.target.move_to(example_neuron.target) def change_activation(num): self.play( example_neuron.set_fill, None, num, ChangingDecimal( example_num, lambda a : example_neuron.get_fill_opacity(), ), UpdateFromFunc( example_num, lambda m : m.set_fill( BLACK if example_neuron.get_fill_opacity() > 0.8 else WHITE ) ) ) self.play(LaggedStartMap(FadeIn, numbers)) self.play( MoveToTarget(example_neuron), MoveToTarget(example_num) ) self.wait() curr_opacity = example_neuron.get_fill_opacity() for num in 0.3, 0.01, 1.0, curr_opacity: change_activation(num) self.wait() rect = SurroundingRectangle(example_num, color = YELLOW) activation = OldTexText("``Activation''") activation.next_to(example_neuron, RIGHT) activation.set_color(rect.get_color()) self.play(ShowCreation(rect)) self.play(Write(activation, run_time = 1)) self.wait() change_activation(1.0) self.wait() change_activation(0.2) self.wait() self.play( example_neuron.restore, example_num.restore, FadeOut(activation), FadeOut(rect), ) self.play(FadeOut(numbers)) def transform_into_full_network(self): network_mob = self.network_mob neurons = self.neurons layer = network_mob.layers[0] layer.save_state() layer.rotate(np.pi/2) layer.center() layer.brace_label.rotate(-np.pi/2) n = network_mob.max_shown_neurons/2 rows = VGroup(*[ VGroup(*neurons[28*i:28*(i+1)]) for i in range(28) ]) self.play( FadeOut(self.braces), FadeOut(self.brace_labels), FadeOut(VGroup(*self.num_pixels_equation[:-1])) ) self.play(rows.space_out_submobjects, 1.2) self.play( rows.arrange, RIGHT, buff = SMALL_BUFF, path_arc = np.pi/2, run_time = 2 ) self.play( ReplacementTransform( VGroup(*neurons[:n]), VGroup(*layer.neurons[:n]), ), ReplacementTransform( VGroup(*neurons[n:-n]), layer.dots, ), ReplacementTransform( VGroup(*neurons[-n:]), VGroup(*layer.neurons[-n:]), ), ) self.play( ReplacementTransform( self.num_pixels_equation[-1], layer.brace_label ), FadeIn(layer.brace), ) self.play(layer.restore, FadeIn(self.corner_image)) self.wait() for edge_group, layer in zip(network_mob.edge_groups, network_mob.layers[1:]): self.play( LaggedStartMap(FadeIn, layer, run_time = 1), ShowCreation(edge_group), ) self.wait() def show_output_layer(self): layer = self.network_mob.layers[-1] labels = self.network_mob.output_labels rect = SurroundingRectangle( VGroup(layer, labels) ) neuron = layer.neurons[-1] neuron.set_fill(WHITE, 0) label = labels[-1] for mob in neuron, label: mob.save_state() mob.generate_target() neuron.target.scale(4) neuron.target.shift(1.5*RIGHT) label.target.scale(1.5) label.target.next_to(neuron.target, RIGHT) activation = DecimalNumber(0) activation.move_to(neuron.target) def change_activation(num): self.play( neuron.set_fill, None, num, ChangingDecimal( activation, lambda a : neuron.get_fill_opacity(), ), UpdateFromFunc( activation, lambda m : m.set_fill( BLACK if neuron.get_fill_opacity() > 0.8 else WHITE ) ) ) self.play(ShowCreation(rect)) self.play(LaggedStartMap(FadeIn, labels)) self.wait() self.play( MoveToTarget(neuron), MoveToTarget(label), ) self.play(FadeIn(activation)) for num in 0.5, 0.38, 0.97: change_activation(num) self.wait() self.play( neuron.restore, neuron.set_fill, None, 1, label.restore, FadeOut(activation), FadeOut(rect), ) self.wait() def show_hidden_layers(self): hidden_layers = VGroup(*self.network_mob.layers[1:3]) rect = SurroundingRectangle(hidden_layers, color = YELLOW) name = OldTexText("``Hidden layers''") name.next_to(rect, UP, SMALL_BUFF) name.set_color(YELLOW) q_marks = VGroup() for layer in hidden_layers: for neuron in layer.neurons: q_mark = OldTexText("?") q_mark.set_height(0.8*neuron.get_height()) q_mark.move_to(neuron) q_marks.add(q_mark) q_marks.set_color_by_gradient(BLUE, YELLOW) q_mark = OldTexText("?").scale(4) q_mark.move_to(hidden_layers) q_mark.set_color(YELLOW) q_marks.add(q_mark) self.play( ShowCreation(rect), Write(name) ) self.wait() self.play(Write(q_marks)) self.wait() self.play( FadeOut(q_marks), Animation(q_marks[-1].copy()) ) def show_propogation(self): self.revert_to_original_skipping_status() self.remove_random_edges(0.7) self.feed_forward(self.image_vect) class DiscussChoiceForHiddenLayers(TeacherStudentsScene): def construct(self): network_mob = MNistNetworkMobject( layer_to_layer_buff = 2.5, neuron_stroke_color = WHITE, ) network_mob.set_height(4) network_mob.to_edge(UP, buff = LARGE_BUFF) layers = VGroup(*network_mob.layers[1:3]) rects = VGroup(*list(map(SurroundingRectangle, layers))) self.add(network_mob) two_words = OldTexText("2 hidden layers") two_words.set_color(YELLOW) sixteen_words = OldTexText("16 neurons each") sixteen_words.set_color(MAROON_B) for words in two_words, sixteen_words: words.next_to(rects, UP) neurons_anim = LaggedStartMap( Indicate, VGroup(*it.chain(*[layer.neurons for layer in layers])), rate_func = there_and_back, scale_factor = 2, color = MAROON_B, ) self.play( ShowCreation(rects), Write(two_words, run_time = 1), self.teacher.change, "raise_right_hand", ) self.wait() self.play( FadeOut(rects), ReplacementTransform(two_words, sixteen_words), neurons_anim ) self.wait() self.play(self.teacher.change, "shruggie") self.play_student_changes("erm", "confused", "sassy") self.wait() self.student_says( "Why 2 \\\\ layers?", index = 1, bubble_config = {"direction" : RIGHT}, run_time = 1, target_mode = "raise_left_hand", ) self.play(self.teacher.change, "happy") self.wait() self.student_says( "Why 16?", index = 0, run_time = 1, ) self.play(neurons_anim, run_time = 3) self.play( self.teacher.change, "shruggie", RemovePiCreatureBubble(self.students[0]), ) self.wait() class MoreHonestMNistNetworkPreview(IntroduceEachLayer): CONFIG = { "network_mob_config" : { "edge_propogation_time" : 1.5, } } def construct(self): PreviewMNistNetwork.construct(self) def get_image_to_layer_one_animation(self, image, start_neurons): neurons = VGroup() for pixel in image: neuron = Circle( radius = pixel.get_width()/2, stroke_width = 1, stroke_color = WHITE, fill_color = WHITE, fill_opacity = pixel.fill_rgb[0] ) neuron.move_to(pixel) neurons.add(neuron) neurons.scale(1.2) neurons.next_to(image, DOWN) n = len(start_neurons) point = VectorizedPoint(start_neurons.get_center()) target = VGroup(*it.chain( start_neurons[:n/2], [point.copy() for x in range(len(neurons)-n)], start_neurons[n/2:], )) mover = image.copy() self.play(Transform(mover, neurons)) return Transform( mover, target, run_time = 2, lag_ratio = 0.5, remover = True ) class AskAboutPropogationAndTraining(TeacherStudentsScene): def construct(self): self.student_says( "How does one layer \\\\ influence the next?", index = 0, run_time = 1 ) self.wait() self.student_says( "How does \\\\ training work?", index = 2, run_time = 1 ) self.wait(3) class AskAboutLayers(PreviewMNistNetwork): def construct(self): self.play( self.network_mob.scale, 0.8, self.network_mob.to_edge, DOWN, ) question = OldTexText("Why the", "layers?") question.to_edge(UP) neuron_groups = [ layer.neurons for layer in self.network_mob.layers ] arrows = VGroup(*[ Arrow( question[1].get_bottom(), group.get_top() ) for group in neuron_groups ]) rects = list(map(SurroundingRectangle, neuron_groups[1:3])) self.play( Write(question, run_time = 1), LaggedStartMap( GrowFromPoint, arrows, lambda a : (a, a.get_start()), run_time = 2 ) ) self.wait() self.play(*list(map(ShowCreation, rects))) self.wait() class BreakUpMacroPatterns(IntroduceEachLayer): CONFIG = { "camera_config" : {"background_opacity" : 1}, "prefixes" : [ "nine", "eight", "four", "upper_loop", "right_line", "lower_loop", "horizontal_line", "upper_left_line" ] } def construct(self): self.setup_network_mob() self.setup_needed_patterns() self.setup_added_patterns() self.show_nine() self.show_eight() self.show_four() self.show_second_to_last_layer() self.show_upper_loop_activation() self.show_what_learning_is_required() def setup_needed_patterns(self): prefixes = self.prefixes vects = [ np.array(Image.open( get_full_raster_image_path("handwritten_" + p), ))[:,:,0].flatten()/255.0 for p in prefixes ] mobjects = list(map(MNistMobject, vects)) for mob in mobjects: image = mob[1] self.make_transparent(image) for prefix, mob in zip(prefixes, mobjects): setattr(self, prefix, mob) def setup_added_patterns(self): image_map = get_organized_images() two, three, five = mobs = [ MNistMobject(image_map[n][0]) for n in (2, 3, 5) ] self.added_patterns = VGroup() for mob in mobs: for i, j in it.product([0, 14], [0, 14]): pattern = mob.deepcopy() pa = pattern[1].pixel_array temp = np.array(pa[i:i+14,j:j+14,:], dtype = 'uint8') pa[:,:] = 0 pa[i:i+14,j:j+14,:] = temp self.make_transparent(pattern[1]) pattern[1].set_color(random_bright_color()) self.added_patterns.add(pattern) self.image_map = image_map def show_nine(self): nine = self.nine upper_loop = self.upper_loop right_line = self.right_line equation = self.get_equation(nine, upper_loop, right_line) equation.to_edge(UP) equation.shift(LEFT) parts = [upper_loop[1], right_line[1]] for mob, color in zip(parts, [YELLOW, RED]): mob.set_color(color) mob.save_state() mob.move_to(nine) right_line[1].pixel_array[:14,:,3] = 0 self.play(FadeIn(nine)) self.wait() self.play(*list(map(FadeIn, parts))) self.wait() self.play( Write(equation[1]), upper_loop[1].restore, FadeIn(upper_loop[0]) ) self.wait() self.play( Write(equation[3]), right_line[1].restore, FadeIn(right_line[0]), ) self.wait() self.nine_equation = equation def show_eight(self): eight = self.eight upper_loop = self.upper_loop.deepcopy() lower_loop = self.lower_loop lower_loop[1].set_color(GREEN) equation = self.get_equation(eight, upper_loop, lower_loop) equation.next_to(self.nine_equation, DOWN) lower_loop[1].save_state() lower_loop[1].move_to(eight[1]) self.play( FadeIn(eight), Write(equation[1]), ) self.play(ReplacementTransform( self.upper_loop.copy(), upper_loop )) self.wait() self.play(FadeIn(lower_loop[1])) self.play( Write(equation[3]), lower_loop[1].restore, FadeIn(lower_loop[0]), ) self.wait() self.eight_equation = equation def show_four(self): four = self.four upper_left_line = self.upper_left_line upper_left_line[1].set_color(BLUE) horizontal_line = self.horizontal_line horizontal_line[1].set_color(MAROON_B) right_line = self.right_line.deepcopy() equation = self.get_equation(four, right_line, upper_left_line, horizontal_line) equation.next_to( self.eight_equation, DOWN, aligned_edge = LEFT ) self.play( FadeIn(four), Write(equation[1]) ) self.play(ReplacementTransform( self.right_line.copy(), right_line )) self.play(LaggedStartMap( FadeIn, VGroup(*equation[3:]) )) self.wait(2) self.four_equation = equation def show_second_to_last_layer(self): everything = VGroup(*it.chain( self.nine_equation, self.eight_equation, self.four_equation, )) patterns = VGroup( self.upper_loop, self.lower_loop, self.right_line, self.upper_left_line, self.horizontal_line, *self.added_patterns[:11] ) for pattern in patterns: pattern.add_to_back( pattern[1].copy().set_color(BLACK, alpha = 1) ) everything.remove(*patterns) network_mob = self.network_mob layer = network_mob.layers[-2] patterns.generate_target() for pattern, neuron in zip(patterns.target, layer.neurons): pattern.set_height(neuron.get_height()) pattern.next_to(neuron, RIGHT, SMALL_BUFF) for pattern in patterns[5:]: pattern.fade(1) self.play(*list(map(FadeOut, everything))) self.play( FadeIn( network_mob, lag_ratio = 0.5, run_time = 3, ), MoveToTarget(patterns) ) self.wait(2) self.patterns = patterns def show_upper_loop_activation(self): neuron = self.network_mob.layers[-2].neurons[0] words = OldTexText("Upper loop neuron...maybe...") words.scale(0.8) words.next_to(neuron, UP) words.shift(RIGHT) rect = SurroundingRectangle(VGroup( neuron, self.patterns[0] )) nine = self.nine upper_loop = self.upper_loop.copy() upper_loop.remove(upper_loop[0]) upper_loop.replace(nine) nine.add(upper_loop) nine.to_corner(UP+LEFT) self.remove_random_edges(0.7) self.network.get_activation_of_all_layers = lambda v : [ np.zeros(784), sigmoid(6*(np.random.random(16)-0.5)), np.array([1, 0, 1] + 13*[0]), np.array(9*[0] + [1]) ] self.play(FadeIn(nine)) self.play( ShowCreation(rect), Write(words) ) self.add_foreground_mobject(self.patterns) self.feed_forward(np.random.random(784)) self.wait(2) def show_what_learning_is_required(self): edge_group = self.network_mob.edge_groups[-1].copy() edge_group.set_stroke(YELLOW, 4) for x in range(3): self.play(LaggedStartMap( ShowCreationThenDestruction, edge_group, run_time = 3 )) self.wait() ###### def get_equation(self, *mobs): equation = VGroup( mobs[0], OldTex("=").scale(2), *list(it.chain(*[ [m, OldTex("+").scale(2)] for m in mobs[1:-1] ])) + [mobs[-1]] ) equation.arrange(RIGHT) return equation def make_transparent(self, image_mob): return make_transparent(image_mob) alpha_vect = np.array( image_mob.pixel_array[:,:,0], dtype = 'uint8' ) image_mob.set_color(WHITE) image_mob.pixel_array[:,:,3] = alpha_vect return image_mob class GenerallyLoopyPattern(Scene): def construct(self): image_map = get_organized_images() images = list(map(MNistMobject, it.chain( image_map[8], image_map[9], ))) random.shuffle(images) for image in images: image.to_corner(DOWN+RIGHT) self.add(image) self.wait(0.2) self.remove(image) class HowWouldYouRecognizeSubcomponent(TeacherStudentsScene): def construct(self): self.student_says( "Okay, but recognizing loops \\\\", "is just as hard!", target_mode = "sassy" ) self.play( self.teacher.change, "guilty" ) self.wait() class BreakUpMicroPatterns(BreakUpMacroPatterns): CONFIG = { "prefixes" : [ "loop", "loop_edge1", "loop_edge2", "loop_edge3", "loop_edge4", "loop_edge5", "right_line", "right_line_edge1", "right_line_edge2", "right_line_edge3", ] } def construct(self): self.setup_network_mob() self.setup_needed_patterns() self.break_down_loop() self.break_down_long_line() def break_down_loop(self): loop = self.loop loop[0].set_color(WHITE) edges = Group(*[ getattr(self, "loop_edge%d"%d) for d in range(1, 6) ]) colors = color_gradient([BLUE, YELLOW, RED], 5) for edge, color in zip(edges, colors): for mob in edge: mob.set_color(color) loop.generate_target() edges.generate_target() for edge in edges: edge[0].set_stroke(width = 0) edge.save_state() edge[1].set_opacity(0) equation = self.get_equation(loop.target, *edges.target) equation.set_width(FRAME_WIDTH - 1) equation.to_edge(UP) symbols = VGroup(*equation[1::2]) randy = Randolph() randy.to_corner(DOWN+LEFT) self.add(randy) self.play( FadeIn(loop), randy.change, "pondering", loop ) self.play(Blink(randy)) self.wait() self.play(LaggedStartMap( ApplyMethod, edges, lambda e : (e.restore,), run_time = 4 )) self.wait() self.play( MoveToTarget(loop, run_time = 2), MoveToTarget(edges, run_time = 2), Write(symbols), randy.change, "happy", equation, ) self.wait() self.loop_equation = equation self.randy = randy def break_down_long_line(self): randy = self.randy line = self.right_line line[0].set_color(WHITE) edges = Group(*[ getattr(self, "right_line_edge%d"%d) for d in range(1, 4) ]) colors = Color(MAROON_B).range_to(PURPLE, 3) for edge, color in zip(edges, colors): for mob in edge: mob.set_color(color) equation = self.get_equation(line, *edges) equation.set_height(self.loop_equation.get_height()) equation.next_to( self.loop_equation, DOWN, MED_LARGE_BUFF, LEFT ) image_map = get_organized_images() digits = VGroup(*[ MNistMobject(image_map[n][1]) for n in (1, 4, 7) ]) digits.arrange(RIGHT) digits.next_to(randy, RIGHT) self.revert_to_original_skipping_status() self.play( FadeIn(line), randy.change, "hesitant", line ) self.play(Blink(randy)) self.play(LaggedStartMap(FadeIn, digits)) self.wait() self.play( LaggedStartMap(FadeIn, Group(*equation[1:])), randy.change, "pondering", equation ) self.wait(3) class SecondLayerIsLittleEdgeLayer(IntroduceEachLayer): CONFIG = { "camera_config" : { "background_opacity" : 1, }, "network_mob_config" : { "layer_to_layer_buff" : 2, "edge_propogation_color" : YELLOW, } } def construct(self): self.setup_network_mob() self.setup_activations_and_nines() self.describe_second_layer() self.show_propogation() self.ask_question() def setup_network_mob(self): self.network_mob.scale(0.7) self.network_mob.to_edge(DOWN) self.remove_random_edges(0.7) def setup_activations_and_nines(self): layers = self.network_mob.layers nine_im, loop_im, line_im = images = [ Image.open(get_full_raster_image_path("handwritten_%s"%s)) for s in ("nine", "upper_loop", "right_line") ] nine_array, loop_array, line_array = [ np.array(im)[:,:,0]/255.0 for im in images ] self.nine = MNistMobject(nine_array.flatten()) self.nine.set_height(1.5) self.nine[0].set_color(WHITE) make_transparent(self.nine[1]) self.nine.next_to(layers[0].neurons, UP) self.activations = self.network.get_activation_of_all_layers( nine_array.flatten() ) self.activations[-2] = np.array([1, 0, 1] + 13*[0]) self.edge_colored_nine = Group() nine_pa = self.nine[1].pixel_array n, k = 6, 4 colors = color_gradient([BLUE, YELLOW, RED, MAROON_B, GREEN], 10) for i, j in it.product(list(range(n)), list(range(k))): mob = ImageMobject(np.zeros((28, 28, 4), dtype = 'uint8')) mob.replace(self.nine[1]) pa = mob.pixel_array color = colors[(k*i + j)%(len(colors))] rgb = (255*color_to_rgb(color)).astype('uint8') pa[:,:,:3] = rgb i0, i1 = 1+(28/n)*i, 1+(28/n)*(i+1) j0, j1 = (28/k)*j, (28/k)*(j+1) pa[i0:i1,j0:j1,3] = nine_pa[i0:i1,j0:j1,3] self.edge_colored_nine.add(mob) self.edge_colored_nine.next_to(layers[1], UP) loop, line = [ ImageMobject(layer_to_image_array(array.flatten())) for array in (loop_array, line_array) ] for mob, color in (loop, YELLOW), (line, RED): make_transparent(mob) mob.set_color(color) mob.replace(self.nine[1]) line.pixel_array[:14,:,:] = 0 self.pattern_colored_nine = Group(loop, line) self.pattern_colored_nine.next_to(layers[2], UP) for mob in self.edge_colored_nine, self.pattern_colored_nine: mob.align_to(self.nine[1], UP) def describe_second_layer(self): layer = self.network_mob.layers[1] rect = SurroundingRectangle(layer) words = OldTexText("``Little edge'' layer?") words.next_to(rect, UP, MED_LARGE_BUFF) words.set_color(YELLOW) self.play( ShowCreation(rect), Write(words, run_time = 2) ) self.wait() self.play(*list(map(FadeOut, [rect, words]))) def show_propogation(self): nine = self.nine edge_colored_nine = self.edge_colored_nine pattern_colored_nine = self.pattern_colored_nine activations = self.activations network_mob = self.network_mob layers = network_mob.layers edge_groups = network_mob.edge_groups.copy() edge_groups.set_stroke(YELLOW, 4) v_nine = PixelsAsSquares(nine[1]) neurons = VGroup() for pixel in v_nine: neuron = Circle( radius = pixel.get_width()/2, stroke_color = WHITE, stroke_width = 1, fill_color = WHITE, fill_opacity = pixel.get_fill_opacity(), ) neuron.rotate(3*np.pi/4) neuron.move_to(pixel) neurons.add(neuron) neurons.set_height(2) neurons.space_out_submobjects(1.2) neurons.next_to(network_mob, LEFT) self.set_neurons_target(neurons, layers[0]) pattern_colored_nine.save_state() pattern_colored_nine.move_to(edge_colored_nine) edge_colored_nine.save_state() edge_colored_nine.move_to(nine[1]) for mob in edge_colored_nine, pattern_colored_nine: for submob in mob: submob.set_opacity(0) active_layers = [ network_mob.get_active_layer(i, a) for i, a in enumerate(activations) ] def activate_layer(i): self.play( ShowCreationThenDestruction( edge_groups[i-1], run_time = 2, lag_ratio = 0.5 ), FadeIn(active_layers[i]) ) self.play(FadeIn(nine)) self.play(ReplacementTransform(v_nine, neurons)) self.play(MoveToTarget( neurons, remover = True, lag_ratio = 0.5, run_time = 2 )) activate_layer(1) self.play(edge_colored_nine.restore) self.separate_parts(edge_colored_nine) self.wait() activate_layer(2) self.play(pattern_colored_nine.restore) self.separate_parts(pattern_colored_nine) activate_layer(3) self.wait(2) def ask_question(self): question = OldTexText( "Does the network \\\\ actually do this?" ) question.to_edge(LEFT) later = OldTexText("We'll get back \\\\ to this") later.to_corner(UP+LEFT) later.set_color(BLUE) arrow = Arrow(later.get_bottom(), question.get_top()) arrow.set_color(BLUE) self.play(Write(question, run_time = 2)) self.wait() self.play( FadeIn(later), GrowFromPoint(arrow, arrow.get_start()) ) self.wait() ### def set_neurons_target(self, neurons, layer): neurons.generate_target() n = len(layer.neurons)/2 Transform( VGroup(*neurons.target[:n]), VGroup(*layer.neurons[:n]), ).update(1) Transform( VGroup(*neurons.target[-n:]), VGroup(*layer.neurons[-n:]), ).update(1) Transform( VGroup(*neurons.target[n:-n]), VectorizedPoint(layer.get_center()) ).update(1) def separate_parts(self, image_group): vects = compass_directions(len(image_group), UP) image_group.generate_target() for im, vect in zip(image_group.target, vects): im.shift(MED_SMALL_BUFF*vect) self.play(MoveToTarget( image_group, rate_func = there_and_back, lag_ratio = 0.5, run_time = 2, )) class EdgeDetection(Scene): CONFIG = { "camera_config" : {"background_opacity" : 1} } def construct(self): lion = ImageMobject("Lion") edges_array = get_edges(lion.pixel_array) edges = ImageMobject(edges_array) group = Group(lion, edges) group.set_height(4) group.arrange(RIGHT) lion_copy = lion.copy() self.play(FadeIn(lion)) self.play(lion_copy.move_to, edges) self.play(Transform(lion_copy, edges, run_time = 3)) self.wait(2) class ManyTasksBreakDownLikeThis(TeacherStudentsScene): def construct(self): audio = self.get_wave_form() audio_label = OldTexText("Raw audio") letters = OldTexText(" ".join("recognition")) syllables = OldTexText("$\\cdot$".join([ "re", "cog", "ni", "tion" ])) word = OldTexText( "re", "cognition", arg_separator = "" ) word[1].set_color(BLUE) arrows = VGroup() def get_arrow(): arrow = Arrow(ORIGIN, RIGHT, color = BLUE) arrows.add(arrow) return arrow sequence = VGroup( audio, get_arrow(), letters, get_arrow(), syllables, get_arrow(), word ) sequence.arrange(RIGHT) sequence.set_width(FRAME_WIDTH - 1) sequence.to_edge(UP) audio_label.next_to(audio, DOWN) VGroup(audio, audio_label).set_color(YELLOW) audio.save_state() self.teacher_says( "Many", "recognition", "tasks\\\\", "break down like this" ) self.play_student_changes(*["pondering"]*3) self.wait() content = self.teacher.bubble.content pre_word = content[1] content.remove(pre_word) audio.move_to(pre_word) self.play( self.teacher.bubble.content.fade, 1, ShowCreation(audio), pre_word.shift, MED_SMALL_BUFF, DOWN ) self.wait(2) self.play( RemovePiCreatureBubble(self.teacher), audio.restore, FadeIn(audio_label), *[ ReplacementTransform( m1, m2 ) for m1, m2 in zip(pre_word, letters) ] ) self.play( GrowFromPoint(arrows[0], arrows[0].get_start()), ) self.wait() self.play( GrowFromPoint(arrows[1], arrows[1].get_start()), LaggedStartMap(FadeIn, syllables, run_time = 1) ) self.wait() self.play( GrowFromPoint(arrows[2], arrows[2].get_start()), LaggedStartMap(FadeIn, word, run_time = 1) ) self.wait() def get_wave_form(self): func = lambda x : abs(sum([ (1./n)*np.sin((n+3)*x) for n in range(1, 5) ])) result = VGroup(*[ Line(func(x)*DOWN, func(x)*UP) for x in np.arange(0, 4, 0.1) ]) result.set_stroke(width = 2) result.arrange(RIGHT, buff = MED_SMALL_BUFF) result.set_height(1) return result class AskAboutWhatEdgesAreDoing(IntroduceEachLayer): CONFIG = { "network_mob_config" : { "layer_to_layer_buff" : 2, } } def construct(self): self.add_question() self.show_propogation() def add_question(self): self.network_mob.scale(0.8) self.network_mob.to_edge(DOWN) edge_groups = self.network_mob.edge_groups self.remove_random_edges(0.7) question = OldTexText( "What are these connections actually doing?" ) question.to_edge(UP) question.shift(RIGHT) arrows = VGroup(*[ Arrow( question.get_bottom(), edge_group.get_top() ) for edge_group in edge_groups ]) self.add(question, arrows) def show_propogation(self): in_vect = get_organized_images()[6][3] image = MNistMobject(in_vect) image.next_to(self.network_mob, LEFT, MED_SMALL_BUFF, UP) self.add(image) self.feed_forward(in_vect) self.wait() class IntroduceWeights(IntroduceEachLayer): CONFIG = { "weights_color" : GREEN, "negative_weights_color" : RED, } def construct(self): self.zoom_in_on_one_neuron() self.show_desired_pixel_region() self.ask_about_parameters() self.show_weights() self.show_weighted_sum() self.organize_weights_as_grid() self.make_most_weights_0() self.add_negative_weights_around_the_edge() def zoom_in_on_one_neuron(self): self.network_mob.to_edge(LEFT) layers = self.network_mob.layers edge_groups = self.network_mob.edge_groups neuron = layers[1].neurons[7].deepcopy() self.play( FadeOut(edge_groups), FadeOut(VGroup(*layers[1:])), FadeOut(self.network_mob.output_labels), Animation(neuron), neuron.edges_in.set_stroke, None, 2, lag_ratio = 0.5, run_time = 2 ) self.neuron = neuron def show_desired_pixel_region(self): neuron = self.neuron d = 28 pixels = PixelsAsSquares(ImageMobject( np.zeros((d, d, 4)) )) pixels.set_stroke(width = 0.5) pixels.set_fill(WHITE, 0) pixels.set_height(4) pixels.next_to(neuron, RIGHT, LARGE_BUFF) rect = SurroundingRectangle(pixels, color = BLUE) pixels_to_detect = self.get_pixels_to_detect(pixels) self.play( FadeIn(rect), ShowCreation( pixels, lag_ratio = 0.5, run_time = 2, ) ) self.play( pixels_to_detect.set_fill, WHITE, 1, lag_ratio = 0.5, run_time = 2 ) self.wait(2) self.pixels = pixels self.pixels_to_detect = pixels_to_detect self.pixels_group = VGroup(rect, pixels) def ask_about_parameters(self): pixels = self.pixels pixels_group = self.pixels_group neuron = self.neuron question = OldTexText("What", "parameters", "should exist?") parameter_word = question.get_part_by_tex("parameters") parameter_word.set_color(self.weights_color) question.move_to(neuron.edges_in.get_top(), LEFT) arrow = Arrow( parameter_word.get_bottom(), neuron.edges_in[0].get_center(), color = self.weights_color ) p_labels = VGroup(*[ OldTex("p_%d\\!:"%(i+1)).set_color(self.weights_color) for i in range(8) ] + [Tex("\\vdots")]) p_labels.arrange(DOWN, aligned_edge = LEFT) p_labels.next_to(parameter_word, DOWN, LARGE_BUFF) p_labels[-1].shift(SMALL_BUFF*RIGHT) def get_alpha_func(i, start = 0): # m = int(5*np.sin(2*np.pi*i/128.)) m = random.randint(1, 10) return lambda a : start + (1-2*start)*np.sin(np.pi*a*m)**2 decimals = VGroup() changing_decimals = [] for i, p_label in enumerate(p_labels[:-1]): decimal = DecimalNumber(0) decimal.next_to(p_label, RIGHT, MED_SMALL_BUFF) decimals.add(decimal) changing_decimals.append(ChangingDecimal( decimal, get_alpha_func(i + 5) )) for i, pixel in enumerate(pixels): pixel.func = get_alpha_func(i, pixel.get_fill_opacity()) pixel_updates = [ UpdateFromAlphaFunc( pixel, lambda p, a : p.set_fill(opacity = p.func(a)) ) for pixel in pixels ] self.play( Write(question, run_time = 2), GrowFromPoint(arrow, arrow.get_start()), pixels_group.set_height, 3, pixels_group.to_edge, RIGHT, LaggedStartMap(FadeIn, p_labels), LaggedStartMap(FadeIn, decimals), ) self.wait() self.play( *changing_decimals + pixel_updates, run_time = 5, rate_func=linear ) self.question = question self.weight_arrow = arrow self.p_labels = p_labels self.decimals = decimals def show_weights(self): p_labels = self.p_labels decimals = self.decimals arrow = self.weight_arrow question = self.question neuron = self.neuron edges = neuron.edges_in parameter_word = question.get_part_by_tex("parameters") question.remove(parameter_word) weights_word = OldTexText("Weights", "")[0] weights_word.set_color(self.weights_color) weights_word.move_to(parameter_word) w_labels = VGroup() for p_label in p_labels: w_label = OldTex( p_label.get_tex().replace("p", "w") ) w_label.set_color(self.weights_color) w_label.move_to(p_label) w_labels.add(w_label) edges.generate_target() random_numbers = 1.5*np.random.random(len(edges))-0.5 self.make_edges_weighted(edges.target, random_numbers) def get_alpha_func(r): return lambda a : (4*r)*a self.play( FadeOut(question), ReplacementTransform(parameter_word, weights_word), ReplacementTransform(p_labels, w_labels) ) self.play( MoveToTarget(edges), *[ ChangingDecimal( decimal, get_alpha_func(r) ) for decimal, r in zip(decimals, random_numbers) ] ) self.play(LaggedStartMap( ApplyMethod, edges, lambda m : (m.rotate, np.pi/24), rate_func = wiggle, run_time = 2 )) self.wait() self.w_labels = w_labels self.weights_word = weights_word self.random_numbers = random_numbers def show_weighted_sum(self): weights_word = self.weights_word weight_arrow = self.weight_arrow w_labels = VGroup(*[ VGroup(*label[:-1]).copy() for label in self.w_labels ]) layer = self.network_mob.layers[0] a_vect = np.random.random(16) active_layer = self.network_mob.get_active_layer(0, a_vect) a_labels = VGroup(*[ OldTex("a_%d"%d) for d in range(1, 5) ]) weighted_sum = VGroup(*it.chain(*[ [w, a, OldTex("+")] for w, a in zip(w_labels, a_labels) ])) weighted_sum.add( OldTex("\\cdots"), OldTex("+"), OldTex("w_n").set_color(self.weights_color), OldTex("a_n") ) weighted_sum.arrange(RIGHT, buff = SMALL_BUFF) weighted_sum.to_edge(UP) self.play(Transform(layer, active_layer)) self.play( FadeOut(weights_word), FadeOut(weight_arrow), *[ ReplacementTransform(n.copy(), a) for n, a in zip(layer.neurons, a_labels) ] + [ ReplacementTransform(n.copy(), weighted_sum[-4]) for n in layer.neurons[4:-1] ] + [ ReplacementTransform( layer.neurons[-1].copy(), weighted_sum[-1] ) ] + [ Write(weighted_sum[i]) for i in list(range(2, 12, 3)) + [-4, -3] ], run_time = 1.5 ) self.wait() self.play(*[ ReplacementTransform(w1.copy(), w2) for w1, w2 in zip(self.w_labels, w_labels)[:4] ]+[ ReplacementTransform(w.copy(), weighted_sum[-4]) for w in self.w_labels[4:-1] ]+[ ReplacementTransform( self.w_labels[-1].copy(), weighted_sum[-2] ) ], run_time = 2) self.wait(2) self.weighted_sum = weighted_sum def organize_weights_as_grid(self): pixels = self.pixels w_labels = self.w_labels decimals = self.decimals weights = 2*np.sqrt(np.random.random(784))-1 weights[:8] = self.random_numbers[:8] weights[-8:] = self.random_numbers[-8:] weight_grid = PixelsFromVect(np.abs(weights)) weight_grid.replace(pixels) weight_grid.next_to(pixels, LEFT) for weight, pixel in zip(weights, weight_grid): if weight >= 0: color = self.weights_color else: color = self.negative_weights_color pixel.set_fill(color, opacity = abs(weight)) self.play(FadeOut(w_labels)) self.play( FadeIn( VGroup(*weight_grid[len(decimals):]), lag_ratio = 0.5, run_time = 3 ), *[ ReplacementTransform(decimal, pixel) for decimal, pixel in zip(decimals, weight_grid) ] ) self.wait() self.weight_grid = weight_grid def make_most_weights_0(self): weight_grid = self.weight_grid pixels = self.pixels pixels_group = self.pixels_group weight_grid.generate_target() for w, p in zip(weight_grid.target, pixels): if p.get_fill_opacity() > 0.1: w.set_fill(GREEN, 0.5) else: w.set_fill(BLACK, 0.5) w.set_stroke(WHITE, 0.5) digit = self.get_digit() digit.replace(pixels) self.play(MoveToTarget( weight_grid, run_time = 2, lag_ratio = 0.5 )) self.wait() self.play(Transform( pixels, digit, run_time = 2, lag_ratio = 0.5 )) self.wait() self.play(weight_grid.move_to, pixels) self.wait() self.play( ReplacementTransform( self.pixels_to_detect.copy(), self.weighted_sum, run_time = 3, lag_ratio = 0.5 ), Animation(weight_grid), ) self.wait() def add_negative_weights_around_the_edge(self): weight_grid = self.weight_grid pixels = self.pixels self.play(weight_grid.next_to, pixels, LEFT) self.play(*[ ApplyMethod( weight_grid[28*y + x].set_fill, self.negative_weights_color, 0.5 ) for y in (6, 10) for x in range(14-4, 14+4) ]) self.wait(2) self.play(weight_grid.move_to, pixels) self.wait(2) #### def get_digit(self): digit_vect = get_organized_images()[7][4] digit = PixelsFromVect(digit_vect) digit.set_stroke(width = 0.5) return digit def get_pixels_to_detect(self, pixels): d = int(np.sqrt(len(pixels))) return VGroup(*it.chain(*[ pixels[d*n + d/2 - 4 : d*n + d/2 + 4] for n in range(7, 10) ])) def get_surrounding_pixels_for_edge(self, pixels): d = int(np.sqrt(len(pixels))) return VGroup(*it.chain(*[ pixels[d*n + d/2 - 4 : d*n + d/2 + 4] for n in (6, 10) ])) def make_edges_weighted(self, edges, weights): for edge, r in zip(edges, weights): if r > 0: color = self.weights_color else: color = self.negative_weights_color edge.set_stroke(color, 6*abs(r)) class MotivateSquishing(Scene): def construct(self): self.add_weighted_sum() self.show_real_number_line() self.show_interval() self.squish_into_interval() def add_weighted_sum(self): weighted_sum = OldTex(*it.chain(*[ ["w_%d"%d, "a_%d"%d, "+"] for d in range(1, 5) ] + [ ["\\cdots", "+", "w_n", "a_n"] ])) weighted_sum.set_color_by_tex("w_", GREEN) weighted_sum.to_edge(UP) self.add(weighted_sum) self.weighted_sum = weighted_sum def show_real_number_line(self): weighted_sum = self.weighted_sum number_line = NumberLine(unit_size = 1.5) number_line.add_numbers() number_line.shift(UP) arrow1, arrow2 = [ Arrow( weighted_sum.get_bottom(), number_line.number_to_point(n), ) for n in (-3, 3) ] self.play(Write(number_line)) self.play(GrowFromPoint(arrow1, arrow1.get_start())) self.play(Transform( arrow1, arrow2, run_time = 5, rate_func = there_and_back )) self.play(FadeOut(arrow1)) self.number_line = number_line def show_interval(self): lower_number_line = self.number_line.copy() lower_number_line.shift(2*DOWN) lower_number_line.set_color(GREY_B) lower_number_line.numbers.set_color(WHITE) interval = Line( lower_number_line.number_to_point(0), lower_number_line.number_to_point(1), color = YELLOW, stroke_width = 5 ) brace = Brace(interval, DOWN, buff = 0.7) words = OldTexText("Activations should be in this range") words.next_to(brace, DOWN, SMALL_BUFF) self.play(ReplacementTransform( self.number_line.copy(), lower_number_line )) self.play( GrowFromCenter(brace), GrowFromCenter(interval), ) self.play(Write(words, run_time = 2)) self.wait() self.lower_number_line = lower_number_line def squish_into_interval(self): line = self.number_line line.remove(*line.numbers) ghost_line = line.copy() ghost_line.fade(0.5) ghost_line.set_color(BLUE_E) self.add(ghost_line, line) lower_line = self.lower_number_line line.generate_target() u = line.unit_size line.target.apply_function( lambda p : np.array([u*sigmoid(p[0])]+list(p[1:])) ) line.target.move_to(lower_line.number_to_point(0.5)) arrow = Arrow( line.numbers.get_bottom(), line.target.get_top(), color = YELLOW ) self.play( MoveToTarget(line), GrowFromPoint(arrow, arrow.get_start()) ) self.wait(2) class IntroduceSigmoid(GraphScene): CONFIG = { "x_min" : -5, "x_max" : 5, "x_axis_width" : 12, "y_min" : -1, "y_max" : 2, "y_axis_label" : "", "graph_origin" : DOWN, "x_labeled_nums" : list(range(-4, 5)), "y_labeled_nums" : list(range(-1, 3)), } def construct(self): self.setup_axes() self.add_title() self.add_graph() self.show_part(-5, -2, RED) self.show_part(2, 5, GREEN) self.show_part(-2, 2, BLUE) def add_title(self): name = OldTexText("Sigmoid") name.next_to(ORIGIN, RIGHT, LARGE_BUFF) name.to_edge(UP) char = self.x_axis_label.replace("$", "") equation = OldTex( "\\sigma(%s) = \\frac{1}{1+e^{-%s}}"%(char, char) ) equation.next_to(name, DOWN) self.add(equation, name) self.equation = equation self.sigmoid_name = name def add_graph(self): graph = self.get_graph( lambda x : 1./(1+np.exp(-x)), color = YELLOW ) self.play(ShowCreation(graph)) self.wait() self.sigmoid_graph = graph ### def show_part(self, x_min, x_max, color): line, graph_part = [ self.get_graph( func, x_min = x_min, x_max = x_max, color = color, ).set_stroke(width = 4) for func in (lambda x : 0, sigmoid) ] self.play(ShowCreation(line)) self.wait() self.play(Transform(line, graph_part)) self.wait() class IncludeBias(IntroduceWeights): def construct(self): self.force_skipping() self.zoom_in_on_one_neuron() self.setup_start() self.revert_to_original_skipping_status() self.add_sigmoid_label() self.words_on_activation() self.comment_on_need_for_bias() self.add_bias() self.summarize_weights_and_biases() def setup_start(self): self.weighted_sum = self.get_weighted_sum() digit = self.get_digit() rect = SurroundingRectangle(digit) d_group = VGroup(digit, rect) d_group.set_height(3) d_group.to_edge(RIGHT) weight_grid = digit.copy() weight_grid.set_fill(BLACK, 0.5) self.get_pixels_to_detect(weight_grid).set_fill( GREEN, 0.5 ) self.get_surrounding_pixels_for_edge(weight_grid).set_fill( RED, 0.5 ) weight_grid.move_to(digit) edges = self.neuron.edges_in self.make_edges_weighted( edges, 1.5*np.random.random(len(edges)) - 0.5 ) Transform( self.network_mob.layers[0], self.network_mob.get_active_layer(0, np.random.random(16)) ).update(1) self.add(self.weighted_sum, digit, weight_grid) self.digit = digit self.weight_grid = weight_grid def add_sigmoid_label(self): name = OldTexText("Sigmoid") sigma = self.weighted_sum[0][0] name.next_to(sigma, UP) name.to_edge(UP, SMALL_BUFF) arrow = Arrow( name.get_bottom(), sigma.get_top(), buff = SMALL_BUFF, use_rectangular_stem = False, max_tip_length_to_length_ratio = 0.3 ) self.play( Write(name), ShowCreation(arrow), ) self.sigmoid_name = name self.sigmoid_arrow = arrow def words_on_activation(self): neuron = self.neuron weighted_sum = self.weighted_sum activation_word = OldTexText("Activation") activation_word.next_to(neuron, RIGHT) arrow = Arrow(neuron, weighted_sum.get_bottom()) arrow.set_color(WHITE) words = OldTexText("How positive is this?") words.next_to(self.weighted_sum, UP, SMALL_BUFF) self.play( FadeIn(activation_word), neuron.set_fill, WHITE, 0.8, ) self.wait() self.play( GrowArrow(arrow), ReplacementTransform(activation_word, words), ) self.wait(2) self.play(FadeOut(arrow)) self.how_positive_words = words def comment_on_need_for_bias(self): neuron = self.neuron weight_grid = self.weight_grid colored_pixels = VGroup( self.get_pixels_to_detect(weight_grid), self.get_surrounding_pixels_for_edge(weight_grid), ) words = OldTexText( "Only activate meaningfully \\\\ when", "weighted sum", "$> 10$" ) words.set_color_by_tex("weighted", GREEN) words.next_to(neuron, RIGHT) self.play(Write(words, run_time = 2)) self.play(ApplyMethod( colored_pixels.shift, MED_LARGE_BUFF*UP, rate_func = there_and_back, run_time = 2, lag_ratio = 0.5 )) self.wait() self.gt_ten = words[-1] def add_bias(self): bias = OldTex("-10") wn, rp = self.weighted_sum[-2:] bias.next_to(wn, RIGHT, SMALL_BUFF) bias.shift(0.02*UP) rp.generate_target() rp.target.next_to(bias, RIGHT, SMALL_BUFF) rect = SurroundingRectangle(bias, buff = 0.5*SMALL_BUFF) name = OldTexText("``bias''") name.next_to(rect, DOWN) VGroup(rect, name).set_color(BLUE) self.play( ReplacementTransform( self.gt_ten.copy(), bias, run_time = 2 ), MoveToTarget(rp), ) self.wait(2) self.play( ShowCreation(rect), Write(name) ) self.wait(2) self.bias_name = name def summarize_weights_and_biases(self): weight_grid = self.weight_grid bias_name = self.bias_name self.play(LaggedStartMap( ApplyMethod, weight_grid, lambda p : (p.set_fill, random.choice([GREEN, GREEN, RED]), random.random() ), rate_func = there_and_back, lag_ratio = 0.4, run_time = 4 )) self.wait() self.play(Indicate(bias_name)) self.wait(2) ### def get_weighted_sum(self): args = ["\\sigma \\big("] for d in range(1, 4): args += ["w_%d"%d, "a_%d"%d, "+"] args += ["\\cdots", "+", "w_n", "a_n"] args += ["\\big)"] weighted_sum = OldTex(*args) weighted_sum.set_color_by_tex("w_", GREEN) weighted_sum.set_color_by_tex("\\big", YELLOW) weighted_sum.to_edge(UP, LARGE_BUFF) weighted_sum.shift(RIGHT) return weighted_sum class BiasForInactiviyWords(Scene): def construct(self): words = OldTexText("Bias for inactivity") words.set_color(BLUE) words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) self.play(Write(words)) self.wait(3) class ContinualEdgeUpdate(VGroup): CONFIG = { "max_stroke_width" : 3, "stroke_width_exp" : 7, "n_cycles" : 5, "colors" : [GREEN, GREEN, GREEN, RED], } def __init__(self, network_mob, **kwargs): VGroup.__init__(self, **kwargs) self.internal_time = 0 n_cycles = self.n_cycles edges = VGroup(*it.chain(*network_mob.edge_groups)) self.move_to_targets = [] for edge in edges: edge.colors = [ random.choice(self.colors) for x in range(n_cycles) ] msw = self.max_stroke_width edge.widths = [ msw*random.random()**self.stroke_width_exp for x in range(n_cycles) ] edge.cycle_time = 1 + random.random() edge.generate_target() edge.target.set_stroke(edge.colors[0], edge.widths[0]) edge.become(edge.target) self.move_to_targets.append(edge) self.edges = edges self.add(edges) self.add_updater(lambda m, dt: self.update_edges(dt)) def update_edges(self, dt): self.internal_time += dt if self.internal_time < 1: alpha = smooth(self.internal_time) for move_to_target in self.move_to_targets: move_to_target.update(alpha) return for edge in self.edges: t = (self.internal_time-1)/edge.cycle_time alpha = ((self.internal_time-1)%edge.cycle_time)/edge.cycle_time low_n = int(t)%len(edge.colors) high_n = int(t+1)%len(edge.colors) color = interpolate_color(edge.colors[low_n], edge.colors[high_n], alpha) width = interpolate(edge.widths[low_n], edge.widths[high_n], alpha) edge.set_stroke(color, width) class ShowRemainingNetwork(IntroduceWeights): def construct(self): self.force_skipping() self.zoom_in_on_one_neuron() self.revert_to_original_skipping_status() self.show_all_of_second_layer() self.count_in_biases() self.compute_layer_two_of_weights_and_biases_count() self.show_remaining_layers() self.show_final_number() self.tweak_weights() def show_all_of_second_layer(self): example_neuron = self.neuron layer = self.network_mob.layers[1] neurons = VGroup(*layer.neurons) neurons.remove(example_neuron) words = OldTexText("784", "weights", "per neuron") words.next_to(layer.neurons[0], RIGHT) words.to_edge(UP) self.play(FadeIn(words)) last_edges = None for neuron in neurons[:7]: edges = neuron.edges_in added_anims = [] if last_edges is not None: added_anims += [ last_edges.set_stroke, None, 1 ] edges.set_stroke(width = 2) self.play( ShowCreation(edges, lag_ratio = 0.5), FadeIn(neuron), *added_anims, run_time = 1.5 ) last_edges = edges self.play( LaggedStartMap( ShowCreation, VGroup(*[ n.edges_in for n in neurons[7:] ]), run_time = 3, ), LaggedStartMap( FadeIn, VGroup(*neurons[7:]), run_time = 3, ), VGroup(*last_edges[1:]).set_stroke, None, 1 ) self.wait() self.weights_words = words def count_in_biases(self): neurons = self.network_mob.layers[1].neurons words = OldTexText("One", "bias","for each") words.next_to(neurons, RIGHT, buff = 2) arrows = VGroup(*[ Arrow( words.get_left(), neuron.get_center(), color = BLUE ) for neuron in neurons ]) self.play( FadeIn(words), LaggedStartMap( GrowArrow, arrows, run_time = 3, lag_ratio = 0.3, ) ) self.wait() self.bias_words = words self.bias_arrows = arrows def compute_layer_two_of_weights_and_biases_count(self): ww1, ww2, ww3 = weights_words = self.weights_words bb1, bb2, bb3 = bias_words = self.bias_words bias_arrows = self.bias_arrows times_16 = OldTex("\\times 16") times_16.next_to(ww1, RIGHT, SMALL_BUFF) ww2.generate_target() ww2.target.next_to(times_16, RIGHT) bias_count = OldTexText("16", "biases") bias_count.next_to(ww2.target, RIGHT, LARGE_BUFF) self.play( Write(times_16), MoveToTarget(ww2), FadeOut(ww3) ) self.wait() self.play( ReplacementTransform(times_16.copy(), bias_count[0]), FadeOut(bb1), ReplacementTransform(bb2, bias_count[1]), FadeOut(bb3), LaggedStartMap(FadeOut, bias_arrows) ) self.wait() self.weights_count = VGroup(ww1, times_16, ww2) self.bias_count = bias_count def show_remaining_layers(self): weights_count = self.weights_count bias_count = self.bias_count for count in weights_count, bias_count: count.generate_target() count.prefix = VGroup(*count.target[:-1]) added_weights = OldTex( "+16\\!\\times\\! 16 + 16 \\!\\times\\! 10" ) added_weights.to_corner(UP+RIGHT) weights_count.prefix.next_to(added_weights, LEFT, SMALL_BUFF) weights_count.target[-1].next_to( VGroup(weights_count.prefix, added_weights), DOWN ) added_biases = OldTex("+ 16 + 10") group = VGroup(bias_count.prefix, added_biases) group.arrange(RIGHT, SMALL_BUFF) group.next_to(weights_count.target[-1], DOWN, LARGE_BUFF) bias_count.target[-1].next_to(group, DOWN) network_mob = self.network_mob edges = VGroup(*it.chain(*network_mob.edge_groups[1:])) neurons = VGroup(*it.chain(*[ layer.neurons for layer in network_mob.layers[2:] ])) self.play( MoveToTarget(weights_count), MoveToTarget(bias_count), Write(added_weights, run_time = 1), Write(added_biases, run_time = 1), LaggedStartMap( ShowCreation, edges, run_time = 4, lag_ratio = 0.3, ), LaggedStartMap( FadeIn, neurons, run_time = 4, lag_ratio = 0.3, ) ) self.wait(2) weights_count.add(added_weights) bias_count.add(added_biases) def show_final_number(self): group = VGroup( self.weights_count, self.bias_count, ) group.generate_target() group.target.scale(0.8) rect = SurroundingRectangle(group.target, buff = MED_SMALL_BUFF) num_mob = OldTex("13{,}002") num_mob.scale(1.5) num_mob.next_to(rect, DOWN) self.play( ShowCreation(rect), MoveToTarget(group), ) self.play(Write(num_mob)) self.wait() self.final_number = num_mob def tweak_weights(self): learning = OldTexText("Learning $\\rightarrow$") finding_words = OldTexText( "Finding the right \\\\ weights and biases" ) group = VGroup(learning, finding_words) group.arrange(RIGHT) group.scale(0.8) group.next_to(self.final_number, DOWN, MED_LARGE_BUFF) self.add(ContinualEdgeUpdate(self.network_mob)) self.wait(5) self.play(Write(group)) self.wait(10) ### def get_edge_weight_wandering_anim(self, edges): for edge in edges: edge.generate_target() edge.target.set_stroke( color = random.choice([GREEN, GREEN, GREEN, RED]), width = 3*random.random()**7 ) self.play( LaggedStartMap( MoveToTarget, edges, lag_ratio = 0.6, run_time = 2, ), *added_anims ) class ImagineSettingByHand(Scene): def construct(self): randy = Randolph() randy.scale(0.7) randy.to_corner(DOWN+LEFT) bubble = randy.get_bubble() network_mob = NetworkMobject( Network(sizes = [8, 6, 6, 4]), neuron_stroke_color = WHITE ) network_mob.scale(0.7) network_mob.move_to(bubble.get_bubble_center()) network_mob.shift(MED_SMALL_BUFF*RIGHT + SMALL_BUFF*(UP+RIGHT)) self.add(randy, bubble, network_mob) self.add(ContinualEdgeUpdate(network_mob)) self.play(randy.change, "pondering") self.wait() self.play(Blink(randy)) self.wait() self.play(randy.change, "horrified", network_mob) self.play(Blink(randy)) self.wait(10) class WhenTheNetworkFails(MoreHonestMNistNetworkPreview): CONFIG = { "network_mob_config" : {"layer_to_layer_buff" : 2} } def construct(self): self.setup_network_mob() self.black_box() self.incorrect_classification() self.ask_about_weights() def setup_network_mob(self): self.network_mob.scale(0.8) self.network_mob.to_edge(DOWN) def black_box(self): network_mob = self.network_mob layers = VGroup(*network_mob.layers[1:3]) box = SurroundingRectangle( layers, stroke_color = WHITE, fill_color = BLACK, fill_opacity = 0.8, ) words = OldTexText("...rather than treating this as a black box") words.next_to(box, UP, LARGE_BUFF) self.play( Write(words, run_time = 2), DrawBorderThenFill(box) ) self.wait() self.play(*list(map(FadeOut, [words, box]))) def incorrect_classification(self): network = self.network training_data, validation_data, test_data = load_data_wrapper() for in_vect, result in test_data[20:]: network_answer = np.argmax(network.feedforward(in_vect)) if network_answer != result: break self.feed_in_image(in_vect) wrong = OldTexText("Wrong!") wrong.set_color(RED) wrong.next_to(self.network_mob.layers[-1], UP+RIGHT) self.play(Write(wrong, run_time = 1)) def ask_about_weights(self): question = OldTexText( "What weights are used here?\\\\", "What are they doing?" ) question.next_to(self.network_mob, UP) self.add(ContinualEdgeUpdate(self.network_mob)) self.play(Write(question)) self.wait(10) ### def reset_display(self, *args): pass class EvenWhenItWorks(TeacherStudentsScene): def construct(self): self.teacher_says( "Even when it works,\\\\", "dig into why." ) self.play_student_changes(*["pondering"]*3) self.wait(7) class IntroduceWeightMatrix(NetworkScene): CONFIG = { "network_mob_config" : { "neuron_stroke_color" : WHITE, "neuron_fill_color" : WHITE, "neuron_radius" : 0.35, "layer_to_layer_buff" : 2, }, "layer_sizes" : [8, 6], } def construct(self): self.setup_network_mob() self.show_weighted_sum() self.organize_activations_into_column() self.organize_weights_as_matrix() self.show_meaning_of_matrix_row() self.connect_weighted_sum_to_matrix_multiplication() self.add_bias_vector() self.apply_sigmoid() self.write_clean_final_expression() def setup_network_mob(self): self.network_mob.to_edge(LEFT, buff = LARGE_BUFF) self.network_mob.layers[1].neurons.shift(0.02*RIGHT) def show_weighted_sum(self): self.fade_many_neurons() self.activate_first_layer() self.show_first_neuron_weighted_sum() self.add_bias() self.add_sigmoid() ## def fade_many_neurons(self): anims = [] neurons = self.network_mob.layers[1].neurons for neuron in neurons[1:]: neuron.save_state() neuron.edges_in.save_state() anims += [ neuron.fade, 0.8, neuron.set_fill, None, 0, neuron.edges_in.fade, 0.8, ] anims += [ Animation(neurons[0]), Animation(neurons[0].edges_in), ] self.play(*anims) def activate_first_layer(self): layer = self.network_mob.layers[0] activations = 0.7*np.random.random(len(layer.neurons)) active_layer = self.network_mob.get_active_layer(0, activations) a_labels = VGroup(*[ OldTex("a^{(0)}_%d"%d) for d in range(len(layer.neurons)) ]) for label, neuron in zip(a_labels, layer.neurons): label.scale(0.75) label.move_to(neuron) self.play( Transform(layer, active_layer), Write(a_labels, run_time = 2) ) self.a_labels = a_labels def show_first_neuron_weighted_sum(self): neuron = self.network_mob.layers[1].neurons[0] a_labels = VGroup(*self.a_labels[:2]).copy() a_labels.generate_target() w_labels = VGroup(*[ OldTex("w_{0, %d}"%d) for d in range(len(a_labels)) ]) weighted_sum = VGroup() symbols = VGroup() for a_label, w_label in zip(a_labels.target, w_labels): a_label.scale(1./0.75) plus = OldTex("+") weighted_sum.add(w_label, a_label, plus) symbols.add(plus) weighted_sum.add( OldTex("\\cdots"), OldTex("+"), OldTex("w_{0, n}"), OldTex("a^{(0)}_n"), ) weighted_sum.arrange(RIGHT) a1_label = OldTex("a^{(1)}_0") a1_label.next_to(neuron, RIGHT) equals = OldTex("=").next_to(a1_label, RIGHT) weighted_sum.next_to(equals, RIGHT) symbols.add(*weighted_sum[-4:-2]) w_labels.add(weighted_sum[-2]) a_labels.add(self.a_labels[-1].copy()) a_labels.target.add(weighted_sum[-1]) a_labels.add(VGroup(*self.a_labels[2:-1]).copy()) a_labels.target.add(VectorizedPoint(weighted_sum[-4].get_center())) VGroup(a1_label, equals, weighted_sum).scale( 0.75, about_point = a1_label.get_left() ) w_labels.set_color(GREEN) w_labels.shift(0.6*SMALL_BUFF*DOWN) a_labels.target.shift(0.5*SMALL_BUFF*UP) self.play( Write(a1_label), Write(equals), neuron.set_fill, None, 0.3, run_time = 1 ) self.play(MoveToTarget(a_labels, run_time = 1.5)) self.play( Write(w_labels), Write(symbols), ) self.a1_label = a1_label self.a1_equals = equals self.w_labels = w_labels self.a_labels_in_sum = a_labels self.symbols = symbols self.weighted_sum = VGroup(w_labels, a_labels, symbols) def add_bias(self): weighted_sum = self.weighted_sum bias = OldTex("+\\,", "b_0") bias.scale(0.75) bias.next_to(weighted_sum, RIGHT, SMALL_BUFF) bias.shift(0.5*SMALL_BUFF*DOWN) name = OldTexText("Bias") name.scale(0.75) name.next_to(bias, DOWN, MED_LARGE_BUFF) arrow = Arrow(name, bias, buff = SMALL_BUFF) VGroup(name, arrow, bias).set_color(BLUE) self.play( FadeIn(name), FadeIn(bias), GrowArrow(arrow), ) self.weighted_sum.add(bias) self.bias = bias self.bias_name = VGroup(name, arrow) def add_sigmoid(self): weighted_sum = self.weighted_sum weighted_sum.generate_target() sigma, lp, rp = mob = OldTex("\\sigma\\big(\\big)") # mob.scale(0.75) sigma.move_to(weighted_sum.get_left()) sigma.shift(0.5*SMALL_BUFF*(DOWN+RIGHT)) lp.next_to(sigma, RIGHT, SMALL_BUFF) weighted_sum.target.next_to(lp, RIGHT, SMALL_BUFF) rp.next_to(weighted_sum.target, RIGHT, SMALL_BUFF) name = OldTexText("Sigmoid") name.next_to(sigma, UP, MED_LARGE_BUFF) arrow = Arrow(name, sigma, buff = SMALL_BUFF) sigmoid_name = VGroup(name, arrow) VGroup(sigmoid_name, mob).set_color(YELLOW) self.play( FadeIn(mob), MoveToTarget(weighted_sum), MaintainPositionRelativeTo(self.bias_name, self.bias), ) self.play(FadeIn(sigmoid_name)) self.sigma = sigma self.sigma_parens = VGroup(lp, rp) self.sigmoid_name = sigmoid_name ## def organize_activations_into_column(self): a_labels = self.a_labels.copy() a_labels.generate_target() column = a_labels.target a_labels_in_sum = self.a_labels_in_sum dots = OldTex("\\vdots") mid_as = VGroup(*column[2:-1]) Transform(mid_as, dots).update(1) last_a = column[-1] new_last_a = OldTex( last_a.get_tex().replace("7", "n") ) new_last_a.replace(last_a) Transform(last_a, new_last_a).update(1) VGroup( *column[:2] + [mid_as] + [column[-1]] ).arrange(DOWN) column.shift(DOWN + 3.5*RIGHT) pre_brackets = self.get_brackets(a_labels) post_bracketes = self.get_brackets(column) pre_brackets.set_fill(opacity = 0) self.play(FocusOn(self.a_labels[0])) self.play(LaggedStartMap( Indicate, self.a_labels, rate_func = there_and_back, run_time = 1 )) self.play( MoveToTarget(a_labels), Transform(pre_brackets, post_bracketes), run_time = 2 ) self.wait() self.play(*[ LaggedStartMap(Indicate, mob, rate_func = there_and_back) for mob in (a_labels, a_labels_in_sum) ]) self.wait() self.a_column = a_labels self.a_column_brackets = pre_brackets def organize_weights_as_matrix(self): a_column = self.a_column a_column_brackets = self.a_column_brackets w_brackets = a_column_brackets.copy() w_brackets.next_to(a_column_brackets, LEFT, SMALL_BUFF) lwb, rwb = w_brackets w_labels = self.w_labels.copy() w_labels.submobjects.insert( 2, self.symbols[-2].copy() ) w_labels.generate_target() w_labels.target.arrange(RIGHT) w_labels.target.next_to(a_column[0], LEFT, buff = 0.8) lwb.next_to(w_labels.target, LEFT, SMALL_BUFF) lwb.align_to(rwb, UP) row_1, row_k = [ VGroup(*list(map(Tex, [ "w_{%s, 0}"%i, "w_{%s, 1}"%i, "\\cdots", "w_{%s, n}"%i, ]))) for i in ("1", "k") ] dots_row = VGroup(*list(map(Tex, [ "\\vdots", "\\vdots", "\\ddots", "\\vdots" ]))) lower_rows = VGroup(row_1, dots_row, row_k) lower_rows.scale(0.75) last_row = w_labels.target for row in lower_rows: for target, mover in zip(last_row, row): mover.move_to(target) if "w" in mover.get_tex(): mover.set_color(GREEN) row.next_to(last_row, DOWN, buff = 0.45) last_row = row self.play( MoveToTarget(w_labels), Write(w_brackets, run_time = 1) ) self.play(FadeIn( lower_rows, run_time = 3, lag_ratio = 0.5, )) self.wait() self.top_matrix_row = w_labels self.lower_matrix_rows = lower_rows self.matrix_brackets = w_brackets def show_meaning_of_matrix_row(self): row = self.top_matrix_row edges = self.network_mob.layers[1].neurons[0].edges_in.copy() edges.set_stroke(GREEN, 5) rect = SurroundingRectangle(row, color = GREEN_B) self.play(ShowCreation(rect)) for x in range(2): self.play(LaggedStartMap( ShowCreationThenDestruction, edges, lag_ratio = 0.8 )) self.wait() self.top_row_rect = rect def connect_weighted_sum_to_matrix_multiplication(self): a_column = self.a_column a_brackets = self.a_column_brackets top_row_rect = self.top_row_rect column_rect = SurroundingRectangle(a_column) equals = OldTex("=") equals.next_to(a_brackets, RIGHT) result_brackets = a_brackets.copy() result_terms = VGroup() for i in 0, 1, 4, -1: a = a_column[i] if i == 4: mob = OldTex("\\vdots") else: # mob = Circle(radius = 0.2, color = YELLOW) mob = OldTex("?").scale(1.3).set_color(YELLOW) result_terms.add(mob.move_to(a)) VGroup(result_brackets, result_terms).next_to(equals, RIGHT) brace = Brace( VGroup(self.w_labels, self.a_labels_in_sum), DOWN ) arrow = Arrow( brace.get_bottom(), result_terms[0].get_top(), buff = SMALL_BUFF ) self.play( GrowArrow(arrow), GrowFromCenter(brace), ) self.play( Write(equals), FadeIn(result_brackets), ) self.play(ShowCreation(column_rect)) self.play(ReplacementTransform( VGroup(top_row_rect, column_rect).copy(), result_terms[0] )) self.play(LaggedStartMap( FadeIn, VGroup(*result_terms[1:]) )) self.wait(2) self.show_meaning_of_lower_rows( arrow, brace, top_row_rect, result_terms ) self.play(*list(map(FadeOut, [ result_terms, result_brackets, equals, column_rect ]))) def show_meaning_of_lower_rows(self, arrow, brace, row_rect, result_terms): n1, n2, nk = neurons = VGroup(*[ self.network_mob.layers[1].neurons[i] for i in (0, 1, -1) ]) for n in neurons: n.save_state() n.edges_in.save_state() rect2 = SurroundingRectangle(result_terms[1]) rectk = SurroundingRectangle(result_terms[-1]) VGroup(rect2, rectk).set_color(WHITE) row2 = self.lower_matrix_rows[0] rowk = self.lower_matrix_rows[-1] def show_edges(neuron): self.play(LaggedStartMap( ShowCreationThenDestruction, neuron.edges_in.copy().set_stroke(GREEN, 5), lag_ratio = 0.7, run_time = 1, )) self.play( row_rect.move_to, row2, n1.fade, n1.set_fill, None, 0, n1.edges_in.set_stroke, None, 1, n2.set_stroke, WHITE, 3, n2.edges_in.set_stroke, None, 3, ReplacementTransform(arrow, rect2), FadeOut(brace), ) show_edges(n2) self.play( row_rect.move_to, rowk, n2.restore, n2.edges_in.restore, nk.set_stroke, WHITE, 3, nk.edges_in.set_stroke, None, 3, ReplacementTransform(rect2, rectk), ) show_edges(nk) self.play( n1.restore, n1.edges_in.restore, nk.restore, nk.edges_in.restore, FadeOut(rectk), FadeOut(row_rect), ) def add_bias_vector(self): bias = self.bias bias_name = self.bias_name a_column_brackets = self.a_column_brackets a_column = self.a_column plus = OldTex("+") b_brackets = a_column_brackets.copy() b_column = VGroup(*list(map(Tex, [ "b_0", "b_1", "\\vdots", "b_n", ]))) b_column.scale(0.85) b_column.arrange(DOWN, buff = 0.35) b_column.move_to(a_column) b_column.set_color(BLUE) plus.next_to(a_column_brackets, RIGHT) VGroup(b_brackets, b_column).next_to(plus, RIGHT) bias_rect = SurroundingRectangle(bias) self.play(ShowCreation(bias_rect)) self.play(FadeOut(bias_rect)) self.play( Write(plus), Write(b_brackets), Transform(self.bias[1].copy(), b_column[0]), run_time = 1 ) self.play(LaggedStartMap( FadeIn, VGroup(*b_column[1:]) )) self.wait() self.bias_plus = plus self.b_brackets = b_brackets self.b_column = b_column def apply_sigmoid(self): expression_bounds = VGroup( self.matrix_brackets[0], self.b_brackets[1] ) sigma = self.sigma.copy() slp, srp = self.sigma_parens.copy() big_lp, big_rp = parens = OldTex("()") parens.scale(3) parens.stretch_to_fit_height(expression_bounds.get_height()) big_lp.next_to(expression_bounds, LEFT, SMALL_BUFF) big_rp.next_to(expression_bounds, RIGHT, SMALL_BUFF) parens.set_color(YELLOW) self.play( sigma.scale, 2, sigma.next_to, big_lp, LEFT, SMALL_BUFF, Transform(slp, big_lp), Transform(srp, big_rp), ) self.wait(2) self.big_sigma_group = VGroup(VGroup(sigma), slp, srp) def write_clean_final_expression(self): self.fade_weighted_sum() expression = OldTex( "\\textbf{a}^{(1)}", "=", "\\sigma", "\\big(", "\\textbf{W}", "\\textbf{a}^{(0)}", "+", "\\textbf{b}", "\\big)", ) expression.set_color_by_tex_to_color_map({ "sigma" : YELLOW, "big" : YELLOW, "W" : GREEN, "\\textbf{b}" : BLUE }) expression.next_to(self.big_sigma_group, UP, LARGE_BUFF) a1, equals, sigma, lp, W, a0, plus, b, rp = expression neuron_anims = [] neurons = VGroup(*self.network_mob.layers[1].neurons[1:]) for neuron in neurons: neuron_anims += [ neuron.restore, neuron.set_fill, None, random.random() ] neuron_anims += [ neuron.edges_in.restore ] neurons.add_to_back(self.network_mob.layers[1].neurons[0]) self.play(ReplacementTransform( VGroup( self.top_matrix_row, self.lower_matrix_rows, self.matrix_brackets ).copy(), VGroup(W), )) self.play(ReplacementTransform( VGroup(self.a_column, self.a_column_brackets).copy(), VGroup(VGroup(a0)), )) self.play( ReplacementTransform( VGroup(self.b_column, self.b_brackets).copy(), VGroup(VGroup(b)) ), ReplacementTransform( self.bias_plus.copy(), plus ) ) self.play(ReplacementTransform( self.big_sigma_group.copy(), VGroup(sigma, lp, rp) )) self.wait() self.play(*neuron_anims, run_time = 2) self.play( ReplacementTransform(neurons.copy(), a1), FadeIn(equals) ) self.wait(2) def fade_weighted_sum(self): self.play(*list(map(FadeOut, [ self.a1_label, self.a1_equals, self.sigma, self.sigma_parens, self.weighted_sum, self.bias_name, self.sigmoid_name, ]))) ### def get_brackets(self, mob): lb, rb = both = OldTex("\\big[\\big]") both.set_width(mob.get_width()) both.stretch_to_fit_height(1.2*mob.get_height()) lb.next_to(mob, LEFT, SMALL_BUFF) rb.next_to(mob, RIGHT, SMALL_BUFF) return both class HorrifiedMorty(Scene): def construct(self): morty = Mortimer() morty.flip() morty.scale(2) for mode in "horrified", "hesitant": self.play( morty.change, mode, morty.look, UP, ) self.play(Blink(morty)) self.wait(2) class SigmoidAppliedToVector(Scene): def construct(self): tex = OldTex(""" \\sigma \\left( \\left[\\begin{array}{c} x \\\\ y \\\\ z \\end{array}\\right] \\right) = \\left[\\begin{array}{c} \\sigma(x) \\\\ \\sigma(y) \\\\ \\sigma(z) \\end{array}\\right] """) tex.set_width(FRAME_WIDTH - 1) tex.to_edge(DOWN) indices = it.chain( [0], list(range(1, 5)), list(range(16, 16+4)), list(range(25, 25+2)), [25+3], list(range(29, 29+2)), [29+3], list(range(33, 33+2)), [33+3], ) for i in indices: tex[i].set_color(YELLOW) self.add(tex) self.wait() class EoLA3Wrapper(PiCreatureScene): def construct(self): morty = self.pi_creature rect = ScreenRectangle(height = 5) rect.next_to(morty, UP+LEFT) rect.to_edge(UP, buff = LARGE_BUFF) title = OldTexText("Essence of linear algebra") title.next_to(rect, UP) self.play( ShowCreation(rect), FadeIn(title), morty.change, "raise_right_hand", rect ) self.wait(4) class FeedForwardCode(ExternallyAnimatedScene): pass class NeuronIsFunction(MoreHonestMNistNetworkPreview): CONFIG = { "network_mob_config" : { "layer_to_layer_buff" : 2 } } def construct(self): self.setup_network_mob() self.activate_network() self.write_neuron_holds_a_number() self.feed_in_new_image(8, 7) self.neuron_is_function() self.show_neuron_as_function() self.fade_network_back_in() self.network_is_a_function() self.feed_in_new_image(9, 4) self.wait(2) def setup_network_mob(self): self.network_mob.scale(0.7) self.network_mob.to_edge(DOWN) self.network_mob.shift(LEFT) def activate_network(self): network_mob = self.network_mob self.image_map = get_organized_images() in_vect = self.image_map[3][0] mnist_mob = MNistMobject(in_vect) mnist_mob.next_to(network_mob, LEFT, MED_LARGE_BUFF, UP) activations = self.network.get_activation_of_all_layers(in_vect) for i, activation in enumerate(activations): layer = self.network_mob.layers[i] Transform( layer, self.network_mob.get_active_layer(i, activation) ).update(1) self.add(mnist_mob) self.image_rect, self.curr_image = mnist_mob def write_neuron_holds_a_number(self): neuron_word = OldTexText("Neuron") arrow = Arrow(ORIGIN, DOWN, color = BLUE) thing_words = OldTexText("Thing that holds \\\\ a number") group = VGroup(neuron_word, arrow, thing_words) group.arrange(DOWN) group.to_corner(UP+RIGHT, buff = LARGE_BUFF) neuron = self.network_mob.layers[2].neurons[2] decimal = DecimalNumber(neuron.get_fill_opacity()) decimal.set_width(0.7*neuron.get_width()) decimal.move_to(neuron) neuron_group = VGroup(neuron, decimal) neuron_group.save_state() decimal.set_fill(opacity = 0) self.play( neuron_group.restore, neuron_group.scale, 3, neuron_group.next_to, neuron_word, LEFT, FadeIn(neuron_word), GrowArrow(arrow), FadeIn( thing_words, run_time = 2, rate_func = squish_rate_func(smooth, 0.3, 1) ) ) self.wait() self.play(neuron_group.restore) self.neuron_word = neuron_word self.neuron_word_arrow = arrow self.thing_words = thing_words self.neuron = neuron self.decimal = decimal def feed_in_new_image(self, digit, choice): in_vect = self.image_map[digit][choice] args = [] for s in "answer_rect", "curr_image", "image_rect": if hasattr(self, s): args.append(getattr(self, s)) else: args.append(VectorizedPoint()) MoreHonestMNistNetworkPreview.reset_display(self, *args) self.feed_in_image(in_vect) def neuron_is_function(self): thing_words = self.thing_words cross = Cross(thing_words) function_word = OldTexText("Function") function_word.move_to(thing_words, UP) self.play( thing_words.fade, ShowCreation(cross) ) self.play( FadeIn(function_word), VGroup(thing_words, cross).to_edge, DOWN, ) self.wait() self.function_word = function_word def show_neuron_as_function(self): neuron = self.neuron.copy() edges = neuron.edges_in.copy() prev_layer = self.network_mob.layers[1].copy() arrow = Arrow(ORIGIN, RIGHT, color = BLUE) arrow.next_to(neuron, RIGHT, SMALL_BUFF) decimal = DecimalNumber(neuron.get_fill_opacity()) decimal.next_to(arrow, RIGHT) self.play( FadeOut(self.network_mob), *list(map(Animation, [neuron, edges, prev_layer])) ) self.play(LaggedStartMap( ShowCreationThenDestruction, edges.copy().set_stroke(YELLOW, 4), )) self.play( GrowArrow(arrow), Transform(self.decimal, decimal) ) self.wait(2) self.non_faded_network_parts = VGroup( neuron, edges, prev_layer ) self.neuron_arrow = arrow def fade_network_back_in(self): anims = [ FadeIn( mob, run_time = 2, lag_ratio = 0.5 ) for mob in (self.network_mob.layers, self.network_mob.edge_groups) ] anims += [ FadeOut(self.neuron_arrow), FadeOut(self.decimal), ] anims.append(Animation(self.non_faded_network_parts)) self.play(*anims) self.remove(self.non_faded_network_parts) def network_is_a_function(self): neuron_word = self.neuron_word network_word = OldTexText("Network") network_word.set_color(YELLOW) network_word.move_to(neuron_word) func_tex = OldTex( "f(a_0, \\dots, a_{783}) = ", """\\left[ \\begin{array}{c} y_0 \\\\ \\vdots \\\\ y_{9} \\end{array} \\right]""" ) func_tex.to_edge(UP) func_tex.shift(MED_SMALL_BUFF*LEFT) self.play( ReplacementTransform(neuron_word, network_word), FadeIn(func_tex) ) ### def reset_display(self, answer_rect, image, image_rect): #Don't do anything, just record these args self.answer_rect = answer_rect self.curr_image = image self.image_rect = image_rect return class ComplicationIsReassuring(TeacherStudentsScene): def construct(self): self.student_says( "It kind of has to \\\\ be complicated, right?", target_mode = "speaking", index = 0 ) self.play(self.teacher.change, "happy") self.wait(4) class NextVideo(MoreHonestMNistNetworkPreview, PiCreatureScene): CONFIG = { "network_mob_config" : { "neuron_stroke_color" : WHITE, "layer_to_layer_buff" : 2.5, "brace_for_large_layers" : False, } } def setup(self): MoreHonestMNistNetworkPreview.setup(self) PiCreatureScene.setup(self) def construct(self): self.network_and_data() self.show_next_video() self.talk_about_subscription() self.show_video_neural_network() def network_and_data(self): morty = self.pi_creature network_mob = self.network_mob network_mob.to_edge(LEFT) for obj in network_mob, self: obj.remove(network_mob.output_labels) network_mob.scale(0.7) network_mob.shift(RIGHT) edge_update = ContinualEdgeUpdate(network_mob) training_data, validation_data, test_data = load_data_wrapper() data_mobs = VGroup() for vect, num in test_data[:30]: image = MNistMobject(vect) image.set_height(0.7) arrow = Arrow(ORIGIN, RIGHT, color = BLUE) num_mob = OldTex(str(num)) group = Group(image, arrow, num_mob) group.arrange(RIGHT, buff = SMALL_BUFF) group.next_to(ORIGIN, RIGHT) data_mobs.add(group) data_mobs.next_to(network_mob, UP) self.add(edge_update) self.play(morty.change, "confused", network_mob) self.wait(2) for data_mob in data_mobs: self.add(data_mob) self.wait(0.2) self.remove(data_mob) self.content = network_mob self.edge_update = edge_update def show_next_video(self): morty = self.pi_creature content = self.content video = VideoIcon() video.set_height(3) video.set_fill(RED, 0.8) video.next_to(morty, UP+LEFT) rect = SurroundingRectangle(video) rect.set_stroke(width = 0) rect.set_fill(BLACK, 0.5) words = OldTexText("On learning") words.next_to(video, UP) if self.edge_update.internal_time < 1: self.edge_update.internal_time = 2 self.play( content.set_height, 0.8*video.get_height(), content.move_to, video, morty.change, "raise_right_hand", FadeIn(rect), FadeIn(video), ) self.add_foreground_mobjects(rect, video) self.wait(2) self.play(Write(words)) self.wait(2) self.video = Group(content, rect, video, words) def talk_about_subscription(self): morty = self.pi_creature morty.generate_target() morty.target.change("hooray") morty.target.rotate( np.pi, axis = UP, about_point = morty.get_left() ) morty.target.shift(LEFT) video = self.video subscribe_word = OldTexText( "Subscribe", "!", arg_separator = "" ) bang = subscribe_word[1] subscribe_word.to_corner(DOWN+RIGHT) subscribe_word.shift(3*UP) q_mark = OldTexText("?") q_mark.move_to(bang, LEFT) arrow = Arrow(ORIGIN, DOWN, color = RED, buff = 0) arrow.next_to(subscribe_word, DOWN) arrow.shift(MED_LARGE_BUFF * RIGHT) self.play( Write(subscribe_word), self.video.shift, 3*LEFT, MoveToTarget(morty), ) self.play(GrowArrow(arrow)) self.wait(2) self.play(morty.change, "maybe", arrow) self.play(Transform(bang, q_mark)) self.wait(3) def show_video_neural_network(self): morty = self.pi_creature network_mob, rect, video, words = self.video network_mob.generate_target(use_deepcopy = True) network_mob.target.set_height(5) network_mob.target.to_corner(UP+LEFT) neurons = VGroup(*network_mob.target.layers[-1].neurons[:2]) neurons.set_stroke(width = 0) video.generate_target() video.target.set_fill(opacity = 1) video.target.set_height(neurons.get_height()) video.target.move_to(neurons, LEFT) self.play( MoveToTarget(network_mob), MoveToTarget(video), FadeOut(words), FadeOut(rect), morty.change, "raise_left_hand" ) neuron_pairs = VGroup(*[ VGroup(*network_mob.layers[-1].neurons[2*i:2*i+2]) for i in range(1, 5) ]) for pair in neuron_pairs: video = video.copy() video.move_to(pair, LEFT) pair.target = video self.play(LaggedStartMap( MoveToTarget, neuron_pairs, run_time = 3 )) self.play(morty.change, "shruggie") self.wait(10) ### class NNPatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Desmos", "Burt Humburg", "CrypticSwarm", "Juan Benet", "Ali Yahya", "William", "Mayank M. Mehrotra", "Lukas Biewald", "Samantha D. Suplee", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Ed Kellett", "Joseph John Cox", "Luc Ritchie", "Andy Nichols", "Harsev Singh", "Mads Elvheim", "Erik Sundell", "Xueqi Li", "David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "Michael McGuffin", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] } class PiCreatureGesture(PiCreatureScene): def construct(self): self.play(self.pi_creature.change, "raise_right_hand") self.wait(5) self.play(self.pi_creature.change, "happy") self.wait(4) class IntroduceReLU(IntroduceSigmoid): CONFIG = { "x_axis_label" : "$a$" } def construct(self): self.setup_axes() self.add_title() self.add_graph() self.old_school() self.show_ReLU() self.label_input_regions() def old_school(self): sigmoid_graph = self.sigmoid_graph sigmoid_title = VGroup( self.sigmoid_name, self.equation ) cross = Cross(sigmoid_title) old_school = OldTexText("Old school") old_school.to_corner(UP+RIGHT) old_school.set_color(RED) arrow = Arrow( old_school.get_bottom(), self.equation.get_right(), color = RED ) self.play(ShowCreation(cross)) self.play( Write(old_school, run_time = 1), GrowArrow(arrow) ) self.wait(2) self.play( ApplyMethod( VGroup(cross, sigmoid_title).shift, FRAME_X_RADIUS*RIGHT, rate_func = running_start ), FadeOut(old_school), FadeOut(arrow), ) self.play(ShowCreation( self.sigmoid_graph, rate_func = lambda t : smooth(1-t), remover = True )) def show_ReLU(self): graph = VGroup( Line( self.coords_to_point(-7, 0), self.coords_to_point(0, 0), ), Line( self.coords_to_point(0, 0), self.coords_to_point(4, 4), ), ) graph.set_color(YELLOW) char = self.x_axis_label.replace("$", "") equation = OldTexText("ReLU($%s$) = max$(0, %s)$"%(char, char)) equation.shift(FRAME_X_RADIUS*LEFT/2) equation.to_edge(UP) equation.add_background_rectangle() name = OldTexText("Rectified linear unit") name.move_to(equation) name.add_background_rectangle() self.play(Write(equation)) self.play(ShowCreation(graph), Animation(equation)) self.wait(2) self.play( Write(name), equation.shift, DOWN ) self.wait(2) self.ReLU_graph = graph def label_input_regions(self): l1, l2 = self.ReLU_graph neg_words = OldTexText("Inactive") neg_words.set_color(RED) neg_words.next_to(self.coords_to_point(-2, 0), UP) pos_words = OldTexText("Same as $f(a) = a$") pos_words.set_color(GREEN) pos_words.next_to( self.coords_to_point(1, 1), DOWN+RIGHT ) self.revert_to_original_skipping_status() self.play(ShowCreation(l1.copy().set_color(RED))) self.play(Write(neg_words)) self.wait() self.play(ShowCreation(l2.copy().set_color(GREEN))) self.play(Write(pos_words)) self.wait(2) class CompareSigmoidReLUOnDeepNetworks(PiCreatureScene): def construct(self): morty, lisha = self.morty, self.lisha sigmoid_graph = FunctionGraph( sigmoid, x_min = -5, x_max = 5, ) sigmoid_graph.stretch_to_fit_width(3) sigmoid_graph.set_color(YELLOW) sigmoid_graph.next_to(lisha, UP+LEFT) sigmoid_graph.shift_onto_screen() sigmoid_name = OldTexText("Sigmoid") sigmoid_name.next_to(sigmoid_graph, UP) sigmoid_graph.add(sigmoid_name) slow_learner = OldTexText("Slow learner") slow_learner.set_color(YELLOW) slow_learner.to_corner(UP+LEFT) slow_arrow = Arrow( slow_learner.get_bottom(), sigmoid_graph.get_top(), ) relu_graph = VGroup( Line(2*LEFT, ORIGIN), Line(ORIGIN, np.sqrt(2)*(RIGHT+UP)), ) relu_graph.set_color(BLUE) relu_graph.next_to(lisha, UP+RIGHT) relu_name = OldTexText("ReLU") relu_name.move_to(relu_graph, UP) relu_graph.add(relu_name) network_mob = NetworkMobject(Network( sizes = [6, 4, 5, 4, 3, 5, 2] )) network_mob.scale(0.8) network_mob.to_edge(UP, buff = MED_SMALL_BUFF) network_mob.shift(RIGHT) edge_update = ContinualEdgeUpdate( network_mob, stroke_width_exp = 1, ) self.play( FadeIn(sigmoid_name), ShowCreation(sigmoid_graph), lisha.change, "raise_left_hand", morty.change, "pondering" ) self.play( Write(slow_learner, run_time = 1), GrowArrow(slow_arrow) ) self.wait() self.play( FadeIn(relu_name), ShowCreation(relu_graph), lisha.change, "raise_right_hand", morty.change, "thinking" ) self.play(FadeIn(network_mob)) self.add(edge_update) self.wait(10) ### def create_pi_creatures(self): morty = Mortimer() morty.shift(FRAME_X_RADIUS*RIGHT/2).to_edge(DOWN) lisha = PiCreature(color = BLUE_C) lisha.shift(FRAME_X_RADIUS*LEFT/2).to_edge(DOWN) self.morty, self.lisha = morty, lisha return morty, lisha class ShowAmplify(PiCreatureScene): def construct(self): morty = self.pi_creature rect = ScreenRectangle(height = 5) rect.to_corner(UP+LEFT) rect.shift(DOWN) email = OldTexText("[email protected]") email.next_to(rect, UP) self.play( ShowCreation(rect), morty.change, "raise_right_hand" ) self.wait(2) self.play(Write(email)) self.play(morty.change, "happy", rect) self.wait(10) class Thumbnail(NetworkScene): CONFIG = { "network_mob_config" : { 'neuron_stroke_color' : WHITE, 'layer_to_layer_buff': 1.25, }, } def construct(self): network_mob = self.network_mob network_mob.set_height(FRAME_HEIGHT - 1) for layer in network_mob.layers: layer.neurons.set_stroke(width = 5) network_mob.set_height(5) network_mob.to_edge(DOWN) network_mob.to_edge(LEFT, buff=1) subtitle = OldTexText( "From the\\\\", "ground up\\\\", ) # subtitle.arrange( # DOWN, # buff=0.25, # aligned_edge=LEFT, # ) subtitle.set_color(YELLOW) subtitle.set_height(2.75) subtitle.next_to(network_mob, RIGHT, buff=MED_LARGE_BUFF) edge_update = ContinualEdgeUpdate( network_mob, max_stroke_width = 10, stroke_width_exp = 4, ) edge_update.internal_time = 3 edge_update.update(0) for mob in network_mob.family_members_with_points(): if mob.get_stroke_width() < 2: mob.set_stroke(width=2) title = OldTexText("Neural Networks") title.scale(3) title.to_edge(UP) self.add(network_mob) self.add(subtitle) self.add(title) # Extra class NeuralNetImageAgain(Scene): def construct(self): layers = VGroup() for length in [16, 16, 16, 10]: circs = VGroup(*[ Circle(radius=1) for x in range(length) ]) circs.arrange(DOWN, buff=0.5) circs.set_stroke(WHITE, 2) layers.add(circs) layers.set_height(6.5) layers.arrange(RIGHT, buff=2.5) dots = OldTex("\\vdots") dots.move_to(layers[0]) layers[0][:8].next_to(dots, UP, MED_SMALL_BUFF) layers[0][8:].next_to(dots, DOWN, MED_SMALL_BUFF) for layer in layers[1:3]: for node in layer: node.set_fill(WHITE, opacity=random.random()) layers[3][6].set_fill(WHITE, 0.9) all_edges = VGroup() for l1, l2 in zip(layers, layers[1:]): edges = VGroup() for n1, n2 in it.product(l1, l2): edge = Line( n1.get_center(), n2.get_center(), buff=n1.get_height() / 2 ) edge.set_stroke(WHITE, 1, opacity=0.75) # edge.set_stroke( # color=random.choice([BLUE, RED]), # width=3 * random.random()**6, # # opacity=0.5 # ) edges.add(edge) all_edges.add(edges) network = VGroup(all_edges, layers, dots) brace = Brace(network, LEFT) self.add(network) self.add(brace)
videos_3b1b/_2017/nn/network.py
""" network.py ~~~~~~~~~~ A module to implement the stochastic gradient descent learning algorithm for a feedforward neural network. Gradients are calculated using backpropagation. Note that I have focused on making the code simple, easily readable, and easily modifiable. It is not optimized, and omits many desirable features. """ #### Libraries # Standard library import os import pickle import random # Third-party libraries import numpy as np from PIL import Image from nn.mnist_loader import load_data_wrapper # from utils.space_ops import get_norm NN_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) # PRETRAINED_DATA_FILE = os.path.join(NN_DIRECTORY, "pretrained_weights_and_biases_80") # PRETRAINED_DATA_FILE = os.path.join(NN_DIRECTORY, "pretrained_weights_and_biases_ReLU") PRETRAINED_DATA_FILE = os.path.join(NN_DIRECTORY, "pretrained_weights_and_biases") IMAGE_MAP_DATA_FILE = os.path.join(NN_DIRECTORY, "image_map") # PRETRAINED_DATA_FILE = "/Users/grant/cs/manim/nn/pretrained_weights_and_biases_on_zero" # DEFAULT_LAYER_SIZES = [28**2, 80, 10] DEFAULT_LAYER_SIZES = [28**2, 16, 16, 10] try: xrange # Python 2 except NameError: xrange = range # Python 3 class Network(object): def __init__(self, sizes, non_linearity = "sigmoid"): """The list ``sizes`` contains the number of neurons in the respective layers of the network. For example, if the list was [2, 3, 1] then it would be a three-layer network, with the first layer containing 2 neurons, the second layer 3 neurons, and the third layer 1 neuron. The biases and weights for the network are initialized randomly, using a Gaussian distribution with mean 0, and variance 1. Note that the first layer is assumed to be an input layer, and by convention we won't set any biases for those neurons, since biases are only ever used in computing the outputs from later layers.""" self.num_layers = len(sizes) self.sizes = sizes self.biases = [np.random.randn(y, 1) for y in sizes[1:]] self.weights = [np.random.randn(y, x) for x, y in zip(sizes[:-1], sizes[1:])] if non_linearity == "sigmoid": self.non_linearity = sigmoid self.d_non_linearity = sigmoid_prime elif non_linearity == "ReLU": self.non_linearity = ReLU self.d_non_linearity = ReLU_prime else: raise Exception("Invalid non_linearity") def feedforward(self, a): """Return the output of the network if ``a`` is input.""" for b, w in zip(self.biases, self.weights): a = self.non_linearity(np.dot(w, a)+b) return a def get_activation_of_all_layers(self, input_a, n_layers = None): if n_layers is None: n_layers = self.num_layers activations = [input_a.reshape((input_a.size, 1))] for bias, weight in zip(self.biases, self.weights)[:n_layers]: last_a = activations[-1] new_a = self.non_linearity(np.dot(weight, last_a) + bias) new_a = new_a.reshape((new_a.size, 1)) activations.append(new_a) return activations def SGD(self, training_data, epochs, mini_batch_size, eta, test_data=None): """Train the neural network using mini-batch stochastic gradient descent. The ``training_data`` is a list of tuples ``(x, y)`` representing the training inputs and the desired outputs. The other non-optional parameters are self-explanatory. If ``test_data`` is provided then the network will be evaluated against the test data after each epoch, and partial progress printed out. This is useful for tracking progress, but slows things down substantially.""" if test_data: n_test = len(test_data) n = len(training_data) for j in range(epochs): random.shuffle(training_data) mini_batches = [ training_data[k:k+mini_batch_size] for k in range(0, n, mini_batch_size)] for mini_batch in mini_batches: self.update_mini_batch(mini_batch, eta) if test_data: print("Epoch {0}: {1} / {2}".format( j, self.evaluate(test_data), n_test)) else: print("Epoch {0} complete".format(j)) def update_mini_batch(self, mini_batch, eta): """Update the network's weights and biases by applying gradient descent using backpropagation to a single mini batch. The ``mini_batch`` is a list of tuples ``(x, y)``, and ``eta`` is the learning rate.""" nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] for x, y in mini_batch: delta_nabla_b, delta_nabla_w = self.backprop(x, y) nabla_b = [nb+dnb for nb, dnb in zip(nabla_b, delta_nabla_b)] nabla_w = [nw+dnw for nw, dnw in zip(nabla_w, delta_nabla_w)] self.weights = [w-(eta/len(mini_batch))*nw for w, nw in zip(self.weights, nabla_w)] self.biases = [b-(eta/len(mini_batch))*nb for b, nb in zip(self.biases, nabla_b)] def backprop(self, x, y): """Return a tuple ``(nabla_b, nabla_w)`` representing the gradient for the cost function C_x. ``nabla_b`` and ``nabla_w`` are layer-by-layer lists of numpy arrays, similar to ``self.biases`` and ``self.weights``.""" nabla_b = [np.zeros(b.shape) for b in self.biases] nabla_w = [np.zeros(w.shape) for w in self.weights] # feedforward activation = x activations = [x] # list to store all the activations, layer by layer zs = [] # list to store all the z vectors, layer by layer for b, w in zip(self.biases, self.weights): z = np.dot(w, activation)+b zs.append(z) activation = self.non_linearity(z) activations.append(activation) # backward pass delta = self.cost_derivative(activations[-1], y) * \ self.d_non_linearity(zs[-1]) nabla_b[-1] = delta nabla_w[-1] = np.dot(delta, activations[-2].transpose()) # Note that the variable l in the loop below is used a little # differently to the notation in Chapter 2 of the book. Here, # l = 1 means the last layer of neurons, l = 2 is the # second-last layer, and so on. It's a renumbering of the # scheme in the book, used here to take advantage of the fact # that Python can use negative indices in lists. for l in range(2, self.num_layers): z = zs[-l] sp = self.d_non_linearity(z) delta = np.dot(self.weights[-l+1].transpose(), delta) * sp nabla_b[-l] = delta nabla_w[-l] = np.dot(delta, activations[-l-1].transpose()) return (nabla_b, nabla_w) def evaluate(self, test_data): """Return the number of test inputs for which the neural network outputs the correct result. Note that the neural network's output is assumed to be the index of whichever neuron in the final layer has the highest activation.""" test_results = [(np.argmax(self.feedforward(x)), y) for (x, y) in test_data] return sum(int(x == y) for (x, y) in test_results) def cost_derivative(self, output_activations, y): """Return the vector of partial derivatives \\partial C_x / \\partial a for the output activations.""" return (output_activations-y) #### Miscellaneous functions def sigmoid(z): """The sigmoid function.""" return 1.0/(1.0+np.exp(-z)) def sigmoid_prime(z): """Derivative of the sigmoid function.""" return sigmoid(z)*(1-sigmoid(z)) def sigmoid_inverse(z): # z = 0.998*z + 0.001 assert(np.max(z) <= 1.0 and np.min(z) >= 0.0) z = 0.998*z + 0.001 return np.log(np.true_divide( 1.0, (np.true_divide(1.0, z) - 1) )) def ReLU(z): result = np.array(z) result[result < 0] = 0 return result def ReLU_prime(z): return (np.array(z) > 0).astype('int') def get_pretrained_network(): data_file = open(PRETRAINED_DATA_FILE, 'rb') weights, biases = pickle.load(data_file, encoding='latin1') sizes = [w.shape[1] for w in weights] sizes.append(weights[-1].shape[0]) network = Network(sizes) network.weights = weights network.biases = biases return network def save_pretrained_network(epochs = 30, mini_batch_size = 10, eta = 3.0): network = Network(sizes = DEFAULT_LAYER_SIZES) training_data, validation_data, test_data = load_data_wrapper() network.SGD(training_data, epochs, mini_batch_size, eta) weights_and_biases = (network.weights, network.biases) data_file = open(PRETRAINED_DATA_FILE, mode = 'w') pickle.dump(weights_and_biases, data_file) data_file.close() def test_network(): network = get_pretrained_network() training_data, validation_data, test_data = load_data_wrapper() n_right, n_wrong = 0, 0 for test_in, test_out in test_data: if np.argmax(network.feedforward(test_in)) == test_out: n_right += 1 else: n_wrong += 1 print((n_right, n_wrong, float(n_right)/(n_right + n_wrong))) def layer_to_image_array(layer): w = int(np.ceil(np.sqrt(len(layer)))) if len(layer) < w**2: layer = np.append(layer, np.zeros(w**2 - len(layer))) layer = layer.reshape((w, w)) # return Image.fromarray((255*layer).astype('uint8')) return (255*layer).astype('int') def maximizing_input(network, layer_index, layer_vect, n_steps = 100, seed_guess = None): pre_sig_layer_vect = sigmoid_inverse(layer_vect) weights, biases = network.weights, network.biases # guess = np.random.random(weights[0].shape[1]) if seed_guess is not None: pre_sig_guess = sigmoid_inverse(seed_guess.flatten()) else: pre_sig_guess = np.random.randn(weights[0].shape[1]) norms = [] for step in range(n_steps): activations = network.get_activation_of_all_layers( sigmoid(pre_sig_guess), layer_index ) jacobian = np.diag(sigmoid_prime(pre_sig_guess).flatten()) for W, a, b in zip(weights, activations, biases): jacobian = np.dot(W, jacobian) a = a.reshape((a.size, 1)) sp = sigmoid_prime(np.dot(W, a) + b) jacobian = np.dot(np.diag(sp.flatten()), jacobian) gradient = np.dot( np.array(layer_vect).reshape((1, len(layer_vect))), jacobian ).flatten() norm = get_norm(gradient) if norm == 0: break norms.append(norm) old_pre_sig_guess = np.array(pre_sig_guess) pre_sig_guess += 0.1*gradient print(get_norm(old_pre_sig_guess - pre_sig_guess)) print("") return sigmoid(pre_sig_guess) def save_organized_images(n_images_per_number = 10): training_data, validation_data, test_data = load_data_wrapper() image_map = dict([(k, []) for k in range(10)]) for im, output_arr in training_data: if min(list(map(len, list(image_map.values())))) >= n_images_per_number: break value = int(np.argmax(output_arr)) if len(image_map[value]) >= n_images_per_number: continue image_map[value].append(im) data_file = open(IMAGE_MAP_DATA_FILE, mode = 'wb') pickle.dump(image_map, data_file) data_file.close() def get_organized_images(): data_file = open(IMAGE_MAP_DATA_FILE, mode = 'r') image_map = pickle.load(data_file, encoding='latin1') data_file.close() return image_map # def maximizing_input(network, layer_index, layer_vect): # if layer_index == 0: # return layer_vect # W = network.weights[layer_index-1] # n = max(W.shape) # W_square = np.identity(n) # W_square[:W.shape[0], :W.shape[1]] = W # zeros = np.zeros((n - len(layer_vect), 1)) # vect = layer_vect.reshape((layer_vect.shape[0], 1)) # vect = np.append(vect, zeros, axis = 0) # b = np.append(network.biases[layer_index-1], zeros, axis = 0) # prev_vect = np.dot( # np.linalg.inv(W_square), # (sigmoid_inverse(vect) - b) # ) # # print layer_vect, sigmoid(np.dot(W, prev_vect)+b) # print W.shape # prev_vect = prev_vect[:W.shape[1]] # prev_vect /= np.max(np.abs(prev_vect)) # # prev_vect /= 1.1 # return maximizing_input(network, layer_index - 1, prev_vect)
videos_3b1b/_2017/nn/part3.py
from _2017.nn.network import * from _2017.nn.part1 import * from _2017.nn.part2 import * class LayOutPlan(Scene): def construct(self): title = OldTexText("Plan") title.scale(1.5) title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS - 1) h_line.next_to(title, DOWN) items = BulletedList( "Recap", "Intuitive walkthrough", "Derivatives in \\\\ computational graphs", ) items.to_edge(LEFT, buff = LARGE_BUFF) self.add(items) rect = ScreenRectangle() rect.set_width(FRAME_WIDTH - items.get_width() - 2) rect.next_to(items, RIGHT, MED_LARGE_BUFF) self.play( Write(title), ShowCreation(h_line), ShowCreation(rect), run_time = 2 ) for i in range(len(items)): self.play(items.fade_all_but, i) self.wait(2) class TODOInsertFeedForwardAnimations(TODOStub): CONFIG = { "message" : "Insert Feed Forward Animations" } class TODOInsertStepsDownCostSurface(TODOStub): CONFIG = { "message" : "Insert Steps Down Cost Surface" } class TODOInsertDefinitionOfCostFunction(TODOStub): CONFIG = { "message" : "Insert Definition of cost function" } class TODOInsertGradientNudging(TODOStub): CONFIG = { "message" : "Insert GradientNudging" } class InterpretGradientComponents(GradientNudging): CONFIG = { "network_mob_config" : { "layer_to_layer_buff" : 3, }, "stroke_width_exp" : 2, "n_decimals" : 6, "n_steps" : 3, "start_cost" : 3.48, "delta_cost" : -0.21, } def construct(self): self.setup_network() self.add_cost() self.add_gradient() self.change_weights_repeatedly() self.ask_about_high_dimensions() self.circle_magnitudes() self.isolate_particular_weights() self.shift_cost_expression() self.tweak_individual_weights() def setup_network(self): self.network_mob.scale(0.55) self.network_mob.to_corner(UP+RIGHT) self.color_network_edges() def add_cost(self): rect = SurroundingRectangle(self.network_mob) rect.set_color(RED) arrow = Vector(DOWN, color = RED) arrow.shift(rect.get_bottom()) cost = DecimalNumber(self.start_cost) cost.set_color(RED) cost.next_to(arrow, DOWN) cost_expression = OldTex( "C(", "w_0, w_1, \\dots, w_{13{,}001}", ")", "=" ) for tex in "()": cost_expression.set_color_by_tex(tex, RED) cost_expression.next_to(cost, DOWN) cost_group = VGroup(cost_expression, cost) cost_group.arrange(RIGHT) cost_group.next_to(arrow, DOWN) self.add(rect, arrow, cost_group) self.set_variables_as_attrs( cost, cost_expression, cost_group, network_rect = rect ) def change_weights_repeatedly(self): decimals = self.grad_vect.decimals grad_terms = self.grad_vect.contents edges = VGroup(*reversed(list( it.chain(*self.network_mob.edge_groups) ))) cost = self.cost for x in range(self.n_steps): self.move_grad_terms_into_position( grad_terms.copy(), *self.get_weight_adjustment_anims(edges, cost) ) self.play(*self.get_decimal_change_anims(decimals)) def ask_about_high_dimensions(self): grad_vect = self.grad_vect words = OldTexText( "Direction in \\\\ ${13{,}002}$ dimensions?!?") words.set_color(YELLOW) words.move_to(grad_vect).to_edge(DOWN) arrow = Arrow( words.get_top(), grad_vect.get_bottom(), buff = SMALL_BUFF ) randy = Randolph() randy.scale(0.6) randy.next_to(words, LEFT) randy.shift_onto_screen() self.play( Write(words, run_time = 2), GrowArrow(arrow), ) self.play(FadeIn(randy)) self.play(randy.change, "confused", words) self.play(Blink(randy)) self.wait() self.play(*list(map(FadeOut, [randy, words, arrow]))) def circle_magnitudes(self): rects = VGroup() for decimal in self.grad_vect.decimals: rects.add(SurroundingRectangle(VGroup(*decimal[-8:]))) rects.set_color(WHITE) self.play(LaggedStartMap(ShowCreation, rects)) self.play(FadeOut(rects)) def isolate_particular_weights(self): vect_contents = self.grad_vect.contents w_terms = self.cost_expression[1] edges = self.network_mob.edge_groups edge1 = self.network_mob.layers[1].neurons[3].edges_in[0].copy() edge2 = self.network_mob.layers[1].neurons[9].edges_in[15].copy() VGroup(edge1, edge2).set_stroke(width = 4) d1 = DecimalNumber(3.2) d2 = DecimalNumber(0.1) VGroup(edge1, d1).set_color(YELLOW) VGroup(edge2, d2).set_color(MAROON_B) new_vect_contents = VGroup( OldTex("\\vdots"), d1, OldTex("\\vdots"), d2, OldTex("\\vdots"), ) new_vect_contents.arrange(DOWN) new_vect_contents.move_to(vect_contents) new_w_terms = OldTex( "\\dots", "w_n", "\\dots", "w_k", "\\dots" ) new_w_terms.move_to(w_terms, DOWN) new_w_terms[1].set_color(d1.get_color()) new_w_terms[3].set_color(d2.get_color()) for d, edge in (d1, edge1), (d2, edge2): d.arrow = Arrow( d.get_right(), edge.get_center(), color = d.get_color() ) self.play( FadeOut(vect_contents), FadeIn(new_vect_contents), FadeOut(w_terms), FadeIn(new_w_terms), edges.set_stroke, GREY_B, 0.35, ) self.play(GrowArrow(d1.arrow)) self.play(ShowCreation(edge1)) self.wait() self.play(GrowArrow(d2.arrow)) self.play(ShowCreation(edge2)) self.wait(2) self.cost_expression.remove(w_terms) self.cost_expression.add(new_w_terms) self.set_variables_as_attrs( edge1, edge2, new_w_terms, new_decimals = VGroup(d1, d2) ) def shift_cost_expression(self): self.play(self.cost_group.shift, DOWN+0.5*LEFT) def tweak_individual_weights(self): cost = self.cost cost_num = cost.number edges = VGroup(self.edge1, self.edge2) decimals = self.new_decimals changes = (1.0, 1./32) wn = self.new_w_terms[1] wk = self.new_w_terms[3] number_line_template = NumberLine( x_min = -1, x_max = 1, tick_frequency = 0.25, numbers_with_elongated_ticks = [], color = WHITE ) for term in wn, wk, cost: term.number_line = number_line_template.copy() term.brace = Brace(term.number_line, DOWN, buff = SMALL_BUFF) group = VGroup(term.number_line, term.brace) group.next_to(term, UP) term.dot = Dot() term.dot.set_color(term.get_color()) term.dot.move_to(term.number_line.get_center()) term.dot.save_state() term.dot.move_to(term) term.dot.set_fill(opacity = 0) term.words = OldTexText("Nudge this weight") term.words.scale(0.7) term.words.next_to(term.number_line, UP, MED_SMALL_BUFF) groups = [ VGroup(d, d.arrow, edge, w) for d, edge, w in zip(decimals, edges, [wn, wk]) ] for group in groups: group.save_state() for i in range(2): group1, group2 = groups[i], groups[1-i] change = changes[i] edge = edges[i] w = group1[-1] added_anims = [] if i == 0: added_anims = [ GrowFromCenter(cost.brace), ShowCreation(cost.number_line), cost.dot.restore ] self.play( group1.restore, group2.fade, 0.7, GrowFromCenter(w.brace), ShowCreation(w.number_line), w.dot.restore, Write(w.words, run_time = 1), *added_anims ) for x in range(2): func = lambda a : interpolate( cost_num, cost_num-change, a ) self.play( ChangingDecimal(cost, func), cost.dot.shift, change*RIGHT, w.dot.shift, 0.25*RIGHT, edge.set_stroke, None, 8, rate_func = lambda t : wiggle(t, 4), run_time = 2, ) self.wait() self.play(*list(map(FadeOut, [ w.dot, w.brace, w.number_line, w.words ]))) ###### def move_grad_terms_into_position(self, grad_terms, *added_anims): cost_expression = self.cost_expression w_terms = self.cost_expression[1] points = VGroup(*[ VectorizedPoint() for term in grad_terms ]) points.arrange(RIGHT) points.replace(w_terms, dim_to_match = 0) grad_terms.generate_target() grad_terms.target[len(grad_terms)/2].rotate(np.pi/2) grad_terms.target.arrange(RIGHT) grad_terms.target.set_width(cost_expression.get_width()) grad_terms.target.next_to(cost_expression, DOWN) words = OldTexText("Nudge weights") words.scale(0.8) words.next_to(grad_terms.target, DOWN) self.play( MoveToTarget(grad_terms), FadeIn(words) ) self.play( Transform( grad_terms, points, remover = True, lag_ratio = 0.5, run_time = 1 ), FadeOut(words), *added_anims ) def get_weight_adjustment_anims(self, edges, cost): start_cost = cost.number target_cost = start_cost + self.delta_cost w_terms = self.cost_expression[1] return [ self.get_edge_change_anim(edges), LaggedStartMap( Indicate, w_terms, rate_func = there_and_back, run_time = 1.5, ), ChangingDecimal( cost, lambda a : interpolate(start_cost, target_cost, a), run_time = 1.5 ) ] class GetLostInNotation(PiCreatureScene): def construct(self): morty = self.pi_creature equations = VGroup( OldTex( "\\delta", "^L", "=", "\\nabla_a", "C", "\\odot \\sigma'(", "z", "^L)" ), OldTex( "\\delta", "^l = ((", "w", "^{l+1})^T", "\\delta", "^{l+1}) \\odot \\sigma'(", "z", "^l)" ), OldTex( "{\\partial", "C", "\\over \\partial", "b", "_j^l} =", "\\delta", "_j^l" ), OldTex( "{\\partial", "C", " \\over \\partial", "w", "_{jk}^l} = ", "a", "_k^{l-1}", "\\delta", "_j^l" ), ) for equation in equations: equation.set_color_by_tex_to_color_map({ "\\delta" : YELLOW, "C" : RED, "b" : MAROON_B, "w" : BLUE, "z" : TEAL, }) equation.set_color_by_tex("nabla", WHITE) equations.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) circle = Circle(radius = 3*FRAME_X_RADIUS) circle.set_fill(WHITE, 0) circle.set_stroke(WHITE, 0) self.play( Write(equations), morty.change, "confused", equations ) self.wait() self.play(morty.change, "pleading") self.wait(2) ## movers = VGroup(*equations.family_members_with_points()) random.shuffle(movers.submobjects) for mover in list(movers): if mover.is_subpath: movers.remove(mover) continue mover.set_stroke(WHITE, width = 0) mover.target = Circle() mover.target.scale(0.5) mover.target.set_fill(mover.get_color(), opacity = 0) mover.target.set_stroke(BLACK, width = 1) mover.target.move_to(mover) self.play( LaggedStartMap( MoveToTarget, movers, run_time = 2, ), morty.change, "pondering", ) self.wait() class TODOInsertPreviewLearning(TODOStub): CONFIG = { "message" : "Insert PreviewLearning" } class ShowAveragingCost(PreviewLearning): CONFIG = { "network_scale_val" : 0.8, "stroke_width_exp" : 1, "start_examples_time" : 5, "examples_per_adjustment_time" : 2, "n_adjustments" : 5, "time_per_example" : 1./15, "image_height" : 1.2, } def construct(self): self.setup_network() self.setup_diff_words() self.show_many_examples() def setup_network(self): self.network_mob.scale(self.network_scale_val) self.network_mob.to_edge(DOWN) self.network_mob.shift(LEFT) self.color_network_edges() def setup_diff_words(self): last_layer_copy = self.network_mob.layers[-1].deepcopy() last_layer_copy.add(self.network_mob.output_labels.copy()) last_layer_copy.shift(1.5*RIGHT) double_arrow = DoubleArrow( self.network_mob.output_labels, last_layer_copy, color = RED ) brace = Brace( VGroup(self.network_mob.layers[-1], last_layer_copy), UP ) cost_words = brace.get_text("Cost of \\\\ one example") cost_words.set_color(RED) self.add(last_layer_copy, double_arrow, brace, cost_words) self.set_variables_as_attrs( last_layer_copy, double_arrow, brace, cost_words ) self.last_layer_copy = last_layer_copy def show_many_examples(self): training_data, validation_data, test_data = load_data_wrapper() average_words = OldTexText("Average over all training examples") average_words.next_to(LEFT, RIGHT) average_words.to_edge(UP) self.add(average_words) n_start_examples = int(self.start_examples_time/self.time_per_example) n_examples_per_adjustment = int(self.examples_per_adjustment_time/self.time_per_example) for train_in, train_out in training_data[:n_start_examples]: self.show_one_example(train_in, train_out) self.wait(self.time_per_example) #Wiggle all edges edges = VGroup(*it.chain(*self.network_mob.edge_groups)) reversed_edges = VGroup(*reversed(edges)) self.play(LaggedStartMap( ApplyFunction, edges, lambda edge : ( lambda m : m.rotate(np.pi/12).set_color(YELLOW), edge, ), rate_func = lambda t : wiggle(t, 4), run_time = 3, )) #Show all, then adjust words = OldTexText( "Each step \\\\ uses every \\\\ example\\\\", "$\\dots$theoretically", alignment = "" ) words.set_color(YELLOW) words.scale(0.8) words.to_corner(UP+LEFT) for x in range(self.n_adjustments): if x < 2: self.play(FadeIn(words[x])) for train_in, train_out in training_data[:n_examples_per_adjustment]: self.show_one_example(train_in, train_out) self.wait(self.time_per_example) self.play(LaggedStartMap( ApplyMethod, reversed_edges, lambda m : (m.rotate, np.pi), run_time = 1, lag_ratio = 0.2, )) if x >= 2: self.wait() #### def show_one_example(self, train_in, train_out): if hasattr(self, "curr_image"): self.remove(self.curr_image) image = MNistMobject(train_in) image.set_height(self.image_height) image.next_to( self.network_mob.layers[0].neurons, UP, aligned_edge = LEFT ) self.add(image) self.network_mob.activate_layers(train_in) index = np.argmax(train_out) self.last_layer_copy.neurons.set_fill(opacity = 0) self.last_layer_copy.neurons[index].set_fill(WHITE, opacity = 1) self.add(self.last_layer_copy) self.curr_image = image class FocusOnOneExample(TeacherStudentsScene): def construct(self): self.teacher_says("Focus on just \\\\ one example") self.wait(2) class WalkThroughTwoExample(ShowAveragingCost): CONFIG = { "random_seed" : 0, } def setup(self): np.random.seed(self.random_seed) random.seed(self.random_seed) self.setup_bases() def construct(self): self.force_skipping() self.setup_network() self.setup_diff_words() self.show_single_example() self.single_example_influencing_weights() self.expand_last_layer() self.show_activation_formula() self.three_ways_to_increase() self.note_connections_to_brightest_neurons() self.fire_together_wire_together() self.show_desired_increase_to_previous_neurons() self.only_keeping_track_of_changes() self.show_other_output_neurons() self.show_recursion() def show_single_example(self): two_vect = get_organized_images()[2][0] two_out = np.zeros(10) two_out[2] = 1.0 self.show_one_example(two_vect, two_out) for layer in self.network_mob.layers: layer.neurons.set_fill(opacity = 0) self.activate_network(two_vect) self.wait() def single_example_influencing_weights(self): two = self.curr_image two.save_state() edge_groups = self.network_mob.edge_groups def adjust_edge_group_anim(edge_group): return LaggedStartMap( ApplyFunction, edge_group, lambda edge : ( lambda m : m.rotate(np.pi/12).set_color(YELLOW), edge ), rate_func = wiggle, run_time = 1, ) self.play( two.next_to, edge_groups[0].get_corner(DOWN+RIGHT), DOWN, adjust_edge_group_anim(edge_groups[0]) ) self.play( ApplyMethod( two.next_to, edge_groups[1].get_corner(UP+RIGHT), UP, path_arc = np.pi/6, ), adjust_edge_group_anim(VGroup(*reversed(edge_groups[1]))) ) self.play( ApplyMethod( two.next_to, edge_groups[2].get_corner(DOWN+RIGHT), DOWN, path_arc = -np.pi/6, ), adjust_edge_group_anim(edge_groups[2]) ) self.play(two.restore) self.wait() def expand_last_layer(self): neurons = self.network_mob.layers[-1].neurons alt_neurons = self.last_layer_copy.neurons output_labels = self.network_mob.output_labels alt_output_labels = self.last_layer_copy[-1] edges = self.network_mob.edge_groups[-1] movers = VGroup( neurons, alt_neurons, output_labels, alt_output_labels, *edges ) to_fade = VGroup(self.brace, self.cost_words, self.double_arrow) for mover in movers: mover.save_state() mover.generate_target() mover.target.scale(2) neurons[2].save_state() neurons.target.to_edge(DOWN, MED_LARGE_BUFF) output_labels.target.next_to(neurons.target, RIGHT, MED_SMALL_BUFF) alt_neurons.target.next_to(neurons.target, RIGHT, buff = 2) alt_output_labels.target.next_to(alt_neurons.target, RIGHT, MED_SMALL_BUFF) n_pairs = it.product( self.network_mob.layers[-2].neurons, neurons.target ) for edge, (n1, n2) in zip(edges, n_pairs): r1 = n1.get_width()/2.0 r2 = n2.get_width()/2.0 c1 = n1.get_center() c2 = n2.get_center() vect = c2 - c1 norm = get_norm(vect) unit_vect = vect / norm edge.target.put_start_and_end_on( c1 + unit_vect*r1, c2 - unit_vect*r2 ) self.play( FadeOut(to_fade), *list(map(MoveToTarget, movers)) ) self.show_decimals(neurons) self.cannot_directly_affect_activations() self.show_desired_activation_nudges(neurons, output_labels, alt_output_labels) self.focus_on_one_neuron(movers) def show_decimals(self, neurons): decimals = VGroup() for neuron in neurons: activation = neuron.get_fill_opacity() decimal = DecimalNumber(activation, num_decimal_places = 1) decimal.set_width(0.7*neuron.get_width()) decimal.move_to(neuron) if activation > 0.8: decimal.set_color(BLACK) decimals.add(decimal) self.play(Write(decimals, run_time = 2)) self.wait() self.decimals = decimals def cannot_directly_affect_activations(self): words = OldTexText("You can only adjust weights and biases") words.next_to(self.curr_image, RIGHT, MED_SMALL_BUFF, UP) edges = VGroup(*self.network_mob.edge_groups.family_members_with_points()) random.shuffle(edges.submobjects) for edge in edges: edge.generate_target() edge.target.set_stroke( random.choice([BLUE, RED]), 2*random.random()**2, ) self.play( LaggedStartMap( Transform, edges, lambda e : (e, e.target), run_time = 4, rate_func = there_and_back, ), Write(words, run_time = 2) ) self.play(FadeOut(words)) def show_desired_activation_nudges(self, neurons, output_labels, alt_output_labels): arrows = VGroup() rects = VGroup() for i, neuron, label in zip(it.count(), neurons, alt_output_labels): activation = neuron.get_fill_opacity() target_val = 1 if i == 2 else 0 diff = abs(activation - target_val) arrow = Arrow( ORIGIN, diff*neuron.get_height()*DOWN, color = RED, ) arrow.move_to(neuron.get_right()) arrow.shift(0.175*RIGHT) if i == 2: arrow.set_color(BLUE) arrow.rotate(np.pi) arrows.add(arrow) rect = SurroundingRectangle(VGroup(neuron, label)) if i == 2: rect.set_color(BLUE) else: rect.set_color(RED) rects.add(rect) self.play( output_labels.shift, SMALL_BUFF*RIGHT, LaggedStartMap(GrowArrow, arrows, run_time = 1) ) self.wait() #Show changing activations anims = [] def get_decimal_update(start, end): return lambda a : interpolate(start, end, a) for i in range(10): target = 1.0 if i == 2 else 0.01 anims += [neurons[i].set_fill, WHITE, target] decimal = self.decimals[i] anims.append(ChangingDecimal( decimal, get_decimal_update(decimal.number, target), num_decimal_places = 1 )) anims.append(UpdateFromFunc( self.decimals[i], lambda m : m.set_fill(WHITE if m.number < 0.8 else BLACK) )) self.play( *anims, run_time = 3, rate_func = there_and_back ) two_rect = rects[2] eight_rect = rects[8].copy() non_two_rects = VGroup(*[r for r in rects if r is not two_rect]) self.play(ShowCreation(two_rect)) self.wait() self.remove(two_rect) self.play(ReplacementTransform(two_rect.copy(), non_two_rects)) self.wait() self.play(LaggedStartMap(FadeOut, non_two_rects, run_time = 1)) self.play(LaggedStartMap( ApplyFunction, arrows, lambda arrow : ( lambda m : m.scale(0.5).set_color(YELLOW), arrow, ), rate_func = wiggle )) self.play(ShowCreation(two_rect)) self.wait() self.play(ReplacementTransform(two_rect, eight_rect)) self.wait() self.play(FadeOut(eight_rect)) self.arrows = arrows def focus_on_one_neuron(self, expanded_mobjects): network_mob = self.network_mob neurons = network_mob.layers[-1].neurons labels = network_mob.output_labels two_neuron = neurons[2] neurons.remove(two_neuron) two_label = labels[2] labels.remove(two_label) expanded_mobjects.remove(*two_neuron.edges_in) two_decimal = self.decimals[2] self.decimals.remove(two_decimal) two_arrow = self.arrows[2] self.arrows.remove(two_arrow) to_fade = VGroup(*it.chain( network_mob.layers[:2], network_mob.edge_groups[:2], expanded_mobjects, self.decimals, self.arrows )) self.play(FadeOut(to_fade)) self.wait() for mob in expanded_mobjects: if mob in [neurons, labels]: mob.scale(0.5) mob.move_to(mob.saved_state) else: mob.restore() for d, a, n in zip(self.decimals, self.arrows, neurons): d.scale(0.5) d.move_to(n) a.scale(0.5) a.move_to(n.get_right()) a.shift(SMALL_BUFF*RIGHT) labels.shift(SMALL_BUFF*RIGHT) self.set_variables_as_attrs( two_neuron, two_label, two_arrow, two_decimal, ) def show_activation_formula(self): rhs = OldTex( "=", "\\sigma(", "w_0", "a_0", "+", "w_1", "a_1", "+", "\\cdots", "+", "w_{n-1}", "a_{n-1}", "+", "b", ")" ) equals = rhs[0] sigma = VGroup(rhs[1], rhs[-1]) w_terms = rhs.get_parts_by_tex("w_") a_terms = rhs.get_parts_by_tex("a_") plus_terms = rhs.get_parts_by_tex("+") b = rhs.get_part_by_tex("b", substring = False) dots = rhs.get_part_by_tex("dots") w_terms.set_color(BLUE) b.set_color(MAROON_B) sigma.set_color(YELLOW) rhs.to_corner(UP+RIGHT) sigma.save_state() sigma.shift(DOWN) sigma.set_fill(opacity = 0) prev_neurons = self.network_mob.layers[-2].neurons edges = self.two_neuron.edges_in neuron_copy = VGroup( self.two_neuron.copy(), self.two_decimal.copy(), ) self.play( neuron_copy.next_to, equals.get_left(), LEFT, self.curr_image.to_corner, UP+LEFT, Write(equals) ) self.play( ReplacementTransform(edges.copy(), w_terms), Write(VGroup(*plus_terms[:-1])), Write(dots), run_time = 1.5 ) self.wait() self.play(ReplacementTransform( prev_neurons.copy(), a_terms, path_arc = np.pi/2 )) self.wait() self.play( Write(plus_terms[-1]), Write(b) ) self.wait() self.play(sigma.restore) self.wait() for mob in b, w_terms, a_terms: self.play( mob.shift, MED_SMALL_BUFF*DOWN, rate_func = there_and_back, lag_ratio = 0.5, run_time = 1.5 ) self.wait() self.set_variables_as_attrs( rhs, w_terms, a_terms, b, lhs = neuron_copy ) def three_ways_to_increase(self): w_terms = self.w_terms a_terms = self.a_terms b = self.b increase_words = VGroup( OldTexText("Increase", "$b$"), OldTexText("Increase", "$w_i$"), OldTexText("Change", "$a_i$"), ) for words in increase_words: words.set_color_by_tex_to_color_map({ "b" : b.get_color(), "w_" : w_terms.get_color(), "a_" : a_terms.get_color(), }) increase_words.arrange( DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ) increase_words.to_edge(LEFT) mobs = [b, w_terms[0], a_terms[0]] for words, mob in zip(increase_words, mobs): self.play( Write(words[0], run_time = 1), ReplacementTransform(mob.copy(), words[1]) ) self.wait() self.increase_words = increase_words def note_connections_to_brightest_neurons(self): w_terms = self.w_terms a_terms = self.a_terms increase_words = self.increase_words prev_neurons = self.network_mob.layers[-2].neurons edges = self.two_neuron.edges_in prev_activations = np.array([n.get_fill_opacity() for n in prev_neurons]) sorted_indices = np.argsort(prev_activations.flatten()) bright_neurons = VGroup() dim_neurons = VGroup() edges_to_bright_neurons = VGroup() for i in sorted_indices[:5]: dim_neurons.add(prev_neurons[i]) for i in sorted_indices[-4:]: bright_neurons.add(prev_neurons[i]) edges_to_bright_neurons.add(edges[i]) bright_edges = edges_to_bright_neurons.copy() bright_edges.set_stroke(YELLOW, 4) added_words = OldTexText("in proportion to $a_i$") added_words.next_to( increase_words[1], DOWN, 1.5*SMALL_BUFF, LEFT ) added_words.set_color(YELLOW) terms_rect = SurroundingRectangle( VGroup(w_terms[0], a_terms[0]), color = WHITE ) self.play(LaggedStartMap( ApplyFunction, edges, lambda edge : ( lambda m : m.rotate(np.pi/12).set_stroke(YELLOW), edge ), rate_func = wiggle )) self.wait() self.play( ShowCreation(bright_edges), ShowCreation(bright_neurons) ) self.play(LaggedStartMap( ApplyMethod, bright_neurons, lambda m : (m.shift, MED_LARGE_BUFF*LEFT), rate_func = there_and_back )) self.wait() self.play( ReplacementTransform(bright_edges[0].copy(), w_terms[0]), ReplacementTransform(bright_neurons[0].copy(), a_terms[0]), ShowCreation(terms_rect) ) self.wait() for x in range(2): self.play(LaggedStartMap(ShowCreationThenDestruction, bright_edges)) self.play(LaggedStartMap(ShowCreation, bright_edges)) self.play(LaggedStartMap( ApplyMethod, dim_neurons, lambda m : (m.shift, MED_LARGE_BUFF*LEFT), rate_func = there_and_back )) self.play(FadeOut(terms_rect)) self.wait() self.play( self.curr_image.shift, MED_LARGE_BUFF*RIGHT, rate_func = wiggle ) self.wait() self.play(Write(added_words)) self.wait() self.set_variables_as_attrs( bright_neurons, bright_edges, in_proportion_to_a = added_words ) def fire_together_wire_together(self): bright_neurons = self.bright_neurons bright_edges = self.bright_edges two_neuron = self.two_neuron two_decimal = self.two_decimal two_activation = two_decimal.number def get_edge_animation(): return LaggedStartMap( ShowCreationThenDestruction, bright_edges, lag_ratio = 0.7 ) neuron_arrows = VGroup(*[ Vector(MED_LARGE_BUFF*RIGHT).next_to(n, LEFT) for n in bright_neurons ]) two_neuron_arrow = Vector(MED_LARGE_BUFF*DOWN) two_neuron_arrow.next_to(two_neuron, UP) VGroup(neuron_arrows, two_neuron_arrow).set_color(YELLOW) neuron_rects = VGroup(*list(map( SurroundingRectangle, bright_neurons ))) two_neuron_rect = SurroundingRectangle(two_neuron) seeing_words = OldTexText("Seeing a 2") seeing_words.scale(0.8) thinking_words = OldTexText("Thinking about a 2") thinking_words.scale(0.8) seeing_words.next_to(neuron_rects, UP) thinking_words.next_to(two_neuron_arrow, RIGHT) morty = Mortimer() morty.scale(0.8) morty.to_corner(DOWN+RIGHT) words = OldTexText(""" ``Neurons that \\\\ fire together \\\\ wire together'' """) words.to_edge(RIGHT) self.play(FadeIn(morty)) self.play( Write(words), morty.change, "speaking", words ) self.play(Blink(morty)) self.play( get_edge_animation(), morty.change, "pondering", bright_edges ) self.play(get_edge_animation()) self.play( LaggedStartMap(GrowArrow, neuron_arrows), get_edge_animation(), ) self.play( GrowArrow(two_neuron_arrow), morty.change, "raise_right_hand", two_neuron ) self.play( ApplyMethod(two_neuron.set_fill, WHITE, 1), ChangingDecimal( two_decimal, lambda a : interpolate(two_activation, 1, a), num_decimal_places = 1, ), UpdateFromFunc( two_decimal, lambda m : m.set_color(WHITE if m.number < 0.8 else BLACK), ), LaggedStartMap(ShowCreation, bright_edges), run_time = 2, ) self.wait() self.play( LaggedStartMap(ShowCreation, neuron_rects), Write(seeing_words, run_time = 2), morty.change, "thinking", seeing_words ) self.wait() self.play( ShowCreation(two_neuron_rect), Write(thinking_words, run_time = 2), morty.look_at, thinking_words ) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( neuron_rects, two_neuron_rect, seeing_words, thinking_words, words, morty, neuron_arrows, two_neuron_arrow, bright_edges, ))) self.play( ApplyMethod(two_neuron.set_fill, WHITE, two_activation), ChangingDecimal( two_decimal, lambda a : interpolate(1, two_activation, a), num_decimal_places = 1, ), UpdateFromFunc( two_decimal, lambda m : m.set_color(WHITE if m.number < 0.8 else BLACK), ), ) def show_desired_increase_to_previous_neurons(self): increase_words = self.increase_words two_neuron = self.two_neuron two_decimal = self.two_decimal edges = two_neuron.edges_in prev_neurons = self.network_mob.layers[-2].neurons positive_arrows = VGroup() negative_arrows = VGroup() all_arrows = VGroup() positive_edges = VGroup() negative_edges = VGroup() positive_neurons = VGroup() negative_neurons = VGroup() for neuron, edge in zip(prev_neurons, edges): value = self.get_edge_value(edge) arrow = self.get_neuron_nudge_arrow(edge) arrow.move_to(neuron.get_left()) arrow.shift(SMALL_BUFF*LEFT) all_arrows.add(arrow) if value > 0: positive_arrows.add(arrow) positive_edges.add(edge) positive_neurons.add(neuron) else: negative_arrows.add(arrow) negative_edges.add(edge) negative_neurons.add(neuron) for s_edges in positive_edges, negative_edges: s_edges.alt_position = VGroup(*[ Line(LEFT, RIGHT, color = s_edge.get_color()) for s_edge in s_edges ]) s_edges.alt_position.arrange(DOWN, MED_SMALL_BUFF) s_edges.alt_position.to_corner(DOWN+RIGHT, LARGE_BUFF) added_words = OldTexText("in proportion to $w_i$") added_words.set_color(self.w_terms.get_color()) added_words.next_to( increase_words[-1], DOWN, SMALL_BUFF, aligned_edge = LEFT ) self.play(LaggedStartMap( ApplyFunction, prev_neurons, lambda neuron : ( lambda m : m.scale(0.5).set_color(YELLOW), neuron ), rate_func = wiggle )) self.wait() for positive in [True, False]: if positive: arrows = positive_arrows s_edges = positive_edges neurons = positive_neurons color = self.positive_edge_color else: arrows = negative_arrows s_edges = negative_edges neurons = negative_neurons color = self.negative_edge_color s_edges.save_state() self.play(Transform(s_edges, s_edges.alt_position)) self.wait(0.5) self.play(s_edges.restore) self.play( LaggedStartMap(GrowArrow, arrows), neurons.set_stroke, color ) self.play(ApplyMethod( neurons.set_fill, color, 1, rate_func = there_and_back, )) self.wait() self.play( two_neuron.set_fill, None, 0.8, ChangingDecimal( two_decimal, lambda a : two_neuron.get_fill_opacity() ), run_time = 3, rate_func = there_and_back ) self.wait() self.play(*[ ApplyMethod( edge.set_stroke, None, 3*edge.get_stroke_width(), rate_func = there_and_back, run_time = 2 ) for edge in edges ]) self.wait() self.play(Write(added_words, run_time = 1)) self.play(prev_neurons.set_stroke, WHITE, 2) self.set_variables_as_attrs( in_proportion_to_w = added_words, prev_neuron_arrows = all_arrows, ) def only_keeping_track_of_changes(self): arrows = self.prev_neuron_arrows prev_neurons = self.network_mob.layers[-2].neurons rect = SurroundingRectangle(VGroup(arrows, prev_neurons)) words1 = OldTexText("No direct influence") words1.next_to(rect, UP) words2 = OldTexText("Just keeping track") words2.move_to(words1) edges = self.network_mob.edge_groups[-2] self.play(ShowCreation(rect)) self.play(Write(words1)) self.play(LaggedStartMap( Indicate, prev_neurons, rate_func = wiggle )) self.wait() self.play(LaggedStartMap( ShowCreationThenDestruction, edges )) self.play(Transform(words1, words2)) self.wait() self.play(FadeOut(VGroup(words1, rect))) def show_other_output_neurons(self): two_neuron = self.two_neuron two_decimal = self.two_decimal two_arrow = self.two_arrow two_label = self.two_label two_edges = two_neuron.edges_in prev_neurons = self.network_mob.layers[-2].neurons neurons = self.network_mob.layers[-1].neurons prev_neuron_arrows = self.prev_neuron_arrows arrows_to_fade = VGroup(prev_neuron_arrows) output_labels = self.network_mob.output_labels quads = list(zip(neurons, self.decimals, self.arrows, output_labels)) self.revert_to_original_skipping_status() self.play( two_neuron.restore, two_decimal.scale, 0.5, two_decimal.move_to, two_neuron.saved_state, two_arrow.scale, 0.5, two_arrow.next_to, two_neuron.saved_state, RIGHT, 0.5*SMALL_BUFF, two_label.scale, 0.5, two_label.next_to, two_neuron.saved_state, RIGHT, 1.5*SMALL_BUFF, FadeOut(VGroup(self.lhs, self.rhs)), *[e.restore for e in two_edges] ) for neuron, decimal, arrow, label in quads[:2] + quads[2:5]: plusses = VGroup() new_arrows = VGroup() for edge, prev_arrow in zip(neuron.edges_in, prev_neuron_arrows): plus = OldTex("+").scale(0.5) plus.move_to(prev_arrow) plus.shift(2*SMALL_BUFF*LEFT) new_arrow = self.get_neuron_nudge_arrow(edge) new_arrow.move_to(plus) new_arrow.shift(2*SMALL_BUFF*LEFT) plusses.add(plus) new_arrows.add(new_arrow) self.play( FadeIn(VGroup(neuron, decimal, arrow, label)), LaggedStartMap(ShowCreation, neuron.edges_in), ) self.play( ReplacementTransform(neuron.edges_in.copy(), new_arrows), Write(plusses, run_time = 2) ) arrows_to_fade.add(new_arrows, plusses) prev_neuron_arrows = new_arrows all_dots_plus = VGroup() for arrow in prev_neuron_arrows: dots_plus = OldTex("\\cdots +") dots_plus.scale(0.5) dots_plus.move_to(arrow.get_center(), RIGHT) dots_plus.shift(2*SMALL_BUFF*LEFT) all_dots_plus.add(dots_plus) arrows_to_fade.add(all_dots_plus) self.play( LaggedStartMap( FadeIn, VGroup(*it.starmap(VGroup, quads[5:])), ), LaggedStartMap( FadeIn, VGroup(*[n.edges_in for n in neurons[5:]]) ), Write(all_dots_plus), run_time = 3, ) self.wait(2) ## words = OldTexText("Propagate backwards") words.to_edge(UP) words.set_color(BLUE) target_arrows = prev_neuron_arrows.copy() target_arrows.next_to(prev_neurons, RIGHT, SMALL_BUFF) rect = SurroundingRectangle(VGroup( self.network_mob.layers[-1], self.network_mob.output_labels )) rect.set_fill(BLACK, 1) rect.set_stroke(BLACK, 0) self.play(Write(words)) self.wait() self.play( FadeOut(self.network_mob.edge_groups[-1]), FadeIn(rect), ReplacementTransform(arrows_to_fade, VGroup(target_arrows)), ) self.prev_neuron_arrows = target_arrows def show_recursion(self): network_mob = self.network_mob words_to_fade = VGroup( self.increase_words, self.in_proportion_to_w, self.in_proportion_to_a, ) edges = network_mob.edge_groups[1] neurons = network_mob.layers[2].neurons prev_neurons = network_mob.layers[1].neurons for neuron in neurons: neuron.edges_in.save_state() self.play( FadeOut(words_to_fade), FadeIn(prev_neurons), LaggedStartMap(ShowCreation, edges), ) self.wait() for neuron, arrow in zip(neurons, self.prev_neuron_arrows): edge_copies = neuron.edges_in.copy() for edge in edge_copies: edge.set_stroke(arrow.get_color(), 2) edge.rotate(np.pi) self.play( edges.set_stroke, None, 0.15, neuron.edges_in.restore, ) self.play(ShowCreationThenDestruction(edge_copies)) self.remove(edge_copies) #### def get_neuron_nudge_arrow(self, edge): value = self.get_edge_value(edge) height = np.sign(value)*0.1 + 0.1*value arrow = Vector(height*UP, color = edge.get_color()) return arrow def get_edge_value(self, edge): value = edge.get_stroke_width() if Color(edge.get_stroke_color()) == Color(self.negative_edge_color): value *= -1 return value class WriteHebbian(Scene): def construct(self): words = OldTexText("Hebbian theory") words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) self.play(Write(words)) self.wait() class NotANeuroScientist(TeacherStudentsScene): def construct(self): quote = OldTexText("``Neurons that fire together wire together''") quote.to_edge(UP) self.add(quote) asterisks = OldTexText("***") asterisks.next_to(quote.get_corner(UP+RIGHT), RIGHT, SMALL_BUFF) asterisks.set_color(BLUE) brain = SVGMobject(file_name = "brain") brain.set_height(1.5) self.add(brain) double_arrow = DoubleArrow(LEFT, RIGHT) double_arrow.next_to(brain, RIGHT) q_marks = OldTexText("???") q_marks.next_to(double_arrow, UP) network = NetworkMobject(Network(sizes = [6, 4, 4, 5])) network.set_height(1.5) network.next_to(double_arrow, RIGHT) group = VGroup(brain, double_arrow, q_marks, network) group.next_to(self.students, UP, buff = 1.5) self.add(group) self.add(ContinualEdgeUpdate( network, stroke_width_exp = 0.5, color = [BLUE, RED], )) rect = SurroundingRectangle(group) no_claim_words = OldTexText("No claims here...") no_claim_words.next_to(rect, UP) no_claim_words.set_color(YELLOW) brain_outline = brain.copy() brain_outline.set_fill(opacity = 0) brain_outline.set_stroke(BLUE, 3) brain_anim = ShowCreationThenDestruction(brain_outline) words = OldTexText("Definitely not \\\\ a neuroscientist") words.next_to(self.teacher, UP, buff = 1.5) words.shift_onto_screen() arrow = Arrow(words.get_bottom(), self.teacher.get_top()) self.play( Write(words), GrowArrow(arrow), self.teacher.change, "guilty", words, run_time = 1, ) self.play_student_changes(*3*["sassy"]) self.play( ShowCreation(rect), Write(no_claim_words, run_time = 1), brain_anim ) self.wait() self.play(brain_anim) self.play(FocusOn(asterisks)) self.play(Write(asterisks, run_time = 1)) for x in range(2): self.play(brain_anim) self.wait() class ConstructGradientFromAllTrainingExamples(Scene): CONFIG = { "image_height" : 0.9, "eyes_height" : 0.25, "n_examples" : 6, "change_scale_val" : 0.8, } def construct(self): self.setup_grid() self.setup_weights() self.show_two_requesting_changes() self.show_all_examples_requesting_changes() self.average_together() self.collapse_into_gradient_vector() def setup_grid(self): h_lines = VGroup(*[ Line(LEFT, RIGHT).scale(0.85*FRAME_X_RADIUS) for x in range(6) ]) h_lines.arrange(DOWN, buff = 1) h_lines.set_stroke(GREY_B, 2) h_lines.to_edge(DOWN, buff = MED_LARGE_BUFF) h_lines.to_edge(LEFT, buff = 0) v_lines = VGroup(*[ Line(UP, DOWN).scale(FRAME_Y_RADIUS - MED_LARGE_BUFF) for x in range(self.n_examples + 1) ]) v_lines.arrange(RIGHT, buff = 1.4) v_lines.set_stroke(GREY_B, 2) v_lines.to_edge(LEFT, buff = 2) # self.add(h_lines, v_lines) self.h_lines = h_lines self.v_lines = v_lines def setup_weights(self): weights = VGroup(*list(map(Tex, [ "w_0", "w_1", "w_2", "\\vdots", "w_{13{,}001}" ]))) for i, weight in enumerate(weights): weight.move_to(self.get_grid_position(i, 0)) weights.to_edge(LEFT, buff = MED_SMALL_BUFF) brace = Brace(weights, RIGHT) weights_words = brace.get_text("All weights and biases") self.add(weights, brace, weights_words) self.set_variables_as_attrs( weights, brace, weights_words, dots = weights[-2] ) def show_two_requesting_changes(self): two = self.get_example(get_organized_images()[2][0], 0) self.two = two self.add(two) self.two_changes = VGroup() for i in list(range(3)) + [4]: weight = self.weights[i] bubble, change = self.get_requested_change_bubble(two) weight.save_state() weight.generate_target() weight.target.next_to(two, RIGHT, aligned_edge = DOWN) self.play( MoveToTarget(weight), two.eyes.look_at_anim(weight.target), FadeIn(bubble), Write(change, run_time = 1), ) if random.random() < 0.5: self.play(two.eyes.blink_anim()) else: self.wait() if i == 0: added_anims = [ FadeOut(self.brace), FadeOut(self.weights_words), ] elif i == 4: dots_copy = self.dots.copy() added_anims = [ dots_copy.move_to, self.get_grid_position(3, 0) ] self.first_column_dots = dots_copy else: added_anims = [] self.play( FadeOut(bubble), weight.restore, two.eyes.look_at_anim(weight.saved_state), change.restore, change.scale, self.change_scale_val, change.move_to, self.get_grid_position(i, 0), *added_anims ) self.two_changes.add(change) self.wait() def show_all_examples_requesting_changes(self): training_data, validation_data, test_data = load_data_wrapper() data = training_data[:self.n_examples-1] examples = VGroup(*[ self.get_example(t[0], j) for t, j in zip(data, it.count(1)) ]) h_dots = OldTex("\\dots") h_dots.next_to(examples, RIGHT, MED_LARGE_BUFF) more_h_dots = VGroup(*[ OldTex("\\dots").move_to( self.get_grid_position(i, self.n_examples) ) for i in range(5) ]) more_h_dots.shift(MED_LARGE_BUFF*RIGHT) more_h_dots[-2].rotate(-np.pi/4) more_v_dots = VGroup(*[ self.dots.copy().move_to( self.get_grid_position(3, j) ) for j in range(1, self.n_examples) ]) changes = VGroup(*[ self.get_random_decimal().move_to( self.get_grid_position(i, j) ) for i in list(range(3)) + [4] for j in range(1, self.n_examples) ]) for change in changes: change.scale(self.change_scale_val) self.play( LaggedStartMap(FadeIn, examples), LaggedStartMap(ShowCreation, self.h_lines), LaggedStartMap(ShowCreation, self.v_lines), Write( h_dots, run_time = 2, rate_func = squish_rate_func(smooth, 0.7, 1) ) ) self.play( Write(changes), Write(more_v_dots), Write(more_h_dots), *[ example.eyes.look_at_anim(random.choice(changes)) for example in examples ] ) for x in range(2): self.play(random.choice(examples).eyes.blink_anim()) k = self.n_examples - 1 self.change_rows = VGroup(*[ VGroup(two_change, *changes[k*i:k*(i+1)]) for i, two_change in enumerate(self.two_changes) ]) for i in list(range(3)) + [-1]: self.change_rows[i].add(more_h_dots[i]) self.all_eyes = VGroup(*[ m.eyes for m in [self.two] + list(examples) ]) self.set_variables_as_attrs( more_h_dots, more_v_dots, h_dots, changes, ) def average_together(self): rects = VGroup() arrows = VGroup() averages = VGroup() for row in self.change_rows: rect = SurroundingRectangle(row) arrow = Arrow(ORIGIN, RIGHT) arrow.next_to(rect, RIGHT) rect.arrow = arrow average = self.get_colored_decimal(3*np.mean([ m.number for m in row if isinstance(m, DecimalNumber) ])) average.scale(self.change_scale_val) average.next_to(arrow, RIGHT) row.target = VGroup(average) rects.add(rect) arrows.add(arrow) averages.add(average) words = OldTexText("Average over \\\\ all training data") words.scale(0.8) words.to_corner(UP+RIGHT) arrow_to_averages = Arrow( words.get_bottom(), averages.get_top(), color = WHITE ) dots = self.dots.copy() dots.move_to(VGroup(*averages[-2:])) look_at_anims = self.get_look_at_anims self.play(Write(words, run_time = 1), *look_at_anims(words)) self.play(ShowCreation(rects[0]), *look_at_anims(rects[0])) self.play( ReplacementTransform(rects[0].copy(), arrows[0]), rects[0].set_stroke, WHITE, 1, ReplacementTransform( self.change_rows[0].copy(), self.change_rows[0].target ), *look_at_anims(averages[0]) ) self.play(GrowArrow(arrow_to_averages)) self.play( LaggedStartMap(ShowCreation, VGroup(*rects[1:])), *look_at_anims(rects[1]) ) self.play( LaggedStartMap( ReplacementTransform, VGroup(*rects[1:]).copy(), lambda m : (m, m.arrow), lag_ratio = 0.7, ), VGroup(*rects[1:]).set_stroke, WHITE, 1, LaggedStartMap( ReplacementTransform, VGroup(*self.change_rows[1:]).copy(), lambda m : (m, m.target), lag_ratio = 0.7, ), Write(dots), *look_at_anims(averages[1]) ) self.blink(3) self.wait() averages.add(dots) self.set_variables_as_attrs( rects, arrows, averages, arrow_to_averages ) def collapse_into_gradient_vector(self): averages = self.averages lb, rb = brackets = OldTex("[]") brackets.scale(2) brackets.stretch_to_fit_height(1.2*averages.get_height()) lb.next_to(averages, LEFT, SMALL_BUFF) rb.next_to(averages, RIGHT, SMALL_BUFF) brackets.set_fill(opacity = 0) shift_vect = 2*LEFT lhs = OldTex( "-", "\\nabla", "C(", "w_1,", "w_2,", "\\dots", "w_{13{,}001}", ")", "=" ) lhs.next_to(lb, LEFT) lhs.shift(shift_vect) minus = lhs[0] w_terms = lhs.get_parts_by_tex("w_") dots_term = lhs.get_part_by_tex("dots") eta = OldTex("\\eta") eta.move_to(minus, RIGHT) eta.set_color(MAROON_B) to_fade = VGroup(*it.chain( self.h_lines, self.v_lines, self.more_h_dots, self.more_v_dots, self.change_rows, self.first_column_dots, self.rects, self.arrows, )) arrow = self.arrow_to_averages self.play(LaggedStartMap(FadeOut, to_fade)) self.play( brackets.shift, shift_vect, brackets.set_fill, WHITE, 1, averages.shift, shift_vect, Transform(arrow, Arrow( arrow.get_start(), arrow.get_end() + shift_vect, buff = 0, color = arrow.get_color(), )), FadeIn(VGroup(*lhs[:3])), FadeIn(VGroup(*lhs[-2:])), *self.get_look_at_anims(lhs) ) self.play( ReplacementTransform(self.weights, w_terms), ReplacementTransform(self.dots, dots_term), *self.get_look_at_anims(w_terms) ) self.blink(2) self.play( GrowFromCenter(eta), minus.shift, MED_SMALL_BUFF*LEFT ) self.wait() #### def get_example(self, in_vect, index): result = MNistMobject(in_vect) result.set_height(self.image_height) eyes = Eyes(result, height = self.eyes_height) result.eyes = eyes result.add(eyes) result.move_to(self.get_grid_position(0, index)) result.to_edge(UP, buff = LARGE_BUFF) return result def get_grid_position(self, i, j): x = VGroup(*self.v_lines[j:j+2]).get_center()[0] y = VGroup(*self.h_lines[i:i+2]).get_center()[1] return x*RIGHT + y*UP def get_requested_change_bubble(self, example_mob): change = self.get_random_decimal() words = OldTexText("Change by") change.next_to(words, RIGHT) change.save_state() content = VGroup(words, change) bubble = SpeechBubble(height = 1.5, width = 3) bubble.add_content(content) group = VGroup(bubble, content) group.shift( example_mob.get_right() + SMALL_BUFF*RIGHT \ -bubble.get_corner(DOWN+LEFT) ) return VGroup(bubble, words), change def get_random_decimal(self): return self.get_colored_decimal( 0.3*(random.random() - 0.5) ) def get_colored_decimal(self, number): result = DecimalNumber(number) if result.number > 0: plus = OldTex("+") plus.next_to(result, LEFT, SMALL_BUFF) result.add_to_back(plus) result.set_color(BLUE) else: result.set_color(RED) return result def get_look_at_anims(self, mob): return [eyes.look_at_anim(mob) for eyes in self.all_eyes] def blink(self, n): for x in range(n): self.play(random.choice(self.all_eyes).blink_anim()) class WatchPreviousScene(TeacherStudentsScene): def construct(self): screen = ScreenRectangle(height = 4.5) screen.to_corner(UP+LEFT) self.play( self.teacher.change, "raise_right_hand", screen, self.change_students( *["thinking"]*3, look_at = screen ), ShowCreation(screen) ) self.wait(10) class OpenCloseSGD(Scene): def construct(self): term = OldTex( "\\langle", "\\text{Stochastic gradient descent}", "\\rangle" ) alt_term0 = OldTex("\\langle /") alt_term0.move_to(term[0], RIGHT) term.save_state() center = term.get_center() term[0].move_to(center, RIGHT) term[2].move_to(center, LEFT) term[1].scale(0.0001).move_to(center) self.play(term.restore) self.wait(2) self.play(Transform(term[0], alt_term0)) self.wait(2) class OrganizeDataIntoMiniBatches(Scene): CONFIG = { "n_rows" : 5, "n_cols" : 12, "example_height" : 1, "random_seed" : 0, } def construct(self): self.seed_random_libraries() self.add_examples() self.shuffle_examples() self.divide_into_minibatches() self.one_step_per_batch() def seed_random_libraries(self): random.seed(self.random_seed) np.random.seed(self.random_seed) def add_examples(self): examples = self.get_examples() self.arrange_examples_in_grid(examples) for example in examples: example.save_state() alt_order_examples = VGroup(*examples) for mob in examples, alt_order_examples: random.shuffle(mob.submobjects) self.arrange_examples_in_grid(examples) self.play(LaggedStartMap( FadeIn, alt_order_examples, lag_ratio = 0.2, run_time = 4 )) self.wait() self.examples = examples def shuffle_examples(self): self.play(LaggedStartMap( ApplyMethod, self.examples, lambda m : (m.restore,), lag_ratio = 0.3, run_time = 3, path_arc = np.pi/3, )) self.wait() def divide_into_minibatches(self): examples = self.examples examples.sort(lambda p : -p[1]) rows = Group(*[ Group(*examples[i*self.n_cols:(i+1)*self.n_cols]) for i in range(self.n_rows) ]) mini_batches_words = OldTexText("``Mini-batches''") mini_batches_words.to_edge(UP) mini_batches_words.set_color(YELLOW) self.play( rows.space_out_submobjects, 1.5, rows.to_edge, UP, 1.5, Write(mini_batches_words, run_time = 1) ) rects = VGroup(*[ SurroundingRectangle( row, stroke_width = 0, fill_color = YELLOW, fill_opacity = 0.25, ) for row in rows ]) self.play(LaggedStartMap( FadeIn, rects, lag_ratio = 0.7, rate_func = there_and_back )) self.wait() self.set_variables_as_attrs(rows, rects, mini_batches_words) def one_step_per_batch(self): rows = self.rows brace = Brace(rows[0], UP, buff = SMALL_BUFF) text = brace.get_text( "Compute gradient descent step (using backprop)", buff = SMALL_BUFF ) def indicate_row(row): row.sort(lambda p : p[0]) return LaggedStartMap( ApplyFunction, row, lambda row : ( lambda m : m.scale(0.75).set_color(YELLOW), row ), rate_func = wiggle ) self.play( FadeOut(self.mini_batches_words), GrowFromCenter(brace), Write(text, run_time = 2), ) self.play(indicate_row(rows[0])) brace.add(text) for last_row, row in zip(rows, rows[1:-1]): self.play( last_row.shift, UP, brace.next_to, row, UP, SMALL_BUFF ) self.play(indicate_row(row)) self.wait() ### def get_examples(self): n_examples = self.n_rows*self.n_cols height = self.example_height training_data, validation_data, test_data = load_data_wrapper() return Group(*[ MNistMobject( t[0], rect_kwargs = {"stroke_width" : 2} ).set_height(height) for t in training_data[:n_examples] ]) # return Group(*[ # Square( # color = BLUE, # stroke_width = 2 # ).set_height(height) # for x in range(n_examples) # ]) def arrange_examples_in_grid(self, examples): examples.arrange_in_grid( n_rows = self.n_rows, buff = SMALL_BUFF ) class SGDSteps(ExternallyAnimatedScene): pass class GradientDescentSteps(ExternallyAnimatedScene): pass class SwimmingInTerms(TeacherStudentsScene): def construct(self): terms = VGroup( OldTexText("Cost surface"), OldTexText("Stochastic gradient descent"), OldTexText("Mini-batches"), OldTexText("Backpropagation"), ) terms.arrange(DOWN) terms.to_edge(UP) self.play( LaggedStartMap(FadeIn, terms), self.change_students(*["horrified"]*3) ) self.wait() self.play( terms[-1].next_to, self.teacher.get_corner(UP+LEFT), UP, FadeOut(VGroup(*terms[:-1])), self.teacher.change, "raise_right_hand", self.change_students(*["pondering"]*3) ) self.wait() class BackpropCode(ExternallyAnimatedScene): pass class BackpropCodeAddOn(PiCreatureScene): def construct(self): words = OldTexText( "The code you'd find \\\\ in Nielsen's book" ) words.to_corner(DOWN+LEFT) morty = self.pi_creature morty.next_to(words, UP) self.add(words) for mode in ["pondering", "thinking", "happy"]: self.play( morty.change, "pondering", morty.look, UP+LEFT ) self.play(morty.look, LEFT) self.wait(2) class CannotFollowCode(TeacherStudentsScene): def construct(self): self.student_says( "I...er...can't follow\\\\ that code at all.", target_mode = "confused", index = 1 ) self.play(self.students[1].change, "sad") self.play_student_changes( "angry", "sad", "angry", look_at = self.teacher.eyes ) self.play(self.teacher.change, "hesitant") self.wait(2) self.teacher_says( "Let's get to the \\\\ calculus then", target_mode = "hooray", added_anims = [self.change_students(*3*["plain"])], run_time = 1 ) self.wait(2) class EOCWrapper(Scene): def construct(self): title = OldTexText("Essence of calculus") title.to_edge(UP) screen = ScreenRectangle(height = 6) screen.next_to(title, DOWN) self.add(title) self.play(ShowCreation(screen)) self.wait() class SimplestNetworkExample(PreviewLearning): CONFIG = { "random_seed" : 6, "z_color" : GREEN, "cost_color" : RED, "desired_output_color" : YELLOW, "derivative_scale_val" : 0.85, } def construct(self): self.seed_random_libraries() self.collapse_ordinary_network() self.show_weights_and_biases() self.focus_just_on_last_two_layers() self.label_neurons() self.show_desired_output() self.show_cost() self.show_activation_formula() self.introduce_z() self.break_into_computational_graph() self.show_preceding_layer_in_computational_graph() self.show_number_lines() self.ask_about_w_sensitivity() self.show_derivative_wrt_w() self.show_chain_of_events() self.show_chain_rule() self.name_chain_rule() self.indicate_everything_on_screen() self.prepare_for_derivatives() self.compute_derivatives() self.get_lost_in_formulas() self.fire_together_wire_together() self.organize_chain_rule_rhs() self.show_average_derivative() self.show_gradient() self.transition_to_derivative_wrt_b() self.show_derivative_wrt_b() self.show_derivative_wrt_a() self.show_previous_weight_and_bias() self.animate_long_path() def seed_random_libraries(self): np.random.seed(self.random_seed) random.seed(self.random_seed) def collapse_ordinary_network(self): network_mob = self.network_mob config = dict(self.network_mob_config) config.pop("include_output_labels") config.update({ "edge_stroke_width" : 3, "edge_propogation_color" : YELLOW, "edge_propogation_time" : 1, "neuron_radius" : 0.3, }) simple_network = Network(sizes = [1, 1, 1, 1]) simple_network_mob = NetworkMobject(simple_network, **config) self.color_network_edges() s_edges = simple_network_mob.edge_groups for edge, weight_matrix in zip(s_edges, simple_network.weights): weight = weight_matrix[0][0] width = 2*abs(weight) color = BLUE if weight > 0 else RED edge.set_stroke(color, width) def edge_collapse_anims(edges, left_attachment_target): return [ ApplyMethod( e.put_start_and_end_on_with_projection, left_attachment_target.get_right(), e.get_end() ) for e in edges ] neuron = simple_network_mob.layers[0].neurons[0] self.play( ReplacementTransform(network_mob.layers[0], neuron), *edge_collapse_anims(network_mob.edge_groups[0], neuron) ) for i, layer in enumerate(network_mob.layers[1:]): neuron = simple_network_mob.layers[i+1].neurons[0] prev_edges = network_mob.edge_groups[i] prev_edge_target = simple_network_mob.edge_groups[i] if i+1 < len(network_mob.edge_groups): edges = network_mob.edge_groups[i+1] added_anims = edge_collapse_anims(edges, neuron) else: added_anims = [FadeOut(network_mob.output_labels)] self.play( ReplacementTransform(layer, neuron), ReplacementTransform(prev_edges, prev_edge_target), *added_anims ) self.remove(network_mob) self.add(simple_network_mob) self.network_mob = simple_network_mob self.network = self.network_mob.neural_network self.feed_forward(np.array([0.5])) self.wait() def show_weights_and_biases(self): network_mob = self.network_mob edges = VGroup(*[eg[0] for eg in network_mob.edge_groups]) neurons = VGroup(*[ layer.neurons[0] for layer in network_mob.layers[1:] ]) expression = OldTex( "C", "(", "w_1", ",", "b_1", ",", "w_2", ",", "b_2", ",", "w_3", ",", "b_3", ")" ) expression.shift(2*UP) expression.set_color_by_tex("C", RED) w_terms = expression.get_parts_by_tex("w_") for w, edge in zip(w_terms, edges): w.set_color(edge.get_color()) b_terms = expression.get_parts_by_tex("b_") variables = VGroup(*it.chain(w_terms, b_terms)) other_terms = VGroup(*[m for m in expression if m not in variables]) random.shuffle(variables.submobjects) self.play(ReplacementTransform(edges.copy(), w_terms)) self.wait() self.play(ReplacementTransform(neurons.copy(), b_terms)) self.wait() self.play(Write(other_terms)) for x in range(2): self.play(LaggedStartMap( Indicate, variables, rate_func = wiggle, run_time = 4, )) self.wait() self.play( FadeOut(other_terms), ReplacementTransform(w_terms, edges), ReplacementTransform(b_terms, neurons), ) self.remove(expression) def focus_just_on_last_two_layers(self): to_fade = VGroup(*it.chain(*list(zip( self.network_mob.layers[:2], self.network_mob.edge_groups[:2], )))) for mob in to_fade: mob.save_state() self.play(LaggedStartMap( ApplyMethod, to_fade, lambda m : (m.fade, 0.9) )) self.wait() self.prev_layers = to_fade def label_neurons(self): neurons = VGroup(*[ self.network_mob.layers[i].neurons[0] for i in (-1, -2) ]) decimals = VGroup() a_labels = VGroup() a_label_arrows = VGroup() superscripts = ["L", "L-1"] superscript_rects = VGroup() for neuron, superscript in zip(neurons, superscripts): decimal = self.get_neuron_activation_decimal(neuron) label = OldTex("a^{(%s)}"%superscript) label.next_to(neuron, DOWN, buff = LARGE_BUFF) superscript_rect = SurroundingRectangle(VGroup(*label[1:])) arrow = Arrow( label[0].get_top(), neuron.get_bottom(), buff = SMALL_BUFF, color = WHITE ) decimal.save_state() decimal.set_fill(opacity = 0) decimal.move_to(label) decimals.add(decimal) a_labels.add(label) a_label_arrows.add(arrow) superscript_rects.add(superscript_rect) self.play( Write(label, run_time = 1), GrowArrow(arrow), ) self.play(decimal.restore) opacity = neuron.get_fill_opacity() self.play( neuron.set_fill, None, 0, ChangingDecimal( decimal, lambda a : interpolate(opacity, 0.01, a) ), UpdateFromFunc( decimal, lambda d : d.set_fill(WHITE if d.number < 0.8 else BLACK) ), run_time = 2, rate_func = there_and_back, ) self.wait() not_exponents = OldTexText("Not exponents") not_exponents.next_to(superscript_rects, DOWN, MED_LARGE_BUFF) not_exponents.set_color(YELLOW) self.play( LaggedStartMap( ShowCreation, superscript_rects, lag_ratio = 0.8, run_time = 1.5 ), Write(not_exponents, run_time = 2) ) self.wait() self.play(*list(map(FadeOut, [not_exponents, superscript_rects]))) self.set_variables_as_attrs( a_labels, a_label_arrows, decimals, last_neurons = neurons ) def show_desired_output(self): neuron = self.network_mob.layers[-1].neurons[0].copy() neuron.shift(2*RIGHT) neuron.set_fill(opacity = 1) decimal = self.get_neuron_activation_decimal(neuron) rect = SurroundingRectangle(neuron) words = OldTexText("Desired \\\\ output") words.next_to(rect, UP) y_label = OldTex("y") y_label.next_to(neuron, DOWN, LARGE_BUFF) y_label.align_to(self.a_labels, DOWN) y_label_arrow = Arrow( y_label, neuron, color = WHITE, buff = SMALL_BUFF ) VGroup(words, rect, y_label).set_color(self.desired_output_color) self.play(*list(map(FadeIn, [neuron, decimal]))) self.play( ShowCreation(rect), Write(words, run_time = 1) ) self.wait() self.play( Write(y_label, run_time = 1), GrowArrow(y_label_arrow) ) self.wait() self.set_variables_as_attrs( y_label, y_label_arrow, desired_output_neuron = neuron, desired_output_decimal = decimal, desired_output_rect = rect, desired_output_words = words, ) def show_cost(self): pre_a = self.a_labels[0].copy() pre_y = self.y_label.copy() cost_equation = OldTex( "C_0", "(", "\\dots", ")", "=", "(", "a^{(L)}", "-", "y", ")", "^2" ) cost_equation.to_corner(UP+RIGHT) C0, a, y = [ cost_equation.get_part_by_tex(tex) for tex in ("C_0", "a^{(L)}", "y") ] y.set_color(YELLOW) cost_word = OldTexText("Cost") cost_word.next_to(C0[0], LEFT, LARGE_BUFF) cost_arrow = Arrow( cost_word, C0, buff = SMALL_BUFF ) VGroup(C0, cost_word, cost_arrow).set_color(self.cost_color) expression = OldTex( "\\text{For example: }" "(", "0.00", "-", "0.00", ")", "^2" ) numbers = expression.get_parts_by_tex("0.00") non_numbers = VGroup(*[m for m in expression if m not in numbers]) expression.next_to(cost_equation, DOWN, aligned_edge = RIGHT) decimals = VGroup( self.decimals[0], self.desired_output_decimal ).copy() decimals.generate_target() for d, n in zip(decimals.target, numbers): d.replace(n, dim_to_match = 1) d.set_color(n.get_color()) self.play( ReplacementTransform(pre_a, a), ReplacementTransform(pre_y, y), ) self.play(LaggedStartMap( FadeIn, VGroup(*[m for m in cost_equation if m not in [a, y]]) )) self.play( MoveToTarget(decimals), FadeIn(non_numbers) ) self.wait() self.play( Write(cost_word, run_time = 1), GrowArrow(cost_arrow) ) self.play(C0.shift, MED_SMALL_BUFF*UP, rate_func = wiggle) self.wait() self.play(*list(map(FadeOut, [decimals, non_numbers]))) self.set_variables_as_attrs( cost_equation, cost_word, cost_arrow ) def show_activation_formula(self): neuron = self.network_mob.layers[-1].neurons[0] edge = self.network_mob.edge_groups[-1][0] pre_aL, pre_aLm1 = self.a_labels.copy() formula = OldTex( "a^{(L)}", "=", "\\sigma", "(", "w^{(L)}", "a^{(L-1)}", "+", "b^{(L)}", ")" ) formula.next_to(neuron, UP, MED_LARGE_BUFF, RIGHT) aL, equals, sigma, lp, wL, aLm1, plus, bL, rp = formula wL.set_color(edge.get_color()) weight_label = wL.copy() bL.set_color(MAROON_B) bias_label = bL.copy() sigma_group = VGroup(sigma, lp, rp) sigma_group.save_state() sigma_group.set_fill(opacity = 0) sigma_group.shift(DOWN) self.play( ReplacementTransform(pre_aL, aL), Write(equals) ) self.play(ReplacementTransform( edge.copy(), wL )) self.wait() self.play(ReplacementTransform(pre_aLm1, aLm1)) self.wait() self.play(Write(VGroup(plus, bL), run_time = 1)) self.wait() self.play(sigma_group.restore) self.wait() weighted_sum_terms = VGroup(wL, aLm1, plus, bL) self.set_variables_as_attrs( formula, weighted_sum_terms ) def introduce_z(self): terms = self.weighted_sum_terms terms.generate_target() terms.target.next_to( self.formula, UP, buff = MED_LARGE_BUFF, aligned_edge = RIGHT ) terms.target.shift(MED_LARGE_BUFF*RIGHT) equals = OldTex("=") equals.next_to(terms.target[0][0], LEFT) z_label = OldTex("z^{(L)}") z_label.next_to(equals, LEFT) z_label.align_to(terms.target, DOWN) z_label.set_color(self.z_color) z_label2 = z_label.copy() aL_start = VGroup(*self.formula[:4]) aL_start.generate_target() aL_start.target.align_to(z_label, LEFT) z_label2.next_to(aL_start.target, RIGHT, SMALL_BUFF) z_label2.align_to(aL_start.target[0], DOWN) rp = self.formula[-1] rp.generate_target() rp.target.next_to(z_label2, RIGHT, SMALL_BUFF) rp.target.align_to(aL_start.target, DOWN) self.play(MoveToTarget(terms)) self.play(Write(z_label), Write(equals)) self.play( ReplacementTransform(z_label.copy(), z_label2), MoveToTarget(aL_start), MoveToTarget(rp), ) self.wait() zL_formula = VGroup(z_label, equals, *terms) aL_formula = VGroup(*list(aL_start) + [z_label2, rp]) self.set_variables_as_attrs(z_label, zL_formula, aL_formula) def break_into_computational_graph(self): network_early_layers = VGroup(*it.chain( self.network_mob.layers[:2], self.network_mob.edge_groups[:2] )) wL, aL, plus, bL = self.weighted_sum_terms top_terms = VGroup(wL, aL, bL).copy() zL = self.z_label.copy() aL = self.formula[0].copy() y = self.y_label.copy() C0 = self.cost_equation[0].copy() targets = VGroup() for mob in top_terms, zL, aL, C0: mob.generate_target() targets.add(mob.target) y.generate_target() top_terms.target.arrange(RIGHT, buff = MED_LARGE_BUFF) targets.arrange(DOWN, buff = LARGE_BUFF) targets.center().to_corner(DOWN+LEFT) y.target.next_to(aL.target, LEFT, LARGE_BUFF, DOWN) top_lines = VGroup(*[ Line( term.get_bottom(), zL.target.get_top(), buff = SMALL_BUFF ) for term in top_terms.target ]) z_to_a_line, a_to_c_line, y_to_c_line = all_lines = [ Line( m1.target.get_bottom(), m2.target.get_top(), buff = SMALL_BUFF ) for m1, m2 in [ (zL, aL), (aL, C0), (y, C0) ] ] for mob in [top_lines] + all_lines: yellow_copy = mob.copy().set_color(YELLOW) mob.flash = ShowCreationThenDestruction(yellow_copy) self.play(MoveToTarget(top_terms)) self.wait() self.play(MoveToTarget(zL)) self.play( ShowCreation(top_lines, lag_ratio = 0), top_lines.flash ) self.wait() self.play(MoveToTarget(aL)) self.play( network_early_layers.fade, 1, ShowCreation(z_to_a_line), z_to_a_line.flash ) self.wait() self.play(MoveToTarget(y)) self.play(MoveToTarget(C0)) self.play(*it.chain(*[ [ShowCreation(line), line.flash] for line in (a_to_c_line, y_to_c_line) ])) self.wait(2) comp_graph = VGroup() comp_graph.wL, comp_graph.aLm1, comp_graph.bL = top_terms comp_graph.top_lines = top_lines comp_graph.zL = zL comp_graph.z_to_a_line = z_to_a_line comp_graph.aL = aL comp_graph.y = y comp_graph.a_to_c_line = a_to_c_line comp_graph.y_to_c_line = y_to_c_line comp_graph.C0 = C0 comp_graph.digest_mobject_attrs() self.comp_graph = comp_graph def show_preceding_layer_in_computational_graph(self): shift_vect = DOWN comp_graph = self.comp_graph comp_graph.save_state() comp_graph.generate_target() comp_graph.target.shift(shift_vect) rect = SurroundingRectangle(comp_graph.aLm1) attrs = ["wL", "aLm1", "bL", "zL"] new_terms = VGroup() for attr in attrs: term = getattr(comp_graph, attr) tex = term.get_tex() if "L-1" in tex: tex = tex.replace("L-1", "L-2") else: tex = tex.replace("L", "L-1") new_term = OldTex(tex) new_term.set_color(term.get_color()) new_term.move_to(term) new_terms.add(new_term) new_edges = VGroup( comp_graph.top_lines.copy(), comp_graph.z_to_a_line.copy(), ) new_subgraph = VGroup(new_terms, new_edges) new_subgraph.next_to(comp_graph.target, UP, SMALL_BUFF) self.wLm1 = new_terms[0] self.zLm1 = new_terms[-1] prev_neuron = self.network_mob.layers[1] prev_neuron.restore() prev_edge = self.network_mob.edge_groups[1] prev_edge.restore() self.play( ShowCreation(rect), FadeIn(prev_neuron), ShowCreation(prev_edge) ) self.play( ReplacementTransform( VGroup(prev_neuron, prev_edge).copy(), new_subgraph ), UpdateFromAlphaFunc( new_terms, lambda m, a : m.set_fill(opacity = a) ), MoveToTarget(comp_graph), rect.shift, shift_vect ) self.wait(2) self.play( FadeOut(new_subgraph), FadeOut(prev_neuron), FadeOut(prev_edge), comp_graph.restore, rect.shift, -shift_vect, rect.set_stroke, BLACK, 0 ) VGroup(prev_neuron, prev_edge).fade(1) self.remove(rect) self.wait() self.prev_comp_subgraph = new_subgraph def show_number_lines(self): comp_graph = self.comp_graph wL, aLm1, bL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "aLm1", "bL", "zL", "aL", "C0"] ] wL.val = self.network.weights[-1][0][0] aL.val = self.decimals[0].number zL.val = sigmoid_inverse(aL.val) C0.val = (aL.val - 1)**2 number_line = UnitInterval( unit_size = 2, stroke_width = 2, tick_size = 0.075, color = GREY_B, ) for mob in wL, zL, aL, C0: mob.number_line = number_line.deepcopy() if mob is wL: mob.number_line.next_to(mob, UP, MED_LARGE_BUFF, LEFT) else: mob.number_line.next_to(mob, RIGHT) if mob is C0: mob.number_line.x_max = 0.5 for tick_mark in mob.number_line.tick_marks[1::2]: mob.number_line.tick_marks.remove(tick_mark) mob.dot = Dot(color = mob.get_color()) mob.dot.move_to( mob.number_line.number_to_point(mob.val) ) if mob is wL: path_arc = 0 dot_spot = mob.dot.get_bottom() else: path_arc = -0.7*np.pi dot_spot = mob.dot.get_top() if mob is C0: mob_spot = mob[0].get_corner(UP+RIGHT) tip_length = 0.15 else: mob_spot = mob.get_corner(UP+RIGHT) tip_length = 0.2 mob.arrow = Arrow( mob_spot, dot_spot, path_arc = path_arc, tip_length = tip_length, buff = SMALL_BUFF, ) mob.arrow.set_color(mob.get_color()) mob.arrow.set_stroke(width = 5) self.play(ShowCreation( mob.number_line, lag_ratio = 0.5 )) self.play( ShowCreation(mob.arrow), ReplacementTransform( mob.copy(), mob.dot, path_arc = path_arc ) ) self.wait() def ask_about_w_sensitivity(self): wL, aLm1, bL, zL, aL, C0 = [ getattr(self.comp_graph, attr) for attr in ["wL", "aLm1", "bL", "zL", "aL", "C0"] ] aLm1_val = self.last_neurons[1].get_fill_opacity() bL_val = self.network.biases[-1][0] get_wL_val = lambda : wL.number_line.point_to_number( wL.dot.get_center() ) get_zL_val = lambda : get_wL_val()*aLm1_val+bL_val get_aL_val = lambda : sigmoid(get_zL_val()) get_C0_val = lambda : (get_aL_val() - 1)**2 def generate_dot_update(term, val_func): def update_dot(dot): dot.move_to(term.number_line.number_to_point(val_func())) return dot return update_dot dot_update_anims = [ UpdateFromFunc(term.dot, generate_dot_update(term, val_func)) for term, val_func in [ (zL, get_zL_val), (aL, get_aL_val), (C0, get_C0_val), ] ] def shake_dot(run_time = 2, rate_func = there_and_back): self.play( ApplyMethod( wL.dot.shift, LEFT, rate_func = rate_func, run_time = run_time ), *dot_update_anims ) wL_line = Line(wL.dot.get_center(), wL.dot.get_center()+LEFT) del_wL = OldTex("\\partial w^{(L)}") del_wL.scale(self.derivative_scale_val) del_wL.brace = Brace(wL_line, UP, buff = SMALL_BUFF) del_wL.set_color(wL.get_color()) del_wL.next_to(del_wL.brace, UP, SMALL_BUFF) C0_line = Line(C0.dot.get_center(), C0.dot.get_center()+MED_SMALL_BUFF*RIGHT) del_C0 = OldTex("\\partial C_0") del_C0.scale(self.derivative_scale_val) del_C0.brace = Brace(C0_line, UP, buff = SMALL_BUFF) del_C0.set_color(C0.get_color()) del_C0.next_to(del_C0.brace, UP, SMALL_BUFF) for sym in del_wL, del_C0: self.play( GrowFromCenter(sym.brace), Write(sym, run_time = 1) ) shake_dot() self.wait() self.set_variables_as_attrs( shake_dot, del_wL, del_C0, ) def show_derivative_wrt_w(self): del_wL = self.del_wL del_C0 = self.del_C0 cost_word = self.cost_word cost_arrow = self.cost_arrow shake_dot = self.shake_dot wL = self.comp_graph.wL dC_dw = OldTex( "{\\partial C_0", "\\over", "\\partial w^{(L)} }" ) dC_dw[0].set_color(del_C0.get_color()) dC_dw[2].set_color(del_wL.get_color()) dC_dw.scale(self.derivative_scale_val) dC_dw.to_edge(UP, buff = MED_SMALL_BUFF) dC_dw.shift(3.5*LEFT) full_rect = SurroundingRectangle(dC_dw) full_rect_copy = full_rect.copy() words = OldTexText("What we want") words.next_to(full_rect, RIGHT) words.set_color(YELLOW) denom_rect = SurroundingRectangle(dC_dw[2]) numer_rect = SurroundingRectangle(dC_dw[0]) self.play( ReplacementTransform(del_C0.copy(), dC_dw[0]), ReplacementTransform(del_wL.copy(), dC_dw[2]), Write(dC_dw[1], run_time = 1) ) self.play( FadeOut(cost_word), FadeOut(cost_arrow), ShowCreation(full_rect), Write(words, run_time = 1), ) self.wait(2) self.play( FadeOut(words), ReplacementTransform(full_rect, denom_rect) ) self.play(Transform(dC_dw[2].copy(), del_wL, remover = True)) shake_dot() self.play(ReplacementTransform(denom_rect, numer_rect)) self.play(Transform(dC_dw[0].copy(), del_C0, remover = True)) shake_dot() self.wait() self.play(ReplacementTransform(numer_rect, full_rect_copy)) self.play(FadeOut(full_rect_copy)) self.wait() self.dC_dw = dC_dw def show_chain_of_events(self): comp_graph = self.comp_graph wL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "zL", "aL", "C0"] ] del_wL = self.del_wL del_C0 = self.del_C0 zL_line = Line(ORIGIN, MED_LARGE_BUFF*LEFT) zL_line.shift(zL.dot.get_center()) del_zL = OldTex("\\partial z^{(L)}") del_zL.set_color(zL.get_color()) del_zL.brace = Brace(zL_line, DOWN, buff = SMALL_BUFF) aL_line = Line(ORIGIN, MED_SMALL_BUFF*LEFT) aL_line.shift(aL.dot.get_center()) del_aL = OldTex("\\partial a^{(L)}") del_aL.set_color(aL.get_color()) del_aL.brace = Brace(aL_line, DOWN, buff = SMALL_BUFF) for sym in del_zL, del_aL: sym.scale(self.derivative_scale_val) sym.brace.stretch_about_point( 0.5, 1, sym.brace.get_top(), ) sym.shift( sym.brace.get_bottom()+SMALL_BUFF*DOWN \ -sym[0].get_corner(UP+RIGHT) ) syms = [del_wL, del_zL, del_aL, del_C0] for s1, s2 in zip(syms, syms[1:]): self.play( ReplacementTransform(s1.copy(), s2), ReplacementTransform(s1.brace.copy(), s2.brace), ) self.shake_dot(run_time = 1.5) self.wait(0.5) self.wait() self.set_variables_as_attrs(del_zL, del_aL) def show_chain_rule(self): dC_dw = self.dC_dw del_syms = [ getattr(self, attr) for attr in ("del_wL", "del_zL", "del_aL", "del_C0") ] dz_dw = OldTex( "{\\partial z^{(L)}", "\\over", "\\partial w^{(L)}}" ) da_dz = OldTex( "{\\partial a^{(L)}", "\\over", "\\partial z^{(L)}}" ) dC_da = OldTex( "{\\partial C0}", "\\over", "\\partial a^{(L)}}" ) dz_dw[2].set_color(self.del_wL.get_color()) VGroup(dz_dw[0], da_dz[2]).set_color(self.z_color) dC_da[0].set_color(self.cost_color) equals = OldTex("=") group = VGroup(equals, dz_dw, da_dz, dC_da) group.arrange(RIGHT, SMALL_BUFF) group.scale(self.derivative_scale_val) group.next_to(dC_dw, RIGHT) for mob in group[1:]: target_y = equals.get_center()[1] y = mob[1].get_center()[1] mob.shift((target_y - y)*UP) self.play(Write(equals, run_time = 1)) for frac, top_sym, bot_sym in zip(group[1:], del_syms[1:], del_syms): self.play(Indicate(top_sym, rate_func = wiggle)) self.play( ReplacementTransform(top_sym.copy(), frac[0]), FadeIn(frac[1]), ) self.play(Indicate(bot_sym, rate_func = wiggle)) self.play(ReplacementTransform( bot_sym.copy(), frac[2] )) self.wait() self.shake_dot() self.wait() self.chain_rule_equation = VGroup(dC_dw, *group) def name_chain_rule(self): graph_parts = self.get_all_comp_graph_parts() equation = self.chain_rule_equation rect = SurroundingRectangle(equation) group = VGroup(equation, rect) group.generate_target() group.target.to_corner(UP+LEFT) words = OldTexText("Chain rule") words.set_color(YELLOW) words.next_to(group.target, DOWN) self.play(ShowCreation(rect)) self.play( MoveToTarget(group), Write(words, run_time = 1), graph_parts.scale, 0.7, graph_parts.get_bottom() ) self.wait(2) self.play(*list(map(FadeOut, [rect, words]))) def indicate_everything_on_screen(self): everything = VGroup(*self.get_top_level_mobjects()) everything = VGroup(*[m for m in everything.family_members_with_points() if not m.is_subpath]) self.play(LaggedStartMap( Indicate, everything, rate_func = wiggle, lag_ratio = 0.2, run_time = 5 )) self.wait() def prepare_for_derivatives(self): zL_formula = self.zL_formula aL_formula = self.aL_formula az_formulas = VGroup(zL_formula, aL_formula) cost_equation = self.cost_equation desired_output_words = self.desired_output_words az_formulas.generate_target() az_formulas.target.to_edge(RIGHT) index = 4 cost_eq = cost_equation[index] z_eq = az_formulas.target[0][1] x_shift = (z_eq.get_center() - cost_eq.get_center())[0]*RIGHT cost_equation.generate_target() Transform( VGroup(*cost_equation.target[1:index]), VectorizedPoint(cost_eq.get_left()) ).update(1) cost_equation.target[0].next_to(cost_eq, LEFT, SMALL_BUFF) cost_equation.target.shift(x_shift) self.play( FadeOut(self.all_comp_graph_parts), FadeOut(self.desired_output_words), MoveToTarget(az_formulas), MoveToTarget(cost_equation) ) def compute_derivatives(self): cost_equation = self.cost_equation zL_formula = self.zL_formula aL_formula = self.aL_formula chain_rule_equation = self.chain_rule_equation.copy() dC_dw, equals, dz_dw, da_dz, dC_da = chain_rule_equation derivs = VGroup(dC_da, da_dz, dz_dw) deriv_targets = VGroup() for deriv in derivs: deriv.generate_target() deriv_targets.add(deriv.target) deriv_targets.arrange(DOWN, buff = MED_LARGE_BUFF) deriv_targets.next_to(dC_dw, DOWN, LARGE_BUFF) for deriv in derivs: deriv.equals = OldTex("=") deriv.equals.next_to(deriv.target, RIGHT) #dC_da self.play( MoveToTarget(dC_da), Write(dC_da.equals) ) index = 4 cost_rhs = VGroup(*cost_equation[index+1:]) dC_da.rhs = cost_rhs.copy() two = dC_da.rhs[-1] two.scale(1.5) two.next_to(dC_da.rhs[0], LEFT, SMALL_BUFF) dC_da.rhs.next_to(dC_da.equals, RIGHT) dC_da.rhs.shift(0.7*SMALL_BUFF*UP) cost_equation.save_state() self.play( cost_equation.next_to, dC_da.rhs, DOWN, MED_LARGE_BUFF, LEFT ) self.wait() self.play(ReplacementTransform( cost_rhs.copy(), dC_da.rhs, path_arc = np.pi/2, )) self.wait() self.play(cost_equation.restore) self.wait() #show_difference neuron = self.last_neurons[0] decimal = self.decimals[0] double_arrow = DoubleArrow( neuron.get_right(), self.desired_output_neuron.get_left(), buff = SMALL_BUFF, color = RED ) moving_decimals = VGroup( self.decimals[0].copy(), self.desired_output_decimal.copy() ) minus = OldTex("-") minus.move_to(moving_decimals) minus.scale(0.7) minus.set_fill(opacity = 0) moving_decimals.submobjects.insert(1, minus) moving_decimals.generate_target(use_deepcopy = True) moving_decimals.target.arrange(RIGHT, buff = SMALL_BUFF) moving_decimals.target.scale(1.5) moving_decimals.target.next_to( dC_da.rhs, DOWN, buff = MED_LARGE_BUFF, aligned_edge = RIGHT, ) moving_decimals.target.set_fill(WHITE, 1) self.play(ReplacementTransform( dC_da.rhs.copy(), double_arrow )) self.wait() self.play(MoveToTarget(moving_decimals)) opacity = neuron.get_fill_opacity() for target_o in 0, opacity: self.wait(2) self.play( neuron.set_fill, None, target_o, *[ ChangingDecimal(d, lambda a : neuron.get_fill_opacity()) for d in (decimal, moving_decimals[0]) ] ) self.play(*list(map(FadeOut, [double_arrow, moving_decimals]))) #da_dz self.play( MoveToTarget(da_dz), Write(da_dz.equals) ) a_rhs = VGroup(*aL_formula[2:]) da_dz.rhs = a_rhs.copy() prime = OldTex("'") prime.move_to(da_dz.rhs[0].get_corner(UP+RIGHT)) da_dz.rhs[0].shift(0.5*SMALL_BUFF*LEFT) da_dz.rhs.add_to_back(prime) da_dz.rhs.next_to(da_dz.equals, RIGHT) da_dz.rhs.shift(0.5*SMALL_BUFF*UP) aL_formula.save_state() self.play( aL_formula.next_to, da_dz.rhs, DOWN, MED_LARGE_BUFF, LEFT ) self.wait() self.play(ReplacementTransform( a_rhs.copy(), da_dz.rhs, )) self.wait() self.play(aL_formula.restore) self.wait() #dz_dw self.play( MoveToTarget(dz_dw), Write(dz_dw.equals) ) z_rhs = VGroup(*zL_formula[2:]) dz_dw.rhs = z_rhs[1].copy() dz_dw.rhs.next_to(dz_dw.equals, RIGHT) dz_dw.rhs.shift(SMALL_BUFF*UP) zL_formula.save_state() self.play( zL_formula.next_to, dz_dw.rhs, DOWN, MED_LARGE_BUFF, LEFT, ) self.wait() rect = SurroundingRectangle(VGroup(*zL_formula[2:4])) self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play(ReplacementTransform( z_rhs[1].copy(), dz_dw.rhs, )) self.wait() self.play(zL_formula.restore) self.wait() self.derivative_equations = VGroup(dC_da, da_dz, dz_dw) def get_lost_in_formulas(self): randy = Randolph() randy.flip() randy.scale(0.7) randy.to_edge(DOWN) randy.shift(LEFT) self.play(FadeIn(randy)) self.play(randy.change, "pleading", self.chain_rule_equation) self.play(Blink(randy)) self.play(randy.change, "maybe") self.play(Blink(randy)) self.play(FadeOut(randy)) def fire_together_wire_together(self): dz_dw = self.derivative_equations[2] rhs = dz_dw.rhs rhs_copy = rhs.copy() del_wL = dz_dw[2].copy() rect = SurroundingRectangle(VGroup(dz_dw, dz_dw.rhs)) edge = self.network_mob.edge_groups[-1][0] edge.save_state() neuron = self.last_neurons[1] decimal = self.decimals[1] def get_decimal_anims(): return [ ChangingDecimal(decimal, lambda a : neuron.get_fill_opacity()), UpdateFromFunc( decimal, lambda m : m.set_color( WHITE if neuron.get_fill_opacity() < 0.8 \ else BLACK ) ) ] self.play(ShowCreation(rect)) self.play(FadeOut(rect)) self.play( del_wL.next_to, edge, UP, SMALL_BUFF ) self.play( edge.set_stroke, None, 10, rate_func = wiggle, run_time = 3, ) self.wait() self.play(rhs.shift, MED_LARGE_BUFF*UP, rate_func = wiggle) self.play( rhs_copy.move_to, neuron, rhs_copy.set_fill, None, 0 ) self.remove(rhs_copy) self.play( neuron.set_fill, None, 0, *get_decimal_anims(), run_time = 3, rate_func = there_and_back ) self.wait() #Fire together wire together opacity = neuron.get_fill_opacity() self.play( neuron.set_fill, None, 0.99, *get_decimal_anims() ) self.play(edge.set_stroke, None, 8) self.play( neuron.set_fill, None, opacity, *get_decimal_anims() ) self.play(edge.restore, FadeOut(del_wL)) self.wait(3) def organize_chain_rule_rhs(self): fracs = self.derivative_equations equals_group = VGroup(*[frac.equals for frac in fracs]) rhs_group = VGroup(*[frac.rhs for frac in reversed(fracs)]) chain_rule_equation = self.chain_rule_equation equals = OldTex("=") equals.next_to(chain_rule_equation, RIGHT) rhs_group.generate_target() rhs_group.target.arrange(RIGHT, buff = SMALL_BUFF) rhs_group.target.next_to(equals, RIGHT) rhs_group.target.shift(SMALL_BUFF*UP) right_group = VGroup( self.cost_equation, self.zL_formula, self.aL_formula, self.network_mob, self.decimals, self.a_labels, self.a_label_arrows, self.y_label, self.y_label_arrow, self.desired_output_neuron, self.desired_output_rect, self.desired_output_decimal, ) self.play( MoveToTarget(rhs_group, path_arc = np.pi/2), Write(equals), FadeOut(fracs), FadeOut(equals_group), right_group.to_corner, DOWN+RIGHT ) self.wait() rhs_group.add(equals) self.chain_rule_rhs = rhs_group def show_average_derivative(self): dC0_dw = self.chain_rule_equation[0] full_derivative = OldTex( "{\\partial C", "\\over", "\\partial w^{(L)}}", "=", "\\frac{1}{n}", "\\sum_{k=0}^{n-1}", "{\\partial C_k", "\\over", "\\partial w^{(L)}}" ) full_derivative.set_color_by_tex_to_color_map({ "partial C" : self.cost_color, "partial w" : self.del_wL.get_color() }) full_derivative.to_edge(LEFT) dCk_dw = VGroup(*full_derivative[-3:]) lhs = VGroup(*full_derivative[:3]) rhs = VGroup(*full_derivative[4:]) lhs_brace = Brace(lhs, DOWN) lhs_text = lhs_brace.get_text("Derivative of \\\\ full cost function") rhs_brace = Brace(rhs, UP) rhs_text = rhs_brace.get_text("Average of all \\\\ training examples") VGroup( full_derivative, lhs_brace, lhs_text, rhs_brace, rhs_text ).to_corner(DOWN+LEFT) mover = dC0_dw.copy() self.play(Transform(mover, dCk_dw)) self.play(Write(full_derivative, run_time = 2)) self.remove(mover) for brace, text in (rhs_brace, rhs_text), (lhs_brace, lhs_text): self.play( GrowFromCenter(brace), Write(text, run_time = 2), ) self.wait(2) self.cycle_through_altnernate_training_examples() self.play(*list(map(FadeOut, [ VGroup(*full_derivative[3:]), lhs_brace, lhs_text, rhs_brace, rhs_text, ]))) self.dC_dw = lhs def cycle_through_altnernate_training_examples(self): neurons = VGroup( self.desired_output_neuron, *self.last_neurons ) decimals = VGroup( self.desired_output_decimal, *self.decimals ) group = VGroup(neurons, decimals) group.save_state() for x in range(20): for n, d in zip(neurons, decimals): o = np.random.random() if n is self.desired_output_neuron: o = np.round(o) n.set_fill(opacity = o) Transform( d, self.get_neuron_activation_decimal(n) ).update(1) self.wait(0.2) self.play(group.restore, run_time = 0.2) def show_gradient(self): dC_dw = self.dC_dw dC_dw.generate_target() terms = VGroup( OldTex("{\\partial C", "\\over", "\\partial w^{(1)}"), OldTex("{\\partial C", "\\over", "\\partial b^{(1)}"), OldTex("\\vdots"), dC_dw.target, OldTex("{\\partial C", "\\over", "\\partial b^{(L)}"), ) for term in terms: if isinstance(term, Tex): term.set_color_by_tex_to_color_map({ "partial C" : RED, "partial w" : BLUE, "partial b" : MAROON_B, }) terms.arrange(DOWN, buff = MED_LARGE_BUFF) lb, rb = brackets = OldTex("[]") brackets.scale(3) brackets.stretch_to_fit_height(1.1*terms.get_height()) lb.next_to(terms, LEFT, buff = SMALL_BUFF) rb.next_to(terms, RIGHT, buff = SMALL_BUFF) vect = VGroup(lb, terms, rb) vect.set_height(5) lhs = OldTex("\\nabla C", "=") lhs[0].set_color(RED) lhs.next_to(vect, LEFT) VGroup(lhs, vect).to_corner(DOWN+LEFT, buff = LARGE_BUFF) terms.remove(dC_dw.target) self.play( MoveToTarget(dC_dw), Write(vect, run_time = 1) ) terms.add(dC_dw) self.play(Write(lhs)) self.wait(2) self.play(FadeOut(VGroup(lhs, vect))) def transition_to_derivative_wrt_b(self): all_comp_graph_parts = self.all_comp_graph_parts all_comp_graph_parts.scale( 1.3, about_point = all_comp_graph_parts.get_bottom() ) comp_graph = self.comp_graph wL, bL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "bL", "zL", "aL", "C0"] ] path_to_C = VGroup(wL, zL, aL, C0) top_expression = VGroup( self.chain_rule_equation, self.chain_rule_rhs ) rect = SurroundingRectangle(top_expression) self.play(ShowCreation(rect)) self.play(FadeIn(comp_graph), FadeOut(rect)) for x in range(2): self.play(LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.7, )) self.wait() def show_derivative_wrt_b(self): comp_graph = self.comp_graph dC0_dw = self.chain_rule_equation[0] dz_dw = self.chain_rule_equation[2] aLm1 = self.chain_rule_rhs[0] left_term_group = VGroup(dz_dw, aLm1) dz_dw_rect = SurroundingRectangle(dz_dw) del_w = dC0_dw[2] del_b = OldTex("\\partial b^{(L)}") del_b.set_color(MAROON_B) del_b.replace(del_w) dz_db = OldTex( "{\\partial z^{(L)}", "\\over", "\\partial b^{(L)}}" ) dz_db.set_color_by_tex_to_color_map({ "partial z" : self.z_color, "partial b" : MAROON_B }) dz_db.replace(dz_dw) one = OldTex("1") one.move_to(aLm1, RIGHT) arrow = Arrow( dz_db.get_bottom(), one.get_bottom(), path_arc = np.pi/2, color = WHITE, ) arrow.set_stroke(width = 2) wL, bL, zL, aL, C0 = [ getattr(comp_graph, attr) for attr in ["wL", "bL", "zL", "aL", "C0"] ] path_to_C = VGroup(bL, zL, aL, C0) def get_path_animation(): return LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.7, ) zL_formula = self.zL_formula b_in_z_formula = zL_formula[-1] z_formula_rect = SurroundingRectangle(zL_formula) b_in_z_rect = SurroundingRectangle(b_in_z_formula) self.play(get_path_animation()) self.play(ShowCreation(dz_dw_rect)) self.play(FadeOut(dz_dw_rect)) self.play( left_term_group.shift, DOWN, left_term_group.fade, 1, ) self.remove(left_term_group) self.chain_rule_equation.remove(dz_dw) self.chain_rule_rhs.remove(aLm1) self.play(Transform(del_w, del_b)) self.play(FadeIn(dz_db)) self.play(get_path_animation()) self.wait() self.play(ShowCreation(z_formula_rect)) self.wait() self.play(ReplacementTransform(z_formula_rect, b_in_z_rect)) self.wait() self.play( ReplacementTransform(b_in_z_formula.copy(), one), FadeOut(b_in_z_rect) ) self.play( ShowCreation(arrow), ReplacementTransform( dz_db.copy(), one, path_arc = arrow.path_arc ) ) self.wait(2) self.play(*list(map(FadeOut, [dz_db, arrow, one]))) self.dz_db = dz_db def show_derivative_wrt_a(self): denom = self.chain_rule_equation[0][2] numer = VGroup(*self.chain_rule_equation[0][:2]) del_aLm1 = OldTex("\\partial a^{(L-1)}") del_aLm1.scale(0.8) del_aLm1.move_to(denom) dz_daLm1 = OldTex( "{\\partial z^{(L)}", "\\over", "\\partial a^{(L-1)}}" ) dz_daLm1.scale(0.8) dz_daLm1.next_to(self.chain_rule_equation[1], RIGHT, SMALL_BUFF) dz_daLm1.shift(0.7*SMALL_BUFF*UP) dz_daLm1[0].set_color(self.z_color) dz_daLm1_rect = SurroundingRectangle(dz_daLm1) wL = self.zL_formula[2].copy() wL.next_to(self.chain_rule_rhs[0], LEFT, SMALL_BUFF) arrow = Arrow( dz_daLm1.get_bottom(), wL.get_bottom(), path_arc = np.pi/2, color = WHITE, ) comp_graph = self.comp_graph path_to_C = VGroup(*[ getattr(comp_graph, attr) for attr in ["aLm1", "zL", "aL", "C0"] ]) def get_path_animation(): return LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.7, ) zL_formula = self.zL_formula z_formula_rect = SurroundingRectangle(zL_formula) a_in_z_rect = SurroundingRectangle(VGroup(*zL_formula[2:4])) wL_in_z = zL_formula[2] for x in range(3): self.play(get_path_animation()) self.play( numer.shift, SMALL_BUFF*UP, Transform(denom, del_aLm1) ) self.play( FadeIn(dz_daLm1), VGroup(*self.chain_rule_equation[-2:]).shift, SMALL_BUFF*RIGHT, ) self.wait() self.play(ShowCreation(dz_daLm1_rect)) self.wait() self.play(ReplacementTransform( dz_daLm1_rect, z_formula_rect )) self.wait() self.play(ReplacementTransform(z_formula_rect, a_in_z_rect)) self.play( ReplacementTransform(wL_in_z.copy(), wL), FadeOut(a_in_z_rect) ) self.play( ShowCreation(arrow), ReplacementTransform( dz_daLm1.copy(), wL, path_arc = arrow.path_arc ) ) self.wait(2) self.chain_rule_rhs.add(wL, arrow) self.chain_rule_equation.add(dz_daLm1) def show_previous_weight_and_bias(self): to_fade = self.chain_rule_rhs comp_graph = self.comp_graph prev_comp_subgraph = self.prev_comp_subgraph prev_comp_subgraph.scale(0.8) prev_comp_subgraph.next_to(comp_graph, UP, SMALL_BUFF) prev_layer = VGroup( self.network_mob.layers[1], self.network_mob.edge_groups[1], ) for mob in prev_layer: mob.restore() prev_layer.next_to(self.last_neurons, LEFT, buff = 0) self.remove(prev_layer) self.play(LaggedStartMap(FadeOut, to_fade, run_time = 1)) self.play( ShowCreation(prev_comp_subgraph, run_time = 1), self.chain_rule_equation.to_edge, RIGHT ) self.play(FadeIn(prev_layer)) ### neuron = self.network_mob.layers[1].neurons[0] decimal = self.get_neuron_activation_decimal(neuron) a_label = OldTex("a^{(L-2)}") a_label.replace(self.a_labels[1]) arrow = self.a_label_arrows[1].copy() VGroup(a_label, arrow).shift( neuron.get_center() - self.last_neurons[1].get_center() ) self.play( Write(a_label, run_time = 1), Write(decimal, run_time = 1), GrowArrow(arrow), ) def animate_long_path(self): comp_graph = self.comp_graph path_to_C = VGroup( self.wLm1, self.zLm1, *[ getattr(comp_graph, attr) for attr in ["aLm1", "zL", "aL", "C0"] ] ) for x in range(2): self.play(LaggedStartMap( Indicate, path_to_C, rate_func = there_and_back, run_time = 1.5, lag_ratio = 0.4, )) self.wait(2) ### def get_neuron_activation_decimal(self, neuron): opacity = neuron.get_fill_opacity() decimal = DecimalNumber(opacity, num_decimal_places = 2) decimal.set_width(0.85*neuron.get_width()) if decimal.number > 0.8: decimal.set_fill(BLACK) decimal.move_to(neuron) return decimal def get_all_comp_graph_parts(self): comp_graph = self.comp_graph result = VGroup(comp_graph) for attr in "wL", "zL", "aL", "C0": sym = getattr(comp_graph, attr) result.add( sym.arrow, sym.number_line, sym.dot ) del_sym = getattr(self, "del_" + attr) result.add(del_sym, del_sym.brace) self.all_comp_graph_parts = result return result class IsntThatOverSimplified(TeacherStudentsScene): def construct(self): self.student_says( "Isn't that over-simplified?", target_mode = "raise_right_hand", run_time = 1 ) self.play_student_changes( "pondering", "raise_right_hand", "pondering" ) self.wait() self.teacher_says( "Not that much, actually!", run_time = 1, target_mode = "hooray" ) self.wait(2) class GeneralFormulas(SimplestNetworkExample): CONFIG = { "layer_sizes" : [3, 3, 2], "network_mob_config" : { "include_output_labels" : False, "neuron_to_neuron_buff" : LARGE_BUFF, "neuron_radius" : 0.3, }, "edge_stroke_width" : 4, "stroke_width_exp" : 0.2, "random_seed" : 9, } def setup(self): self.seed_random_libraries() self.setup_bases() def construct(self): self.setup_network_mob() self.show_all_a_labels() self.only_show_abstract_a_labels() self.add_desired_output() self.show_cost() self.show_example_weight() self.show_values_between_weight_and_cost() self.show_weight_chain_rule() self.show_derivative_wrt_prev_activation() self.show_multiple_paths_from_prev_layer_neuron() self.show_previous_layer() def setup_network_mob(self): self.color_network_edges() self.network_mob.to_edge(LEFT) self.network_mob.shift(DOWN) in_vect = np.random.random(self.layer_sizes[0]) self.network_mob.activate_layers(in_vect) self.remove(self.network_mob.layers[0]) self.remove(self.network_mob.edge_groups[0]) def show_all_a_labels(self): Lm1_neurons = self.network_mob.layers[-2].neurons L_neurons = self.network_mob.layers[-1].neurons all_arrows = VGroup() all_labels = VGroup() all_decimals = VGroup() all_subscript_rects = VGroup() for neurons in L_neurons, Lm1_neurons: is_L = neurons is L_neurons vect = LEFT if is_L else RIGHT s = "L" if is_L else "L-1" arrows = VGroup() labels = VGroup() decimals = VGroup() subscript_rects = VGroup() for i, neuron in enumerate(neurons): arrow = Arrow(ORIGIN, vect) arrow.next_to(neuron, -vect) arrow.set_fill(WHITE) label = OldTex("a^{(%s)}_%d"%(s, i)) label.next_to(arrow, -vect, SMALL_BUFF) rect = SurroundingRectangle(label[-1], buff = 0.5*SMALL_BUFF) decimal = self.get_neuron_activation_decimal(neuron) neuron.arrow = arrow neuron.label = label neuron.decimal = decimal arrows.add(arrow) labels.add(label) decimals.add(decimal) subscript_rects.add(rect) all_arrows.add(arrows) all_labels.add(labels) all_decimals.add(decimals) all_subscript_rects.add(subscript_rects) start_labels, start_arrows = [ VGroup(*list(map(VGroup, [group[i][0] for i in (0, 1)]))).copy() for group in (all_labels, all_arrows) ] for label in start_labels: label[0][-1].set_color(BLACK) self.add(all_decimals) self.play(*it.chain( list(map(Write, start_labels)), [GrowArrow(a[0]) for a in start_arrows] )) self.wait() self.play( ReplacementTransform(start_labels, all_labels), ReplacementTransform(start_arrows, all_arrows), ) self.play(LaggedStartMap( ShowCreationThenDestruction, VGroup(*all_subscript_rects.family_members_with_points()), lag_ratio = 0.7 )) self.wait() self.set_variables_as_attrs( L_neurons, Lm1_neurons, all_arrows, all_labels, all_decimals, all_subscript_rects, ) def only_show_abstract_a_labels(self): arrows_to_fade = VGroup() labels_to_fade = VGroup() labels_to_change = VGroup() self.chosen_neurons = VGroup() rects = VGroup() for x, layer in enumerate(self.network_mob.layers[-2:]): for y, neuron in enumerate(layer.neurons): if (x == 0 and y == 1) or (x == 1 and y == 0): tex = "k" if x == 0 else "j" neuron.label.generate_target() self.replace_subscript(neuron.label.target, tex) self.chosen_neurons.add(neuron) labels_to_change.add(neuron.label) rects.add(SurroundingRectangle( neuron.label.target[-1], buff = 0.5*SMALL_BUFF )) else: labels_to_fade.add(neuron.label) arrows_to_fade.add(neuron.arrow) self.play( LaggedStartMap(FadeOut, labels_to_fade), LaggedStartMap(FadeOut, arrows_to_fade), run_time = 1 ) for neuron, rect in zip(self.chosen_neurons, rects): self.play( MoveToTarget(neuron.label), ShowCreation(rect) ) self.play(FadeOut(rect)) self.wait() self.wait() def add_desired_output(self): layer = self.network_mob.layers[-1] desired_output = layer.deepcopy() desired_output.shift(3*RIGHT) desired_output_decimals = VGroup() arrows = VGroup() labels = VGroup() for i, neuron in enumerate(desired_output.neurons): neuron.set_fill(opacity = i) decimal = self.get_neuron_activation_decimal(neuron) neuron.decimal = decimal neuron.arrow = Arrow(ORIGIN, LEFT, color = WHITE) neuron.arrow.next_to(neuron, RIGHT) neuron.label = OldTex("y_%d"%i) neuron.label.next_to(neuron.arrow, RIGHT) neuron.label.set_color(self.desired_output_color) desired_output_decimals.add(decimal) arrows.add(neuron.arrow) labels.add(neuron.label) rect = SurroundingRectangle(desired_output, buff = 0.5*SMALL_BUFF) words = OldTexText("Desired output") words.next_to(rect, DOWN) VGroup(words, rect).set_color(self.desired_output_color) self.play( FadeIn(rect), FadeIn(words), ReplacementTransform(layer.copy(), desired_output), FadeIn(labels), *[ ReplacementTransform(n1.decimal.copy(), n2.decimal) for n1, n2 in zip(layer.neurons, desired_output.neurons) ] + list(map(GrowArrow, arrows)) ) self.wait() self.set_variables_as_attrs( desired_output, desired_output_decimals, desired_output_rect = rect, desired_output_words = words, ) def show_cost(self): aj = self.chosen_neurons[1].label.copy() yj = self.desired_output.neurons[0].label.copy() cost_equation = OldTex( "C_0", "=", "\\sum_{j = 0}^{n_L - 1}", "(", "a^{(L)}_j", "-", "y_j", ")", "^2" ) cost_equation.to_corner(UP+RIGHT) cost_equation[0].set_color(self.cost_color) aj.target = cost_equation.get_part_by_tex("a^{(L)}_j") yj.target = cost_equation.get_part_by_tex("y_j") yj.target.set_color(self.desired_output_color) to_fade_in = VGroup(*[m for m in cost_equation if m not in [aj.target, yj.target]]) sum_part = cost_equation.get_part_by_tex("sum") self.play(*[ ReplacementTransform(mob, mob.target) for mob in (aj, yj) ]) self.play(LaggedStartMap(FadeIn, to_fade_in)) self.wait(2) self.play(LaggedStartMap( Indicate, sum_part, rate_func = wiggle, )) self.wait() for mob in aj.target, yj.target, cost_equation[-1]: self.play(Indicate(mob)) self.wait() self.set_variables_as_attrs(cost_equation) def show_example_weight(self): edges = self.network_mob.edge_groups[-1] edge = self.chosen_neurons[1].edges_in[1] faded_edges = VGroup(*[e for e in edges if e is not edge]) faded_edges.save_state() for faded_edge in faded_edges: faded_edge.save_state() w_label = OldTex("w^{(L)}_{jk}") subscripts = VGroup(*w_label[-2:]) w_label.scale(1.2) w_label.add_background_rectangle() w_label.next_to(ORIGIN, UP, SMALL_BUFF) w_label.rotate(edge.get_angle()) w_label.shift(edge.get_center()) w_label.set_color(BLUE) edges.save_state() edges.generate_target() for e in edges.target: e.rotate(-e.get_angle()) edges.target.arrange(DOWN) edges.target.move_to(edges) edges.target.to_edge(UP) self.play(MoveToTarget(edges)) self.play(LaggedStartMap( ApplyFunction, edges, lambda e : ( lambda m : m.rotate(np.pi/12).set_color(YELLOW), e ), rate_func = wiggle )) self.play(edges.restore) self.play(faded_edges.fade, 0.9) for neuron in self.chosen_neurons: self.play(Indicate(neuron), Animation(neuron.decimal)) self.play(Write(w_label)) self.wait() self.play(Indicate(subscripts)) for x in range(2): self.play(Swap(*subscripts)) self.wait() self.set_variables_as_attrs(faded_edges, w_label) def show_values_between_weight_and_cost(self): z_formula = OldTex( "z^{(L)}_j", "=", "w^{(L)}_{j0}", "a^{(L-1)}_0", "+", "w^{(L)}_{j1}", "a^{(L-1)}_1", "+", "w^{(L)}_{j2}", "a^{(L-1)}_2", "+", "b^{(L)}_j" ) compact_z_formula = OldTex( "z^{(L)}_j", "=", "\\cdots", "", "+" "w^{(L)}_{jk}", "a^{(L-1)}_k", "+", "\\cdots", "", "", "", ) for expression in z_formula, compact_z_formula: expression.to_corner(UP+RIGHT) expression.set_color_by_tex_to_color_map({ "z^" : self.z_color, "w^" : self.w_label.get_color(), "b^" : MAROON_B, }) w_part = z_formula.get_parts_by_tex("w^")[1] aLm1_part = z_formula.get_parts_by_tex("a^{(L-1)}")[1] a_formula = OldTex( "a^{(L)}_j", "=", "\\sigma(", "z^{(L)}_j", ")" ) a_formula.set_color_by_tex("z^", self.z_color) a_formula.next_to(z_formula, DOWN, MED_LARGE_BUFF) a_formula.align_to(self.cost_equation, LEFT) aL_part = a_formula[0] to_fade = VGroup( self.desired_output, self.desired_output_decimals, self.desired_output_rect, self.desired_output_words, *[ VGroup(n.arrow, n.label) for n in self.desired_output.neurons ] ) self.play( FadeOut(to_fade), self.cost_equation.next_to, a_formula, DOWN, MED_LARGE_BUFF, self.cost_equation.to_edge, RIGHT, ReplacementTransform(self.w_label[1].copy(), w_part), ReplacementTransform( self.chosen_neurons[0].label.copy(), aLm1_part ), ) self.play(Write(VGroup(*[m for m in z_formula if m not in [w_part, aLm1_part]]))) self.wait() self.play(ReplacementTransform( self.chosen_neurons[1].label.copy(), aL_part )) self.play( Write(VGroup(*a_formula[1:3] + [a_formula[-1]])), ReplacementTransform( z_formula[0].copy(), a_formula.get_part_by_tex("z^") ) ) self.wait() self.set_variables_as_attrs(z_formula, compact_z_formula, a_formula) def show_weight_chain_rule(self): chain_rule = self.get_chain_rule( "{\\partial C_0", "\\over", "\\partial w^{(L)}_{jk}}", "=", "{\\partial z^{(L)}_j", "\\over", "\\partial w^{(L)}_{jk}}", "{\\partial a^{(L)}_j", "\\over", "\\partial z^{(L)}_j}", "{\\partial C_0", "\\over", "\\partial a^{(L)}_j}", ) terms = VGroup(*[ VGroup(*chain_rule[i:i+3]) for i in range(4,len(chain_rule), 3) ]) rects = VGroup(*[ SurroundingRectangle(term, buff = 0.5*SMALL_BUFF) for term in terms ]) rects.set_color_by_gradient(GREEN, WHITE, RED) self.play(Transform( self.z_formula, self.compact_z_formula )) self.play(Write(chain_rule)) self.wait() self.play(LaggedStartMap( ShowCreationThenDestruction, rects, lag_ratio = 0.7, run_time = 3 )) self.wait() self.set_variables_as_attrs(chain_rule) def show_derivative_wrt_prev_activation(self): chain_rule = self.get_chain_rule( "{\\partial C_0", "\\over", "\\partial a^{(L-1)}_k}", "=", "\\sum_{j=0}^{n_L - 1}", "{\\partial z^{(L)}_j", "\\over", "\\partial a^{(L-1)}_k}", "{\\partial a^{(L)}_j", "\\over", "\\partial z^{(L)}_j}", "{\\partial C_0", "\\over", "\\partial a^{(L)}_j}", ) formulas = VGroup(self.z_formula, self.a_formula, self.cost_equation) n = chain_rule.index_of_part_by_tex("sum") self.play(ReplacementTransform( self.chain_rule, VGroup(*chain_rule[:n] + chain_rule[n+1:]) )) self.play(Write(chain_rule[n], run_time = 1)) self.wait() self.set_variables_as_attrs(chain_rule) def show_multiple_paths_from_prev_layer_neuron(self): neurons = self.network_mob.layers[-1].neurons labels, arrows, decimals = [ VGroup(*[getattr(n, attr) for n in neurons]) for attr in ("label", "arrow", "decimal") ] edges = VGroup(*[n.edges_in[1] for n in neurons]) labels[0].generate_target() self.replace_subscript(labels[0].target, "0") paths = [ VGroup( self.chosen_neurons[0].label, self.chosen_neurons[0].arrow, self.chosen_neurons[0], self.chosen_neurons[0].decimal, edges[i], neurons[i], decimals[i], arrows[i], labels[i], ) for i in range(2) ] path_lines = VGroup() for path in paths: points = [path[0].get_center()] for mob in path[1:]: if isinstance(mob, DecimalNumber): continue points.append(mob.get_center()) path_line = VMobject() path_line.set_points_as_corners(points) path_lines.add(path_line) path_lines.set_color(YELLOW) chain_rule = self.chain_rule n = chain_rule.index_of_part_by_tex("sum") brace = Brace(VGroup(*chain_rule[n:]), DOWN, buff = SMALL_BUFF) words = brace.get_text("Sum over layer L", buff = SMALL_BUFF) cost_aL = self.cost_equation.get_part_by_tex("a^{(L)}") self.play( MoveToTarget(labels[0]), FadeIn(labels[1]), GrowArrow(arrows[1]), edges[1].restore, FadeOut(self.w_label), ) for x in range(5): anims = [ ShowCreationThenDestruction( path_line, run_time = 1.5, time_width = 0.5, ) for path_line in path_lines ] if x == 2: anims += [ FadeIn(words), GrowFromCenter(brace) ] self.play(*anims) self.wait() for path, path_line in zip(paths, path_lines): label = path[-1] self.play( LaggedStartMap( Indicate, path, rate_func = wiggle, run_time = 1, ), ShowCreation(path_line), Animation(label) ) self.wait() group = VGroup(label, cost_aL) self.play( group.shift, MED_SMALL_BUFF*UP, rate_func = wiggle ) self.play(FadeOut(path_line)) self.wait() def show_previous_layer(self): mid_neurons = self.network_mob.layers[1].neurons layer = self.network_mob.layers[0] edges = self.network_mob.edge_groups[0] faded_edges = self.faded_edges to_fade = VGroup( self.chosen_neurons[0].label, self.chosen_neurons[0].arrow, ) for neuron in layer.neurons: neuron.add(self.get_neuron_activation_decimal(neuron)) all_edges_out = VGroup(*[ VGroup(*[n.edges_in[i] for n in mid_neurons]).copy() for i in range(len(layer.neurons)) ]) all_edges_out.set_stroke(YELLOW, 3) deriv = VGroup(*self.chain_rule[:3]) deriv_rect = SurroundingRectangle(deriv) mid_neuron_outlines = mid_neurons.copy() mid_neuron_outlines.set_fill(opacity = 0) mid_neuron_outlines.set_stroke(YELLOW, 5) def get_neurons_decimal_anims(neuron): return [ ChangingDecimal( neuron.decimal, lambda a : neuron.get_fill_opacity(), ), UpdateFromFunc( neuron.decimal, lambda m : m.set_fill( WHITE if neuron.get_fill_opacity() < 0.8 else BLACK ) ) ] self.play(ShowCreation(deriv_rect)) self.play(LaggedStartMap( ShowCreationThenDestruction, mid_neuron_outlines )) self.play(*it.chain(*[ [ ApplyMethod(n.set_fill, None, random.random()), ] + get_neurons_decimal_anims(n) for n in mid_neurons ]), run_time = 4, rate_func = there_and_back) self.play(faded_edges.restore) self.play( LaggedStartMap( GrowFromCenter, layer.neurons, run_time = 1 ), LaggedStartMap(ShowCreation, edges), FadeOut(to_fade) ) for x in range(3): for edges_out in all_edges_out: self.play(ShowCreationThenDestruction(edges_out)) self.wait() #### def replace_subscript(self, label, tex): subscript = label[-1] new_subscript = OldTex(tex)[0] new_subscript.replace(subscript, dim_to_match = 1) label.remove(subscript) label.add(new_subscript) return label def get_chain_rule(self, *tex): chain_rule = OldTex(*tex) chain_rule.scale(0.8) chain_rule.to_corner(UP+LEFT) chain_rule.set_color_by_tex_to_color_map({ "C_0" : self.cost_color, "z^" : self.z_color, "w^" : self.w_label.get_color() }) return chain_rule class ThatsPrettyMuchIt(TeacherStudentsScene): def construct(self): self.teacher_says( "That's pretty \\\\ much it!", target_mode = "hooray", run_time = 1, ) self.wait(2) class PatYourselfOnTheBack(TeacherStudentsScene): def construct(self): self.teacher_says( "Pat yourself on \\\\ the back!", target_mode = "hooray" ) self.play_student_changes(*["hooray"]*3) self.wait(3) class ThatsALotToThinkAbout(TeacherStudentsScene): def construct(self): self.teacher_says( "That's a lot to \\\\ think about!", target_mode = "surprised" ) self.play_student_changes(*["thinking"]*3) self.wait(4) class LayersOfComplexity(Scene): def construct(self): chain_rule_equations = self.get_chain_rule_equations() chain_rule_equations.to_corner(UP+RIGHT) brace = Brace(chain_rule_equations, LEFT) arrow = Vector(LEFT, color = RED) arrow.next_to(brace, LEFT) gradient = OldTex("\\nabla C") gradient.scale(2) gradient.set_color(RED) gradient.next_to(arrow, LEFT) self.play(LaggedStartMap(FadeIn, chain_rule_equations)) self.play(GrowFromCenter(brace)) self.play(GrowArrow(arrow)) self.play(Write(gradient)) self.wait() def get_chain_rule_equations(self): w_deriv = OldTex( "{\\partial C", "\\over", "\\partial w^{(l)}_{jk}}", "=", "a^{(l-1)}_k", "\\sigma'(z^{(l)}_j)", "{\\partial C", "\\over", "\\partial a^{(l)}_j}", ) lil_rect = SurroundingRectangle( VGroup(*w_deriv[-3:]), buff = 0.5*SMALL_BUFF ) a_deriv = OldTex( "\\sum_{j = 0}^{n_{l+1} - 1}", "w^{(l+1)}_{jk}", "\\sigma'(z^{(l+1)}_j)", "{\\partial C", "\\over", "\\partial a^{(l+1)}_j}", ) or_word = OldTexText("or") last_a_deriv = OldTex("2(a^{(L)}_j - y_j)") a_deriv.next_to(w_deriv, DOWN, LARGE_BUFF) or_word.next_to(a_deriv, DOWN) last_a_deriv.next_to(or_word, DOWN, MED_LARGE_BUFF) big_rect = SurroundingRectangle(VGroup(a_deriv, last_a_deriv)) arrow = Arrow( lil_rect.get_corner(DOWN+LEFT), big_rect.get_top(), ) result = VGroup( w_deriv, lil_rect, arrow, big_rect, a_deriv, or_word, last_a_deriv ) for expression in w_deriv, a_deriv, last_a_deriv: expression.set_color_by_tex_to_color_map({ "C" : RED, "z^" : GREEN, "w^" : BLUE, "b^" : MAROON_B, }) return result class SponsorFrame(PiCreatureScene): def construct(self): morty = self.pi_creature screen = ScreenRectangle(height = 5) screen.to_corner(UP+LEFT) url = OldTexText("http://3b1b.co/crowdflower") url.move_to(screen, UP+LEFT) screen.shift(LARGE_BUFF*DOWN) arrow = Arrow(LEFT, RIGHT, color = WHITE) arrow.next_to(url, RIGHT) t_shirt_words = OldTexText("Free T-Shirt") t_shirt_words.scale(1.5) t_shirt_words.set_color(YELLOW) t_shirt_words.next_to(morty, UP, aligned_edge = RIGHT) human_in_the_loop = OldTexText("Human-in-the-loop approach") human_in_the_loop.next_to(screen, DOWN) self.play( morty.change, "hooray", t_shirt_words, Write(t_shirt_words, run_time = 2) ) self.wait() self.play( morty.change, "raise_right_hand", screen, ShowCreation(screen) ) self.play( t_shirt_words.scale, 1./1.5, t_shirt_words.next_to, arrow, RIGHT ) self.play(Write(url)) self.play(GrowArrow(arrow)) self.wait(2) self.play(morty.change, "thinking", url) self.wait(3) self.play(Write(human_in_the_loop)) self.play(morty.change, "happy", url) self.play(morty.look_at, screen) self.wait(7) t_shirt_words_outline = t_shirt_words.copy() t_shirt_words_outline.set_fill(opacity = 0) t_shirt_words_outline.set_stroke(GREEN, 3) self.play( morty.change, "hooray", t_shirt_words, LaggedStartMap(ShowCreation, t_shirt_words_outline), ) self.play(FadeOut(t_shirt_words_outline)) self.play(LaggedStartMap( Indicate, url, rate_func = wiggle, color = PINK, run_time = 3 )) self.wait(3) class NN3PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Randall Hunt", "Burt Humburg", "CrypticSwarm", "Juan Benet", "David Kedmey", "Michael Hardwicke", "Nathan Weeks", "Marcus Schiebold", "Ali Yahya", "William", "Mayank M. Mehrotra", "Lukas Biewald", "Samantha D. Suplee", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Ed Kellett", "Joseph John Cox", "Luc Ritchie", "1stViewMaths", "Jacob Magnuson", "Mark Govea", "Dagan Harrington", "Clark Gaebel", "Eric Chow", "Mathias Jansson", "Robert Teed", "Pedro Perez Sanchez", "David Clark", "Michael Gardner", "Harsev Singh", "Mads Elvheim", "Erik Sundell", "Xueqi Li", "Dr. David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ], "max_patron_group_size" : 25, "patron_scale_val" : 0.7, } class Thumbnail(PreviewLearning): CONFIG = { "layer_sizes" : [8, 6, 6, 4], "network_mob_config" : { "neuron_radius" : 0.3, "neuron_to_neuron_buff" : MED_SMALL_BUFF, "include_output_labels" : False, }, "stroke_width_exp" : 1, "max_stroke_width" : 5, "title" : "Backpropagation", "network_scale_val" : 0.8, } def construct(self): self.color_network_edges() network_mob = self.network_mob network_mob.scale( self.network_scale_val, about_point = network_mob.get_bottom() ) network_mob.activate_layers(np.random.random(self.layer_sizes[0])) for edge in it.chain(*network_mob.edge_groups): arrow = Arrow( edge.get_end(), edge.get_start(), buff = 0, tip_length = 0.1, color = edge.get_color() ) network_mob.add(arrow.tip) arrow = Vector( 3*LEFT, tip_length = 0.75, rectangular_stem_width = 0.2, color = BLUE, ) arrow.next_to(network_mob.edge_groups[1], UP, MED_LARGE_BUFF) network_mob.add(arrow) self.add(network_mob) title = OldTexText(self.title) title.scale(2) title.to_edge(UP) self.add(title) class SupplementThumbnail(Thumbnail): CONFIG = { "title" : "Backpropagation \\\\ calculus", "network_scale_val" : 0.7, } def construct(self): Thumbnail.construct(self) self.network_mob.to_edge(DOWN, buff = MED_SMALL_BUFF) for layer in self.network_mob.layers: for neuron in layer.neurons: partial = OldTex("\\partial") partial.move_to(neuron) self.remove(neuron) self.add(partial)
videos_3b1b/_2017/nn/playground.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os.path from functools import reduce sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from constants import * from manim_imports_ext import * from _2017.nn.network import * from _2017.nn.part1 import * class Test(Scene): def construct(self): network = get_pretrained_network() training_data, validation_data, test_data = load_data_wrapper() self.show_weight_rows(network, index = 0) # self.show_maximizing_inputs(network) # self.show_all_activation_images(network, test_data) # group = Group() # for k in range(10): # v = np.zeros((10, 1)) # v[k] = 1 # h_group = Group() # for W, b in reversed(zip(network.weights, network.biases)): # h_group.add(MNistMobject(v)) # v = np.dot(W.T, sigmoid_inverse(v) - b) # v = sigmoid(v) # h_group.add(MNistMobject(v)) # h_group.arrange(LEFT) # group.add(h_group) # group.arrange(DOWN) # group.set_height(FRAME_HEIGHT - 1) # self.add(group) def show_random_results(self): group = Group(*[ Group(*[ MNistMobject(a) for a in network.get_activation_of_all_layers( np.random.randn(784, 1) ) ]).arrange(RIGHT) for x in range(10) ]).arrange(DOWN) group.set_height(FRAME_HEIGHT - 1) self.add(group) def show_weight_rows(self, network, index): group = VGroup() for row in network.weights[index]: mob = PixelsFromVect(np.zeros(row.size)) for n, pixel in zip(row, mob): color = GREEN if n > 0 else RED opacity = 2*(sigmoid(abs(n)) - 0.5) pixel.set_fill(color, opacity = opacity) group.add(mob) group.arrange_in_grid() group.set_height(FRAME_HEIGHT - 1) self.add(group) def show_all_activation_images(self, network, test_data): image_samples = Group(*[ self.get_activation_images(digit, network, test_data) for digit in range(10) ]) image_samples.arrange_in_grid( n_rows = 2, buff = LARGE_BUFF ) image_samples.set_height(FRAME_HEIGHT - 1) self.add(image_samples) def get_activation_images(self, digit, network, test_data, n_examples = 8): input_vectors = [ data[0] for data in test_data if data[1] == digit ] activation_iamges = Group(*[ Group(*[ MNistMobject(a) for a in network.get_activation_of_all_layers(vect) ]).arrange(RIGHT) for vect in input_vectors[:n_examples] ]).arrange(DOWN) activation_iamges.set_height(FRAME_HEIGHT - 1) return activation_iamges def show_two_blend(self): training_data, validation_data, test_data = load_data_wrapper() vects = [ data[0] for data in training_data[:30] if np.argmax(data[1]) == 2 ] mean_vect = reduce(op.add, vects)/len(vects) self.add(MNistMobject(mean_vect)) def show_maximizing_inputs(self, network): training_data, validation_data, test_data = load_data_wrapper() layer = 1 n_neurons = DEFAULT_LAYER_SIZES[layer] groups = Group() for k in range(n_neurons): out = np.zeros(n_neurons) out[k] = 1 in_vect = maximizing_input(network, layer, out) new_out = network.get_activation_of_all_layers(in_vect)[layer] group = Group(*list(map(MNistMobject, [in_vect, new_out]))) group.arrange(DOWN+RIGHT, SMALL_BUFF) groups.add(group) groups.arrange_in_grid() groups.set_height(FRAME_HEIGHT - 1) self.add(groups) def show_test_input(self, network): training_data, validation_data, test_data = load_data_wrapper() group = Group(*[ self.get_set(network, test) for test in test_data[3:20] if test[1] in [4, 9] ]) group.arrange(DOWN, buff = MED_LARGE_BUFF) group.set_height(FRAME_HEIGHT - 1) self.play(FadeIn(group)) def get_set(self, network, test): test_in, test_out = test activations = network.get_activation_of_all_layers(test_in) group = Group(*list(map(MNistMobject, activations))) group.arrange(RIGHT, buff = LARGE_BUFF) return group # def show_frame(self): # pass if __name__ == "__main__": save_pretrained_network() test_network()
videos_3b1b/_2017/nn/part2.py
import sys import os.path import cv2 from manim_imports_ext import * from _2017.nn.network import * from _2017.nn.part1 import * POSITIVE_COLOR = BLUE NEGATIVE_COLOR = RED def get_training_image_group(train_in, train_out): image = MNistMobject(train_in) image.set_height(1) arrow = Vector(RIGHT, color = BLUE, buff = 0) output = np.argmax(train_out) output_tex = OldTex(str(output)).scale(1.5) result = Group(image, arrow, output_tex) result.arrange(RIGHT) result.to_edge(UP) return result def get_decimal_vector(nums, with_dots = True): decimals = VGroup() for num in nums: decimal = DecimalNumber(num) if num > 0: decimal.set_color(POSITIVE_COLOR) else: decimal.set_color(NEGATIVE_COLOR) decimals.add(decimal) contents = VGroup(*decimals) if with_dots: dots = OldTex("\\vdots") contents.submobjects.insert(len(decimals)/2, dots) contents.arrange(DOWN) lb, rb = brackets = OldTex("\\big[", "\\big]") brackets.scale(2) brackets.stretch_to_fit_height(1.2*contents.get_height()) lb.next_to(contents, LEFT, SMALL_BUFF) rb.next_to(contents, RIGHT, SMALL_BUFF) result = VGroup(lb, contents, brackets) result.lb = lb result.rb = rb result.brackets = brackets result.decimals = decimals result.contents = contents if with_dots: result.dots = dots return result ######## class ShowLastVideo(TeacherStudentsScene): def construct(self): frame = ScreenRectangle() frame.set_height(4.5) frame.to_corner(UP+LEFT) title = OldTexText("But what \\emph{is} a Neural Network") title.move_to(frame) title.to_edge(UP) frame.next_to(title, DOWN) assumption_words = OldTexText( "I assume you've\\\\ watched this" ) assumption_words.move_to(frame) assumption_words.to_edge(RIGHT) arrow = Arrow(RIGHT, LEFT, color = BLUE) arrow.next_to(assumption_words, LEFT) self.play( ShowCreation(frame), self.teacher.change, "raise_right_hand" ) self.play( Write(title), self.change_students(*["thinking"]*3) ) self.play( Animation(title), GrowArrow(arrow), FadeIn(assumption_words) ) self.wait(5) class ShowPlan(Scene): def construct(self): title = OldTexText("Plan").scale(1.5) title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.set_color(WHITE) h_line.next_to(title, DOWN) self.add(title, h_line) items = VGroup(*[ OldTexText("$\\cdot$ %s"%s) for s in [ "Recap", "Gradient descent", "Analyze this network", "Where to learn more", "Research corner", ] ]) items.arrange(DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT) items.to_edge(LEFT, buff = LARGE_BUFF) rect = SurroundingRectangle(VGroup(*items[1:3])) self.add(items) self.wait() self.play(ShowCreation(rect)) self.play(FadeOut(rect)) for item in items[1:]: to_fade = VGroup(*[i for i in items if i is not item]) self.play( to_fade.set_fill, None, 0.5, item.set_fill, None, 1, ) self.wait() class BeginAndEndRecap(Scene): def construct(self): recap = OldTex( "\\langle", "\\text{Recap}", "\\rangle" ) new_langle = OldTex("\\langle/") new_langle.scale(2) recap.scale(2) new_langle.move_to(recap[0], RIGHT) self.add(recap) self.wait(2) self.play(Transform(recap[0], new_langle)) self.wait(2) class PreviewLearning(NetworkScene): CONFIG = { "layer_sizes" : DEFAULT_LAYER_SIZES, "network_mob_config" : { "neuron_to_neuron_buff" : SMALL_BUFF, "layer_to_layer_buff" : 2, "edge_stroke_width" : 1, "neuron_stroke_color" : WHITE, "neuron_stroke_width" : 2, "neuron_fill_color" : WHITE, "average_shown_activation_of_large_layer" : False, "edge_propogation_color" : GREEN, "edge_propogation_time" : 2, "include_output_labels" : True, }, "n_examples" : 15, "max_stroke_width" : 3, "stroke_width_exp" : 3, "eta" : 3.0, "positive_edge_color" : BLUE, "negative_edge_color" : RED, "positive_change_color" : BLUE_C, "negative_change_color" : average_color(*2*[RED] + [YELLOW]), "default_activate_run_time" : 1.5, } def construct(self): self.initialize_network() self.add_training_words() self.show_training() def initialize_network(self): self.network_mob.scale(0.7) self.network_mob.to_edge(DOWN) self.color_network_edges() def add_training_words(self): words = OldTexText("Training in \\\\ progress$\\dots$") words.scale(1.5) words.to_corner(UP+LEFT) self.add(words) def show_training(self): training_data, validation_data, test_data = load_data_wrapper() for train_in, train_out in training_data[:self.n_examples]: image = get_training_image_group(train_in, train_out) self.activate_network(train_in, FadeIn(image)) self.backprop_one_example( train_in, train_out, FadeOut(image), self.network_mob.layers.restore ) def activate_network(self, train_in, *added_anims, **kwargs): network_mob = self.network_mob layers = network_mob.layers layers.save_state() activations = self.network.get_activation_of_all_layers(train_in) active_layers = [ self.network_mob.get_active_layer(i, vect) for i, vect in enumerate(activations) ] all_edges = VGroup(*it.chain(*network_mob.edge_groups)) run_time = kwargs.get("run_time", self.default_activate_run_time) edge_animation = LaggedStartMap( ShowCreationThenDestruction, all_edges.copy().set_fill(YELLOW), run_time = run_time, lag_ratio = 0.3, remover = True, ) layer_animation = Transform( VGroup(*layers), VGroup(*active_layers), run_time = run_time, lag_ratio = 0.5, rate_func=linear, ) self.play(edge_animation, layer_animation, *added_anims) def backprop_one_example(self, train_in, train_out, *added_outro_anims): network_mob = self.network_mob nabla_b, nabla_w = self.network.backprop(train_in, train_out) neuron_groups = VGroup(*[ layer.neurons for layer in network_mob.layers[1:] ]) delta_neuron_groups = neuron_groups.copy() edge_groups = network_mob.edge_groups delta_edge_groups = VGroup(*[ edge_group.copy() for edge_group in edge_groups ]) tups = list(zip( it.count(), nabla_b, nabla_w, delta_neuron_groups, neuron_groups, delta_edge_groups, edge_groups )) pc_color = self.positive_change_color nc_color = self.negative_change_color for i, nb, nw, delta_neurons, neurons, delta_edges, edges in reversed(tups): shown_nw = self.get_adjusted_first_matrix(nw) if np.max(shown_nw) == 0: shown_nw = (2*np.random.random(shown_nw.shape)-1)**5 max_b = np.max(np.abs(nb)) max_w = np.max(np.abs(shown_nw)) for neuron, b in zip(delta_neurons, nb): color = nc_color if b > 0 else pc_color # neuron.set_fill(color, abs(b)/max_b) neuron.set_stroke(color, 3) for edge, w in zip(delta_edges.split(), shown_nw.T.flatten()): edge.set_stroke( nc_color if w > 0 else pc_color, 3*abs(w)/max_w ) edge.rotate(np.pi) if i == 2: delta_edges.submobjects = [ delta_edges[j] for j in np.argsort(shown_nw.T.flatten()) ] network = self.network network.weights[i] -= self.eta*nw network.biases[i] -= self.eta*nb self.play( ShowCreation( delta_edges, lag_ratio = 0 ), FadeIn(delta_neurons), run_time = 0.5 ) edge_groups.save_state() self.color_network_edges() self.remove(edge_groups) self.play(*it.chain( [ReplacementTransform( edge_groups.saved_state, edge_groups, )], list(map(FadeOut, [delta_edge_groups, delta_neuron_groups])), added_outro_anims, )) ##### def get_adjusted_first_matrix(self, matrix): n = self.network_mob.max_shown_neurons if matrix.shape[1] > n: half = matrix.shape[1]/2 return matrix[:,half-n/2:half+n/2] else: return matrix def color_network_edges(self): layers = self.network_mob.layers weight_matrices = self.network.weights for layer, matrix in zip(layers[1:], weight_matrices): matrix = self.get_adjusted_first_matrix(matrix) matrix_max = np.max(matrix) for neuron, row in zip(layer.neurons, matrix): for edge, w in zip(neuron.edges_in, row): if w > 0: color = self.positive_edge_color else: color = self.negative_edge_color msw = self.max_stroke_width swe = self.stroke_width_exp sw = msw*(abs(w)/matrix_max)**swe sw = min(sw, msw) edge.set_stroke(color, sw) def get_edge_animation(self): edges = VGroup(*it.chain(*self.network_mob.edge_groups)) return LaggedStartMap( ApplyFunction, edges, lambda mob : ( lambda m : m.rotate(np.pi/12).set_color(YELLOW), mob ), rate_func = wiggle ) class BackpropComingLaterWords(Scene): def construct(self): words = OldTexText("(Backpropagation be \\\\ the next video)") words.set_width(FRAME_WIDTH-1) words.to_edge(DOWN) self.add(words) class TrainingVsTestData(Scene): CONFIG = { "n_examples" : 10, "n_new_examples_shown" : 10, } def construct(self): self.initialize_data() self.introduce_all_data() self.subdivide_into_training_and_testing() self.scroll_through_much_data() def initialize_data(self): training_data, validation_data, test_data = load_data_wrapper() self.data = training_data self.curr_index = 0 def get_examples(self): ci = self.curr_index self.curr_index += self.n_examples group = Group(*it.starmap( get_training_image_group, self.data[ci:ci+self.n_examples] )) group.arrange(DOWN) group.scale(0.5) return group def introduce_all_data(self): training_examples, test_examples = [ self.get_examples() for x in range(2) ] training_examples.next_to(ORIGIN, LEFT) test_examples.next_to(ORIGIN, RIGHT) self.play( LaggedStartMap(FadeIn, training_examples), LaggedStartMap(FadeIn, test_examples), ) self.training_examples = training_examples self.test_examples = test_examples def subdivide_into_training_and_testing(self): training_examples = self.training_examples test_examples = self.test_examples for examples in training_examples, test_examples: examples.generate_target() training_examples.target.shift(2*LEFT) test_examples.target.shift(2*RIGHT) train_brace = Brace(training_examples.target, LEFT) train_words = train_brace.get_text("Train on \\\\ these") test_brace = Brace(test_examples.target, RIGHT) test_words = test_brace.get_text("Test on \\\\ these") bools = [True]*(len(test_examples)-1) + [False] random.shuffle(bools) marks = VGroup() for is_correct, test_example in zip(bools, test_examples.target): if is_correct: mark = OldTex("\\checkmark") mark.set_color(GREEN) else: mark = OldTex("\\times") mark.set_color(RED) mark.next_to(test_example, LEFT) marks.add(mark) self.play( MoveToTarget(training_examples), GrowFromCenter(train_brace), FadeIn(train_words) ) self.wait() self.play( MoveToTarget(test_examples), GrowFromCenter(test_brace), FadeIn(test_words) ) self.play(Write(marks)) self.wait() def scroll_through_much_data(self): training_examples = self.training_examples colors = color_gradient([BLUE, YELLOW], self.n_new_examples_shown) for color in colors: new_examples = self.get_examples() new_examples.move_to(training_examples) for train_ex, new_ex in zip(training_examples, new_examples): self.remove(train_ex) self.add(new_ex) new_ex[0][0].set_color(color) self.wait(1./30) training_examples = new_examples class MNistDescription(Scene): CONFIG = { "n_grids" : 5, "n_rows_per_grid" : 10, "n_cols_per_grid" : 8, "time_per_example" : 1./120, } def construct(self): title = OldTexText("MNIST Database") title.scale(1.5) title.set_color(BLUE) authors = OldTexText("LeCun, Cortes and Burges") authors.next_to(title, DOWN) link_words = OldTexText("(links in the description)") link_words.next_to(authors, DOWN, MED_LARGE_BUFF) arrows = VGroup(*[Vector(DOWN) for x in range(4)]) arrows.arrange(RIGHT, buff = LARGE_BUFF) arrows.next_to(link_words, DOWN) arrows.set_color(BLUE) word_group = VGroup(title, authors, link_words, arrows) word_group.center() self.add(title, authors) self.play( Write(link_words, run_time = 2), LaggedStartMap(GrowArrow, arrows), ) self.wait() training_data, validation_data, test_data = load_data_wrapper() epc = self.n_rows_per_grid*self.n_cols_per_grid training_data_groups = [ training_data[i*epc:(i+1)*epc] for i in range(self.n_grids) ] for i, td_group in enumerate(training_data_groups): print(i) group = Group(*[ self.get_digit_pair(v_in, v_out) for v_in, v_out in td_group ]) group.arrange_in_grid( n_rows = self.n_rows_per_grid, ) group.set_height(FRAME_HEIGHT - 1) if i == 0: self.play( LaggedStartMap(FadeIn, group), FadeOut(word_group), ) else: pairs = list(zip(last_group, group)) random.shuffle(pairs) time = 0 for t1, t2 in pairs: time += self.time_per_example self.remove(t1) self.add(t2) if time > self.frame_duration: self.wait(self.frame_duration) time = 0 last_group = group def get_digit_pair(self, v_in, v_out): tup = Group(*Tex("(", "00", ",", "0", ")")) tup.scale(2) # image = PixelsFromVect(v_in) # image.add(SurroundingRectangle(image, color = BLUE, buff = SMALL_BUFF)) image = MNistMobject(v_in) label = OldTex(str(np.argmax(v_out))) image.replace(tup[1]) tup.submobjects[1] = image label.replace(tup[3], dim_to_match = 1) tup.submobjects[3] = label return tup class NotSciFi(TeacherStudentsScene): def construct(self): students = self.students self.student_says( "Machines learning?!?", index = 0, target_mode = "pleading", run_time = 1, ) bubble = students[0].bubble students[0].bubble = None self.student_says( "Should we \\\\ be worried?", index = 2, target_mode = "confused", bubble_config = {"direction" : LEFT}, run_time = 1, ) self.wait() students[0].bubble = bubble self.teacher_says( "It's actually \\\\ just calculus.", run_time = 1 ) self.teacher.bubble = None self.wait() self.student_says( "Even worse!", target_mode = "horrified", bubble_config = { "direction" : LEFT, "width" : 3, "height" : 2, }, ) self.wait(2) class FunctionMinmization(GraphScene): CONFIG = { "x_labeled_nums" : list(range(-1, 10)), } def construct(self): self.setup_axes() title = OldTexText("Finding minima") title.to_edge(UP) self.add(title) def func(x): x -= 4.5 return 0.03*(x**4 - 16*x**2) + 0.3*x + 4 graph = self.get_graph(func) graph_label = self.get_graph_label(graph, "C(x)") self.add(graph, graph_label) dots = VGroup(*[ Dot().move_to(self.input_to_graph_point(x, graph)) for x in range(10) ]) dots.set_color_by_gradient(YELLOW, RED) def update_dot(dot, dt): x = self.x_axis.point_to_number(dot.get_center()) slope = self.slope_of_tangent(x, graph) x -= slope*dt dot.move_to(self.input_to_graph_point(x, graph)) self.add(*[ Mobject.add_updater(dot, update_dot) for dot in dots ]) self.wait(10) class ChangingDecimalWithColor(ChangingDecimal): def interpolate_mobject(self, alpha): ChangingDecimal.interpolate_mobject(self, alpha) num = self.number_update_func(alpha) self.decimal_number.set_fill( interpolate_color(BLACK, WHITE, 0.5+num*0.5), opacity = 1 ) class IntroduceCostFunction(PreviewLearning): CONFIG = { "max_stroke_width" : 2, "full_edges_exp" : 5, "n_training_examples" : 100, "bias_color" : MAROON_B } def construct(self): self.network_mob.shift(LEFT) self.isolate_one_neuron() self.reminder_of_weights_and_bias() self.bring_back_rest_of_network() self.feed_in_example() self.make_fun_of_output() self.need_a_cost_function() self.fade_all_but_last_layer() self.break_down_cost_function() self.show_small_cost_output() self.average_over_all_training_data() def isolate_one_neuron(self): network_mob = self.network_mob neurons = VGroup(*it.chain(*[ layer.neurons for layer in network_mob.layers[1:] ])) edges = VGroup(*it.chain(*network_mob.edge_groups)) neuron = network_mob.layers[1].neurons[7] neurons.remove(neuron) edges.remove(*neuron.edges_in) output_labels = network_mob.output_labels kwargs = { "lag_ratio" : 0.5, "run_time" : 2, } self.play( FadeOut(edges, **kwargs), FadeOut(neurons, **kwargs), FadeOut(output_labels, **kwargs), Animation(neuron), neuron.edges_in.set_stroke, None, 2, ) self.neuron = neuron def reminder_of_weights_and_bias(self): neuron = self.neuron layer0 = self.network_mob.layers[0] active_layer0 = self.network_mob.get_active_layer( 0, np.random.random(len(layer0.neurons)) ) prev_neurons = layer0.neurons weighted_edges = VGroup(*[ self.color_edge_randomly(edge.copy(), exp = 1) for edge in neuron.edges_in ]) formula = OldTex( "=", "\\sigma(", "w_1", "a_1", "+", "w_2", "a_2", "+", "\\cdots", "+", "w_n", "a_n", "+", "b", ")" ) w_labels = formula.get_parts_by_tex("w_") a_labels = formula.get_parts_by_tex("a_") b = formula.get_part_by_tex("b") sigma = VGroup( formula.get_part_by_tex("\\sigma"), formula.get_part_by_tex(")"), ) symbols = VGroup(*[ formula.get_parts_by_tex(tex) for tex in ("=", "+", "dots") ]) w_labels.set_color(self.positive_edge_color) b.set_color(self.bias_color) sigma.set_color(YELLOW) formula.next_to(neuron, RIGHT) weights_word = OldTexText("Weights") weights_word.next_to(neuron.edges_in, RIGHT, aligned_edge = UP) weights_word.set_color(self.positive_edge_color) weights_arrow_to_edges = Arrow( weights_word.get_bottom(), neuron.edges_in[0].get_center(), color = self.positive_edge_color ) weights_arrow_to_syms = VGroup(*[ Arrow( weights_word.get_bottom(), w_label.get_top(), color = self.positive_edge_color ) for w_label in w_labels ]) bias_word = OldTexText("Bias") bias_arrow = Vector(DOWN, color = self.bias_color) bias_arrow.next_to(b, UP, SMALL_BUFF) bias_word.next_to(bias_arrow, UP, SMALL_BUFF) bias_word.set_color(self.bias_color) self.play( Transform(layer0, active_layer0), neuron.set_fill, None, 0.5, FadeIn(formula), run_time = 2, lag_ratio = 0.5 ) self.play(LaggedStartMap( ShowCreationThenDestruction, neuron.edges_in.copy().set_stroke(YELLOW, 3), run_time = 1.5, lag_ratio = 0.7, remover = True )) self.play( Write(weights_word), *list(map(GrowArrow, weights_arrow_to_syms)), run_time = 1 ) self.wait() self.play( ReplacementTransform( w_labels.copy(), weighted_edges, remover = True ), Transform(neuron.edges_in, weighted_edges), ReplacementTransform( weights_arrow_to_syms, VGroup(weights_arrow_to_edges), ) ) self.wait() self.play( Write(bias_word), GrowArrow(bias_arrow), run_time = 1 ) self.wait(2) ## Initialize randomly w_random = OldTexText("Initialize randomly") w_random.move_to(weights_word, LEFT) b_random = w_random.copy() b_random.move_to(bias_word, RIGHT) self.play( Transform(weights_word, w_random), Transform(bias_word, b_random), *[ ApplyFunction(self.color_edge_randomly, edge) for edge in neuron.edges_in ] ) self.play(LaggedStartMap( ApplyMethod, neuron.edges_in, lambda m : (m.rotate, np.pi/12), rate_func = wiggle, run_time = 2 )) self.play(*list(map(FadeOut, [ weights_word, weights_arrow_to_edges, bias_word, bias_arrow, formula ]))) def bring_back_rest_of_network(self): network_mob = self.network_mob neurons = VGroup(*network_mob.layers[1].neurons) neurons.remove(self.neuron) for layer in network_mob.layers[2:]: neurons.add(*layer.neurons) neurons.add(*network_mob.output_labels) edges = VGroup(*network_mob.edge_groups[0]) edges.remove(*self.neuron.edges_in) for edge_group in network_mob.edge_groups[1:]: edges.add(*edge_group) for edge in edges: self.color_edge_randomly(edge, exp = self.full_edges_exp) self.play(*[ LaggedStartMap( FadeIn, group, run_time = 3, ) for group in (neurons, edges) ]) def feed_in_example(self): vect = get_organized_images()[3][5] image = PixelsFromVect(vect) image.to_corner(UP+LEFT) rect = SurroundingRectangle(image, color = BLUE) neurons = VGroup(*[ Circle( stroke_width = 1, stroke_color = WHITE, fill_opacity = pixel.fill_rgb[0], fill_color = WHITE, radius = pixel.get_height()/2 ).move_to(pixel) for pixel in image ]) layer0= self.network_mob.layers[0] n = self.network_mob.max_shown_neurons neurons.target = VGroup(*it.chain( VGroup(*layer0.neurons[:n/2]).set_fill(opacity = 0), [ VectorizedPoint(layer0.dots.get_center()) for x in range(len(neurons)-n) ], VGroup(*layer0.neurons[-n/2:]).set_fill(opacity = 0), )) self.play( self.network_mob.shift, 0.5*RIGHT, ShowCreation(rect), LaggedStartMap(DrawBorderThenFill, image), LaggedStartMap(DrawBorderThenFill, neurons), run_time = 1 ) self.play( MoveToTarget( neurons, lag_ratio = 0.5, remover = True ), layer0.neurons.set_fill, None, 0, ) self.activate_network(vect, run_time = 2) self.image = image self.image_rect = rect def make_fun_of_output(self): last_layer = self.network_mob.layers[-1].neurons last_layer.add(self.network_mob.output_labels) rect = SurroundingRectangle(last_layer) words = OldTexText("Utter trash") words.next_to(rect, DOWN, aligned_edge = LEFT) VGroup(rect, words).set_color(YELLOW) self.play( ShowCreation(rect), Write(words, run_time = 2) ) self.wait() self.trash_rect = rect self.trash_words = words def need_a_cost_function(self): vect = np.zeros(10) vect[3] = 1 output_labels = self.network_mob.output_labels desired_layer = self.network_mob.get_active_layer(-1, vect) layer = self.network_mob.layers[-1] layer.add(output_labels) desired_layer.add(output_labels.copy()) desired_layer.shift(2*RIGHT) layers = VGroup(layer, desired_layer) words = OldTexText( "What's the", "``cost''\\\\", "of this difference?", ) words.set_color_by_tex("cost", RED) words.next_to(layers, UP) words.to_edge(UP) words.shift_onto_screen() double_arrow = DoubleArrow( layer.get_right(), desired_layer.get_left(), color = RED ) self.play(FadeIn(words)) self.play(ReplacementTransform(layer.copy(), desired_layer)) self.play(GrowFromCenter(double_arrow)) self.wait(2) self.desired_last_layer = desired_layer self.diff_arrow = double_arrow def fade_all_but_last_layer(self): network_mob = self.network_mob to_fade = VGroup(*it.chain(*list(zip( network_mob.layers[:-1], network_mob.edge_groups )))) self.play(LaggedStartMap(FadeOut, to_fade, run_time = 1)) def break_down_cost_function(self): layer = self.network_mob.layers[-1] desired_layer = self.desired_last_layer decimal_groups = VGroup(*[ self.num_vect_to_decimals(self.layer_to_num_vect(l)) for l in (layer, desired_layer) ]) terms = VGroup() symbols = VGroup() for d1, d2 in zip(*decimal_groups): term = OldTex( "(", "0.00", "-", "0.00", ")^2", "+", ) term.scale(d1.get_height()/term[1].get_height()) for d, i in (d1, 1), (d2, 3): term.submobjects[i] = d.move_to(term[i]) terms.add(term) symbols.add(*term) symbols.remove(d1, d2) last_plus = term[-1] for mob in terms[-1], symbols: mob.remove(last_plus) terms.arrange( DOWN, buff = SMALL_BUFF, aligned_edge = LEFT ) terms.set_height(1.5*layer.get_height()) terms.next_to(layer, LEFT, buff = 2) image_group = Group(self.image, self.image_rect) image_group.generate_target() image_group.target.scale(0.5) cost_of = OldTexText("Cost of").set_color(RED) cost_group = VGroup(cost_of, image_group.target) cost_group.arrange(RIGHT) brace = Brace(terms, LEFT) cost_group.next_to(brace, LEFT) self.revert_to_original_skipping_status() self.play(*[ ReplacementTransform( VGroup(*l.neurons[:10]).copy(), dg ) for l, dg in zip([layer, desired_layer], decimal_groups) ]) self.play( FadeIn(symbols), MoveToTarget(image_group), FadeIn(cost_of), GrowFromCenter(brace), ) self.wait() self.decimal_groups = decimal_groups self.image_group = image_group self.cost_group = VGroup(cost_of, image_group) self.brace = brace def show_small_cost_output(self): decimals, desired_decimals = self.decimal_groups neurons = self.network_mob.layers[-1].neurons brace = self.brace cost_group = self.cost_group neurons.save_state() cost_group.save_state() brace.save_state() brace.generate_target() arrows = VGroup(*[ Arrow(ORIGIN, LEFT).next_to(d, LEFT, MED_LARGE_BUFF) for d in decimals ]) arrows.set_color(WHITE) def generate_term_update_func(decimal, desired_decimal): return lambda a : (decimal.number - desired_decimal.number)**2 terms = VGroup() term_updates = [] for arrow, d1, d2 in zip(arrows, *self.decimal_groups): term = DecimalNumber(0, num_decimal_places = 4) term.set_height(d1.get_height()) term.next_to(arrow, LEFT) term.num_update_func = generate_term_update_func(d1, d2) terms.add(term) term_updates.append(ChangingDecimalWithColor( term, term.num_update_func, num_decimal_places = 4 )) brace.target.next_to(terms, LEFT) sum_term = DecimalNumber(0) sum_term.next_to(brace.target, LEFT) sum_term.set_color(RED) def sum_update(alpha): return sum([ (d1.number - d2.number)**2 for d1, d2 in zip(*self.decimal_groups) ]) term_updates.append(ChangingDecimal(sum_term, sum_update)) for update in term_updates: update.interpolate_mobject(0) target_vect = 0.1*np.random.random(10) target_vect[3] = 0.97 def generate_decimal_update_func(start, target): return lambda a : interpolate(start, target, a) update_decimals = [ ChangingDecimalWithColor( decimal, generate_decimal_update_func(decimal.number, t) ) for decimal, t in zip(decimals, target_vect) ] self.play( cost_group.scale, 0.5, cost_group.to_corner, UP+LEFT, MoveToTarget(brace), LaggedStartMap(GrowArrow, arrows), LaggedStartMap(FadeIn, terms), FadeIn(sum_term), Animation(decimals) ) self.play(*it.chain( update_decimals, term_updates, [ ApplyMethod(neuron.set_fill, None, t) for neuron, t in zip(neurons, target_vect) ] )) self.wait() self.play(LaggedStartMap(Indicate, decimals, rate_func = there_and_back)) self.wait() for update in update_decimals: update.rate_func = lambda a : smooth(1-a) self.play(*it.chain( update_decimals, term_updates, [neurons.restore] ), run_time = 2) self.wait() self.play( cost_group.restore, brace.restore, FadeOut(VGroup(terms, sum_term, arrows)), ) def average_over_all_training_data(self): image_group = self.image_group decimal_groups = self.decimal_groups random_neurons = self.network_mob.layers[-1].neurons desired_neurons = self.desired_last_layer.neurons wait_times = iter(it.chain( 4*[0.5], 4*[0.25], 8*[0.125], it.repeat(0.1) )) words = OldTexText("Average cost of \\\\ all training data...") words.set_color(BLUE) words.to_corner(UP+LEFT) self.play( Write(words, run_time = 1), ) training_data, validation_data, test_data = load_data_wrapper() for in_vect, out_vect in training_data[:self.n_training_examples]: random_v = np.random.random(10) new_decimal_groups = VGroup(*[ self.num_vect_to_decimals(v) for v in (random_v, out_vect) ]) for ds, nds in zip(decimal_groups, new_decimal_groups): for old_d, new_d in zip(ds, nds): new_d.replace(old_d) self.remove(decimal_groups) self.add(new_decimal_groups) decimal_groups = new_decimal_groups for pair in (random_v, random_neurons), (out_vect, desired_neurons): for n, neuron in zip(*pair): neuron.set_fill(opacity = n) new_image_group = MNistMobject(in_vect) new_image_group.replace(image_group) self.remove(image_group) self.add(new_image_group) image_group = new_image_group self.wait(next(wait_times)) #### def color_edge_randomly(self, edge, exp = 1): r = (2*np.random.random()-1)**exp r *= self.max_stroke_width pc, nc = self.positive_edge_color, self.negative_edge_color edge.set_stroke( color = pc if r > 0 else nc, width = abs(r), ) return edge def layer_to_num_vect(self, layer, n_terms = 10): return [ n.get_fill_opacity() for n in layer.neurons ][:n_terms] def num_vect_to_decimals(self, num_vect): return VGroup(*[ DecimalNumber(n).set_fill(opacity = 0.5*n + 0.5) for n in num_vect ]) def num_vect_to_column_vector(self, num_vect, height): decimals = VGroup(*[ DecimalNumber(n).set_fill(opacity = 0.5*n + 0.5) for n in num_vect ]) decimals.arrange(DOWN) decimals.set_height(height) lb, rb = brackets = OldTex("[]") brackets.scale(2) brackets.stretch_to_fit_height(height + SMALL_BUFF) lb.next_to(decimals, LEFT) rb.next_to(decimals, RIGHT) result = VGroup(brackets, decimals) result.brackets = brackets result.decimals = decimals return result class YellAtNetwork(PiCreatureScene, PreviewLearning): def setup(self): PiCreatureScene.setup(self) PreviewLearning.setup(self) def construct(self): randy = self.randy network_mob, eyes = self.get_network_and_eyes() three_vect = get_organized_images()[3][5] self.activate_network(three_vect) image = PixelsFromVect(three_vect) image.add(SurroundingRectangle(image, color = BLUE)) arrow = Arrow(LEFT, RIGHT, color = WHITE) layer = network_mob.layers[-1] layer.add(network_mob.output_labels) layer_copy = layer.deepcopy() for neuron in layer_copy.neurons: neuron.set_fill(WHITE, opacity = 0) layer_copy.neurons[3].set_fill(WHITE, 1) layer_copy.scale(1.5) desired = Group(image, arrow, layer_copy) desired.arrange(RIGHT) desired.to_edge(UP) q_marks = OldTex("???").set_color(RED) q_marks.next_to(arrow, UP, SMALL_BUFF) self.play( PiCreatureBubbleIntroduction( randy, "Bad network!", target_mode = "angry", look_at = eyes, run_time = 1, ), eyes.look_at_anim(randy.eyes) ) self.play(eyes.change_mode_anim("sad")) self.play(eyes.look_at_anim(3*DOWN + 3*RIGHT)) self.play( FadeIn(desired), RemovePiCreatureBubble( randy, target_mode = "sassy", look_at = desired ), eyes.look_at_anim(desired) ) self.play(eyes.blink_anim()) rect = SurroundingRectangle( VGroup(layer_copy.neurons[3], layer_copy[-1][3]), ) self.play(ShowCreation(rect)) layer_copy.add(rect) self.wait() self.play( layer.copy().replace, layer_copy, 1, Write(q_marks, run_time = 1), layer_copy.shift, 1.5*RIGHT, randy.change, "angry", eyes, ) self.play(eyes.look_at_anim(3*RIGHT + 3*RIGHT)) self.wait() #### def get_network_and_eyes(self): randy = self.randy network_mob = self.network_mob network_mob.scale(0.5) network_mob.next_to(randy, RIGHT, LARGE_BUFF) self.color_network_edges() eyes = Eyes(network_mob.edge_groups[1]) return network_mob, eyes def create_pi_creature(self): randy = self.randy = Randolph() randy.shift(3*LEFT).to_edge(DOWN) return randy class ThisIsVeryComplicated(TeacherStudentsScene): def construct(self): self.teacher_says( "Very complicated!", target_mode = "surprised", run_time = 1, ) self.play_student_changes(*3*["guilty"]) self.wait(2) class EmphasizeComplexityOfCostFunction(IntroduceCostFunction): CONFIG = { "stroke_width_exp" : 3, "n_examples" : 32, } def construct(self): self.setup_sides() self.show_network_as_a_function() self.show_cost_function() def setup_sides(self): v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) network_mob = self.network_mob network_mob.set_width(FRAME_X_RADIUS - 1) network_mob.to_corner(DOWN+LEFT) self.add(v_line) self.color_network_edges() def show_network_as_a_function(self): title = OldTexText("Neural network function") title.shift(FRAME_X_RADIUS*RIGHT/2) title.to_edge(UP) underline = Line(LEFT, RIGHT) underline.stretch_to_fit_width(title.get_width()) underline.next_to(title, DOWN, SMALL_BUFF) self.add(title, underline) words = self.get_function_description_words( "784 numbers (pixels)", "10 numbers", "13{,}002 weights/biases", ) input_words, output_words, parameter_words = words for word in words: self.add(word[0]) in_vect = get_organized_images()[7][8] activations = self.network.get_activation_of_all_layers(in_vect) image = MNistMobject(in_vect) image.set_height(1.5) image_label = OldTexText("Input") image_label.set_color(input_words[0].get_color()) image_label.next_to(image, UP, SMALL_BUFF) arrow = Arrow(LEFT, RIGHT, color = WHITE) arrow.next_to(image, RIGHT) output = self.num_vect_to_column_vector(activations[-1], 2) output.next_to(arrow, RIGHT) group = Group(image, image_label, arrow, output) group.next_to(self.network_mob, UP, 0, RIGHT) dot = Dot() dot.move_to(input_words.get_right()) dot.set_fill(opacity = 0.5) self.play(FadeIn(input_words[1], lag_ratio = 0.5)) self.play( dot.move_to, image, dot.set_fill, None, 0, FadeIn(image), FadeIn(image_label), ) self.activate_network(in_vect, GrowArrow(arrow), FadeIn(output), FadeIn(output_words[1]) ) self.wait() self.play( FadeIn(parameter_words[1]), self.get_edge_animation() ) self.wait(2) self.to_fade = group self.curr_words = words self.title = title self.underline = underline def show_cost_function(self): network_mob = self.network_mob to_fade = self.to_fade input_words, output_words, parameter_words = self.curr_words network_mob.generate_target() network_mob.target.scale(0.7) network_mob.target.to_edge(UP, buff = LARGE_BUFF) rect = SurroundingRectangle(network_mob.target, color = BLUE) network_label = OldTexText("Input") network_label.set_color(input_words[0].get_color()) network_label.next_to(rect, UP, SMALL_BUFF) new_output_word = OldTexText("1 number", "(the cost)") new_output_word[1].set_color(RED).scale(0.9) new_output_word.move_to(output_words[1], LEFT) new_output_word.shift(0.5*SMALL_BUFF*DOWN) new_parameter_word = OldTexText(""" \\begin{flushleft} Many, many, many \\\\ training examples \\end{flushleft} """).scale(0.9) new_parameter_word.move_to(parameter_words[1], UP+LEFT) new_title = OldTexText("Cost function") new_title.set_color(RED) new_title.move_to(self.title) arrow = Arrow(UP, DOWN, color = WHITE) arrow.next_to(rect, DOWN) cost = OldTexText("Cost: 5.4") cost.set_color(RED) cost.next_to(arrow, DOWN) training_data, validation_data, test_data = load_data_wrapper() training_examples = Group(*list(map( self.get_training_pair_mob, training_data[:self.n_examples] ))) training_examples.next_to(parameter_words, DOWN, buff = LARGE_BUFF) self.play( FadeOut(to_fade), FadeOut(input_words[1]), FadeOut(output_words[1]), MoveToTarget(network_mob), FadeIn(rect), FadeIn(network_label), Transform(self.title, new_title), self.underline.stretch_to_fit_width, new_title.get_width() ) self.play( ApplyMethod( parameter_words[1].move_to, input_words[1], LEFT, path_arc = np.pi, ), self.get_edge_animation() ) self.wait() self.play( GrowArrow(arrow), Write(cost, run_time = 1) ) self.play(Write(new_output_word, run_time = 1)) self.wait() self.play( FadeIn(new_parameter_word), FadeIn(training_examples[0]) ) self.wait(0.5) for last_ex, ex in zip(training_examples, training_examples[1:]): activations = self.network.get_activation_of_all_layers( ex.in_vect ) for i, a in enumerate(activations): layer = self.network_mob.layers[i] active_layer = self.network_mob.get_active_layer(i, a) Transform(layer, active_layer).update(1) self.remove(last_ex) self.add(ex) self.wait(0.25) #### def get_function_description_words(self, w1, w2, w3): input_words = OldTexText("Input:", w1) input_words[0].set_color(BLUE) output_words = OldTexText("Output:", w2) output_words[0].set_color(YELLOW) parameter_words = OldTexText("Parameters:", w3) parameter_words[0].set_color(GREEN) words = VGroup(input_words, output_words, parameter_words) words.arrange(DOWN, aligned_edge = LEFT) words.scale(0.9) words.next_to(ORIGIN, RIGHT) words.shift(UP) return words def get_training_pair_mob(self, data): in_vect, out_vect = data image = MNistMobject(in_vect) image.set_height(1) comma = OldTexText(",") comma.next_to(image, RIGHT, SMALL_BUFF, DOWN) output = OldTex(str(np.argmax(out_vect))) output.set_height(0.75) output.next_to(image, RIGHT, MED_SMALL_BUFF) lp, rp = parens = OldTexText("()") parens.scale(2) parens.stretch_to_fit_height(1.2*image.get_height()) lp.next_to(image, LEFT, SMALL_BUFF) rp.next_to(lp, RIGHT, buff = 2) result = Group(lp, image, comma, output, rp) result.in_vect = in_vect return result class NetworkGrowthMindset(YellAtNetwork): def construct(self): randy = self.pi_creature network_mob, eyes = self.get_network_and_eyes() eyes.look_at_anim(randy.eyes).update(1) edge_update = ContinualEdgeUpdate( network_mob, colors = [BLUE, RED] ) self.play( PiCreatureSays( randy, "Awful, just awful!", target_mode = "angry", look_at = eyes, run_time = 1, ), eyes.change_mode_anim("concerned_musician") ) self.wait() self.add(edge_update) self.pi_creature_says( "But we can do better! \\\\ Growth mindset!", target_mode = "hooray" ) self.play(eyes.change_mode_anim("happy")) self.wait(3) class SingleVariableCostFunction(GraphScene): CONFIG = { "x_axis_label" : "$w$", "y_axis_label" : "", "x_min" : -5, "x_max" : 7, "x_axis_width" : 12, "graph_origin" : 2.5*DOWN + LEFT, "tangent_line_color" : YELLOW, } def construct(self): self.reduce_full_function_to_single_variable() self.show_graph() self.find_exact_solution() self.make_function_more_complicated() self.take_steps() self.take_steps_based_on_slope() self.ball_rolling_down_hill() self.note_step_sizes() def reduce_full_function_to_single_variable(self): name = OldTexText("Cost function") cf1 = OldTex("C(", "w_1, w_2, \\dots, w_{13{,}002}", ")") cf2 = OldTex("C(", "w", ")") for cf in cf1, cf2: VGroup(cf[0], cf[2]).set_color(RED) big_brace, lil_brace = [ Brace(cf[1], DOWN) for cf in (cf1, cf2) ] big_brace_text = big_brace.get_text("Weights and biases") lil_brace_text = lil_brace.get_text("Single input") name.next_to(cf1, UP, LARGE_BUFF) name.set_color(RED) self.add(name, cf1) self.play( GrowFromCenter(big_brace), FadeIn(big_brace_text) ) self.wait() self.play( ReplacementTransform(big_brace, lil_brace), ReplacementTransform(big_brace_text, lil_brace_text), ReplacementTransform(cf1, cf2), ) # cf2.add_background_rectangle() lil_brace_text.add_background_rectangle() self.brace_group = VGroup(lil_brace, lil_brace_text) cf2.add(self.brace_group) self.function_label = cf2 self.to_fade = name def show_graph(self): function_label = self.function_label self.setup_axes() graph = self.get_graph( lambda x : 0.5*(x - 3)**2 + 2, color = RED ) self.play( FadeOut(self.to_fade), Write(self.axes), Animation(function_label), run_time = 1, ) self.play( function_label.next_to, self.input_to_graph_point(5, graph), RIGHT, ShowCreation(graph) ) self.wait() self.graph = graph def find_exact_solution(self): function_label = self.function_label graph = self.graph w_min = OldTex("w", "_{\\text{min}}", arg_separator = "") w_min.move_to(function_label[1], UP+LEFT) w_min[1].fade(1) x = 3 dot = Dot( self.input_to_graph_point(x, graph), color = YELLOW ) line = self.get_vertical_line_to_graph( x, graph, line_class = DashedLine, color = YELLOW ) formula = OldTex("\\frac{dC}{dw}(w) = 0") formula.next_to(dot, UP, buff = 2) formula.shift(LEFT) arrow = Arrow(formula.get_bottom(), dot.get_center()) self.play( w_min.shift, line.get_bottom() - w_min[0].get_top(), MED_SMALL_BUFF*DOWN, w_min.set_fill, WHITE, 1, ) self.play(ShowCreation(line)) self.play(DrawBorderThenFill(dot, run_time = 1)) self.wait() self.play(Write(formula, run_time = 2)) self.play(GrowArrow(arrow)) self.wait() self.dot = dot self.line = line self.w_min = w_min self.deriv_group = VGroup(formula, arrow) def make_function_more_complicated(self): dot = self.dot line = self.line w_min = self.w_min deriv_group = self.deriv_group function_label = self.function_label brace_group = function_label[-1] function_label.remove(brace_group) brace = Brace(deriv_group, UP) words = OldTexText("Sometimes \\\\ infeasible") words.next_to(deriv_group, UP) words.set_color(BLUE) words.next_to(brace, UP) graph = self.get_graph( lambda x : 0.05*((x+2)*(x-1)*(x-3))**2 + 2 + 0.3*(x-3), color = RED ) self.play( ReplacementTransform(self.graph, graph), function_label.shift, 2*UP+1.9*LEFT, FadeOut(brace_group), Animation(dot) ) self.graph = graph self.play( Write(words, run_time = 1), GrowFromCenter(brace) ) self.wait(2) self.play(FadeOut(VGroup(words, brace, deriv_group))) def take_steps(self): dot = self.dot line = self.line w_mob, min_mob = self.w_min graph = self.graph def update_line(line): x = self.x_axis.point_to_number(w_mob.get_center()) line.put_start_and_end_on_with_projection( self.coords_to_point(x, 0), self.input_to_graph_point(x, graph) ) return line line_update_anim = UpdateFromFunc(line, update_line) def update_dot(dot): dot.move_to(line.get_end()) return dot dot_update_anim = UpdateFromFunc(dot, update_dot) point = self.coords_to_point(2, 0) arrows = VGroup() q_marks = VGroup() for vect, color in (LEFT, BLUE), (RIGHT, GREEN): arrow = Arrow(ORIGIN, vect, buff = SMALL_BUFF) arrow.shift(point + SMALL_BUFF*UP) arrow.set_color(color) arrows.add(arrow) q_mark = OldTexText("?") q_mark.next_to(arrow, UP, buff = 0) q_mark.add_background_rectangle() q_marks.add(q_mark) self.play( w_mob.next_to, point, DOWN, FadeOut(min_mob), line_update_anim, dot_update_anim, ) self.wait() self.play(*it.chain( list(map(GrowArrow, arrows)), list(map(FadeIn, q_marks)), )) self.wait() self.arrow_group = VGroup(arrows, q_marks) self.line_update_anim = line_update_anim self.dot_update_anim = dot_update_anim self.w_mob = w_mob def take_steps_based_on_slope(self): arrows, q_marks = arrow_group = self.arrow_group line_update_anim = self.line_update_anim dot_update_anim = self.dot_update_anim dot = self.dot w_mob = self.w_mob graph = self.graph x = self.x_axis.point_to_number(w_mob.get_center()) tangent_line = self.get_tangent_line(x, arrows[0].get_color()) self.play( ShowCreation(tangent_line), Animation(dot), ) self.play(VGroup(arrows[1], q_marks).set_fill, None, 0) self.play( w_mob.shift, MED_SMALL_BUFF*LEFT, MaintainPositionRelativeTo(arrow_group, w_mob), line_update_anim, dot_update_anim, ) self.wait() new_x = 0.3 new_point = self.coords_to_point(new_x, 0) new_tangent_line = self.get_tangent_line( new_x, arrows[1].get_color() ) self.play( FadeOut(tangent_line), w_mob.next_to, new_point, DOWN, arrow_group.next_to, new_point, UP, SMALL_BUFF, arrow_group.set_fill, None, 1, dot_update_anim, line_update_anim, ) self.play( ShowCreation(new_tangent_line), Animation(dot), Animation(arrow_group), ) self.wait() self.play(VGroup(arrows[0], q_marks).set_fill, None, 0) self.play( w_mob.shift, MED_SMALL_BUFF*RIGHT, MaintainPositionRelativeTo(arrow_group, w_mob), line_update_anim, dot_update_anim, ) self.play( FadeOut(VGroup(new_tangent_line, arrow_group)), Animation(dot), ) self.wait() for x in 0.8, 1.1, 0.95: self.play( w_mob.next_to, self.coords_to_point(x, 0), DOWN, line_update_anim, dot_update_anim, ) self.wait() def ball_rolling_down_hill(self): ball = self.dot graph = self.graph point = VectorizedPoint(self.coords_to_point(-0.5, 0)) w_mob = self.w_mob def update_ball(ball): x = self.x_axis.point_to_number(ball.point.get_center()) graph_point = self.input_to_graph_point(x, graph) vect = rotate_vector(UP, self.angle_of_tangent(x, graph)) radius = ball.get_width()/2 ball.move_to(graph_point + radius*vect) return ball def update_point(point, dt): x = self.x_axis.point_to_number(point.get_center()) slope = self.slope_of_tangent(x, graph) if abs(slope) > 0.5: slope = 0.5 * slope / abs(slope) x -= slope*dt point.move_to(self.coords_to_point(x, 0)) ball.generate_target() ball.target.scale(2) ball.target.set_fill(opacity = 0) ball.target.set_stroke(BLUE, 3) ball.point = point ball.target.point = point update_ball(ball.target) self.play(MoveToTarget(ball)) self.play( point.move_to, w_mob, UpdateFromFunc(ball, update_ball), run_time = 3, ) self.wait(2) points = [ VectorizedPoint(self.coords_to_point(x, 0)) for x in np.linspace(-2.7, 3.7, 11) ] balls = VGroup() updates = [] for point in points: new_ball = ball.copy() new_ball.point = point balls.add(new_ball) updates += [ Mobject.add_updater(point, update_point), Mobject.add_updater(new_ball, update_ball) ] balls.set_color_by_gradient(BLUE, GREEN) self.play(ReplacementTransform(ball, balls)) self.add(*updates) self.wait(5) self.remove(*updates) self.remove(*points) self.play(FadeOut(balls)) def note_step_sizes(self): w_mob = self.w_mob line_update_anim = self.line_update_anim x = -0.5 target_x = 0.94 point = VectorizedPoint(self.coords_to_point(x, 0)) line = self.get_tangent_line(x) line.scale(0.5) def update_line(line): x = self.x_axis.point_to_number(point.get_center()) self.make_line_tangent(line, x) return line self.play( ShowCreation(line), w_mob.next_to, point, DOWN, line_update_anim, ) for n in range(6): x = self.x_axis.point_to_number(point.get_center()) new_x = interpolate(x, target_x, 0.5) self.play( point.move_to, self.coords_to_point(new_x, 0), MaintainPositionRelativeTo(w_mob, point), line_update_anim, UpdateFromFunc(line, update_line), ) self.wait(0.5) self.wait() ### def get_tangent_line(self, x, color = YELLOW): tangent_line = Line(LEFT, RIGHT).scale(3) tangent_line.set_color(color) self.make_line_tangent(tangent_line, x) return tangent_line def make_line_tangent(self, line, x): graph = self.graph line.rotate(self.angle_of_tangent(x, graph) - line.get_angle()) line.move_to(self.input_to_graph_point(x, graph)) class LocalVsGlobal(TeacherStudentsScene): def construct(self): self.teacher_says(""" Local minimum = Doable \\\\ Global minimum = Crazy hard """) self.play_student_changes(*["pondering"]*3) self.wait(2) class TwoVariableInputSpace(Scene): def construct(self): self.add_plane() self.ask_about_direction() self.show_gradient() def add_plane(self): plane = NumberPlane( x_radius = FRAME_X_RADIUS/2 ) plane.add_coordinates() name = OldTexText("Input space") name.add_background_rectangle() name.next_to(plane.get_corner(UP+LEFT), DOWN+RIGHT) x, y = list(map(Tex, ["x", "y"])) x.next_to(plane.coords_to_point(3.25, 0), UP, SMALL_BUFF) y.next_to(plane.coords_to_point(0, 3.6), RIGHT, SMALL_BUFF) self.play( *list(map(Write, [plane, name, x, y])), run_time = 1 ) self.wait() self.plane = plane def ask_about_direction(self): point = self.plane.coords_to_point(2, 1) dot = Dot(point, color = YELLOW) dot.save_state() dot.move_to(FRAME_Y_RADIUS*UP + FRAME_X_RADIUS*RIGHT/2) dot.fade(1) arrows = VGroup(*[ Arrow(ORIGIN, vect).shift(point) for vect in compass_directions(8) ]) arrows.set_color(WHITE) question = OldTexText( "Which direction decreases \\\\", "$C(x, y)$", "most quickly?" ) question.scale(0.7) question.set_color(YELLOW) question.set_color_by_tex("C(x, y)", RED) question.add_background_rectangle() question.next_to(arrows, LEFT) self.play(dot.restore) self.play( FadeIn(question), LaggedStartMap(GrowArrow, arrows) ) self.wait() self.arrows = arrows self.dot = dot self.question = question def show_gradient(self): arrows = self.arrows dot = self.dot question = self.question arrow = arrows[3] new_arrow = Arrow( dot.get_center(), arrow.get_end(), buff = 0, color = GREEN ) new_arrow.set_color(GREEN) arrow.save_state() gradient = OldTex("\\nabla C(x, y)") gradient.add_background_rectangle() gradient.next_to(arrow.get_end(), UP, SMALL_BUFF) gradient_words = OldTexText( "``Gradient'', the direction\\\\ of", "steepest increase" ) gradient_words.scale(0.7) gradient_words[-1].set_color(GREEN) gradient_words.next_to(gradient, UP, SMALL_BUFF) gradient_words.add_background_rectangle(opacity = 1) gradient_words.shift(LEFT) anti_arrow = new_arrow.copy() anti_arrow.rotate(np.pi, about_point = dot.get_center()) anti_arrow.set_color(RED) self.play( Transform(arrow, new_arrow), Animation(dot), *[FadeOut(a) for a in arrows if a is not arrow] ) self.play(FadeIn(gradient)) self.play(Write(gradient_words, run_time = 2)) self.wait(2) self.play( arrow.fade, ReplacementTransform( arrow.copy(), anti_arrow ) ) self.wait(2) class CostSurface(ExternallyAnimatedScene): pass class KhanAcademyMVCWrapper(PiCreatureScene): def construct(self): screen = ScreenRectangle(height = 5) screen.to_corner(UP+LEFT) morty = self.pi_creature self.play( ShowCreation(screen), morty.change, "raise_right_hand", ) self.wait(3) self.play(morty.change, "happy", screen) self.wait(5) class KAGradientPreview(ExternallyAnimatedScene): pass class GradientDescentAlgorithm(Scene): def construct(self): words = VGroup( OldTexText("Compute", "$\\nabla C$"), OldTexText("Small step in", "$-\\nabla C$", "direction"), OldTexText("Repeat."), ) words.arrange(DOWN, aligned_edge = LEFT) words.set_width(FRAME_WIDTH - 1) words.to_corner(DOWN+LEFT) for word in words[:2]: word[1].set_color(RED) for word in words: self.play(Write(word, run_time = 1)) self.wait() class GradientDescentName(Scene): def construct(self): words = OldTexText("Gradient descent") words.set_color(BLUE) words.set_width(FRAME_WIDTH - 1) words.to_edge(DOWN) self.play(Write(words, run_time = 2)) self.wait() class ShowFullCostFunctionGradient(PreviewLearning): def construct(self): self.organize_weights_as_column_vector() self.show_gradient() def organize_weights_as_column_vector(self): network_mob = self.network_mob edges = VGroup(*it.chain(*network_mob.edge_groups)) layers = VGroup(*network_mob.layers) layers.add(network_mob.output_labels) self.color_network_edges() nums = [2.25, -1.57, 1.98, -1.16, 3.82, 1.21] decimals = VGroup(*[ DecimalNumber(num).set_color( BLUE_D if num > 0 else RED ) for num in nums ]) dots = OldTex("\\vdots") decimals.submobjects.insert(3, dots) decimals.arrange(DOWN) decimals.shift(2*LEFT + 0.5*DOWN) lb, rb = brackets = OldTex("\\big[", "\\big]") brackets.scale(2) brackets.stretch_to_fit_height(1.2*decimals.get_height()) lb.next_to(decimals, LEFT, SMALL_BUFF) rb.next_to(decimals, RIGHT, SMALL_BUFF) column_vect = VGroup(lb, decimals, rb) edges_target = VGroup(*it.chain( decimals[:3], [dots]*(len(edges) - 6), decimals[-3:] )) words = OldTexText("$13{,}002$ weights and biases") words.next_to(column_vect, UP) lhs = OldTex("\\vec{\\textbf{W}}", "=") lhs[0].set_color(YELLOW) lhs.next_to(column_vect, LEFT) self.play( FadeOut(layers), edges.space_out_submobjects, 1.2, ) self.play( ReplacementTransform( edges, edges_target, run_time = 2, lag_ratio = 0.5 ), LaggedStartMap(FadeIn, words), ) self.play(*list(map(Write, [lb, rb, lhs])), run_time = 1) self.wait() self.column_vect = column_vect def show_gradient(self): column_vect = self.column_vect lhs = OldTex( "-", "\\nabla", "C(", "\\vec{\\textbf{W}}", ")", "=" ) lhs.shift(2*RIGHT) lhs.set_color_by_tex("W", YELLOW) old_decimals = VGroup(*[m for m in column_vect[1] if isinstance(m, DecimalNumber)]) new_decimals = VGroup() new_nums = [0.18, 0.45, -0.51, 0.4, -0.32, 0.82] for decimal, new_num in zip(old_decimals, new_nums): new_decimal = DecimalNumber(new_num) new_decimal.set_color(BLUE if new_num > 0 else RED_B) new_decimal.move_to(decimal) new_decimals.add(new_decimal) rhs = VGroup( column_vect[0].copy(), new_decimals, column_vect[2].copy(), ) rhs.to_edge(RIGHT, buff = 1.75) lhs.next_to(rhs, LEFT) words = OldTexText("How to nudge all \\\\ weights and biases") words.next_to(rhs, UP) self.play(Write(VGroup(lhs, rhs))) self.play(FadeIn(words)) for od, nd in zip(old_decimals, new_decimals): nd = nd.deepcopy() od_num = od.number nd_num = nd.number self.play( nd.move_to, od, nd.shift, 1.5*RIGHT ) self.play( Transform( nd, VectorizedPoint(od.get_center()), lag_ratio = 0.5, remover = True ), ChangingDecimal( od, lambda a : interpolate(od_num, od_num+nd_num, a) ) ) self.wait() class DotsInsert(Scene): def construct(self): dots = OldTex("\\vdots") dots.set_height(FRAME_HEIGHT - 1) self.add(dots) class HowMinimizingCostMeansBetterTrainingPerformance(IntroduceCostFunction): def construct(self): IntroduceCostFunction.construct(self) self.improve_last_layer() def improve_last_layer(self): decimals = self.decimal_groups[0] neurons = self.network_mob.layers[-1].neurons values = [d.number for d in decimals] target_values = 0.1*np.random.random(10) target_values[3] = 0.98 words = OldTexText("Minimize cost $\\dots$") words.next_to(decimals, UP, MED_LARGE_BUFF) words.set_color(YELLOW) # words.shift(LEFT) def generate_update(n1, n2): return lambda a : interpolate(n1, n2, a) updates = [ generate_update(n1, n2) for n1, n2 in zip(values, target_values) ] self.play(LaggedStartMap(FadeIn, words, run_time = 1)) self.play(*[ ChangingDecimal(d, update) for d, update in zip(decimals, updates) ] + [ UpdateFromFunc( d, lambda mob: mob.set_fill( interpolate_color(BLACK, WHITE, 0.5+0.5*mob.number), opacity = 1 ) ) for d in decimals ] + [ ApplyMethod(neuron.set_fill, WHITE, target_value) for neuron, target_value in zip(neurons, target_values) ], run_time = 3) self.wait() ### def average_over_all_training_data(self): pass #So that IntroduceCostFunction.construct doesn't do this class CostSurfaceSteps(ExternallyAnimatedScene): pass class ConfusedAboutHighDimension(TeacherStudentsScene): def construct(self): self.student_says( "13{,}002-dimensional \\\\ nudge?", target_mode = "confused" ) self.play_student_changes(*["confused"]*3) self.wait(2) self.teacher_thinks( "", bubble_config = {"width" : 6, "height" : 4}, added_anims = [self.change_students(*["plain"]*3)] ) self.zoom_in_on_thought_bubble() class NonSpatialGradientIntuition(Scene): CONFIG = { "w_color" : YELLOW, "positive_color" : BLUE, "negative_color" : RED, "vect_height" : FRAME_Y_RADIUS - MED_LARGE_BUFF, "text_scale_value" : 0.7, } def construct(self): self.add_vector() self.add_gradient() self.show_sign_interpretation() self.show_magnitude_interpretation() def add_vector(self): lhs = OldTex("\\vec{\\textbf{W}}", "=") lhs[0].set_color(self.w_color) lhs.to_edge(LEFT) ws = VGroup(*[ VGroup(OldTex(tex)) for tex in it.chain( ["w_%d"%d for d in range(3)], ["\\vdots"], ["w_{13{,}00%d}"%d for d in range(3)] ) ]) ws.set_color(self.w_color) ws.arrange(DOWN) lb, rb = brackets = OldTex("\\big[", "\\big]").scale(2) brackets.stretch_to_fit_height(1.2*ws.get_height()) lb.next_to(ws, LEFT) rb.next_to(ws, RIGHT) vect = VGroup(lb, ws, rb) vect.set_height(self.vect_height) vect.to_edge(UP).shift(2*LEFT) lhs.next_to(vect, LEFT) self.add(lhs, vect) self.vect = vect self.top_lhs = lhs def add_gradient(self): lb, ws, rb = vect = self.vect ws = VGroup(*ws) dots = ws[len(ws)/2] ws.remove(dots) lhs = OldTex( "-\\nabla", "C(", "\\vec{\\textbf{W}}", ")", "=" ) lhs.next_to(vect, RIGHT, LARGE_BUFF) lhs.set_color_by_tex("W", self.w_color) decimals = VGroup() nums = [0.31, 0.03, -1.25, 0.78, -0.37, 0.16] for num, w in zip(nums, ws): decimal = DecimalNumber(num) decimal.scale(self.text_scale_value) if num > 0: decimal.set_color(self.positive_color) else: decimal.set_color(self.negative_color) decimal.move_to(w) decimals.add(decimal) new_dots = dots.copy() grad_content = VGroup(*it.chain( decimals[:3], new_dots, decimals[3:] )) grad_vect = VGroup(lb.copy(), grad_content, rb.copy()) VGroup(grad_vect[0], grad_vect[-1]).space_out_submobjects(0.8) grad_vect.set_height(self.vect_height) grad_vect.next_to(self.vect, DOWN) lhs.next_to(grad_vect, LEFT) brace = Brace(grad_vect, RIGHT) words = brace.get_text("Example gradient") self.wait() self.play( ReplacementTransform(self.top_lhs.copy(), lhs), ReplacementTransform(self.vect.copy(), grad_vect), GrowFromCenter(brace), FadeIn(words) ) self.wait() self.play(FadeOut(VGroup(brace, words))) self.ws = ws self.grad_lhs = lhs self.grad_vect = grad_vect self.decimals = decimals def show_sign_interpretation(self): ws = self.ws.copy() decimals = self.decimals direction_phrases = VGroup() for w, decimal in zip(ws, decimals): if decimal.number > 0: verb = "increase" color = self.positive_color else: verb = "decrease" color = self.negative_color phrase = OldTexText("should", verb) phrase.scale(self.text_scale_value) phrase.set_color_by_tex(verb, color) w.generate_target() group = VGroup(w.target, phrase) group.arrange(RIGHT) w.target.shift(0.7*SMALL_BUFF*DOWN) group.move_to(decimal.get_center() + RIGHT, LEFT) direction_phrases.add(phrase) self.play( LaggedStartMap(MoveToTarget, ws), LaggedStartMap(FadeIn, direction_phrases) ) self.wait(2) self.direction_phrases = direction_phrases self.ws = ws def show_magnitude_interpretation(self): direction_phrases = self.direction_phrases ws = self.ws decimals = self.decimals magnitude_words = VGroup() rects = VGroup() for phrase, decimal in zip(direction_phrases, decimals): if abs(decimal.number) < 0.2: adj = "a little" color = interpolate_color(BLACK, WHITE, 0.5) elif abs(decimal.number) < 0.5: adj = "somewhat" color = GREY_B else: adj = "a lot" color = WHITE words = OldTexText(adj) words.scale(self.text_scale_value) words.set_color(color) words.next_to(phrase, RIGHT, SMALL_BUFF) magnitude_words.add(words) rect = SurroundingRectangle( VGroup(*decimal[-4:]), buff = SMALL_BUFF, color = GREY_B ) rect.target = words rects.add(rect) self.play(LaggedStartMap(ShowCreation, rects)) self.play(LaggedStartMap(MoveToTarget, rects)) self.wait(2) class SomeConnectionsMatterMoreThanOthers(PreviewLearning): def setup(self): np.random.seed(1) PreviewLearning.setup(self) self.color_network_edges() ex_in = get_organized_images()[3][4] image = MNistMobject(ex_in) image.to_corner(UP+LEFT) self.add(image) self.ex_in = ex_in def construct(self): self.activate_network(self.ex_in) self.fade_edges() self.show_important_connection() self.show_unimportant_connection() def fade_edges(self): edges = VGroup(*it.chain(*self.network_mob.edge_groups)) self.play(*[ ApplyMethod( edge.set_stroke, BLACK, 0, rate_func = lambda a : 0.5*smooth(a) ) for edge in edges ]) def show_important_connection(self): layers = self.network_mob.layers edge = self.get_edge(2, 3) edge.set_stroke(YELLOW, 4) words = OldTexText("This weight \\\\ matters a lot") words.next_to(layers[-1], UP).to_edge(UP) words.set_color(YELLOW) arrow = Arrow(words.get_bottom(), edge.get_center()) self.play( ShowCreation(edge), GrowArrow(arrow), FadeIn(words) ) self.wait() def show_unimportant_connection(self): color = TEAL edge = self.get_edge(11, 6) edge.set_stroke(color, 5) words = OldTexText("Who even cares \\\\ about this weight?") words.next_to(self.network_mob.layers[-1], DOWN) words.to_edge(DOWN) words.set_color(color) arrow = Arrow(words.get_top(), edge.get_center(), buff = SMALL_BUFF) arrow.set_color(color) self.play( ShowCreation(edge), GrowArrow(arrow), FadeIn(words) ) self.wait() ### def get_edge(self, i1, i2): layers = self.network_mob.layers n1 = layers[-2].neurons[i1] n2 = layers[-1].neurons[i2] return self.network_mob.get_edge(n1, n2) class SpinningVectorWithLabel(Scene): def construct(self): plane = NumberPlane( x_unit_size = 2, y_unit_size = 2, ) plane.add_coordinates() self.add(plane) vector = Vector(2*RIGHT) label = get_decimal_vector([-1, -1], with_dots = False) label.add_to_back(BackgroundRectangle(label)) label.next_to(vector.get_end(), UP+RIGHT) label.decimals.set_fill(opacity = 0) decimals = label.decimals.copy() decimals.set_fill(WHITE, 1) cd1 = ChangingDecimal( decimals[0], lambda a : np.cos(vector.get_angle()), tracked_mobject = label.decimals[0], ) cd2 = ChangingDecimal( decimals[1], lambda a : np.sin(vector.get_angle()), tracked_mobject = label.decimals[1], ) self.play( Rotate( vector, 0.999*np.pi, in_place = False, run_time = 8, rate_func = there_and_back ), UpdateFromFunc( label, lambda m : m.next_to(vector.get_end(), UP+RIGHT) ), cd1, cd2, ) self.wait() class TwoGradientInterpretationsIn2D(Scene): def construct(self): self.force_skipping() self.setup_plane() self.add_function_definitions() self.point_out_direction() self.point_out_relative_importance() self.wiggle_in_neighborhood() def setup_plane(self): plane = NumberPlane() plane.add_coordinates() self.add(plane) self.plane = plane def add_function_definitions(self): func = OldTex( "C(", "x, y", ")", "=", "\\frac{3}{2}x^2", "+", "\\frac{1}{2}y^2", ) func.shift(FRAME_X_RADIUS*LEFT/2).to_edge(UP) grad = OldTex("\\nabla", "C(", "1, 1", ")", "=") vect = OldTex( "\\left[\\begin{array}{c} 3 \\\\ 1 \\end{array}\\right]" ) vect.next_to(grad, RIGHT, SMALL_BUFF) grad_group = VGroup(grad, vect) grad_group.next_to(ORIGIN, RIGHT).to_edge(UP, buff = MED_SMALL_BUFF) for mob in grad, vect, func: mob.add_background_rectangle() mob.background_rectangle.scale(1.1) self.play(Write(func, run_time = 1)) self.play(Write(grad_group, run_time = 2)) self.wait() self.func = func self.grad = grad self.vect = vect def point_out_direction(self): coords = self.grad.get_part_by_tex("1, 1").copy() vect = self.vect[1].copy() coords.set_color(YELLOW) vect.set_color(GREEN) dot = Dot(self.plane.coords_to_point(1, 1)) dot.set_color(coords.get_color()) arrow = Arrow( self.plane.coords_to_point(1, 1), self.plane.coords_to_point(4, 2), buff = 0, color = vect.get_color() ) words = OldTexText("Direction of \\\\ steepest ascent") words.add_background_rectangle() words.next_to(ORIGIN, DOWN) words.rotate(arrow.get_angle()) words.shift(arrow.get_center()) self.play(DrawBorderThenFill(coords, run_time = 1)) self.play(ReplacementTransform(coords.copy(), dot)) self.play(DrawBorderThenFill(vect, run_time = 1)) self.play( ReplacementTransform(vect.copy(), arrow), Animation(dot) ) self.play(Write(words)) self.wait() self.remove(vect) self.vect[1].set_color(vect.get_color()) self.remove(coords) self.grad.get_part_by_tex("1, 1").set_color(coords.get_color()) self.steepest_words = words self.dot = dot def point_out_relative_importance(self): func = self.func grad_group = VGroup(self.grad, self.vect) x_part = func.get_part_by_tex("x^2") y_part = func.get_part_by_tex("y^2") self.play(func.shift, 1.5*DOWN) x_rect = SurroundingRectangle(x_part, color = YELLOW) y_rect = SurroundingRectangle(y_part, color = TEAL) x_words = OldTexText("$x$ has 3 times \\\\ the impact...") x_words.set_color(x_rect.get_color()) x_words.add_background_rectangle() x_words.next_to(x_rect, UP) # x_words.to_edge(LEFT) y_words = OldTexText("...as $y$") y_words.set_color(y_rect.get_color()) y_words.add_background_rectangle() y_words.next_to(y_rect, DOWN) self.play( Write(x_words, run_time = 2), ShowCreation(x_rect) ) self.wait() self.play( Write(y_words, run_time = 1), ShowCreation(y_rect) ) self.wait(2) def wiggle_in_neighborhood(self): dot = self.dot steepest_words = self.steepest_words neighborhood = Circle( fill_color = BLUE, fill_opacity = 0.25, stroke_width = 0, radius = 0.5, ) neighborhood.move_to(dot) self.revert_to_original_skipping_status() self.play( FadeOut(steepest_words), GrowFromCenter(neighborhood) ) self.wait() for vect in RIGHT, UP, 0.3*(3*RIGHT + UP): self.play( dot.shift, 0.5*vect, rate_func = lambda t : wiggle(t, 4), run_time = 3, ) self.wait() class ParaboloidGraph(ExternallyAnimatedScene): pass class TODOInsertEmphasizeComplexityOfCostFunctionCopy(TODOStub): CONFIG = { "message" : "Insert EmphasizeComplexityOfCostFunction copy" } class GradientNudging(PreviewLearning): CONFIG = { "n_steps" : 10, "n_decimals" : 8, } def construct(self): self.setup_network_mob() self.add_gradient() self.change_weights_repeatedly() def setup_network_mob(self): network_mob = self.network_mob self.color_network_edges() network_mob.scale(0.7) network_mob.to_corner(DOWN+RIGHT) def add_gradient(self): lhs = OldTex( "-", "\\nabla", "C(", "\\dots", ")", "=" ) brace = Brace(lhs.get_part_by_tex("dots"), DOWN) words = brace.get_text("All weights \\\\ and biases") words.scale(0.8, about_point = words.get_top()) np.random.seed(3) nums = 4*(np.random.random(self.n_decimals)-0.5) vect = get_decimal_vector(nums) vect.next_to(lhs, RIGHT) group = VGroup(lhs, brace, words, vect) group.to_corner(UP+LEFT) self.add(*group) self.set_variables_as_attrs( grad_lhs = lhs, grad_vect = vect, grad_arg_words = words, grad_arg_brace = brace ) def change_weights_repeatedly(self): network_mob = self.network_mob edges = VGroup(*reversed(list( it.chain(*network_mob.edge_groups) ))) decimals = self.grad_vect.decimals words = OldTexText( "Change by some small\\\\", "multiple of $-\\nabla C(\\dots)$" ) words.next_to(network_mob, UP).to_edge(UP) arrows = VGroup(*[ Arrow( words.get_bottom(), edge_group.get_top(), color = WHITE ) for edge_group in network_mob.edge_groups ]) mover = VGroup(*decimals.family_members_with_points()).copy() # mover.set_fill(opacity = 0) mover.set_stroke(width = 0) target = VGroup(*self.network_mob.edge_groups.family_members_with_points()).copy() target.set_fill(opacity = 0) ApplyMethod(target.set_stroke, YELLOW, 2).update(0.3) self.play( ReplacementTransform(mover, target), FadeIn(words), LaggedStartMap(GrowArrow, arrows, run_time = 1) ) self.play(FadeOut(target)) self.play(self.get_edge_change_anim(edges)) self.play(*self.get_decimal_change_anims(decimals)) for x in range(self.n_steps): self.play(self.get_edge_change_anim(edges)) self.play(*self.get_decimal_change_anims(decimals)) self.wait() ### def get_edge_change_anim(self, edges): target_nums = 6*(np.random.random(len(edges))-0.5) edges.generate_target() for edge, target_num in zip(edges.target, target_nums): curr_num = edge.get_stroke_width() if Color(edge.get_stroke_color()) == Color(self.negative_edge_color): curr_num *= -1 new_num = interpolate(curr_num, target_num, 0.2) if new_num > 0: new_color = self.positive_edge_color else: new_color = self.negative_edge_color edge.set_stroke(new_color, abs(new_num)) edge.rotate(np.pi) return MoveToTarget( edges, lag_ratio = 0.5, run_time = 1.5 ) def get_decimal_change_anims(self, decimals): words = OldTexText("Recompute \\\\ gradient") words.next_to(decimals, DOWN, MED_LARGE_BUFF) def wrf(t): if t < 1./3: return smooth(3*t) elif t < 2./3: return 1 else: return smooth(3 - 3*t) changes = 0.2*(np.random.random(len(decimals))-0.5) def generate_change_func(x, dx): return lambda a : interpolate(x, x+dx, a) return [ ChangingDecimal( decimal, generate_change_func(decimal.number, change) ) for decimal, change in zip(decimals, changes) ] + [ FadeIn(words, rate_func = wrf, run_time = 1.5, remover = True) ] class BackPropWrapper(PiCreatureScene): def construct(self): morty = self.pi_creature screen = ScreenRectangle(height = 5) screen.to_corner(UP+LEFT) screen.shift(MED_LARGE_BUFF*DOWN) title = OldTexText("Backpropagation", "(next video)") title.next_to(screen, UP) self.play( morty.change, "raise_right_hand", screen, ShowCreation(screen) ) self.play(Write(title[0], run_time = 1)) self.wait() self.play(Write(title[1], run_time = 1)) self.play(morty.change, "happy", screen) self.wait(5) class TODOInsertCostSurfaceSteps(TODOStub): CONFIG = { "message" : "Insert CostSurfaceSteps" } class ContinuouslyRangingNeuron(PreviewLearning): def construct(self): self.color_network_edges() network_mob = self.network_mob network_mob.scale(0.8) network_mob.to_edge(DOWN) neuron = self.network_mob.layers[2].neurons[6] decimal = DecimalNumber(0) decimal.set_width(0.8*neuron.get_width()) decimal.move_to(neuron) decimal.generate_target() neuron.generate_target() group = VGroup(neuron.target, decimal.target) group.set_height(1) group.next_to(network_mob, UP) decimal.set_fill(opacity = 0) def update_decimal_color(decimal): if neuron.get_fill_opacity() > 0.8: decimal.set_color(BLACK) else: decimal.set_color(WHITE) decimal_color_anim = UpdateFromFunc(decimal, update_decimal_color) self.play(*list(map(MoveToTarget, [neuron, decimal]))) for x in 0.7, 0.35, 0.97, 0.23, 0.54: curr_num = neuron.get_fill_opacity() self.play( neuron.set_fill, None, x, ChangingDecimal( decimal, lambda a : interpolate(curr_num, x, a) ), decimal_color_anim ) self.wait() class AskHowItDoes(TeacherStudentsScene): def construct(self): self.student_says( "How well \\\\ does it do?", index = 0 ) self.wait(5) class TestPerformance(PreviewLearning): CONFIG = { "n_examples" : 300, "time_per_example" : 0.1, "wrong_wait_time" : 0.5, "stroke_width_exp" : 2, "decimal_kwargs" : { "num_decimal_places" : 3, } } def construct(self): self.setup_network_mob() self.init_testing_data() self.add_title() self.add_fraction() self.run_through_examples() def setup_network_mob(self): self.network_mob.set_height(5) self.network_mob.to_corner(DOWN+LEFT) self.network_mob.to_edge(DOWN, buff = MED_SMALL_BUFF) def init_testing_data(self): training_data, validation_data, test_data = load_data_wrapper() self.test_data = iter(test_data[:self.n_examples]) def add_title(self): title = OldTexText("Testing data") title.to_edge(UP, buff = MED_SMALL_BUFF) title.to_edge(LEFT, buff = LARGE_BUFF) self.add(title) self.title = title def add_fraction(self): self.n_correct = 0 self.total = 0 self.decimal = DecimalNumber(0, **self.decimal_kwargs) word_frac = OldTex( "{\\text{Number correct}", "\\over", "\\text{total}}", "=", ) word_frac[0].set_color(GREEN) self.frac = self.get_frac() self.equals = OldTex("=") fracs = VGroup( word_frac, self.frac, self.equals, self.decimal ) fracs.arrange(RIGHT) fracs.to_corner(UP+RIGHT, buff = LARGE_BUFF) self.add(fracs) def run_through_examples(self): title = self.title rects = [ SurroundingRectangle( VGroup(neuron, label), buff = 0.5*SMALL_BUFF ) for neuron, label in zip( self.network_mob.layers[-1].neurons, self.network_mob.output_labels ) ] rect_wrong = OldTexText("Wrong!") rect_wrong.set_color(RED) num_wrong = rect_wrong.copy() arrow = Arrow(LEFT, RIGHT, color = WHITE) guess_word = OldTexText("Guess") self.add(arrow, guess_word) from tqdm import tqdm as ProgressDisplay for test_in, test_out in ProgressDisplay(list(self.test_data)): self.total += 1 activations = self.activate_layers(test_in) choice = np.argmax(activations[-1]) image = MNistMobject(test_in) image.set_height(1.5) choice_mob = OldTex(str(choice)) choice_mob.scale(1.5) group = VGroup(image, arrow, choice_mob) group.arrange(RIGHT) group.shift( self.title.get_bottom()+MED_SMALL_BUFF*DOWN -\ image.get_top() ) self.add(image, choice_mob) guess_word.next_to(arrow, UP, SMALL_BUFF) rect = rects[choice] self.add(rect) correct = (choice == test_out) if correct: self.n_correct += 1 else: rect_wrong.next_to(rect, RIGHT) num_wrong.next_to(choice_mob, DOWN) self.add(rect_wrong, num_wrong) new_frac = self.get_frac() new_frac.shift( self.frac[1].get_left() - \ new_frac[1].get_left() ) self.remove(self.frac) self.add(new_frac) self.frac = new_frac self.equals.next_to(new_frac, RIGHT) new_decimal = DecimalNumber( float(self.n_correct)/self.total, **self.decimal_kwargs ) new_decimal.next_to(self.equals, RIGHT) self.remove(self.decimal) self.add(new_decimal) self.decimal = new_decimal self.wait(self.time_per_example) if not correct: self.wait(self.wrong_wait_time) self.remove(rect, rect_wrong, num_wrong, image, choice_mob) self.add(rect, image, choice_mob) ### def add_network(self): self.network_mob = MNistNetworkMobject(**self.network_mob_config) self.network_mob.scale(0.8) self.network_mob.to_edge(DOWN) self.network = self.network_mob.neural_network self.add(self.network_mob) self.color_network_edges() def get_frac(self): frac = OldTex("{%d"%self.n_correct, "\\over", "%d}"%self.total) frac[0].set_color(GREEN) return frac def activate_layers(self, test_in): activations = self.network.get_activation_of_all_layers(test_in) layers = self.network_mob.layers for layer, activation in zip(layers, activations)[1:]: for neuron, a in zip(layer.neurons, activation): neuron.set_fill(opacity = a) return activations class ReactToPerformance(TeacherStudentsScene): def construct(self): title = VGroup( OldTexText("Play with network structure"), Arrow(LEFT, RIGHT, color = WHITE), OldTexText("98\\%", "testing accuracy") ) title.arrange(RIGHT) title.to_edge(UP) title[-1][0].set_color(GREEN) self.play(Write(title, run_time = 2)) last_words = OldTexText( "State of the art \\\\ is", "99.79\\%" ) last_words[-1].set_color(GREEN) self.teacher_says( "That's pretty", "good!", target_mode = "surprised", run_time = 1 ) self.play_student_changes(*["hooray"]*3) self.wait() self.teacher_says(last_words, target_mode = "hesitant") self.play_student_changes( *["pondering"]*3, look_at = self.teacher.bubble ) self.wait() class NoticeWhereItMessesUp(TeacherStudentsScene): def construct(self): self.teacher_says( "Look where it \\\\ messes up", run_time = 1 ) self.wait(2) class WrongExamples(TestPerformance): CONFIG = { "time_per_example" : 0 } class TODOBreakUpNineByPatterns(TODOStub): CONFIG = { "message" : "Insert the scene with 9 \\\\ broken up by patterns" } class NotAtAll(TeacherStudentsScene, PreviewLearning): def setup(self): TeacherStudentsScene.setup(self) PreviewLearning.setup(self) def construct(self): words = OldTexText("Well...\\\\", "not at all!") words[1].set_color(BLACK) network_mob = self.network_mob network_mob.set_height(4) network_mob.to_corner(UP+LEFT) self.add(network_mob) self.color_network_edges() self.teacher_says( words, target_mode = "guilty", run_time = 1 ) self.play_student_changes(*["sassy"]*3) self.play( self.teacher.change, "concerned_musician", words[1].set_color, WHITE ) self.wait(2) class InterpretFirstWeightMatrixRows(TestPerformance): CONFIG = { "stroke_width_exp" : 1, } def construct(self): self.slide_network_to_side() self.prepare_pixel_arrays() self.show_all_pixel_array() def slide_network_to_side(self): network_mob = self.network_mob network_mob.generate_target() to_fade = VGroup(*it.chain( network_mob.edge_groups[1:], network_mob.layers[2:], network_mob.output_labels )) to_keep = VGroup(*it.chain( network_mob.edge_groups[0], network_mob.layers[:2] )) shift_val = FRAME_X_RADIUS*LEFT + MED_LARGE_BUFF*RIGHT - \ to_keep.get_left() self.play( to_fade.shift, shift_val, to_fade.fade, 1, to_keep.shift, shift_val ) self.remove(to_fade) def prepare_pixel_arrays(self): pixel_arrays = VGroup() w_matrix = self.network.weights[0] for row in w_matrix: max_val = np.max(np.abs(row)) shades = np.array(row)/max_val pixel_array = PixelsFromVect(np.zeros(row.size)) for pixel, shade in zip(pixel_array, shades): if shade > 0: color = self.positive_edge_color else: color = self.negative_edge_color pixel.set_fill(color, opacity = abs(shade)**(0.3)) pixel_arrays.add(pixel_array) pixel_arrays.arrange_in_grid(buff = MED_LARGE_BUFF) pixel_arrays.set_height(FRAME_HEIGHT - 2.5) pixel_arrays.to_corner(DOWN+RIGHT) for pixel_array in pixel_arrays: rect = SurroundingRectangle(pixel_array) rect.set_color(WHITE) pixel_array.rect = rect words = OldTexText("What second layer \\\\ neurons look for") words.next_to(pixel_arrays, UP).to_edge(UP) self.pixel_arrays = pixel_arrays self.words = words def show_all_pixel_array(self): edges = self.network_mob.edge_groups[0] neurons = self.network_mob.layers[1].neurons edges.remove(neurons[0].edges_in) self.play( VGroup(*neurons[1:]).set_stroke, None, 0.5, FadeIn(self.words), neurons[0].edges_in.set_stroke, None, 2, *[ ApplyMethod(edge.set_stroke, None, 0.25) for edge in edges if edge not in neurons[0].edges_in ] ) self.wait() last_neuron = None for neuron, pixel_array in zip(neurons, self.pixel_arrays): if last_neuron: self.play( last_neuron.edges_in.set_stroke, None, 0.25, last_neuron.set_stroke, None, 0.5, neuron.set_stroke, None, 3, neuron.edges_in.set_stroke, None, 2, ) self.play(ReplacementTransform( neuron.edges_in.copy().set_fill(opacity = 0), pixel_array, )) self.play(ShowCreation(pixel_array.rect)) last_neuron = neuron class InputRandomData(TestPerformance): def construct(self): self.color_network_edges() self.show_random_image() self.show_expected_outcomes() self.feed_in_random_data() self.network_speaks() def show_random_image(self): np.random.seed(4) rand_vect = np.random.random(28*28) image = PixelsFromVect(rand_vect) image.to_edge(LEFT) image.shift(UP) rect = SurroundingRectangle(image) arrow = Arrow( rect.get_top(), self.network_mob.layers[0].neurons.get_top(), path_arc = -2*np.pi/3, ) arrow.tip.set_stroke(width = 3) self.play( ShowCreation(rect), LaggedStartMap( DrawBorderThenFill, image, stroke_width = 0.5 ) ) self.play(ShowCreation(arrow)) self.wait() self.image = image self.rand_vect = rand_vect self.image_rect = rect self.arrow = arrow def show_expected_outcomes(self): neurons = self.network_mob.layers[-1].neurons words = OldTexText("What might you expect?") words.to_corner(UP+RIGHT) arrow = Arrow( words.get_bottom(), neurons.get_top(), color = WHITE ) self.play( Write(words, run_time = 1), GrowArrow(arrow) ) vects = [np.random.random(10) for x in range(2)] vects += [np.zeros(10), 0.4*np.ones(10)] for vect in vects: neurons.generate_target() for neuron, o in zip(neurons, vect): neuron.generate_target() neuron.target.set_fill(WHITE, opacity = o) self.play(LaggedStartMap( MoveToTarget, neurons, run_time = 1 )) self.wait() self.play(FadeOut(VGroup(words, arrow))) def feed_in_random_data(self): neurons = self.network_mob.layers[0].neurons rand_vect = self.rand_vect image = self.image.copy() output_labels = self.network_mob.output_labels opacities = it.chain(rand_vect[:8], rand_vect[-8:]) target_neurons = neurons.copy() for n, o in zip(target_neurons, opacities): n.set_fill(WHITE, opacity = o) point = VectorizedPoint(neurons.get_center()) image.target = VGroup(*it.chain( target_neurons[:len(neurons)/2], [point]*(len(image) - len(neurons)), target_neurons[-len(neurons)/2:] )) self.play(MoveToTarget( image, run_time = 2, lag_ratio = 0.5 )) self.activate_network(rand_vect, FadeOut(image)) ### React ### neurons = self.network_mob.layers[-1].neurons choice = np.argmax([n.get_fill_opacity() for n in neurons]) rect = SurroundingRectangle(VGroup( neurons[choice], output_labels[choice] )) word = OldTexText("What?!?") word.set_color(YELLOW) word.next_to(rect, RIGHT) self.play(ShowCreation(rect)) self.play(Write(word, run_time = 1)) self.wait() self.network_mob.add(rect, word) self.choice = choice def network_speaks(self): network_mob = self.network_mob network_mob.generate_target(use_deepcopy = True) network_mob.target.scale(0.7) network_mob.target.to_edge(DOWN) eyes = Eyes( network_mob.target.edge_groups[1], height = 0.45, ) eyes.shift(0.5*SMALL_BUFF*UP) bubble = SpeechBubble( height = 3, width = 5, direction = LEFT ) bubble.pin_to(network_mob.target.edge_groups[-1]) bubble.write("Looks like a \\\\ %d to me!"%self.choice) self.play( MoveToTarget(network_mob), FadeIn(eyes) ) self.play(eyes.look_at_anim(self.image)) self.play( ShowCreation(bubble), Write(bubble.content, run_time = 1) ) self.play(eyes.blink_anim()) self.wait() class CannotDraw(PreviewLearning): def construct(self): network_mob = self.network_mob self.color_network_edges() network_mob.scale(0.5) network_mob.to_corner(DOWN+RIGHT) eyes = Eyes(network_mob.edge_groups[1]) eyes.shift(SMALL_BUFF*UP) self.add(eyes) bubble = SpeechBubble( height = 3, width = 4, direction = RIGHT ) bubble.pin_to(network_mob.edge_groups[0]) bubble.write("Uh...I'm really \\\\ more of a multiple \\\\ choice guy") randy = Randolph() randy.to_corner(DOWN+LEFT) eyes.look_at_anim(randy.eyes).update(1) self.play(PiCreatureSays( randy, "Draw a \\\\ 5 for me", look_at = eyes, run_time = 1 )) self.play(eyes.change_mode_anim("concerned_musician")) self.play( ShowCreation(bubble), Write(bubble.content), eyes.look_at_anim(network_mob.get_corner(DOWN+RIGHT)) ) self.play(eyes.blink_anim()) self.play(Blink(randy)) self.wait() class TODOShowCostFunctionDef(TODOStub): CONFIG = { "message" : "Insert cost function averaging portion" } class TODOBreakUpNineByPatterns2(TODOBreakUpNineByPatterns): pass class SomethingToImproveUpon(PiCreatureScene, TestPerformance): CONFIG = { "n_examples" : 15, "time_per_example" : 0.15, } def setup(self): self.setup_bases() self.color_network_edges() self.network_mob.to_edge(LEFT) edge_update = ContinualEdgeUpdate( self.network_mob, colors = [BLUE, BLUE, RED] ) edge_update.internal_time = 1 self.add(edge_update) def construct(self): self.show_path() self.old_news() self.recognizing_digits() self.hidden_layers() def show_path(self): network_mob = self.network_mob morty = self.pi_creature line = Line(LEFT, RIGHT).scale(5) line.shift(UP) dots = VGroup(*[ Dot(line.point_from_proportion(a)) for a in np.linspace(0, 1, 5) ]) dots.set_color_by_gradient(BLUE, YELLOW) path = VGroup(line, dots) words = OldTexText("This series") words.next_to(line, DOWN) self.play( network_mob.scale, 0.25, network_mob.next_to, path.get_right(), UP, ShowCreation(path), Write(words, run_time = 1), morty.change, "sassy", ) self.wait(2) self.play( ApplyMethod( network_mob.next_to, path.get_left(), UP, path_arc = np.pi/2, ), Rotate(path, np.pi, in_place = True), morty.change, "raise_right_hand" ) self.wait(3) self.line = line self.path = path self.this_series = words def old_news(self): network_mob = self.network_mob morty = self.pi_creature line = self.line words = OldTexText("Old technology!") words.to_edge(UP) arrow = Arrow(words.get_left(), network_mob.get_right()) name = OldTexText("``Multilayer perceptron''") name.next_to(words, DOWN) cnn = OldTexText("Convolutional NN") lstm = OldTexText("LSTM") cnn.next_to(line.get_center(), UP) lstm.next_to(line.get_right(), UP) modern_variants = VGroup(cnn, lstm) modern_variants.set_color(YELLOW) self.play( Write(words, run_time = 1), GrowArrow(arrow), morty.change_mode, "hesitant" ) self.play(Write(name)) self.wait() self.play( FadeIn(modern_variants), FadeOut(VGroup(words, arrow, name)), morty.change, "thinking" ) self.wait(2) self.modern_variants = modern_variants def recognizing_digits(self): training_data, validation_data, test_data = load_data_wrapper() for v_in, choice in validation_data[:self.n_examples]: image = MNistMobject(v_in) image.set_height(1) choice = OldTex(str(choice)) choice.scale(2) arrow = Vector(RIGHT, color = WHITE) group = Group(image, arrow, choice) group.arrange(RIGHT) group.next_to(self.line, DOWN, LARGE_BUFF) group.to_edge(LEFT, buff = LARGE_BUFF) self.add(group) self.wait(self.time_per_example) self.remove(group) def hidden_layers(self): morty = self.pi_creature network_mob = self.network_mob self.play( network_mob.scale, 4, network_mob.center, network_mob.to_edge, LEFT, FadeOut(VGroup(self.path, self.modern_variants, self.this_series)), morty.change, "confused", ) hidden_layers = network_mob.layers[1:3] rects = VGroup(*list(map(SurroundingRectangle, hidden_layers))) np.random.seed(0) self.play(ShowCreation(rects)) self.activate_network(np.random.random(28*28)) self.wait(3) class ShiftingFocus(Scene): def construct(self): how, do, networks, learn = words = OldTexText( "How", "do", "neural networks", "learn?" ) networks.set_color(BLUE) cross = Cross(networks) viewers = OldTexText("video viewers") viewers.move_to(networks) viewers.set_color(YELLOW) cap_do = OldTexText("Do") cap_do.move_to(do, DOWN+LEFT) self.play(Write(words, run_time = 1)) self.wait() self.play(ShowCreation(cross)) self.play( VGroup(networks, cross).shift, DOWN, Write(viewers, run_time = 1) ) self.wait(2) self.play( FadeOut(how), Transform(do, cap_do) ) self.wait(2) class PauseAndPonder(TeacherStudentsScene): def construct(self): screen = ScreenRectangle(height = 3.5) screen.to_edge(UP+LEFT) self.teacher_says( "Pause and \\\\ ponder!", target_mode = "hooray", run_time = 1 ) self.play( ShowCreation(screen), self.change_students(*["pondering"]*3), ) self.wait(6) class ConvolutionalNetworkPreview(Scene): def construct(self): vect = get_organized_images()[9][0] image = PixelsFromVect(vect) image.set_stroke(width = 1) image.set_height(FRAME_HEIGHT - 1) self.add(image) kernels = [ PixelsFromVect(np.zeros(16)) for x in range(2) ] for i, pixel in enumerate(kernels[0]): x = i%4 y = i//4 if x == y: pixel.set_fill(BLUE, 1) elif abs(x - y) == 1: pixel.set_fill(BLUE, 0.5) for i, pixel in enumerate(kernels[1]): x = i%4 if x == 1: pixel.set_fill(BLUE, 1) elif x == 2: pixel.set_fill(RED, 1) for kernel in kernels: kernel.set_stroke(width = 1) kernel.scale(image[0].get_height()/kernel[0].get_height()) kernel.add(SurroundingRectangle( kernel, color = YELLOW, buff = 0 )) self.add(kernel) for i, pixel in enumerate(image): x = i%28 y = i//28 if x > 24 or y > 24: continue kernel.move_to(pixel, UP+LEFT) self.wait(self.frame_duration) self.remove(kernel) class RandomlyLabeledImageData(Scene): CONFIG = { "image_label_pairs" : [ ("lion", "Lion"), ("Newton", "Genius"), ("Fork", "Fork"), ("Trilobite", "Trilobite"), ("Puppy", "Puppy"), ("Astrolabe", "Astrolabe"), ("Adele", "Songbird of \\\\ our generation"), ("Cow", "Cow"), ("Sculling", "Sculling"), ("Pierre_de_Fermat", "Tease"), ] } def construct(self): groups = Group() labels = VGroup() for i, (image_name, label_name) in enumerate(self.image_label_pairs): x = i//5 y = i%5 group = self.get_training_group(image_name, label_name) group.shift(4.5*LEFT + x*FRAME_X_RADIUS*RIGHT) group.shift(3*UP + 1.5*y*DOWN) groups.add(group) labels.add(group[-1]) permutation = list(range(len(labels))) while any(np.arange(len(labels)) == permutation): random.shuffle(permutation) for label, i in zip(labels, permutation): label.generate_target() label.target.move_to(labels[i], LEFT) label.target.set_color(YELLOW) self.play(LaggedStartMap( FadeIn, groups, run_time = 3, lag_ratio = 0.3, )) self.wait() self.play(LaggedStartMap( MoveToTarget, labels, run_time = 4, lag_ratio = 0.5, path_arc = np.pi/3, )) self.wait() def get_training_group(self, image_name, label_name): arrow = Vector(RIGHT, color = WHITE) image = ImageMobject(image_name) image.set_height(1.3) image.next_to(arrow, LEFT) label = OldTexText(label_name) label.next_to(arrow, RIGHT) group = Group(image, arrow, label) return group class TrainOnImages(PreviewLearning, RandomlyLabeledImageData): CONFIG = { "layer_sizes" : [17, 17, 17, 17, 17, 17], "network_mob_config" : { "brace_for_large_layers" : False, "include_output_labels" : False, }, } def construct(self): self.setup_network_mob() image_names, label_names = list(zip(*self.image_label_pairs)) label_names = list(label_names) random.shuffle(label_names) groups = [ self.get_training_group(image_name, label_name) for image_name, label_name in zip(image_names, label_names) ] edges = VGroup(*reversed(list( it.chain(*self.network_mob.edge_groups) ))) for group in groups: for edge in edges: edge.generate_target() edge.target.rotate(np.pi) alt_edge = random.choice(edges) color = alt_edge.get_stroke_color() width = alt_edge.get_stroke_width() edge.target.set_stroke(color, width) group.to_edge(UP) self.add(group) self.play(LaggedStartMap( MoveToTarget, edges, lag_ratio = 0.4, run_time = 2, )) self.remove(group) def setup_network_mob(self): self.network_mob.set_height(5) self.network_mob.to_edge(DOWN) self.color_network_edges() class IntroduceDeepNetwork(Scene): def construct(self): pass class AskNetworkAboutMemorizing(YellAtNetwork): def construct(self): randy = self.pi_creature network_mob, eyes = self.get_network_and_eyes() eyes.look_at_anim(randy.eyes).update(1) self.add(eyes) self.pi_creature_says( "Are you just \\\\ memorizing?", target_mode = "sassy", look_at = eyes, run_time = 2 ) self.wait() self.play(eyes.change_mode_anim("sad")) self.play(eyes.blink_anim()) self.wait() class CompareLearningCurves(GraphScene): CONFIG = { "x_min" : 0, "y_axis_label" : "Value of \\\\ cost function", "x_axis_label" : "Number of gradient \\\\ descent steps", "graph_origin" : 2*DOWN + 3.5*LEFT, } def construct(self): self.setup_axes() self.x_axis_label_mob.to_edge(DOWN) self.y_axis_label_mob.to_edge(LEFT) self.y_axis_label_mob.set_color(RED) slow_decrease = self.get_graph( lambda x : 9 - 0.25*x ) faster_decrease = self.get_graph( lambda x : 4.3*sigmoid(5*(2-x)) + 3 + 0.5*ReLU(3-x) ) for decrease, p in (slow_decrease, 0.2), (faster_decrease, 0.07): y_vals = decrease.get_anchors()[:,1] y_vals -= np.cumsum(p*np.random.random(len(y_vals))) decrease.make_jagged() faster_decrease.move_to(slow_decrease, UP+LEFT) slow_label = OldTexText("Randomly-labeled data") slow_label.set_color(slow_decrease.get_color()) slow_label.to_corner(UP+RIGHT) slow_line = Line(ORIGIN, RIGHT) slow_line.set_stroke(slow_decrease.get_color(), 5) slow_line.next_to(slow_label, LEFT) fast_label = OldTexText("Properly-labeled data") fast_label.set_color(faster_decrease.get_color()) fast_label.next_to(slow_label, DOWN) fast_line = slow_line.copy() fast_line.set_color(faster_decrease.get_color()) fast_line.next_to(fast_label, LEFT) self.play(FadeIn(slow_label), ShowCreation(slow_line)) self.play(ShowCreation( slow_decrease, run_time = 12, rate_func=linear, )) self.play(FadeIn(fast_label), ShowCreation(fast_line)) self.play(ShowCreation( faster_decrease, run_time = 12, rate_func=linear, )) self.wait() #### line = Line( self.coords_to_point(1, 2), self.coords_to_point(3, 9), ) rect = Rectangle() rect.set_fill(YELLOW, 0.3) rect.set_stroke(width = 0) rect.replace(line, stretch = True) words = OldTexText("Learns structured data more quickly") words.set_color(YELLOW) words.next_to(rect, DOWN) words.add_background_rectangle() self.play(DrawBorderThenFill(rect)) self.play(Write(words)) self.wait() class ManyMinimaWords(Scene): def construct(self): words = OldTexText( "Many local minima,\\\\", "roughly equal quality" ) words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) self.play(Write(words)) self.wait() class NNPart2PatreonThanks(PatreonThanks): CONFIG = { "specific_patrons" : [ "Desmos", "Burt Humburg", "CrypticSwarm", "Juan Benet", "Ali Yahya", "William", "Mayank M. Mehrotra", "Lukas Biewald", "Samantha D. Suplee", "Yana Chernobilsky", "Kaustuv DeBiswas", "Kathryn Schmiedicke", "Yu Jun", "Dave Nicponski", "Damion Kistler", "Markus Persson", "Yoni Nazarathy", "Ed Kellett", "Joseph John Cox", "Luc Ritchie", "Eric Chow", "Mathias Jansson", "Pedro Perez Sanchez", "David Clark", "Michael Gardner", "Harsev Singh", "Mads Elvheim", "Erik Sundell", "Xueqi Li", "David G. Stork", "Tianyu Ge", "Ted Suzman", "Linh Tran", "Andrew Busey", "John Haley", "Ankalagon", "Eric Lavault", "Boris Veselinovich", "Julian Pulgarin", "Jeff Linse", "Cooper Jones", "Ryan Dahl", "Mark Govea", "Robert Teed", "Jason Hise", "Meshal Alshammari", "Bernd Sing", "James Thornton", "Mustafa Mahdi", "Mathew Bramson", "Jerry Ling", "Vecht", "Shimin Kuang", "Rish Kundalia", "Achille Brighton", "Ripta Pasay", ] }
videos_3b1b/once_useful_constructs/counting.py
from manimlib.animation.creation import ShowCreation from manimlib.animation.fading import FadeIn from manimlib.animation.transform import MoveToTarget from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.geometry import Arrow from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Dot from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene import itertools as it class CountingScene(Scene): CONFIG = { "digit_place_colors": [YELLOW, MAROON_B, RED, GREEN, BLUE, PURPLE_D], "counting_dot_starting_position": (FRAME_X_RADIUS - 1) * RIGHT + (FRAME_Y_RADIUS - 1) * UP, "count_dot_starting_radius": 0.5, "dot_configuration_height": 2, "ones_configuration_location": UP + 2 * RIGHT, "num_scale_factor": 2, "num_start_location": 2 * DOWN, } def setup(self): self.dots = VGroup() self.number = 0 self.max_place = 0 self.number_mob = VGroup(OldTex(str(self.number))) self.number_mob.scale(self.num_scale_factor) self.number_mob.shift(self.num_start_location) self.dot_templates = [] self.dot_template_iterators = [] self.curr_configurations = [] self.arrows = VGroup() self.add(self.number_mob) def get_template_configuration(self, place): # This should probably be replaced for non-base-10 counting scenes down_right = (0.5) * RIGHT + (np.sqrt(3) / 2) * DOWN result = [] for down_right_steps in range(5): for left_steps in range(down_right_steps): result.append( down_right_steps * down_right + left_steps * LEFT ) return reversed(result[:self.get_place_max(place)]) def get_dot_template(self, place): # This should be replaced for non-base-10 counting scenes dots = VGroup(*[ Dot( point, radius=0.25, fill_opacity=0, stroke_width=2, stroke_color=WHITE, ) for point in self.get_template_configuration(place) ]) dots.set_height(self.dot_configuration_height) return dots def add_configuration(self): new_template = self.get_dot_template(len(self.dot_templates)) new_template.move_to(self.ones_configuration_location) left_vect = (new_template.get_width() + LARGE_BUFF) * LEFT new_template.shift( left_vect * len(self.dot_templates) ) self.dot_templates.append(new_template) self.dot_template_iterators.append( it.cycle(new_template) ) self.curr_configurations.append(VGroup()) def count(self, max_val, run_time_per_anim=1): for x in range(max_val): self.increment(run_time_per_anim) def increment(self, run_time_per_anim=1): moving_dot = Dot( self.counting_dot_starting_position, radius=self.count_dot_starting_radius, color=self.digit_place_colors[0], ) moving_dot.generate_target() moving_dot.set_fill(opacity=0) kwargs = { "run_time": run_time_per_anim } continue_rolling_over = True first_move = True place = 0 while continue_rolling_over: added_anims = [] if first_move: added_anims += self.get_digit_increment_animations() first_move = False moving_dot.target.replace( next(self.dot_template_iterators[place]) ) self.play(MoveToTarget(moving_dot), *added_anims, **kwargs) self.curr_configurations[place].add(moving_dot) if len(self.curr_configurations[place].split()) == self.get_place_max(place): full_configuration = self.curr_configurations[place] self.curr_configurations[place] = VGroup() place += 1 center = full_configuration.get_center_of_mass() radius = 0.6 * max( full_configuration.get_width(), full_configuration.get_height(), ) circle = Circle( radius=radius, stroke_width=0, fill_color=self.digit_place_colors[place], fill_opacity=0.5, ) circle.move_to(center) moving_dot = VGroup(circle, full_configuration) moving_dot.generate_target() moving_dot[0].set_fill(opacity=0) else: continue_rolling_over = False def get_digit_increment_animations(self): result = [] self.number += 1 is_next_digit = self.is_next_digit() if is_next_digit: self.max_place += 1 new_number_mob = self.get_number_mob(self.number) new_number_mob.move_to(self.number_mob, RIGHT) if is_next_digit: self.add_configuration() place = len(new_number_mob.split()) - 1 result.append(FadeIn(self.dot_templates[place])) arrow = Arrow( new_number_mob[place].get_top(), self.dot_templates[place].get_bottom(), color=self.digit_place_colors[place] ) self.arrows.add(arrow) result.append(ShowCreation(arrow)) result.append(Transform( self.number_mob, new_number_mob, lag_ratio=0.5 )) return result def get_number_mob(self, num): result = VGroup() place = 0 max_place = self.max_place while place < max_place: digit = OldTex(str(self.get_place_num(num, place))) if place >= len(self.digit_place_colors): self.digit_place_colors += self.digit_place_colors digit.set_color(self.digit_place_colors[place]) digit.scale(self.num_scale_factor) digit.next_to(result, LEFT, buff=SMALL_BUFF, aligned_edge=DOWN) result.add(digit) place += 1 return result def is_next_digit(self): return False def get_place_num(self, num, place): return 0 def get_place_max(self, place): return 0 class PowerCounter(CountingScene): def is_next_digit(self): number = self.number while number > 1: if number % self.base != 0: return False number /= self.base return True def get_place_max(self, place): return self.base def get_place_num(self, num, place): return (num / (self.base ** place)) % self.base class CountInDecimal(PowerCounter): CONFIG = { "base": 10, } def construct(self): for x in range(11): self.increment() for x in range(85): self.increment(0.25) for x in range(20): self.increment() class CountInTernary(PowerCounter): CONFIG = { "base": 3, "dot_configuration_height": 1, "ones_configuration_location": UP + 4 * RIGHT } def construct(self): self.count(27) # def get_template_configuration(self, place): # return [ORIGIN, UP] class CountInBinaryTo256(PowerCounter): CONFIG = { "base": 2, "dot_configuration_height": 1, "ones_configuration_location": UP + 5 * RIGHT } def construct(self): self.count(128, 0.3) def get_template_configuration(self, place): return [ORIGIN, UP] class FactorialBase(CountingScene): CONFIG = { "dot_configuration_height": 1, "ones_configuration_location": UP + 4 * RIGHT } def construct(self): self.count(30, 0.4) def is_next_digit(self): return self.number == self.factorial(self.max_place + 1) def get_place_max(self, place): return place + 2 def get_place_num(self, num, place): return (num / self.factorial(place + 1)) % self.get_place_max(place) def factorial(self, n): if (n == 1): return 1 else: return n * self.factorial(n - 1)
videos_3b1b/once_useful_constructs/graph_theory.py
from functools import reduce import itertools as it import operator as op import numpy as np from manimlib.constants import * from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import there_and_back from manimlib.utils.space_ops import center_of_mass class Graph(): def __init__(self): # List of points in R^3 # vertices = [] # List of pairs of indices of vertices # edges = [] # List of tuples of indices of vertices. The last should # be a cycle whose interior is the entire graph, and when # regions are computed its complement will be taken. # region_cycles = [] self.construct() def construct(self): pass def __str__(self): return self.__class__.__name__ class CubeGraph(Graph): """ 5 7 12 03 4 6 """ def construct(self): self.vertices = [ (x, y, 0) for r in (1, 2) for x, y in it.product([-r, r], [-r, r]) ] self.edges = [ (0, 1), (0, 2), (3, 1), (3, 2), (4, 5), (4, 6), (7, 5), (7, 6), (0, 4), (1, 5), (2, 6), (3, 7), ] self.region_cycles = [ [0, 2, 3, 1], [4, 0, 1, 5], [4, 6, 2, 0], [6, 7, 3, 2], [7, 5, 1, 3], [4, 6, 7, 5], # By convention, last region will be "outside" ] class SampleGraph(Graph): """ 4 2 3 8 0 1 7 5 6 """ def construct(self): self.vertices = [ (0, 0, 0), (2, 0, 0), (1, 2, 0), (3, 2, 0), (-1, 2, 0), (-2, -2, 0), (2, -2, 0), (4, -1, 0), (6, 2, 0), ] self.edges = [ (0, 1), (1, 2), (1, 3), (3, 2), (2, 4), (4, 0), (2, 0), (4, 5), (0, 5), (1, 5), (5, 6), (6, 7), (7, 1), (7, 8), (8, 3), ] self.region_cycles = [ (0, 1, 2), (1, 3, 2), (2, 4, 0), (4, 5, 0), (0, 5, 1), (1, 5, 6, 7), (1, 7, 8, 3), (4, 5, 6, 7, 8, 3, 2), ] class OctohedronGraph(Graph): """ 3 1 0 2 4 5 """ def construct(self): self.vertices = [ (r * np.cos(angle), r * np.sin(angle) - 1, 0) for r, s in [(1, 0), (3, 3)] for angle in (np.pi / 6) * np.array([s, 4 + s, 8 + s]) ] self.edges = [ (0, 1), (1, 2), (2, 0), (5, 0), (0, 3), (3, 5), (3, 1), (3, 4), (1, 4), (4, 2), (4, 5), (5, 2), ] self.region_cycles = [ (0, 1, 2), (0, 5, 3), (3, 1, 0), (3, 4, 1), (1, 4, 2), (2, 4, 5), (5, 0, 2), (3, 4, 5), ] class CompleteGraph(Graph): def __init__(self, num_vertices, radius=3): self.num_vertices = num_vertices self.radius = radius Graph.__init__(self) def construct(self): self.vertices = [ (self.radius * np.cos(theta), self.radius * np.sin(theta), 0) for x in range(self.num_vertices) for theta in [2 * np.pi * x / self.num_vertices] ] self.edges = it.combinations(list(range(self.num_vertices)), 2) def __str__(self): return Graph.__str__(self) + str(self.num_vertices) class DiscreteGraphScene(Scene): args_list = [ (CubeGraph(),), (SampleGraph(),), (OctohedronGraph(),), ] @staticmethod def args_to_string(*args): return str(args[0]) def __init__(self, graph, *args, **kwargs): # See CubeGraph() above for format of graph self.graph = graph Scene.__init__(self, *args, **kwargs) def construct(self): self._points = list(map(np.array, self.graph.vertices)) self.vertices = self.dots = [Dot(p) for p in self._points] self.edges = self.lines = [ Line(self._points[i], self._points[j]) for i, j in self.graph.edges ] self.add(*self.dots + self.edges) def generate_regions(self): regions = [ self.region_from_cycle(cycle) for cycle in self.graph.region_cycles ] regions[-1].complement() # Outer region painted outwardly... self.regions = regions def region_from_cycle(self, cycle): point_pairs = [ [ self._points[cycle[i]], self._points[cycle[(i + 1) % len(cycle)]] ] for i in range(len(cycle)) ] return region_from_line_boundary( *point_pairs, shape=self.shape ) def draw_vertices(self, **kwargs): self.clear() self.play(ShowCreation(Mobject(*self.vertices), **kwargs)) def draw_edges(self): self.play(*[ ShowCreation(edge, run_time=1.0) for edge in self.edges ]) def accent_vertices(self, **kwargs): self.remove(*self.vertices) start = Mobject(*self.vertices) end = Mobject(*[ Dot(point, radius=3 * Dot.DEFAULT_RADIUS, color="lightgreen") for point in self._points ]) self.play(Transform( start, end, rate_func=there_and_back, **kwargs )) self.remove(start) self.add(*self.vertices) def replace_vertices_with(self, mobject): mobject.center() diameter = max(mobject.get_height(), mobject.get_width()) self.play(*[ CounterclockwiseTransform( vertex, mobject.copy().shift(vertex.get_center()) ) for vertex in self.vertices ] + [ ApplyMethod( edge.scale, (edge.get_length() - diameter) / edge.get_length() ) for edge in self.edges ]) def annotate_edges(self, mobject, fade_in=True, **kwargs): angles = list(map(np.arctan, list(map(Line.get_slope, self.edges)))) self.edge_annotations = [ mobject.copy().rotate(angle).move_to(edge.get_center()) for angle, edge in zip(angles, self.edges) ] if fade_in: self.play(*[ FadeIn(ann, **kwargs) for ann in self.edge_annotations ]) def trace_cycle(self, cycle=None, color="yellow", run_time=2.0): if cycle is None: cycle = self.graph.region_cycles[0] next_in_cycle = it.cycle(cycle) next(next_in_cycle) # jump one ahead self.traced_cycle = Mobject(*[ Line(self._points[i], self._points[j]).set_color(color) for i, j in zip(cycle, next_in_cycle) ]) self.play( ShowCreation(self.traced_cycle), run_time=run_time ) def generate_spanning_tree(self, root=0, color="yellow"): self.spanning_tree_root = 0 pairs = deepcopy(self.graph.edges) pairs += [tuple(reversed(pair)) for pair in pairs] self.spanning_tree_index_pairs = [] curr = root spanned_vertices = set([curr]) to_check = set([curr]) while len(to_check) > 0: curr = to_check.pop() for pair in pairs: if pair[0] == curr and pair[1] not in spanned_vertices: self.spanning_tree_index_pairs.append(pair) spanned_vertices.add(pair[1]) to_check.add(pair[1]) self.spanning_tree = Mobject(*[ Line( self._points[pair[0]], self._points[pair[1]] ).set_color(color) for pair in self.spanning_tree_index_pairs ]) def generate_treeified_spanning_tree(self): bottom = -FRAME_Y_RADIUS + 1 x_sep = 1 y_sep = 2 if not hasattr(self, "spanning_tree"): self.generate_spanning_tree() root = self.spanning_tree_root color = self.spanning_tree.get_color() indices = list(range(len(self._points))) # Build dicts parent_of = dict([ tuple(reversed(pair)) for pair in self.spanning_tree_index_pairs ]) children_of = dict([(index, []) for index in indices]) for child in parent_of: children_of[parent_of[child]].append(child) x_coord_of = {root: 0} y_coord_of = {root: bottom} # width to allocate to a given node, computed as # the maximum number of decendents in a single generation, # minus 1, multiplied by x_sep width_of = {} for index in indices: next_generation = children_of[index] curr_max = max(1, len(next_generation)) while next_generation != []: next_generation = reduce(op.add, [ children_of[node] for node in next_generation ]) curr_max = max(curr_max, len(next_generation)) width_of[index] = x_sep * (curr_max - 1) to_process = [root] while to_process != []: index = to_process.pop() if index not in y_coord_of: y_coord_of[index] = y_sep + y_coord_of[parent_of[index]] children = children_of[index] left_hand = x_coord_of[index] - width_of[index] / 2.0 for child in children: x_coord_of[child] = left_hand + width_of[child] / 2.0 left_hand += width_of[child] + x_sep to_process += children new_points = [ np.array([ x_coord_of[index], y_coord_of[index], 0 ]) for index in indices ] self.treeified_spanning_tree = Mobject(*[ Line(new_points[i], new_points[j]).set_color(color) for i, j in self.spanning_tree_index_pairs ]) def generate_dual_graph(self): point_at_infinity = np.array([np.inf] * 3) cycles = self.graph.region_cycles self.dual_points = [ center_of_mass([ self._points[index] for index in cycle ]) for cycle in cycles ] self.dual_vertices = [ Dot(point).set_color("green") for point in self.dual_points ] self.dual_vertices[-1] = Circle().scale(FRAME_X_RADIUS + FRAME_Y_RADIUS) self.dual_points[-1] = point_at_infinity self.dual_edges = [] for pair in self.graph.edges: dual_point_pair = [] for cycle in cycles: if not (pair[0] in cycle and pair[1] in cycle): continue index1, index2 = cycle.index(pair[0]), cycle.index(pair[1]) if abs(index1 - index2) in [1, len(cycle) - 1]: dual_point_pair.append( self.dual_points[cycles.index(cycle)] ) assert(len(dual_point_pair) == 2) for i in 0, 1: if all(dual_point_pair[i] == point_at_infinity): new_point = np.array(dual_point_pair[1 - i]) vect = center_of_mass([ self._points[pair[0]], self._points[pair[1]] ]) - new_point new_point += FRAME_X_RADIUS * vect / get_norm(vect) dual_point_pair[i] = new_point self.dual_edges.append( Line(*dual_point_pair).set_color() )
videos_3b1b/once_useful_constructs/light.py
from traceback import * from scipy.spatial import ConvexHull from manimlib.animation.composition import LaggedStartMap from manimlib.animation.fading import FadeIn from manimlib.animation.fading import FadeOut from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.geometry import AnnularSector from manimlib.mobject.geometry import Annulus from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.mobject.types.vectorized_mobject import VectorizedPoint from manimlib.utils.space_ops import angle_between_vectors from manimlib.utils.space_ops import project_along_vector from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import z_to_vector LIGHT_COLOR = YELLOW SHADOW_COLOR = BLACK SWITCH_ON_RUN_TIME = 1.5 FAST_SWITCH_ON_RUN_TIME = 0.1 NUM_LEVELS = 30 NUM_CONES = 7 # in first lighthouse scene NUM_VISIBLE_CONES = 5 # ibidem ARC_TIP_LENGTH = 0.2 AMBIENT_FULL = 0.8 AMBIENT_DIMMED = 0.5 SPOTLIGHT_FULL = 0.8 SPOTLIGHT_DIMMED = 0.5 LIGHTHOUSE_HEIGHT = 0.8 DEGREES = TAU / 360 def inverse_power_law(maxint, scale, cutoff, exponent): return (lambda r: maxint * (cutoff / (r / scale + cutoff))**exponent) def inverse_quadratic(maxint, scale, cutoff): return inverse_power_law(maxint, scale, cutoff, 2) class SwitchOn(LaggedStartMap): CONFIG = { "lag_ratio": 0.2, "run_time": SWITCH_ON_RUN_TIME } def __init__(self, light, **kwargs): if (not isinstance(light, AmbientLight) and not isinstance(light, Spotlight)): raise Exception( "Only AmbientLights and Spotlights can be switched on") LaggedStartMap.__init__( self, FadeIn, light, **kwargs ) class SwitchOff(LaggedStartMap): CONFIG = { "lag_ratio": 0.2, "run_time": SWITCH_ON_RUN_TIME } def __init__(self, light, **kwargs): if (not isinstance(light, AmbientLight) and not isinstance(light, Spotlight)): raise Exception( "Only AmbientLights and Spotlights can be switched off") light.set_submobjects(light.submobjects[::-1]) LaggedStartMap.__init__(self, FadeOut, light, **kwargs) light.set_submobjects(light.submobjects[::-1]) class Lighthouse(SVGMobject): CONFIG = { "height": LIGHTHOUSE_HEIGHT, "fill_color": WHITE, "fill_opacity": 1.0, } def __init__(self, **kwargs): super().__init__("lighthouse", **kwargs) def move_to(self, point): self.next_to(point, DOWN, buff=0) class AmbientLight(VMobject): # Parameters are: # * a source point # * an opacity function # * a light color # * a max opacity # * a radius (larger than the opacity's dropoff length) # * the number of subdivisions (levels, annuli) CONFIG = { "source_point": VectorizedPoint(location=ORIGIN, stroke_width=0, fill_opacity=0), "opacity_function": lambda r: 1.0 / (r + 1.0)**2, "color": LIGHT_COLOR, "max_opacity": 1.0, "num_levels": NUM_LEVELS, "radius": 5.0 } def init_points(self): # in theory, this method is only called once, right? # so removing submobs shd not be necessary # # Note: Usually, yes, it is only called within Mobject.__init__, # but there is no strong guarantee of that, and you may want certain # update functions to regenerate points here and there. for submob in self.submobjects: self.remove(submob) self.add(self.source_point) # create annuli self.radius = float(self.radius) dr = self.radius / self.num_levels for r in np.arange(0, self.radius, dr): alpha = self.max_opacity * self.opacity_function(r) annulus = Annulus( inner_radius=r, outer_radius=r + dr, color=self.color, fill_opacity=alpha ) annulus.move_to(self.get_source_point()) self.add(annulus) def move_source_to(self, point): # old_source_point = self.get_source_point() # self.shift(point - old_source_point) self.move_to(point) return self def get_source_point(self): return self.source_point.get_location() def dimming(self, new_alpha): old_alpha = self.max_opacity self.max_opacity = new_alpha for submob in self.submobjects: old_submob_alpha = submob.fill_opacity new_submob_alpha = old_submob_alpha * new_alpha / old_alpha submob.set_fill(opacity=new_submob_alpha) class Spotlight(VMobject): CONFIG = { "source_point": VectorizedPoint(location=ORIGIN, stroke_width=0, fill_opacity=0), "opacity_function": lambda r: 1.0 / (r / 2 + 1.0)**2, "color": GREEN, # LIGHT_COLOR, "max_opacity": 1.0, "num_levels": 10, "radius": 10.0, "screen": None, "camera_mob": None } def projection_direction(self): # Note: This seems reasonable, though for it to work you'd # need to be sure that any 3d scene including a spotlight # somewhere assigns that spotlights "camera" attribute # to be the camera associated with that scene. if self.camera_mob is None: return OUT else: [phi, theta, r] = self.camera_mob.get_center() v = np.array([np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi)]) return v # /get_norm(v) def project(self, point): v = self.projection_direction() w = project_along_vector(point, v) return w def get_source_point(self): return self.source_point.get_location() def init_points(self): self.set_submobjects([]) self.add(self.source_point) if self.screen is not None: # look for the screen and create annular sectors lower_angle, upper_angle = self.viewing_angles(self.screen) self.radius = float(self.radius) dr = self.radius / self.num_levels lower_ray, upper_ray = self.viewing_rays(self.screen) for r in np.arange(0, self.radius, dr): new_sector = self.new_sector(r, dr, lower_angle, upper_angle) self.add(new_sector) def new_sector(self, r, dr, lower_angle, upper_angle): alpha = self.max_opacity * self.opacity_function(r) annular_sector = AnnularSector( inner_radius=r, outer_radius=r + dr, color=self.color, fill_opacity=alpha, start_angle=lower_angle, angle=upper_angle - lower_angle ) # rotate (not project) it into the viewing plane rotation_matrix = z_to_vector(self.projection_direction()) annular_sector.apply_matrix(rotation_matrix) # now rotate it inside that plane rotated_RIGHT = np.dot(RIGHT, rotation_matrix.T) projected_RIGHT = self.project(RIGHT) omega = angle_between_vectors(rotated_RIGHT, projected_RIGHT) annular_sector.rotate(omega, axis=self.projection_direction()) annular_sector.move_arc_center_to(self.get_source_point()) return annular_sector def viewing_angle_of_point(self, point): # as measured from the positive x-axis v1 = self.project(RIGHT) v2 = self.project(np.array(point) - self.get_source_point()) absolute_angle = angle_between_vectors(v1, v2) # determine the angle's sign depending on their plane's # choice of orientation. That choice is set by the camera # position, i. e. projection direction if np.dot(self.projection_direction(), np.cross(v1, v2)) > 0: return absolute_angle else: return -absolute_angle def viewing_angles(self, screen): screen_points = screen.get_anchors() projected_screen_points = list(map(self.project, screen_points)) viewing_angles = np.array(list(map(self.viewing_angle_of_point, projected_screen_points))) lower_angle = upper_angle = 0 if len(viewing_angles) != 0: lower_angle = np.min(viewing_angles) upper_angle = np.max(viewing_angles) if upper_angle - lower_angle > TAU / 2: lower_angle, upper_angle = upper_angle, lower_angle + TAU return lower_angle, upper_angle def viewing_rays(self, screen): lower_angle, upper_angle = self.viewing_angles(screen) projected_RIGHT = self.project( RIGHT) / get_norm(self.project(RIGHT)) lower_ray = rotate_vector( projected_RIGHT, lower_angle, axis=self.projection_direction()) upper_ray = rotate_vector( projected_RIGHT, upper_angle, axis=self.projection_direction()) return lower_ray, upper_ray def opening_angle(self): l, u = self.viewing_angles(self.screen) return u - l def start_angle(self): l, u = self.viewing_angles(self.screen) return l def stop_angle(self): l, u = self.viewing_angles(self.screen) return u def move_source_to(self, point): self.source_point.set_location(np.array(point)) # self.source_point.move_to(np.array(point)) # self.move_to(point) self.update_sectors() return self def update_sectors(self): if self.screen is None: return for submob in self.submobjects: if type(submob) == AnnularSector: lower_angle, upper_angle = self.viewing_angles(self.screen) # dr = submob.outer_radius - submob.inner_radius dr = self.radius / self.num_levels new_submob = self.new_sector( submob.inner_radius, dr, lower_angle, upper_angle ) # submob.points = new_submob.points # submob.set_fill(opacity = 10 * self.opacity_function(submob.outer_radius)) Transform(submob, new_submob).update(1) def dimming(self, new_alpha): old_alpha = self.max_opacity self.max_opacity = new_alpha for submob in self.submobjects: # Note: Maybe it'd be best to have a Shadow class so that the # type can be checked directly? if type(submob) != AnnularSector: # it's the shadow, don't dim it continue old_submob_alpha = submob.fill_opacity new_submob_alpha = old_submob_alpha * new_alpha / old_alpha submob.set_fill(opacity=new_submob_alpha) def change_opacity_function(self, new_f): self.opacity_function = new_f dr = self.radius / self.num_levels sectors = [] for submob in self.submobjects: if type(submob) == AnnularSector: sectors.append(submob) for (r, submob) in zip(np.arange(0, self.radius, dr), sectors): if type(submob) != AnnularSector: # it's the shadow, don't dim it continue alpha = self.opacity_function(r) submob.set_fill(opacity=alpha) # Warning: This class is likely quite buggy. class LightSource(VMobject): # combines: # a lighthouse # an ambient light # a spotlight # and a shadow CONFIG = { "source_point": VectorizedPoint(location=ORIGIN, stroke_width=0, fill_opacity=0), "color": LIGHT_COLOR, "num_levels": 10, "radius": 10.0, "screen": None, "opacity_function": inverse_quadratic(1, 2, 1), "max_opacity_ambient": AMBIENT_FULL, "max_opacity_spotlight": SPOTLIGHT_FULL, "camera_mob": None } def init_points(self): self.add(self.source_point) self.lighthouse = Lighthouse() self.ambient_light = AmbientLight( source_point=VectorizedPoint(location=self.get_source_point()), color=self.color, num_levels=self.num_levels, radius=self.radius, opacity_function=self.opacity_function, max_opacity=self.max_opacity_ambient ) if self.has_screen(): self.spotlight = Spotlight( source_point=VectorizedPoint(location=self.get_source_point()), color=self.color, num_levels=self.num_levels, radius=self.radius, screen=self.screen, opacity_function=self.opacity_function, max_opacity=self.max_opacity_spotlight, camera_mob=self.camera_mob ) else: self.spotlight = Spotlight() self.shadow = VMobject(fill_color=SHADOW_COLOR, fill_opacity=1.0, stroke_color=BLACK) self.lighthouse.next_to(self.get_source_point(), DOWN, buff=0) self.ambient_light.move_source_to(self.get_source_point()) if self.has_screen(): self.spotlight.move_source_to(self.get_source_point()) self.update_shadow() self.add(self.ambient_light, self.spotlight, self.lighthouse, self.shadow) def has_screen(self): if self.screen is None: return False elif self.screen.get_num_points() == 0: return False else: return True def dim_ambient(self): self.set_max_opacity_ambient(AMBIENT_DIMMED) def set_max_opacity_ambient(self, new_opacity): self.max_opacity_ambient = new_opacity self.ambient_light.dimming(new_opacity) def dim_spotlight(self): self.set_max_opacity_spotlight(SPOTLIGHT_DIMMED) def set_max_opacity_spotlight(self, new_opacity): self.max_opacity_spotlight = new_opacity self.spotlight.dimming(new_opacity) def set_camera_mob(self, new_cam_mob): self.camera_mob = new_cam_mob self.spotlight.camera_mob = new_cam_mob def set_screen(self, new_screen): if self.has_screen(): self.spotlight.screen = new_screen else: # Note: See below index = self.submobjects.index(self.spotlight) # camera_mob = self.spotlight.camera_mob self.remove(self.spotlight) self.spotlight = Spotlight( source_point=VectorizedPoint(location=self.get_source_point()), color=self.color, num_levels=self.num_levels, radius=self.radius, screen=new_screen, camera_mob=self.camera_mob, opacity_function=self.opacity_function, max_opacity=self.max_opacity_spotlight, ) self.spotlight.move_source_to(self.get_source_point()) # Note: This line will make spotlight show up at the end # of the submojects list, which can make it show up on # top of the shadow. To make it show up in the # same spot, you could try the following line, # where "index" is what I defined above: self.submobjects.insert(index, self.spotlight) # self.add(self.spotlight) # in any case self.screen = new_screen def move_source_to(self, point): apoint = np.array(point) v = apoint - self.get_source_point() # Note: As discussed, things stand to behave better if source # point is a submobject, so that it automatically interpolates # during an animation, and other updates can be defined wrt # that source point's location self.source_point.set_location(apoint) # self.lighthouse.next_to(apoint,DOWN,buff = 0) # self.ambient_light.move_source_to(apoint) self.lighthouse.shift(v) # self.ambient_light.shift(v) self.ambient_light.move_source_to(apoint) if self.has_screen(): self.spotlight.move_source_to(apoint) self.update() return self def change_spotlight_opacity_function(self, new_of): self.spotlight.change_opacity_function(new_of) def set_radius(self, new_radius): self.radius = new_radius self.ambient_light.radius = new_radius self.spotlight.radius = new_radius def update(self): self.update_lighthouse() self.update_ambient() self.spotlight.update_sectors() self.update_shadow() def update_lighthouse(self): self.lighthouse.move_to(self.get_source_point()) # new_lh = Lighthouse() # new_lh.move_to(ORIGIN) # new_lh.apply_matrix(self.rotation_matrix()) # new_lh.shift(self.get_source_point()) # self.lighthouse.submobjects = new_lh.submobjects def update_ambient(self): new_ambient_light = AmbientLight( source_point=VectorizedPoint(location=ORIGIN), color=self.color, num_levels=self.num_levels, radius=self.radius, opacity_function=self.opacity_function, max_opacity=self.max_opacity_ambient ) new_ambient_light.apply_matrix(self.rotation_matrix()) new_ambient_light.move_source_to(self.get_source_point()) self.ambient_light.set_submobjects(new_ambient_light.submobjects) def get_source_point(self): return self.source_point.get_location() def rotation_matrix(self): if self.camera_mob is None: return np.eye(3) phi = self.camera_mob.get_center()[0] theta = self.camera_mob.get_center()[1] R1 = np.array([ [1, 0, 0], [0, np.cos(phi), -np.sin(phi)], [0, np.sin(phi), np.cos(phi)] ]) R2 = np.array([ [np.cos(theta + TAU / 4), -np.sin(theta + TAU / 4), 0], [np.sin(theta + TAU / 4), np.cos(theta + TAU / 4), 0], [0, 0, 1] ]) R = np.dot(R2, R1) return R def update_shadow(self): point = self.get_source_point() projected_screen_points = [] if not self.has_screen(): return for point in self.screen.get_anchors(): projected_screen_points.append(self.spotlight.project(point)) projected_source = project_along_vector( self.get_source_point(), self.spotlight.projection_direction()) projected_point_cloud_3d = np.append( projected_screen_points, np.reshape(projected_source, (1, 3)), axis=0 ) # z_to_vector(self.spotlight.projection_direction()) rotation_matrix = self.rotation_matrix() back_rotation_matrix = rotation_matrix.T # i. e. its inverse rotated_point_cloud_3d = np.dot( projected_point_cloud_3d, back_rotation_matrix.T) # these points now should all have z = 0 point_cloud_2d = rotated_point_cloud_3d[:, :2] # now we can compute the convex hull hull_2d = ConvexHull(point_cloud_2d) # guaranteed to run ccw hull = [] # we also need the projected source point source_point_2d = np.dot(self.spotlight.project( self.get_source_point()), back_rotation_matrix.T)[:2] index = 0 for point in point_cloud_2d[hull_2d.vertices]: if np.all(np.abs(point - source_point_2d) < 1.0e-6): source_index = index index += 1 continue point_3d = np.array([point[0], point[1], 0]) hull.append(point_3d) index += 1 hull_mobject = VMobject() hull_mobject.set_points_as_corners(hull) hull_mobject.apply_matrix(rotation_matrix) anchors = hull_mobject.get_anchors() # add two control points for the outer cone if np.size(anchors) == 0: self.shadow.resize_points(0) return ray1 = anchors[source_index - 1] - projected_source ray1 = ray1 / get_norm(ray1) * 100 ray2 = anchors[source_index] - projected_source ray2 = ray2 / get_norm(ray2) * 100 outpoint1 = anchors[source_index - 1] + ray1 outpoint2 = anchors[source_index] + ray2 new_anchors = anchors[:source_index] new_anchors = np.append(new_anchors, np.array( [outpoint1, outpoint2]), axis=0) new_anchors = np.append(new_anchors, anchors[source_index:], axis=0) self.shadow.set_points_as_corners(new_anchors) # shift it closer to the camera so it is in front of the spotlight self.shadow.mark_paths_closed = True # Redefining what was once a ContinualAnimation class # as a function def ScreenTracker(light_source): light_source.add_updater(lambda m: m.update()) return light_source
videos_3b1b/once_useful_constructs/homeless.py
from manim_imports_ext import * class Cycloidify(Scene): def construct(self): def cart_to_polar(xxx_todo_changeme): (x, y, z) = xxx_todo_changeme return x*RIGHT+x*y*UP def polar_to_cycloid(point): epsilon = 0.00001 t = get_norm(point) R = point[1]/(point[0]+epsilon)+epsilon return R*(t/R-np.sin(t/R))*RIGHT+R*(1-np.cos(t/R))*UP polar = Mobject(*[ Line(ORIGIN, T*(np.cos(theta)*RIGHT+np.sin(theta)*UP)) for R in np.arange(0.25, 4, 0.25) for theta in [np.arctan(R)] for T in [R*2*np.pi] ]) polar.set_color(BLUE) cycloids = polar.copy().apply_function(polar_to_cycloid) cycloids.set_color(YELLOW) for mob in polar, cycloids: mob.rotate(np.pi, RIGHT) mob.to_corner(UP+LEFT) lines = polar.copy() self.add(lines) self.wait() self.play(Transform( lines, cycloids, run_time = 3, path_func = path_along_arc(np.pi/2) )) self.wait() self.play(Transform( lines, polar, run_time = 3, path_func = path_along_arc(-np.pi/2) )) self.wait() class PythagoreanTransformation(Scene): def construct(self): triangle = Mobject( Line(ORIGIN, 4*UP, color = "#FF69B4"), Line(4*UP, 2*RIGHT, color = YELLOW_C), Line(2*RIGHT, ORIGIN, color = BLUE_D) ) arrangment1 = Mobject(*[ triangle.copy().rotate(theta).shift(3*vect) for theta, vect in zip( np.arange(0, 2*np.pi, np.pi/2), compass_directions(4, DOWN+LEFT) ) ]) arrangment2 = Mobject( triangle.copy().rotate(np.pi, UP).rotate(-np.pi/2).shift(3*DOWN+3*LEFT), triangle.copy().rotate(np.pi, UP).rotate(np.pi/2).shift(DOWN+RIGHT), triangle.copy().shift(DOWN+RIGHT), triangle.copy().rotate(np.pi).shift(3*UP+3*RIGHT) ) growth = 1.2 a_region, b_region, c_region = regions = [ MobjectFromRegion( region_from_polygon_vertices( *compass_directions(4, growth*start) ), color ).scale(1/growth).shift(shift_val) for start, color, shift_val in [ (DOWN+RIGHT, BLUE_D, 2*(DOWN+RIGHT)), (2*(DOWN+RIGHT), MAROON_B, UP+LEFT), (3*RIGHT+DOWN, YELLOW_E, ORIGIN), ] ] for mob, char in zip(regions, "abc"): mob.add( OldTex("%s^2"%char).shift(mob.get_center()) ) square = Square(side_length = 6, color = WHITE) mover = arrangment1.copy() self.add(square, mover) self.play(FadeIn(c_region)) self.wait(2) self.remove(c_region) self.play(Transform( mover, arrangment2, run_time = 3, path_func = path_along_arc(np.pi/2) )) self.remove(c_region) self.play(*[ FadeIn(region) for region in (a_region, b_region) ]) self.wait(2) self.clear() self.add(mover, square) self.play(Transform( mover, arrangment1, run_time = 3, path_func = path_along_arc(-np.pi/2) )) self.wait() class PullCurveStraight(Scene): def construct(self): start = -1.5 end = 1.5 parabola = ParametricCurve( lambda t : (t**3-t)*RIGHT + (2*np.exp(-t**2))*UP, start = start, end = end, color = BLUE_D, density = 2*DEFAULT_POINT_DENSITY_1D ) from scipy import integrate integral = integrate.quad( lambda x : np.sqrt(1 + 4*x**2), start, end ) length = integral[0] line = Line( 0.5*length*LEFT, 0.5*length*RIGHT, color = BLUE_D ) brace = Brace(line, UP) label = OldTexText("What is this length?") label.next_to(brace, UP) self.play(ShowCreation(parabola)) self.wait() self.play(Transform( parabola, line, path_func = path_along_arc(np.pi/2), run_time = 2 )) self.play( GrowFromCenter(brace), ShimmerIn(label) ) self.wait(3) class StraghtenCircle(Scene): def construct(self): radius = 1.5 radius_line = Line(ORIGIN, radius*RIGHT, color = RED_D) radius_brace = Brace(radius_line, UP) r = OldTex("r").next_to(radius_brace, UP) circle = Circle(radius = radius, color = BLUE_D) line = Line( np.pi*radius*LEFT, np.pi*radius*RIGHT, color = circle.get_color() ) line_brace = Brace(line, UP) two_pi_r = OldTex("2\\pi r").next_to(line_brace, UP) self.play(ShowCreation(radius_line)) self.play(ShimmerIn(r), GrowFromCenter(radius_brace)) self.wait() self.remove(r, radius_brace) self.play( ShowCreation(circle), Rotating( radius_line, axis = OUT, rate_func = smooth, in_place = False ), run_time = 2 ) self.wait() self.remove(radius_line) self.play(Transform( circle, line, run_time = 2 )) self.play( ShimmerIn(two_pi_r), GrowFromCenter(line_brace) ) self.wait(3) class SingleVariableFunc(Scene): def construct(self): start = OldTex("3").set_color(GREEN) start.scale(2).shift(5*LEFT+2*UP) end = OldTex("9").set_color(RED) end.scale(2).shift(5*RIGHT+2*DOWN) point = Point() func = OldTex("f(x) = x^2") circle = Circle(color = WHITE, radius = func.get_width()/1.5) self.add(start, circle, func) self.wait() self.play(Transform( start, point, path_func = path_along_arc(np.pi/2) )) self.play(Transform( start, end, path_func = path_along_arc(-np.pi/2) )) self.wait() class MultivariableFunc(Scene): def construct(self): start = OldTex("(1, 2)").set_color(GREEN) start.scale(1.5).shift(5*LEFT, 2*UP) end = OldTex("(5, -3)").set_color(RED) end.scale(1.5).shift(5*RIGHT, 2*DOWN) point = Point() func = OldTex("f(x, y) = (x^2+y^2, x^2-y^2)") circle = Circle(color = WHITE) circle.stretch_to_fit_width(func.get_width()+1) self.add(start, circle, func) self.wait() self.play(Transform( start, point, path_func = path_along_arc(np.pi/2) )) self.play(Transform( start, end, path_func = path_along_arc(-np.pi/2) )) self.wait() def prime_factors(n): i = 2 factors = [] while i * i <= n: if n % i: i += 1 else: n //= i factors.append(i) if n > 1: factors.append(n) return factors class ShowSumOfSquaresPattern(Scene): def construct(self): dots = VGroup(*[ VGroup(*[ Dot() for x in range(2*n + 1) ]).arrange(DOWN, buff = SMALL_BUFF) for n in range(30) ]).arrange(RIGHT, buff = MED_LARGE_BUFF, aligned_edge = UP) dots = VGroup(*it.chain(*dots)) dots.to_edge(UP) numbers = VGroup() for n, dot in enumerate(dots): factors = prime_factors(n) color = True factors_to_counts = dict() for factor in factors: if factor not in factors_to_counts: factors_to_counts[factor] = 0 factors_to_counts[factor] += 1 for factor, count in list(factors_to_counts.items()): if factor%4 == 3 and count%2 == 1: color = False n_mob = Integer(n) n_mob.replace(dot, dim_to_match = 1) if color: n_mob.set_color(RED) numbers.add(n_mob) self.add(numbers)
videos_3b1b/once_useful_constructs/region.py
from copy import deepcopy import itertools as it from manimlib.constants import * from manimlib.mobject.mobject import Mobject from manimlib.utils.iterables import adjacent_pairs # Warning: This is all now pretty deprecated, and should not be expected to work class Region(Mobject): CONFIG = { "display_mode": "region" } def __init__(self, condition=(lambda x, y: True), **kwargs): """ Condition must be a function which takes in two real arrays (representing x and y values of space respectively) and return a boolean array. This can essentially look like a function from R^2 to {True, False}, but & and | must be used in place of "and" and "or" """ Mobject.__init__(self, **kwargs) self.condition = condition def _combine(self, region, op): self.condition = lambda x, y: op( self.condition(x, y), region.condition(x, y) ) def union(self, region): self._combine(region, lambda bg1, bg2: bg1 | bg2) return self def intersect(self, region): self._combine(region, lambda bg1, bg2: bg1 & bg2) return self def complement(self): self.bool_grid = ~self.bool_grid return self class HalfPlane(Region): def __init__(self, point_pair, upper_left=True, *args, **kwargs): """ point_pair of the form [(x_0, y_0,...), (x_1, y_1,...)] Pf upper_left is True, the side of the region will be everything on the upper left side of the line through the point pair """ if not upper_left: point_pair = list(point_pair) point_pair.reverse() (x0, y0), (x1, y1) = point_pair[0][:2], point_pair[1][:2] def condition(x, y): return (x1 - x0) * (y - y0) > (y1 - y0) * (x - x0) Region.__init__(self, condition, *args, **kwargs) def region_from_line_boundary(*lines, **kwargs): reg = Region(**kwargs) for line in lines: reg.intersect(HalfPlane(line, **kwargs)) return reg def region_from_polygon_vertices(*vertices, **kwargs): return region_from_line_boundary(*adjacent_pairs(vertices), **kwargs) def plane_partition(*lines, **kwargs): """ A 'line' is a pair of points [(x0, y0,...), (x1, y1,...)] Returns the list of regions of the plane cut out by these lines """ result = [] half_planes = [HalfPlane(line, **kwargs) for line in lines] complements = [deepcopy(hp).complement() for hp in half_planes] num_lines = len(lines) for bool_list in it.product(*[[True, False]] * num_lines): reg = Region(**kwargs) for i in range(num_lines): if bool_list[i]: reg.intersect(half_planes[i]) else: reg.intersect(complements[i]) if reg.bool_grid.any(): result.append(reg) return result def plane_partition_from_points(*points, **kwargs): """ Returns list of regions cut out by the complete graph with points from the argument as vertices. Each point comes in the form (x, y) """ lines = [[p1, p2] for (p1, p2) in it.combinations(points, 2)] return plane_partition(*lines, **kwargs)
videos_3b1b/once_useful_constructs/sample_space_scene.py
from manimlib.animation.animation import Animation from manimlib.animation.transform import MoveToTarget from manimlib.animation.transform import Transform from manimlib.animation.update import UpdateFromFunc from manimlib.constants import DOWN, RIGHT from manimlib.constants import MED_LARGE_BUFF, SMALL_BUFF from manimlib.mobject.probability import SampleSpace from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene class SampleSpaceScene(Scene): def get_sample_space(self, **config): self.sample_space = SampleSpace(**config) return self.sample_space def add_sample_space(self, **config): self.add(self.get_sample_space(**config)) def get_division_change_animations( self, sample_space, parts, p_list, dimension=1, new_label_kwargs=None, **kwargs ): if new_label_kwargs is None: new_label_kwargs = {} anims = [] p_list = sample_space.complete_p_list(p_list) space_copy = sample_space.copy() vect = DOWN if dimension == 1 else RIGHT parts.generate_target() for part, p in zip(parts.target, p_list): part.replace(space_copy, stretch=True) part.stretch(p, dimension) parts.target.arrange(vect, buff=0) parts.target.move_to(space_copy) anims.append(MoveToTarget(parts)) if hasattr(parts, "labels") and parts.labels is not None: label_kwargs = parts.label_kwargs label_kwargs.update(new_label_kwargs) new_braces, new_labels = sample_space.get_subdivision_braces_and_labels( parts.target, **label_kwargs ) anims += [ Transform(parts.braces, new_braces), Transform(parts.labels, new_labels), ] return anims def get_horizontal_division_change_animations(self, p_list, **kwargs): assert(hasattr(self.sample_space, "horizontal_parts")) return self.get_division_change_animations( self.sample_space, self.sample_space.horizontal_parts, p_list, dimension=1, **kwargs ) def get_vertical_division_change_animations(self, p_list, **kwargs): assert(hasattr(self.sample_space, "vertical_parts")) return self.get_division_change_animations( self.sample_space, self.sample_space.vertical_parts, p_list, dimension=0, **kwargs ) def get_conditional_change_anims( self, sub_sample_space_index, value, post_rects=None, **kwargs ): parts = self.sample_space.horizontal_parts sub_sample_space = parts[sub_sample_space_index] anims = self.get_division_change_animations( sub_sample_space, sub_sample_space.vertical_parts, value, dimension=0, **kwargs ) if post_rects is not None: anims += self.get_posterior_rectangle_change_anims(post_rects) return anims def get_top_conditional_change_anims(self, *args, **kwargs): return self.get_conditional_change_anims(0, *args, **kwargs) def get_bottom_conditional_change_anims(self, *args, **kwargs): return self.get_conditional_change_anims(1, *args, **kwargs) def get_prior_rectangles(self): return VGroup(*[ self.sample_space.horizontal_parts[i].vertical_parts[0] for i in range(2) ]) def get_posterior_rectangles(self, buff=MED_LARGE_BUFF): prior_rects = self.get_prior_rectangles() areas = [ rect.get_width() * rect.get_height() for rect in prior_rects ] total_area = sum(areas) total_height = prior_rects.get_height() post_rects = prior_rects.copy() for rect, area in zip(post_rects, areas): rect.stretch_to_fit_height(total_height * area / total_area) rect.stretch_to_fit_width( area / rect.get_height() ) post_rects.arrange(DOWN, buff=0) post_rects.next_to( self.sample_space, RIGHT, buff ) return post_rects def get_posterior_rectangle_braces_and_labels( self, post_rects, labels, direction=RIGHT, **kwargs ): return self.sample_space.get_subdivision_braces_and_labels( post_rects, labels, direction, **kwargs ) def update_posterior_braces(self, post_rects): braces = post_rects.braces labels = post_rects.labels for rect, brace, label in zip(post_rects, braces, labels): brace.stretch_to_fit_height(rect.get_height()) brace.next_to(rect, RIGHT, SMALL_BUFF) label.next_to(brace, RIGHT, SMALL_BUFF) def get_posterior_rectangle_change_anims(self, post_rects): def update_rects(rects): new_rects = self.get_posterior_rectangles() Transform(rects, new_rects).update(1) if hasattr(rects, "braces"): self.update_posterior_braces(rects) return rects anims = [UpdateFromFunc(post_rects, update_rects)] if hasattr(post_rects, "braces"): anims += list(map(Animation, [ post_rects.labels, post_rects.braces ])) return anims
videos_3b1b/once_useful_constructs/arithmetic.py
import numpy as np from manimlib.animation.animation import Animation from manimlib.mobject.mobject import Mobject from manimlib.constants import * from manimlib.mobject.svg.tex_mobject import Tex from manimlib.scene.scene import Scene from manimlib.utils.paths import path_along_arc class RearrangeEquation(Scene): def construct( self, start_terms, end_terms, index_map, path_arc=np.pi, start_transform=None, end_transform=None, leave_start_terms=False, transform_kwargs={}, ): transform_kwargs["path_func"] = path_along_arc(path_arc) start_mobs, end_mobs = self.get_mobs_from_terms( start_terms, end_terms ) if start_transform: start_mobs = start_transform(Mobject(*start_mobs)).split() if end_transform: end_mobs = end_transform(Mobject(*end_mobs)).split() unmatched_start_indices = set(range(len(start_mobs))) unmatched_end_indices = set(range(len(end_mobs))) unmatched_start_indices.difference_update( [n % len(start_mobs) for n in index_map] ) unmatched_end_indices.difference_update( [n % len(end_mobs) for n in list(index_map.values())] ) mobject_pairs = [ (start_mobs[a], end_mobs[b]) for a, b in index_map.items() ] + [ (Point(end_mobs[b].get_center()), end_mobs[b]) for b in unmatched_end_indices ] if not leave_start_terms: mobject_pairs += [ (start_mobs[a], Point(start_mobs[a].get_center())) for a in unmatched_start_indices ] self.add(*start_mobs) if leave_start_terms: self.add(Mobject(*start_mobs)) self.wait() self.play(*[ Transform(*pair, **transform_kwargs) for pair in mobject_pairs ]) self.wait() def get_mobs_from_terms(self, start_terms, end_terms): """ Need to ensure that all image mobjects for a tex expression stemming from the same string are point-for-point copies of one and other. This makes transitions much smoother, and not look like point-clouds. """ num_start_terms = len(start_terms) all_mobs = np.array( OldTex(start_terms).split() + OldTex(end_terms).split()) all_terms = np.array(start_terms + end_terms) for term in set(all_terms): matches = all_terms == term if sum(matches) > 1: base_mob = all_mobs[list(all_terms).index(term)] all_mobs[matches] = [ base_mob.copy().replace(target_mob) for target_mob in all_mobs[matches] ] return all_mobs[:num_start_terms], all_mobs[num_start_terms:] class FlipThroughSymbols(Animation): def __init__( self, tex_list, start_center=ORIGIN, end_center=ORIGIN, **kwargs ): self.tex_list = tex_list self.start_center = start_center self.end_center = end_center mobject = OldTex(self.curr_tex).shift(start_center) Animation.__init__(self, mobject, **kwargs) def interpolate_mobject(self, alpha): new_tex = self.tex_list[np.ceil(alpha * len(self.tex_list)) - 1] if new_tex != self.curr_tex: self.curr_tex = new_tex self.mobject = OldTex(new_tex).shift(self.start_center) if not all(self.start_center == self.end_center): self.mobject.center().shift( (1 - alpha) * self.start_center + alpha * self.end_center )
videos_3b1b/once_useful_constructs/sed.py
from manim_imports_ext import * import csv import time from datetime import datetime class SEDTest(MovingCameraScene): def construct(self): file_name1 = "/Users/grant/Desktop/SED_launch_data.csv" file_name2 = "/Users/grant/Desktop/SED_scrub_data.csv" times = [] heart_rates = [] with open(file_name1, newline='') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') for row in reader: try: values = row[0].split(",") timestamp = str(values[8]) heart_rate = int(values[10]) dt = datetime.fromisoformat(timestamp) curr_time = time.mktime(dt.timetuple()) times.append(curr_time) heart_rates.append(heart_rate) except ValueError: continue times = np.array(times) times -= times[0] heart_rates = np.array(heart_rates) average_over = 100 hr_averages = np.array([ np.mean(heart_rates[i:i + average_over]) for i in range(len(heart_rates) - average_over) ]) prop = 10 shown_times = times[::prop] # shown_heart_rates = heart_rates[::prop] shown_heart_rates = hr_averages[::prop] min_time = np.min(times) max_time = np.max(times) min_HR = np.min(heart_rates) max_HR = np.max(heart_rates) axes = Axes( x_min=-1, x_max=12, y_min=0, y_max=130, y_axis_config={ "unit_size": 1.0 / 25, "tick_frequency": 10, } ) axes.to_corner(UL) axes.set_stroke(width=2) def c2p(t, h): t_coord = t / 20 # 20 minute intervals return axes.coords_to_point(t_coord, h) # x_axis_labels = VGroup() # for t in range(0, 190, 60): # point = c2p(t, 0) # label = Integer(t) # label.next_to(point, DOWN, MED_SMALL_BUFF) # x_axis_labels.add(label) # axes.x_axis.add(x_axis_labels) # x_label = OldTexText("Time (minutes)") # x_label.next_to(axes.x_axis, UP, SMALL_BUFF) # x_label.to_edge(RIGHT) # axes.x_axis.add(x_label) y_axis_labels = VGroup() for y in range(50, 150, 50): point = axes.coords_to_point(0, y) label = Integer(y) label.next_to(point, LEFT) y_axis_labels.add(label) axes.y_axis.add(y_axis_labels) y_label = OldTexText("Heart rates") y_label.next_to(axes.y_axis, RIGHT, aligned_edge=UP) axes.y_axis.add(y_label) def point_to_color(point): hr = axes.y_axis.point_to_number(point) ratio = (hr - 50) / (120 - 50) if ratio < 0.5: return interpolate_color(BLUE_D, GREEN, 2 * ratio) else: return interpolate_color(GREEN, RED, 2 * ratio - 1) def get_v_line(t, label=None, **kwargs): line = DashedLine(c2p(t, 0), c2p(t, 120), **kwargs) line.set_stroke(width=2) if label is not None: label_mob = OldTexText(label) label_mob.next_to(line, UP) label_mob.set_color(WHITE) line.label = label_mob return line points = [] for t, hr in zip(shown_times, shown_heart_rates): points.append(c2p(t / 60, hr)) lines = VGroup() for p1, p2, p3, p4 in zip(points, points[1:], points[2:], points[3:]): line = Line(p1, p2) line.set_points_smoothly([p1, p2, p3, p4]) line.set_color(( point_to_color(p1), point_to_color(p2), )) line.set_sheen_direction(line.get_vector()) lines.add(line) lines.set_stroke(width=2) def get_lines_after_value(lines, t): result = VGroup() for line in lines: line_t = axes.x_axis.point_to_number(line.get_center()) line_t *= 20 if t - 7 < line_t < t + 7: result.add(line) # if t < line_t: # alpha = 1 - smooth(abs(line_t - t) / 20) # elif line_t > t - 5: # alpha = 1 - (t - line_t) / 5 # line.set_stroke( # width=interpolate(2, 10, alpha), # opacity=interpolate(0.5, 1, alpha), # ) return result # base_line = Line( # c2p(0, 55), c2p(180, 55), # ) # base_line_label = OldTexText( # "(Felipe's resting HR)" # ) # base_line_label.next_to(base_line, DOWN) # base_line_label.to_edge(RIGHT) # 22:22, yt launch time # 18:32, T-minus 4 # 28:22, separation launch_time = 116 for mark in axes.x_axis.tick_marks: mark.shift(c2p(0, 0) - c2p(4, 0)) if mark.get_center()[0] < c2p(0, 0)[0]: mark.fade(1) times_and_words = [ (launch_time - 60, "T-minus\\\\1 hour"), (launch_time, "Launch!"), (launch_time + 60, "1 hour \\\\ into flight"), ] time_labels = VGroup() for t, words in times_and_words: point = c2p(t, 0) tick = Line(DOWN, UP) tick.set_height(0.5) tick.move_to(point) label = OldTexText(words) label.next_to(tick, DOWN) time_labels.add(VGroup(tick, label)) tm4_time = launch_time - 4 tm4_line = get_v_line(tm4_time, "T-minus 4 (aka Game on!)") tm4_line.label.shift(2 * RIGHT) # self.add(tm4_line) sep1_time = launch_time + 5 + (35 / 60) sep1_line = get_v_line(sep1_time, "First stage separation") sep2_time = launch_time + 37 # Second stage separation sep2_line = get_v_line(sep2_time, "Second stage separation") sep3_time = launch_time + 43 sep3_line = get_v_line(sep3_time, "Third stage (probe) separation") frame = self.camera.frame from _2017.eoc.uncertainty import FalconHeavy rocket = FalconHeavy() rocket.logo.set_fill(WHITE, opacity=0).scale(0) rocket.set_height(1) rocket.move_to(c2p(launch_time, 0)) time_line_pairs = [ (tm4_time, tm4_line), (sep1_time, sep1_line), (sep2_time, sep2_line), (sep3_time, sep3_line), ] # Introduce self.play(Write(axes), run_time=1) self.play( LaggedStartMap(FadeInFromLarge, lines, run_time=5, lag_ratio=0.1) ) self.play(LaggedStartMap(FadeInFromDown, time_labels)) self.wait() # Point indications curr_line = get_v_line(launch_time) last_label = VectorizedPoint() self.play( ShowCreation(curr_line), rocket.to_edge, UP, UpdateFromAlphaFunc( rocket, lambda r, a: r.set_fill( opacity=min(2 - 2 * a, 1), ), remover=True ), run_time=2 ) for t, line in time_line_pairs: post_t_lines = get_lines_after_value(lines, t).copy() flicker = LaggedStartMap( UpdateFromAlphaFunc, post_t_lines, lambda mob: ( mob, lambda l, a: l.set_stroke( width=interpolate(2, 10, a), opacity=interpolate(0.5, 1, a), ) ), rate_func=there_and_back, run_time=1.5 ) self.play( flicker, lines.set_stroke, {"opacity": 0.5}, # ApplyFunction( # lambda m: emphasize_lines_near_value(m, t), # lines, # run_time=1, # lag_ratio=0.5, # ), Transform(curr_line, line), FadeInFromDown(line.label), FadeOut(last_label, DOWN), ) for x in range(3): self.play(flicker) last_label = line.label # self.show_frame() # T -4 spike # Separation of arrays # Deployment of arrays # Indication of power positive
videos_3b1b/once_useful_constructs/graph_scene.py
import itertools as it from manimlib.animation.creation import Write, DrawBorderThenFill, ShowCreation from manimlib.animation.transform import Transform from manimlib.animation.update import UpdateFromAlphaFunc from manimlib.constants import * from manimlib.mobject.functions import ParametricCurve from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import RegularPolygon from manimlib.mobject.number_line import NumberLine from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VectorizedPoint from manimlib.scene.scene import Scene from manimlib.utils.bezier import interpolate from manimlib.utils.color import color_gradient from manimlib.utils.color import invert_color from manimlib.utils.space_ops import angle_of_vector # TODO, this class should be deprecated, with all its # functionality moved to Axes and handled at the mobject # level rather than the scene level class GraphScene(Scene): x_min = -1 x_max = 10 x_axis_width = 9 x_tick_frequency = 1 x_leftmost_tick = None # Change if different from x_min x_labeled_nums = None x_axis_label = "$x$" y_min = -1 y_max = 10 y_axis_height = 6 y_tick_frequency = 1 y_bottom_tick = None # Change if different from y_min y_labeled_nums = None y_axis_label = "$y$" axes_color = GREY graph_origin = 2.5 * DOWN + 4 * LEFT exclude_zero_label = True default_graph_colors = [BLUE, GREEN, YELLOW] default_derivative_color = GREEN default_input_color = YELLOW default_riemann_start_color = BLUE default_riemann_end_color = GREEN area_opacity = 0.8 num_rects = 50 def setup(self): self.default_graph_colors_cycle = it.cycle(self.default_graph_colors) self.left_T_label = VGroup() self.left_v_line = VGroup() self.right_T_label = VGroup() self.right_v_line = VGroup() def setup_axes(self, animate=False): # TODO, once eoc is done, refactor this to be less redundant. x_num_range = float(self.x_max - self.x_min) self.space_unit_to_x = self.x_axis_width / x_num_range if self.x_labeled_nums is None: self.x_labeled_nums = [] if self.x_leftmost_tick is None: self.x_leftmost_tick = self.x_min x_axis = NumberLine( x_min=self.x_min, x_max=self.x_max, unit_size=self.space_unit_to_x, tick_frequency=self.x_tick_frequency, leftmost_tick=self.x_leftmost_tick, numbers_with_elongated_ticks=self.x_labeled_nums, color=self.axes_color ) x_axis.shift(self.graph_origin - x_axis.number_to_point(0)) if len(self.x_labeled_nums) > 0: if self.exclude_zero_label: self.x_labeled_nums = [x for x in self.x_labeled_nums if x != 0] x_axis.add_numbers(self.x_labeled_nums) if self.x_axis_label: x_label = OldTexText(self.x_axis_label) x_label.next_to( x_axis.get_tick_marks(), UP + RIGHT, buff=SMALL_BUFF ) x_label.shift_onto_screen() x_axis.add(x_label) self.x_axis_label_mob = x_label y_num_range = float(self.y_max - self.y_min) self.space_unit_to_y = self.y_axis_height / y_num_range if self.y_labeled_nums is None: self.y_labeled_nums = [] if self.y_bottom_tick is None: self.y_bottom_tick = self.y_min y_axis = NumberLine( x_min=self.y_min, x_max=self.y_max, unit_size=self.space_unit_to_y, tick_frequency=self.y_tick_frequency, leftmost_tick=self.y_bottom_tick, numbers_with_elongated_ticks=self.y_labeled_nums, color=self.axes_color, line_to_number_vect=LEFT, label_direction=LEFT, ) y_axis.shift(self.graph_origin - y_axis.number_to_point(0)) y_axis.rotate(np.pi / 2, about_point=y_axis.number_to_point(0)) if len(self.y_labeled_nums) > 0: if self.exclude_zero_label: self.y_labeled_nums = [y for y in self.y_labeled_nums if y != 0] y_axis.add_numbers(self.y_labeled_nums) if self.y_axis_label: y_label = OldTexText(self.y_axis_label) y_label.next_to( y_axis.get_corner(UP + RIGHT), UP + RIGHT, buff=SMALL_BUFF ) y_label.shift_onto_screen() y_axis.add(y_label) self.y_axis_label_mob = y_label if animate: self.play(Write(VGroup(x_axis, y_axis))) else: self.add(x_axis, y_axis) self.x_axis, self.y_axis = self.axes = VGroup(x_axis, y_axis) self.default_graph_colors = it.cycle(self.default_graph_colors) def coords_to_point(self, x, y): assert(hasattr(self, "x_axis") and hasattr(self, "y_axis")) result = self.x_axis.number_to_point(x)[0] * RIGHT result += self.y_axis.number_to_point(y)[1] * UP return result def point_to_coords(self, point): return (self.x_axis.point_to_number(point), self.y_axis.point_to_number(point)) def get_graph( self, func, color=None, x_min=None, x_max=None, **kwargs ): if color is None: color = next(self.default_graph_colors_cycle) if x_min is None: x_min = self.x_min if x_max is None: x_max = self.x_max def parameterized_function(alpha): x = interpolate(x_min, x_max, alpha) y = func(x) if not np.isfinite(y): y = self.y_max return self.coords_to_point(x, y) graph = ParametricCurve( parameterized_function, color=color, **kwargs ) graph.underlying_function = func return graph def input_to_graph_point(self, x, graph): return self.coords_to_point(x, graph.underlying_function(x)) def angle_of_tangent(self, x, graph, dx=0.01): vect = self.input_to_graph_point( x + dx, graph) - self.input_to_graph_point(x, graph) return angle_of_vector(vect) def slope_of_tangent(self, *args, **kwargs): return np.tan(self.angle_of_tangent(*args, **kwargs)) def get_derivative_graph(self, graph, dx=0.01, **kwargs): if "color" not in kwargs: kwargs["color"] = self.default_derivative_color def deriv(x): return self.slope_of_tangent(x, graph, dx) / self.space_unit_to_y return self.get_graph(deriv, **kwargs) def get_graph_label( self, graph, label="f(x)", x_val=None, direction=RIGHT, buff=MED_SMALL_BUFF, color=None, ): label = OldTex(label) color = color or graph.get_color() label.set_color(color) if x_val is None: # Search from right to left for x in np.linspace(self.x_max, self.x_min, 100): point = self.input_to_graph_point(x, graph) if point[1] < FRAME_Y_RADIUS: break x_val = x label.next_to( self.input_to_graph_point(x_val, graph), direction, buff=buff ) label.shift_onto_screen() return label def get_riemann_rectangles( self, graph, x_min=None, x_max=None, dx=0.1, input_sample_type="left", stroke_width=1, stroke_color=BLACK, fill_opacity=1, start_color=None, end_color=None, show_signed_area=True, width_scale_factor=1.001 ): x_min = x_min if x_min is not None else self.x_min x_max = x_max if x_max is not None else self.x_max if start_color is None: start_color = self.default_riemann_start_color if end_color is None: end_color = self.default_riemann_end_color rectangles = VGroup() x_range = np.arange(x_min, x_max, dx) colors = color_gradient([start_color, end_color], len(x_range)) for x, color in zip(x_range, colors): if input_sample_type == "left": sample_input = x elif input_sample_type == "right": sample_input = x + dx elif input_sample_type == "center": sample_input = x + 0.5 * dx else: raise Exception("Invalid input sample type") graph_point = self.input_to_graph_point(sample_input, graph) points = VGroup(*list(map(VectorizedPoint, [ self.coords_to_point(x, 0), self.coords_to_point(x + width_scale_factor * dx, 0), graph_point ]))) rect = Rectangle() rect.replace(points, stretch=True) if graph_point[1] < self.graph_origin[1] and show_signed_area: fill_color = invert_color(color) else: fill_color = color rect.set_fill(fill_color, opacity=fill_opacity) rect.set_stroke(stroke_color, width=stroke_width) rectangles.add(rect) return rectangles def get_riemann_rectangles_list( self, graph, n_iterations, max_dx=0.5, power_base=2, stroke_width=1, **kwargs ): return [ self.get_riemann_rectangles( graph=graph, dx=float(max_dx) / (power_base**n), stroke_width=float(stroke_width) / (power_base**n), **kwargs ) for n in range(n_iterations) ] def get_area(self, graph, t_min, t_max): numerator = max(t_max - t_min, 0.0001) dx = float(numerator) / self.num_rects return self.get_riemann_rectangles( graph, x_min=t_min, x_max=t_max, dx=dx, stroke_width=0, ).set_fill(opacity=self.area_opacity) def transform_between_riemann_rects(self, curr_rects, new_rects, **kwargs): transform_kwargs = { "run_time": 2, "lag_ratio": 0.5 } added_anims = kwargs.get("added_anims", []) transform_kwargs.update(kwargs) curr_rects.align_family(new_rects) x_coords = set() # Keep track of new repetitions for rect in curr_rects: x = rect.get_center()[0] if x in x_coords: rect.set_fill(opacity=0) else: x_coords.add(x) self.play( Transform(curr_rects, new_rects, **transform_kwargs), *added_anims ) def get_vertical_line_to_graph( self, x, graph, line_class=Line, **line_kwargs ): if "color" not in line_kwargs: line_kwargs["color"] = graph.get_color() return line_class( self.coords_to_point(x, 0), self.input_to_graph_point(x, graph), **line_kwargs ) def get_vertical_lines_to_graph( self, graph, x_min=None, x_max=None, num_lines=20, **kwargs ): x_min = x_min or self.x_min x_max = x_max or self.x_max return VGroup(*[ self.get_vertical_line_to_graph(x, graph, **kwargs) for x in np.linspace(x_min, x_max, num_lines) ]) def get_secant_slope_group( self, x, graph, dx=None, dx_line_color=None, df_line_color=None, dx_label=None, df_label=None, include_secant_line=True, secant_line_color=None, secant_line_length=10, ): """ Resulting group is of the form VGroup( dx_line, df_line, dx_label, (if applicable) df_label, (if applicable) secant_line, (if applicable) ) with attributes of those names. """ kwargs = locals() kwargs.pop("self") group = VGroup() group.kwargs = kwargs dx = dx or float(self.x_max - self.x_min) / 10 dx_line_color = dx_line_color or self.default_input_color df_line_color = df_line_color or graph.get_color() p1 = self.input_to_graph_point(x, graph) p2 = self.input_to_graph_point(x + dx, graph) interim_point = p2[0] * RIGHT + p1[1] * UP group.dx_line = Line( p1, interim_point, color=dx_line_color ) group.df_line = Line( interim_point, p2, color=df_line_color ) group.add(group.dx_line, group.df_line) labels = VGroup() if dx_label is not None: group.dx_label = OldTex(dx_label) labels.add(group.dx_label) group.add(group.dx_label) if df_label is not None: group.df_label = OldTex(df_label) labels.add(group.df_label) group.add(group.df_label) if len(labels) > 0: max_width = 0.8 * group.dx_line.get_width() max_height = 0.8 * group.df_line.get_height() if labels.get_width() > max_width: labels.set_width(max_width) if labels.get_height() > max_height: labels.set_height(max_height) if dx_label is not None: group.dx_label.next_to( group.dx_line, np.sign(dx) * DOWN, buff=group.dx_label.get_height() / 2 ) group.dx_label.set_color(group.dx_line.get_color()) if df_label is not None: group.df_label.next_to( group.df_line, np.sign(dx) * RIGHT, buff=group.df_label.get_height() / 2 ) group.df_label.set_color(group.df_line.get_color()) if include_secant_line: secant_line_color = secant_line_color or self.default_derivative_color group.secant_line = Line(p1, p2, color=secant_line_color) group.secant_line.scale( secant_line_length / group.secant_line.get_length() ) group.add(group.secant_line) return group def add_T_label(self, x_val, side=RIGHT, label=None, color=WHITE, animated=False, **kwargs): triangle = RegularPolygon(n=3, start_angle=np.pi / 2) triangle.set_height(MED_SMALL_BUFF) triangle.move_to(self.coords_to_point(x_val, 0), UP) triangle.set_fill(color, 1) triangle.set_stroke(width=0) if label is None: T_label = OldTex(self.variable_point_label, fill_color=color) else: T_label = OldTex(label, fill_color=color) T_label.next_to(triangle, DOWN) v_line = self.get_vertical_line_to_graph( x_val, self.v_graph, color=YELLOW ) if animated: self.play( DrawBorderThenFill(triangle), ShowCreation(v_line), Write(T_label, run_time=1), **kwargs ) if np.all(side == LEFT): self.left_T_label_group = VGroup(T_label, triangle) self.left_v_line = v_line self.add(self.left_T_label_group, self.left_v_line) elif np.all(side == RIGHT): self.right_T_label_group = VGroup(T_label, triangle) self.right_v_line = v_line self.add(self.right_T_label_group, self.right_v_line) def get_animation_integral_bounds_change( self, graph, new_t_min, new_t_max, fade_close_to_origin=True, run_time=1.0 ): curr_t_min = self.x_axis.point_to_number(self.area.get_left()) curr_t_max = self.x_axis.point_to_number(self.area.get_right()) if new_t_min is None: new_t_min = curr_t_min if new_t_max is None: new_t_max = curr_t_max group = VGroup(self.area) group.add(self.left_v_line) group.add(self.left_T_label_group) group.add(self.right_v_line) group.add(self.right_T_label_group) def update_group(group, alpha): area, left_v_line, left_T_label, right_v_line, right_T_label = group t_min = interpolate(curr_t_min, new_t_min, alpha) t_max = interpolate(curr_t_max, new_t_max, alpha) new_area = self.get_area(graph, t_min, t_max) new_left_v_line = self.get_vertical_line_to_graph( t_min, graph ) new_left_v_line.set_color(left_v_line.get_color()) left_T_label.move_to(new_left_v_line.get_bottom(), UP) new_right_v_line = self.get_vertical_line_to_graph( t_max, graph ) new_right_v_line.set_color(right_v_line.get_color()) right_T_label.move_to(new_right_v_line.get_bottom(), UP) # Fade close to 0 if fade_close_to_origin: if len(left_T_label) > 0: left_T_label[0].set_fill(opacity=min(1, np.abs(t_min))) if len(right_T_label) > 0: right_T_label[0].set_fill(opacity=min(1, np.abs(t_max))) Transform(area, new_area).update(1) Transform(left_v_line, new_left_v_line).update(1) Transform(right_v_line, new_right_v_line).update(1) return group return UpdateFromAlphaFunc(group, update_group, run_time=run_time) def animate_secant_slope_group_change( self, secant_slope_group, target_dx=None, target_x=None, run_time=3, added_anims=None, **anim_kwargs ): if target_dx is None and target_x is None: raise Exception( "At least one of target_x and target_dx must not be None") if added_anims is None: added_anims = [] start_dx = secant_slope_group.kwargs["dx"] start_x = secant_slope_group.kwargs["x"] if target_dx is None: target_dx = start_dx if target_x is None: target_x = start_x def update_func(group, alpha): dx = interpolate(start_dx, target_dx, alpha) x = interpolate(start_x, target_x, alpha) kwargs = dict(secant_slope_group.kwargs) kwargs["dx"] = dx kwargs["x"] = x new_group = self.get_secant_slope_group(**kwargs) group.become(new_group) return group self.play( UpdateFromAlphaFunc( secant_slope_group, update_func, run_time=run_time, **anim_kwargs ), *added_anims ) secant_slope_group.kwargs["x"] = target_x secant_slope_group.kwargs["dx"] = target_dx
videos_3b1b/once_useful_constructs/dict_shenanigans.py
import inspect from manimlib.utils.dict_ops import merge_dicts_recursively def filtered_locals(caller_locals): result = caller_locals.copy() ignored_local_args = ["self", "kwargs"] for arg in ignored_local_args: result.pop(arg, caller_locals) return result def digest_config(obj, kwargs, caller_locals={}): """ (Deprecated) Sets init args and CONFIG values as local variables The purpose of this function is to ensure that all configuration of any object is inheritable, able to be easily passed into instantiation, and is attached as an attribute of the object. """ # Assemble list of CONFIGs from all super classes classes_in_hierarchy = [obj.__class__] static_configs = [] while len(classes_in_hierarchy) > 0: Class = classes_in_hierarchy.pop() classes_in_hierarchy += Class.__bases__ if hasattr(Class, "CONFIG"): static_configs.append(Class.CONFIG) # Order matters a lot here, first dicts have higher priority caller_locals = filtered_locals(caller_locals) all_dicts = [kwargs, caller_locals, obj.__dict__] all_dicts += static_configs obj.__dict__ = merge_dicts_recursively(*reversed(all_dicts)) def digest_locals(obj, keys=None): caller_locals = filtered_locals( inspect.currentframe().f_back.f_locals ) if keys is None: keys = list(caller_locals.keys()) for key in keys: setattr(obj, key, caller_locals[key]) # Occasionally convenient in order to write dict.x instead of more laborious # (and less in keeping with all other attr accesses) dict["x"] class DictAsObject(object): def __init__(self, dict): self.__dict__ = dict def get_all_descendent_classes(Class): awaiting_review = [Class] result = [] while awaiting_review: Child = awaiting_review.pop() awaiting_review += Child.__subclasses__() result.append(Child) return result
videos_3b1b/once_useful_constructs/linear_algebra.py
from __future__ import annotations import itertools as it import numpy as np from manimlib.constants import DEFAULT_MOBJECT_TO_MOBJECT_BUFFER from manimlib.constants import LEFT, RIGHT from manimlib.constants import WHITE from manimlib.mobject.shape_matchers import BackgroundRectangle from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Sequence, Union import numpy.typing as npt from manimlib.typing import ManimColor, VectNArray, Self VECTOR_LABEL_SCALE_FACTOR = 0.8 def matrix_to_tex_string(matrix: npt.ArrayLike) -> str: matrix = np.array(matrix).astype("str") if matrix.ndim == 1: matrix = matrix.reshape((matrix.size, 1)) n_rows, n_cols = matrix.shape prefix = R"\left[ \begin{array}{%s}" % ("c" * n_cols) suffix = R"\end{array} \right]" rows = [ " & ".join(row) for row in matrix ] return prefix + R" \\ ".join(rows) + suffix def matrix_to_mobject(matrix: npt.ArrayLike) -> Tex: return Tex(matrix_to_tex_string(matrix)) def vector_coordinate_label( vector_mob: VMobject, integer_labels: bool = True, n_dim: int = 2, color: ManimColor = WHITE ) -> Matrix: vect = np.array(vector_mob.get_end()) if integer_labels: vect = np.round(vect).astype(int) vect = vect[:n_dim] vect = vect.reshape((n_dim, 1)) label = Matrix(vect, add_background_rectangles_to_entries=True) label.scale(VECTOR_LABEL_SCALE_FACTOR) shift_dir = np.array(vector_mob.get_end()) if shift_dir[0] >= 0: # Pointing right shift_dir -= label.get_left() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * LEFT else: # Pointing left shift_dir -= label.get_right() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * RIGHT label.shift(shift_dir) label.set_color(color) label.rect = BackgroundRectangle(label) label.add_to_back(label.rect) return label def get_det_text( matrix: Matrix, determinant: int | str | None = None, background_rect: bool = False, initial_scale_factor: int = 2 ) -> VGroup: parens = Tex("()") parens.scale(initial_scale_factor) parens.stretch_to_fit_height(matrix.get_height()) l_paren, r_paren = parens.split() l_paren.next_to(matrix, LEFT, buff=0.1) r_paren.next_to(matrix, RIGHT, buff=0.1) det = TexText("det") det.scale(initial_scale_factor) det.next_to(l_paren, LEFT, buff=0.1) if background_rect: det.add_background_rectangle() det_text = VGroup(det, l_paren, r_paren) if determinant is not None: eq = Tex("=") eq.next_to(r_paren, RIGHT, buff=0.1) result = Tex(str(determinant)) result.next_to(eq, RIGHT, buff=0.2) det_text.add(eq, result) return det_text
videos_3b1b/once_useful_constructs/reconfigurable_scene.py
from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.mobject import Mobject from manimlib.scene.scene import Scene class ReconfigurableScene(Scene): """ Note, this seems to no longer work as intented. """ CONFIG = { "allow_recursion": True, } def setup(self): self.states = [] self.num_recursions = 0 def transition_to_alt_config( self, return_to_original_configuration=True, transformation_kwargs=None, **new_config ): if transformation_kwargs is None: transformation_kwargs = {} original_state = self.get_state() state_copy = original_state.copy() self.states.append(state_copy) if not self.allow_recursion: return alt_scene = self.__class__( skip_animations=True, allow_recursion=False, **new_config ) alt_state = alt_scene.states[len(self.states) - 1] if return_to_original_configuration: self.clear() self.transition_between_states( state_copy, alt_state, **transformation_kwargs ) self.transition_between_states( state_copy, original_state, **transformation_kwargs ) self.clear() self.add(*original_state) else: self.transition_between_states( original_state, alt_state, **transformation_kwargs ) self.__dict__.update(new_config) def get_state(self): # Want to return a mobject that maintains the most # structure. The way to do that is to extract only # those that aren't inside another. return Mobject(*self.get_top_level_mobjects()) def transition_between_states(self, start_state, target_state, **kwargs): self.play(Transform(start_state, target_state, **kwargs)) self.wait()
videos_3b1b/once_useful_constructs/fractals.py
from functools import reduce import random from manimlib.constants import * # from manimlib.for_3b1b_videos.pi_creature import PiCreature # from manimlib.for_3b1b_videos.pi_creature import Randolph # from manimlib.for_3b1b_videos.pi_creature import get_all_pi_creature_modes from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Polygon from manimlib.mobject.geometry import RegularPolygon from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import interpolate from manimlib.utils.color import color_gradient from manimlib.utils.dict_ops import digest_config from manimlib.utils.space_ops import center_of_mass from manimlib.utils.space_ops import compass_directions from manimlib.utils.space_ops import rotate_vector from manimlib.utils.space_ops import rotation_matrix def rotate(points, angle=np.pi, axis=OUT): if axis is None: return points matrix = rotation_matrix(angle, axis) points = np.dot(points, np.transpose(matrix)) return points def fractalify(vmobject, order=3, *args, **kwargs): for x in range(order): fractalification_iteration(vmobject) return vmobject def fractalification_iteration(vmobject, dimension=1.05, num_inserted_anchors_range=list(range(1, 4))): num_points = vmobject.get_num_points() if num_points > 0: # original_anchors = vmobject.get_anchors() original_anchors = [ vmobject.point_from_proportion(x) for x in np.linspace(0, 1 - 1. / num_points, num_points) ] new_anchors = [] for p1, p2, in zip(original_anchors, original_anchors[1:]): num_inserts = random.choice(num_inserted_anchors_range) inserted_points = [ interpolate(p1, p2, alpha) for alpha in np.linspace(0, 1, num_inserts + 2)[1:-1] ] mass_scaling_factor = 1. / (num_inserts + 1) length_scaling_factor = mass_scaling_factor**(1. / dimension) target_length = get_norm(p1 - p2) * length_scaling_factor curr_length = get_norm(p1 - p2) * mass_scaling_factor # offset^2 + curr_length^2 = target_length^2 offset_len = np.sqrt(target_length**2 - curr_length**2) unit_vect = (p1 - p2) / get_norm(p1 - p2) offset_unit_vect = rotate_vector(unit_vect, np.pi / 2) inserted_points = [ point + u * offset_len * offset_unit_vect for u, point in zip(it.cycle([-1, 1]), inserted_points) ] new_anchors += [p1] + inserted_points new_anchors.append(original_anchors[-1]) vmobject.set_points_as_corners(new_anchors) vmobject.set_submobjects([ fractalification_iteration( submob, dimension, num_inserted_anchors_range) for submob in vmobject.submobjects ]) return vmobject class SelfSimilarFractal(VMobject): order = 5 num_subparts = 3 height = 4 colors = [RED, WHITE] stroke_width = 1 # Not the right way to assign stroke width fill_opacity = 1 # Not the right way to assign fill opacity def init_colors(self): VMobject.init_colors(self) self.set_color_by_gradient(*self.colors) def init_points(self): order_n_self = self.get_order_n_self(self.order) if self.order == 0: self.set_submobjects([order_n_self]) else: self.set_submobjects(order_n_self.submobjects) return self def get_order_n_self(self, order): if order == 0: result = self.get_seed_shape() else: lower_order = self.get_order_n_self(order - 1) subparts = [ lower_order.copy() for x in range(self.num_subparts) ] self.arrange_subparts(*subparts) result = VGroup(*subparts) result.set_height(self.height) result.center() return result def get_seed_shape(self): raise Exception("Not implemented") def arrange_subparts(self, *subparts): raise Exception("Not implemented") class Sierpinski(SelfSimilarFractal): def get_seed_shape(self): return Polygon( RIGHT, np.sqrt(3) * UP, LEFT, ) def arrange_subparts(self, *subparts): tri1, tri2, tri3 = subparts tri1.move_to(tri2.get_corner(DOWN + LEFT), UP) tri3.move_to(tri2.get_corner(DOWN + RIGHT), UP) class DiamondFractal(SelfSimilarFractal): num_subparts = 4 height = 4 colors = [GREEN_E, YELLOW] def get_seed_shape(self): return RegularPolygon(n=4) def arrange_subparts(self, *subparts): # VGroup(*subparts).rotate(np.pi/4) for part, vect in zip(subparts, compass_directions(start_vect=UP + RIGHT)): part.next_to(ORIGIN, vect, buff=0) VGroup(*subparts).rotate(np.pi / 4, about_point=ORIGIN) class PentagonalFractal(SelfSimilarFractal): num_subparts = 5 colors = [MAROON_B, YELLOW, RED] height = 6 def get_seed_shape(self): return RegularPolygon(n=5, start_angle=np.pi / 2) def arrange_subparts(self, *subparts): for x, part in enumerate(subparts): part.shift(0.95 * part.get_height() * UP) part.rotate(2 * np.pi * x / 5, about_point=ORIGIN) class PentagonalPiCreatureFractal(PentagonalFractal): def init_colors(self): SelfSimilarFractal.init_colors(self) internal_pis = [ pi for pi in self.get_family() if isinstance(pi, PiCreature) ] colors = color_gradient(self.colors, len(internal_pis)) for pi, color in zip(internal_pis, colors): pi.init_colors() pi.body.set_stroke(color, width=0.5) pi.set_color(color) def get_seed_shape(self): return Randolph(mode="shruggie") def arrange_subparts(self, *subparts): for part in subparts: part.rotate(2 * np.pi / 5, about_point=ORIGIN) PentagonalFractal.arrange_subparts(self, *subparts) class PiCreatureFractal(VMobject): order = 7 scale_val = 2.5 start_mode = "hooray" height = 6 colors = [ BLUE_D, BLUE_B, MAROON_B, MAROON_D, GREY, YELLOW, RED, GREY_BROWN, RED, RED_E, ] random_seed = 0 stroke_width = 0 def init_colors(self): VMobject.init_colors(self) internal_pis = [ pi for pi in self.get_family() if isinstance(pi, PiCreature) ] random.seed(self.random_seed) for pi in reversed(internal_pis): color = random.choice(self.colors) pi.set_color(color) pi.set_stroke(color, width=0) def init_points(self): random.seed(self.random_seed) modes = get_all_pi_creature_modes() seed = PiCreature(mode=self.start_mode) seed.set_height(self.height) seed.to_edge(DOWN) creatures = [seed] self.add(VGroup(seed)) for x in range(self.order): new_creatures = [] for creature in creatures: for eye, vect in zip(creature.eyes, [LEFT, RIGHT]): new_creature = PiCreature( mode=random.choice(modes) ) new_creature.set_height( self.scale_val * eye.get_height() ) new_creature.next_to( eye, vect, buff=0, aligned_edge=DOWN ) new_creatures.append(new_creature) creature.look_at(random.choice(new_creatures)) self.add_to_back(VGroup(*new_creatures)) creatures = new_creatures # def init_colors(self): # VMobject.init_colors(self) # self.set_color_by_gradient(*self.colors) class WonkyHexagonFractal(SelfSimilarFractal): num_subparts = 7 def get_seed_shape(self): return RegularPolygon(n=6) def arrange_subparts(self, *subparts): for i, piece in enumerate(subparts): piece.rotate(i * np.pi / 12, about_point=ORIGIN) p1, p2, p3, p4, p5, p6, p7 = subparts center_row = VGroup(p1, p4, p7) center_row.arrange(RIGHT, buff=0) for p in p2, p3, p5, p6: p.set_width(p1.get_width()) p2.move_to(p1.get_top(), DOWN + LEFT) p3.move_to(p1.get_bottom(), UP + LEFT) p5.move_to(p4.get_top(), DOWN + LEFT) p6.move_to(p4.get_bottom(), UP + LEFT) class CircularFractal(SelfSimilarFractal): num_subparts = 3 colors = [GREEN, BLUE, GREY] def get_seed_shape(self): return Circle() def arrange_subparts(self, *subparts): if not hasattr(self, "been_here"): self.num_subparts = 3 + self.order self.been_here = True for i, part in enumerate(subparts): theta = np.pi / self.num_subparts part.next_to( ORIGIN, UP, buff=self.height / (2 * np.tan(theta)) ) part.rotate(i * 2 * np.pi / self.num_subparts, about_point=ORIGIN) self.num_subparts -= 1 ######## Space filling curves ############ class JaggedCurvePiece(VMobject): def insert_n_curves(self, n): if self.get_num_curves() == 0: self.set_points(np.zeros((1, 3))) anchors = self.get_anchors() indices = np.linspace( 0, len(anchors) - 1, n + len(anchors) ).astype('int') self.set_points_as_corners(anchors[indices]) class FractalCurve(VMobject): radius = 3 order = 5 colors = [RED, GREEN] num_submobjects = 20 monochromatic = False order_to_stroke_width_map = { 3: 3, 4: 2, 5: 1, } def init_points(self): points = self.get_anchor_points() self.set_points_as_corners(points) if not self.monochromatic: alphas = np.linspace(0, 1, self.num_submobjects) for alpha_pair in zip(alphas, alphas[1:]): submobject = JaggedCurvePiece() submobject.pointwise_become_partial( self, *alpha_pair ) self.add(submobject) self.set_points(np.zeros((0, 3))) def init_colors(self): VMobject.init_colors(self) self.set_color_by_gradient(*self.colors) for order in sorted(self.order_to_stroke_width_map.keys()): if self.order >= order: self.set_stroke(width=self.order_to_stroke_width_map[order]) def get_anchor_points(self): raise Exception("Not implemented") class LindenmayerCurve(FractalCurve): axiom = "A" rule = {} scale_factor = 2 radius = 3 start_step = RIGHT angle = np.pi / 2 def expand_command_string(self, command): result = "" for letter in command: if letter in self.rule: result += self.rule[letter] else: result += letter return result def get_command_string(self): result = self.axiom for x in range(self.order): result = self.expand_command_string(result) return result def get_anchor_points(self): step = float(self.radius) * self.start_step step /= (self.scale_factor**self.order) curr = np.zeros(3) result = [curr] for letter in self.get_command_string(): if letter == "+": step = rotate(step, self.angle) elif letter == "-": step = rotate(step, -self.angle) else: curr = curr + step result.append(curr) return np.array(result) - center_of_mass(result) class SelfSimilarSpaceFillingCurve(FractalCurve): offsets = [] # keys must awkwardly be in string form... offset_to_rotation_axis = {} scale_factor = 2 radius_scale_factor = 0.5 def transform(self, points, offset): """ How to transform the copy of points shifted by offset. Generally meant to be extended in subclasses """ copy = np.array(points) if str(offset) in self.offset_to_rotation_axis: copy = rotate( copy, axis=self.offset_to_rotation_axis[str(offset)] ) copy /= self.scale_factor, copy += offset * self.radius * self.radius_scale_factor return copy def refine_into_subparts(self, points): transformed_copies = [ self.transform(points, offset) for offset in self.offsets ] return reduce( lambda a, b: np.append(a, b, axis=0), transformed_copies ) def get_anchor_points(self): points = np.zeros((1, 3)) for count in range(self.order): points = self.refine_into_subparts(points) return points def generate_grid(self): raise Exception("Not implemented") class HilbertCurve(SelfSimilarSpaceFillingCurve): offsets = [ LEFT + DOWN, LEFT + UP, RIGHT + UP, RIGHT + DOWN, ] offset_to_rotation_axis = { str(LEFT + DOWN): RIGHT + UP, str(RIGHT + DOWN): RIGHT + DOWN, } class HilbertCurve3D(SelfSimilarSpaceFillingCurve): offsets = [ RIGHT + DOWN + IN, LEFT + DOWN + IN, LEFT + DOWN + OUT, RIGHT + DOWN + OUT, RIGHT + UP + OUT, LEFT + UP + OUT, LEFT + UP + IN, RIGHT + UP + IN, ] offset_to_rotation_axis_and_angle = { str(RIGHT + DOWN + IN): (LEFT + UP + OUT, 2 * np.pi / 3), str(LEFT + DOWN + IN): (RIGHT + DOWN + IN, 2 * np.pi / 3), str(LEFT + DOWN + OUT): (RIGHT + DOWN + IN, 2 * np.pi / 3), str(RIGHT + DOWN + OUT): (UP, np.pi), str(RIGHT + UP + OUT): (UP, np.pi), str(LEFT + UP + OUT): (LEFT + DOWN + OUT, 2 * np.pi / 3), str(LEFT + UP + IN): (LEFT + DOWN + OUT, 2 * np.pi / 3), str(RIGHT + UP + IN): (RIGHT + UP + IN, 2 * np.pi / 3), } # Rewrote transform method to include the rotation angle def transform(self, points, offset): copy = np.array(points) copy = rotate( copy, axis=self.offset_to_rotation_axis_and_angle[str(offset)][0], angle=self.offset_to_rotation_axis_and_angle[str(offset)][1], ) copy /= self.scale_factor, copy += offset * self.radius * self.radius_scale_factor return copy class PeanoCurve(SelfSimilarSpaceFillingCurve): colors = [PURPLE, TEAL] offsets = [ LEFT + DOWN, LEFT, LEFT + UP, UP, ORIGIN, DOWN, RIGHT + DOWN, RIGHT, RIGHT + UP, ] offset_to_rotation_axis = { str(LEFT): UP, str(UP): RIGHT, str(ORIGIN): LEFT + UP, str(DOWN): RIGHT, str(RIGHT): UP, } scale_factor = 3 radius_scale_factor = 2.0 / 3 class TriangleFillingCurve(SelfSimilarSpaceFillingCurve): colors = [MAROON, YELLOW] offsets = [ LEFT / 4. + DOWN / 6., ORIGIN, RIGHT / 4. + DOWN / 6., UP / 3., ] offset_to_rotation_axis = { str(ORIGIN): RIGHT, str(UP / 3.): UP, } scale_factor = 2 radius_scale_factor = 1.5 class HexagonFillingCurve(SelfSimilarSpaceFillingCurve): start_color = WHITE end_color = BLUE_D axis_offset_pairs = [ (None, 1.5*DOWN + 0.5*np.sqrt(3)*LEFT), (UP+np.sqrt(3)*RIGHT, 1.5*DOWN + 0.5*np.sqrt(3)*RIGHT), (np.sqrt(3)*UP+RIGHT, ORIGIN), ((UP, RIGHT), np.sqrt(3)*LEFT), (None, 1.5*UP + 0.5*np.sqrt(3)*LEFT), (None, 1.5*UP + 0.5*np.sqrt(3)*RIGHT), (RIGHT, np.sqrt(3)*RIGHT), ] scale_factor = 3 radius_scale_factor = 2/(3*np.sqrt(3)) def refine_into_subparts(self, points): return SelfSimilarSpaceFillingCurve.refine_into_subparts( self, rotate(points, np.pi/6, IN) ) class UtahFillingCurve(SelfSimilarSpaceFillingCurve): colors = [WHITE, BLUE_D] axis_offset_pairs = [] scale_factor = 3 radius_scale_factor = 2 / (3 * np.sqrt(3)) class FlowSnake(LindenmayerCurve): colors = [YELLOW, GREEN] axiom = "A" rule = { "A": "A-B--B+A++AA+B-", "B": "+A-BB--B-A++A+B", } radius = 6 # TODO, this is innaccurate scale_factor = np.sqrt(7) start_step = RIGHT angle = -np.pi / 3 def __init__(self, **kwargs): LindenmayerCurve.__init__(self, **kwargs) self.rotate(-self.order * np.pi / 9, about_point=ORIGIN) class SierpinskiCurve(LindenmayerCurve): colors = [RED, WHITE] axiom = "B" rule = { "A": "+B-A-B+", "B": "-A+B+A-", } radius = 6 # TODO, this is innaccurate scale_factor = 2 start_step = RIGHT angle = -np.pi / 3 class KochSnowFlake(LindenmayerCurve): colors = [BLUE_D, WHITE, BLUE_D] axiom = "A--A--A--" rule = { "A": "A+A--A+A" } radius = 4 scale_factor = 3 start_step = RIGHT angle = np.pi / 3 order_to_stroke_width_map = { 3: 3, 5: 2, 6: 1, } def __init__(self, **kwargs): digest_config(self, kwargs) self.scale_factor = 2 * (1 + np.cos(self.angle)) LindenmayerCurve.__init__(self, **kwargs) class KochCurve(KochSnowFlake): axiom = "A--" class QuadraticKoch(LindenmayerCurve): colors = [YELLOW, WHITE, MAROON_B] axiom = "A" rule = {"A": "A+A-A-AA+A+A-A"} radius = 4 scale_factor = 4 start_step = RIGHT angle = np.pi / 2 class QuadraticKochIsland(QuadraticKoch): axiom = "A+A+A+A" class StellarCurve(LindenmayerCurve): start_color = RED end_color = BLUE_E rule = { "A": "+B-A-B+A-B+", "B": "-A+B+A-B+A-", } scale_factor = 3 angle = 2 * np.pi / 5 class SnakeCurve(FractalCurve): start_color = BLUE end_color = YELLOW def get_anchor_points(self): result = [] resolution = 2**self.order step = 2.0 * self.radius / resolution lower_left = ORIGIN + \ LEFT * (self.radius - step / 2) + \ DOWN * (self.radius - step / 2) for y in range(resolution): x_range = list(range(resolution)) if y % 2 == 0: x_range.reverse() for x in x_range: result.append( lower_left + x * step * RIGHT + y * step * UP ) return result
videos_3b1b/once_useful_constructs/matrix_multiplication.py
import numpy as np from manimlib.animation.creation import ShowCreation from manimlib.animation.fading import FadeOut from manimlib.animation.transform import ApplyMethod from manimlib.animation.transform import Transform from manimlib.constants import * from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Line from manimlib.mobject.matrix import Matrix from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene class NumericalMatrixMultiplication(Scene): left_matrix = [[1, 2], [3, 4]] right_matrix = [[5, 6], [7, 8]] use_parens = True def construct(self): left_string_matrix, right_string_matrix = [ np.array(matrix).astype("string") for matrix in (self.left_matrix, self.right_matrix) ] if right_string_matrix.shape[0] != left_string_matrix.shape[1]: raise Exception("Incompatible shapes for matrix multiplication") left = Matrix(left_string_matrix) right = Matrix(right_string_matrix) result = self.get_result_matrix( left_string_matrix, right_string_matrix ) self.organize_matrices(left, right, result) self.animate_product(left, right, result) def get_result_matrix(self, left, right): (m, k), n = left.shape, right.shape[1] mob_matrix = np.array([VGroup()]).repeat(m * n).reshape((m, n)) for a in range(m): for b in range(n): template = "(%s)(%s)" if self.use_parens else "%s%s" parts = [ prefix + template % (left[a][c], right[c][b]) for c in range(k) for prefix in ["" if c == 0 else "+"] ] mob_matrix[a][b] = OldTex(parts, next_to_buff=0.1) return Matrix(mob_matrix) def add_lines(self, left, right): line_kwargs = { "color": BLUE, "stroke_width": 2, } left_rows = [ VGroup(*row) for row in left.get_mob_matrix() ] h_lines = VGroup() for row in left_rows[:-1]: h_line = Line(row.get_left(), row.get_right(), **line_kwargs) h_line.next_to(row, DOWN, buff=left.v_buff / 2.) h_lines.add(h_line) right_cols = [ VGroup(*col) for col in np.transpose(right.get_mob_matrix()) ] v_lines = VGroup() for col in right_cols[:-1]: v_line = Line(col.get_top(), col.get_bottom(), **line_kwargs) v_line.next_to(col, RIGHT, buff=right.h_buff / 2.) v_lines.add(v_line) self.play(ShowCreation(h_lines)) self.play(ShowCreation(v_lines)) self.wait() self.show_frame() def organize_matrices(self, left, right, result): equals = OldTex("=") everything = VGroup(left, right, equals, result) everything.arrange() everything.set_width(FRAME_WIDTH - 1) self.add(everything) def animate_product(self, left, right, result): l_matrix = left.get_mob_matrix() r_matrix = right.get_mob_matrix() result_matrix = result.get_mob_matrix() circle = Circle( radius=l_matrix[0][0].get_height(), color=GREEN ) circles = VGroup(*[ entry.get_point_mobject() for entry in (l_matrix[0][0], r_matrix[0][0]) ]) (m, k), n = l_matrix.shape, r_matrix.shape[1] for mob in result_matrix.flatten(): mob.set_color(BLACK) lagging_anims = [] for a in range(m): for b in range(n): for c in range(k): l_matrix[a][c].set_color(YELLOW) r_matrix[c][b].set_color(YELLOW) for c in range(k): start_parts = VGroup( l_matrix[a][c].copy(), r_matrix[c][b].copy() ) result_entry = result_matrix[a][b].split()[c] new_circles = VGroup(*[ circle.copy().shift(part.get_center()) for part in start_parts.split() ]) self.play(Transform(circles, new_circles)) self.play( Transform( start_parts, result_entry.copy().set_color(YELLOW), path_arc=-np.pi / 2, lag_ratio=0, ), *lagging_anims ) result_entry.set_color(YELLOW) self.remove(start_parts) lagging_anims = [ ApplyMethod(result_entry.set_color, WHITE) ] for c in range(k): l_matrix[a][c].set_color(WHITE) r_matrix[c][b].set_color(WHITE) self.play(FadeOut(circles), *lagging_anims) self.wait()
videos_3b1b/once_useful_constructs/butterfly_curve.py
from manim_imports_ext import * class RotatingButterflyCurve(Animation): """ Pretty hacky, but should only be redone in the context of a broader 4d mobject class """ CONFIG = { "space_epsilon": 0.002, "grid_line_sep": 0.2, "radius": 2, "radians": 2 * np.pi, "run_time": 15, "rate_func": linear, } def __init__(self, **kwargs): digest_config(self, kwargs) fine_range = np.arange(-self.radius, self.radius, self.space_epsilon) corse_range = np.arange(-self.radius, self.radius, self.grid_line_sep) self.points = np.array([ [x, y, x * x, y * y] for a in fine_range for b in corse_range for x, y in [(a, b), (b, a)] ]) graph_rgb = Color(TEAL).get_rgb() self.rgbas = np.array([graph_rgb] * len(self.points)) colors = iter([YELLOW_A, YELLOW_B, YELLOW_C, YELLOW_D]) for i in range(4): vect = np.zeros(4) vect[i] = 1 line_range = np.arange(-FRAME_Y_RADIUS, FRAME_Y_RADIUS, self.space_epsilon) self.points = np.append(self.points, [ x * vect for x in line_range ], axis=0) axis_rgb = Color(next(colors)).get_rgb() self.rgbas = np.append( self.rgbas, [axis_rgb] * len(line_range), axis=0) self.quads = [(0, 1, 2, 3), (0, 1, 0, 1), (3, 2, 1, 0)] self.multipliers = [0.9, 1, 1.1] Animation.__init__(self, Mobject(), **kwargs) def interpolate_mobject(self, alpha): angle = alpha * self.radians rot_matrix = np.identity(4) for quad, mult in zip(self.quads, self.multipliers): base = np.identity(4) theta = mult * angle base[quad[:2], quad[2]] = [np.cos(theta), np.sin(theta)] base[quad[:2], quad[3]] = [-np.sin(theta), np.cos(theta)] rot_matrix = np.dot(rot_matrix, base) points = np.dot(self.points, np.transpose(rot_matrix)) self.mobject.points = points[:, :3] self.mobject.rgbas = self.rgbas class RotatingFourDButterflyCurve(Scene): def construct(self): self.play(RotatingButterflyCurve())
videos_3b1b/once_useful_constructs/combinatorics.py
from manimlib.constants import * from manimlib.mobject.numbers import Integer from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.types.vectorized_mobject import VMobject, VGroup from manimlib.scene.scene import Scene from manimlib.utils.simple_functions import choose DEFAULT_COUNT_NUM_OFFSET = (FRAME_X_RADIUS - 1, FRAME_Y_RADIUS - 1, 0) DEFAULT_COUNT_RUN_TIME = 5.0 class CountingScene(Scene): def count(self, items, item_type="mobject", *args, **kwargs): if item_type == "mobject": self.count_mobjects(items, *args, **kwargs) elif item_type == "region": self.count_regions(items, *args, **kwargs) else: raise Exception("Unknown item_type, should be mobject or region") return self def count_mobjects( self, mobjects, mode="highlight", color="red", display_numbers=True, num_offset=DEFAULT_COUNT_NUM_OFFSET, run_time=DEFAULT_COUNT_RUN_TIME, ): """ Note, leaves final number mobject as "number" attribute mode can be "highlight", "show_creation" or "show", otherwise a warning is given and nothing is animating during the count """ if len(mobjects) > 50: # TODO raise Exception("I don't know if you should be counting \ too many mobjects...") if len(mobjects) == 0: raise Exception("Counting mobject list of length 0") if mode not in ["highlight", "show_creation", "show"]: raise Warning("Unknown mode") frame_time = run_time / len(mobjects) if mode == "highlight": self.add(*mobjects) for mob, num in zip(mobjects, it.count(1)): if display_numbers: num_mob = OldTex(str(num)) num_mob.center().shift(num_offset) self.add(num_mob) if mode == "highlight": original_color = mob.color mob.set_color(color) self.wait(frame_time) mob.set_color(original_color) if mode == "show_creation": self.play(ShowCreation(mob, run_time=frame_time)) if mode == "show": self.add(mob) self.wait(frame_time) if display_numbers: self.remove(num_mob) if display_numbers: self.add(num_mob) self.number = num_mob return self def count_regions(self, regions, mode="one_at_a_time", num_offset=DEFAULT_COUNT_NUM_OFFSET, run_time=DEFAULT_COUNT_RUN_TIME, **unused_kwargsn): if mode not in ["one_at_a_time", "show_all"]: raise Warning("Unknown mode") frame_time = run_time / (len(regions)) for region, count in zip(regions, it.count(1)): num_mob = OldTex(str(count)) num_mob.center().shift(num_offset) self.add(num_mob) self.set_color_region(region) self.wait(frame_time) if mode == "one_at_a_time": self.reset_background() self.remove(num_mob) self.add(num_mob) self.number = num_mob return self def combinationMobject(n, k): return Integer(choose(n, k)) class GeneralizedPascalsTriangle(VMobject): nrows = 7 height = FRAME_HEIGHT - 1 width = 1.5 * FRAME_X_RADIUS portion_to_fill = 0.7 submob_class = combinationMobject def init_points(self): self.cell_height = float(self.height) / self.nrows self.cell_width = float(self.width) / self.nrows self.bottom_left = (self.cell_width * self.nrows / 2.0) * LEFT + \ (self.cell_height * self.nrows / 2.0) * DOWN self.coords_to_mobs = {} self.coords = [ (n, k) for n in range(self.nrows) for k in range(n + 1) ] for n, k in self.coords: center = self.coords_to_center(n, k) num_mob = self.submob_class(n, k) # OldTex(str(num)) scale_factor = min( 1, self.portion_to_fill * self.cell_height / num_mob.get_height(), self.portion_to_fill * self.cell_width / num_mob.get_width(), ) num_mob.center().scale(scale_factor).shift(center) if n not in self.coords_to_mobs: self.coords_to_mobs[n] = {} self.coords_to_mobs[n][k] = num_mob self.add(*[ self.coords_to_mobs[n][k] for n, k in self.coords ]) return self def coords_to_center(self, n, k): x_offset = self.cell_width * (k + self.nrows / 2.0 - n / 2.0) y_offset = self.cell_height * (self.nrows - n) return self.bottom_left + x_offset * RIGHT + y_offset * UP def generate_n_choose_k_mobs(self): self.coords_to_n_choose_k = {} for n, k in self.coords: nck_mob = OldTex(r"{%d \choose %d}" % (n, k)) scale_factor = min( 1, self.portion_to_fill * self.cell_height / nck_mob.get_height(), self.portion_to_fill * self.cell_width / nck_mob.get_width(), ) center = self.coords_to_mobs[n][k].get_center() nck_mob.center().scale(scale_factor).shift(center) if n not in self.coords_to_n_choose_k: self.coords_to_n_choose_k[n] = {} self.coords_to_n_choose_k[n][k] = nck_mob return self def fill_with_n_choose_k(self): if not hasattr(self, "coords_to_n_choose_k"): self.generate_n_choose_k_mobs() self.set_submobjects([]) self.add(*[ self.coords_to_n_choose_k[n][k] for n, k in self.coords ]) return self def generate_sea_of_zeros(self): zero = OldTex("0") self.sea_of_zeros = [] for n in range(self.nrows): for a in range((self.nrows - n) / 2 + 1): for k in (n + a + 1, -a - 1): self.coords.append((n, k)) mob = zero.copy() mob.shift(self.coords_to_center(n, k)) self.coords_to_mobs[n][k] = mob self.add(mob) return self def get_lowest_row(self): n = self.nrows - 1 lowest_row = VGroup(*[ self.coords_to_mobs[n][k] for k in range(n + 1) ]) return lowest_row class PascalsTriangle(GeneralizedPascalsTriangle): submob_class = combinationMobject
videos_3b1b/once_useful_constructs/complex_transformation_scene.py
from manimlib.animation.animation import Animation from manimlib.animation.movement import ComplexHomotopy from manimlib.animation.transform import MoveToTarget from manimlib.constants import * from manimlib.mobject.coordinate_systems import ComplexPlane from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene # TODO, refactor this full scene class ComplexTransformationScene(Scene): CONFIG = { "plane_config": {}, "background_fade_factor": 0.5, "use_multicolored_plane": False, "vert_start_color": BLUE, # TODO "vert_end_color": BLUE, "horiz_start_color": BLUE, "horiz_end_color": BLUE, "num_anchors_to_add_per_line": 50, "post_transformation_stroke_width": None, "default_apply_complex_function_kwargs": { "run_time": 5, }, "background_label_scale_val": 0.5, "include_coordinate_labels": True, } def setup(self): self.foreground_mobjects = [] self.transformable_mobjects = [] self.add_background_plane() if self.include_coordinate_labels: self.add_coordinate_labels() def add_foreground_mobject(self, mobject): self.add_foreground_mobjects(mobject) def add_transformable_mobjects(self, *mobjects): self.transformable_mobjects += list(mobjects) self.add(*mobjects) def add_foreground_mobjects(self, *mobjects): self.foreground_mobjects += list(mobjects) Scene.add(self, *mobjects) def add(self, *mobjects): Scene.add(self, *list(mobjects) + self.foreground_mobjects) def play(self, *animations, **kwargs): Scene.play( self, *list(animations) + list(map(Animation, self.foreground_mobjects)), **kwargs ) def add_background_plane(self): background = ComplexPlane(**self.plane_config) background.fade(self.background_fade_factor) self.add(background) self.background = background def add_coordinate_labels(self): self.background.add_coordinates() self.add(self.background) def add_transformable_plane(self, **kwargs): self.plane = self.get_transformable_plane() self.add(self.plane) def get_transformable_plane(self, x_range=None, y_range=None): """ x_range and y_range would be tuples (min, max) """ plane_config = dict(self.plane_config) shift_val = ORIGIN if x_range is not None: x_min, x_max = x_range plane_config["x_radius"] = x_max - x_min shift_val += (x_max + x_min) * RIGHT / 2. if y_range is not None: y_min, y_max = y_range plane_config["y_radius"] = y_max - y_min shift_val += (y_max + y_min) * UP / 2. plane = ComplexPlane(**plane_config) plane.shift(shift_val) if self.use_multicolored_plane: self.paint_plane(plane) return plane def prepare_for_transformation(self, mob): if hasattr(mob, "prepare_for_nonlinear_transform"): mob.prepare_for_nonlinear_transform( self.num_anchors_to_add_per_line ) # TODO... def paint_plane(self, plane): for lines in planes, plane.secondary_lines: lines.set_color_by_gradient( self.vert_start_color, self.vert_end_color, self.horiz_start_color, self.horiz_end_color, ) # plane.axes.set_color_by_gradient( # self.horiz_start_color, # self.vert_start_color # ) def z_to_point(self, z): return self.background.number_to_point(z) def get_transformer(self, **kwargs): transform_kwargs = dict(self.default_apply_complex_function_kwargs) transform_kwargs.update(kwargs) transformer = VGroup() if hasattr(self, "plane"): self.prepare_for_transformation(self.plane) transformer.add(self.plane) transformer.add(*self.transformable_mobjects) return transformer, transform_kwargs def apply_complex_function(self, func, added_anims=[], **kwargs): transformer, transform_kwargs = self.get_transformer(**kwargs) transformer.generate_target() # Rescale, apply function, scale back transformer.target.shift(-self.background.get_center_point()) transformer.target.scale(1. / self.background.unit_size) transformer.target.apply_complex_function(func) transformer.target.scale(self.background.unit_size) transformer.target.shift(self.background.get_center_point()) # for mob in transformer.target[0].family_members_with_points(): mob.make_smooth() if self.post_transformation_stroke_width is not None: transformer.target.set_stroke( width=self.post_transformation_stroke_width) self.play( MoveToTarget(transformer, **transform_kwargs), *added_anims ) def apply_complex_homotopy(self, complex_homotopy, added_anims=[], **kwargs): transformer, transform_kwargs = self.get_transformer(**kwargs) # def homotopy(x, y, z, t): # output = complex_homotopy(complex(x, y), t) # rescaled_output = self.z_to_point(output) # return (rescaled_output.real, rescaled_output.imag, z) self.play( ComplexHomotopy(complex_homotopy, transformer, **transform_kwargs), *added_anims )
videos_3b1b/once_useful_constructs/vector_space_scene.py
import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.creation import ShowCreation from manimlib.animation.creation import Write from manimlib.animation.fading import FadeOut from manimlib.animation.growing import GrowArrow from manimlib.animation.transform import ApplyFunction from manimlib.animation.transform import ApplyPointwiseFunction from manimlib.animation.transform import Transform from manimlib.constants import BLACK, BLUE_D, GREEN_C, RED_C, GREY, WHITE, YELLOW from manimlib.constants import DL, DOWN, ORIGIN, RIGHT, UP from manimlib.constants import FRAME_WIDTH, FRAME_X_RADIUS, FRAME_Y_RADIUS from manimlib.constants import SMALL_BUFF from manimlib.mobject.coordinate_systems import Axes from manimlib.mobject.coordinate_systems import NumberPlane from manimlib.mobject.geometry import Arrow from manimlib.mobject.geometry import Dot from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Vector from manimlib.mobject.matrix import Matrix from manimlib.mobject.matrix import VECTOR_LABEL_SCALE_FACTOR from manimlib.mobject.matrix import vector_coordinate_label from manimlib.mobject.mobject import Mobject from manimlib.mobject.svg.tex_mobject import Tex from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import rush_from from manimlib.utils.rate_functions import rush_into from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.space_ops import get_norm from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor from typing import List X_COLOR = GREEN_C Y_COLOR = RED_C Z_COLOR = BLUE_D # TODO: Much of this scene type seems dependent on the coordinate system chosen. # That is, being centered at the origin with grid units corresponding to the # arbitrary space units. Change it! # # Also, methods I would have thought of as getters, like coords_to_vector, are # actually doing a lot of animating. class VectorScene(Scene): basis_vector_stroke_width: int = 6 def add_plane(self, animate=False, **kwargs): plane = NumberPlane(**kwargs) if animate: self.play(ShowCreation(plane, lag_ratio=0.5)) self.add(plane) return plane def add_axes(self, animate=False, color=WHITE, **kwargs): axes = Axes(color=color, tick_frequency=1) if animate: self.play(ShowCreation(axes)) self.add(axes) return axes def lock_in_faded_grid(self, dimness=0.7, axes_dimness=0.5): plane = self.add_plane() axes = plane.get_axes() plane.fade(dimness) axes.set_color(WHITE) axes.fade(axes_dimness) self.add(axes) self.freeze_background() def get_vector(self, numerical_vector, **kwargs): return Arrow( self.plane.coords_to_point(0, 0), self.plane.coords_to_point(*numerical_vector[:2]), buff=0, **kwargs ) def add_vector(self, vector, color=YELLOW, animate=True, **kwargs): if not isinstance(vector, Arrow): vector = Vector(vector, color=color, **kwargs) if animate: self.play(GrowArrow(vector)) self.add(vector) return vector def write_vector_coordinates(self, vector, **kwargs): coords = vector_coordinate_label(vector, **kwargs) self.play(Write(coords)) return coords def get_basis_vectors(self, i_hat_color=X_COLOR, j_hat_color=Y_COLOR): return VGroup(*[ Vector( vect, color=color, stroke_width=self.basis_vector_stroke_width ) for vect, color in [ ([1, 0], i_hat_color), ([0, 1], j_hat_color) ] ]) def get_basis_vector_labels(self, **kwargs): i_hat, j_hat = self.get_basis_vectors() return VGroup(*[ self.get_vector_label( vect, label, color=color, label_scale_factor=1, **kwargs ) for vect, label, color in [ (i_hat, "\\hat{\\imath}", X_COLOR), (j_hat, "\\hat{\\jmath}", Y_COLOR), ] ]) def get_vector_label(self, vector, label, at_tip=False, direction="left", rotate=False, color=None, label_scale_factor=VECTOR_LABEL_SCALE_FACTOR): if not isinstance(label, Tex): if len(label) == 1: label = "\\vec{\\textbf{%s}}" % label label = OldTex(label) if color is None: color = vector.get_color() label.set_color(color) label.scale(label_scale_factor) label.add_background_rectangle() if at_tip: vect = vector.get_vector() vect /= get_norm(vect) label.next_to(vector.get_end(), vect, buff=SMALL_BUFF) else: angle = vector.get_angle() if not rotate: label.rotate(-angle, about_point=ORIGIN) if direction == "left": label.shift(-label.get_bottom() + 0.1 * UP) else: label.shift(-label.get_top() + 0.1 * DOWN) label.rotate(angle, about_point=ORIGIN) label.shift((vector.get_end() - vector.get_start()) / 2) return label def label_vector(self, vector, label, animate=True, **kwargs): label = self.get_vector_label(vector, label, **kwargs) if animate: self.play(Write(label, run_time=1)) self.add(label) return label def position_x_coordinate(self, x_coord, x_line, vector): x_coord.next_to(x_line, -np.sign(vector[1]) * UP) x_coord.set_color(X_COLOR) return x_coord def position_y_coordinate(self, y_coord, y_line, vector): y_coord.next_to(y_line, np.sign(vector[0]) * RIGHT) y_coord.set_color(Y_COLOR) return y_coord def coords_to_vector(self, vector, coords_start=2 * RIGHT + 2 * UP, clean_up=True): starting_mobjects = list(self.mobjects) array = Matrix(vector) array.shift(coords_start) arrow = Vector(vector) x_line = Line(ORIGIN, vector[0] * RIGHT) y_line = Line(x_line.get_end(), arrow.get_end()) x_line.set_color(X_COLOR) y_line.set_color(Y_COLOR) x_coord, y_coord = array.get_mob_matrix().flatten() self.play(Write(array, run_time=1)) self.wait() self.play(ApplyFunction( lambda x: self.position_x_coordinate(x, x_line, vector), x_coord )) self.play(ShowCreation(x_line)) self.play( ApplyFunction( lambda y: self.position_y_coordinate(y, y_line, vector), y_coord ), FadeOut(array.get_brackets()) ) y_coord, brackets = self.get_mobjects_from_last_animation() self.play(ShowCreation(y_line)) self.play(ShowCreation(arrow)) self.wait() if clean_up: self.clear() self.add(*starting_mobjects) def vector_to_coords(self, vector, integer_labels=True, clean_up=True): starting_mobjects = list(self.mobjects) show_creation = False if isinstance(vector, Arrow): arrow = vector vector = arrow.get_end()[:2] else: arrow = Vector(vector) show_creation = True array = vector_coordinate_label(arrow, integer_labels=integer_labels) x_line = Line(ORIGIN, vector[0] * RIGHT) y_line = Line(x_line.get_end(), arrow.get_end()) x_line.set_color(X_COLOR) y_line.set_color(Y_COLOR) x_coord, y_coord = array.get_mob_matrix().flatten() x_coord_start = self.position_x_coordinate( x_coord.copy(), x_line, vector ) y_coord_start = self.position_y_coordinate( y_coord.copy(), y_line, vector ) brackets = array.get_brackets() if show_creation: self.play(ShowCreation(arrow)) self.play( ShowCreation(x_line), Write(x_coord_start), run_time=1 ) self.play( ShowCreation(y_line), Write(y_coord_start), run_time=1 ) self.wait() self.play( Transform(x_coord_start, x_coord, lag_ratio=0), Transform(y_coord_start, y_coord, lag_ratio=0), Write(brackets, run_time=1), ) self.wait() self.remove(x_coord_start, y_coord_start, brackets) self.add(array) if clean_up: self.clear() self.add(*starting_mobjects) return array, x_line, y_line def show_ghost_movement(self, vector): if isinstance(vector, Arrow): vector = vector.get_end() - vector.get_start() elif len(vector) == 2: vector = np.append(np.array(vector), 0.0) x_max = int(FRAME_X_RADIUS + abs(vector[0])) y_max = int(FRAME_Y_RADIUS + abs(vector[1])) dots = VMobject(*[ Dot(x * RIGHT + y * UP) for x in range(-x_max, x_max) for y in range(-y_max, y_max) ]) dots.set_fill(BLACK, opacity=0) dots_halfway = dots.copy().shift(vector / 2).set_fill(WHITE, 1) dots_end = dots.copy().shift(vector) self.play(Transform( dots, dots_halfway, rate_func=rush_into )) self.play(Transform( dots, dots_end, rate_func=rush_from )) self.remove(dots) class LinearTransformationScene(VectorScene): include_background_plane: bool = True include_foreground_plane: bool = True foreground_plane_kwargs: dict = dict( x_max=FRAME_WIDTH / 2, x_min=-FRAME_WIDTH / 2, y_max=FRAME_WIDTH / 2, y_min=-FRAME_WIDTH / 2, faded_line_ratio=0 ) background_plane_kwargs: dict = dict( color=GREY, axis_config=dict(color=GREY), background_line_style=dict( stroke_color=GREY, stroke_width=1, ), ) show_coordinates: bool = True show_basis_vectors: bool = True basis_vector_stroke_width: float = 6.0 i_hat_color: ManimColor = X_COLOR j_hat_color: ManimColor = Y_COLOR leave_ghost_vectors: bool = False t_matrix: List[List[float]] = [[3, 0], [1, 2]] def setup(self): # The has_already_setup attr is to not break all the old Scenes if hasattr(self, "has_already_setup"): return self.has_already_setup = True self.background_mobjects = [] self.foreground_mobjects = [] self.transformable_mobjects = [] self.moving_vectors = [] self.transformable_labels = [] self.moving_mobjects = [] self.t_matrix = np.array(self.t_matrix) self.background_plane = NumberPlane( **self.background_plane_kwargs ) if self.show_coordinates: self.background_plane.add_coordinates() if self.include_background_plane: self.add_background_mobject(self.background_plane) if self.include_foreground_plane: self.plane = NumberPlane(**self.foreground_plane_kwargs) self.add_transformable_mobject(self.plane) if self.show_basis_vectors: self.basis_vectors = self.get_basis_vectors( i_hat_color=self.i_hat_color, j_hat_color=self.j_hat_color, ) self.moving_vectors += list(self.basis_vectors) self.i_hat, self.j_hat = self.basis_vectors self.add(self.basis_vectors) def add_special_mobjects(self, mob_list, *mobs_to_add): for mobject in mobs_to_add: if mobject not in mob_list: mob_list.append(mobject) self.add(mobject) def add_background_mobject(self, *mobjects): self.add_special_mobjects(self.background_mobjects, *mobjects) # TODO, this conflicts with Scene.add_fore def add_foreground_mobject(self, *mobjects): self.add_special_mobjects(self.foreground_mobjects, *mobjects) def add_transformable_mobject(self, *mobjects): self.add_special_mobjects(self.transformable_mobjects, *mobjects) def add_moving_mobject(self, mobject, target_mobject=None): mobject.target = target_mobject self.add_special_mobjects(self.moving_mobjects, mobject) def get_unit_square(self, color=YELLOW, opacity=0.3, stroke_width=3): square = self.square = Rectangle( color=color, width=self.plane.get_x_unit_size(), height=self.plane.get_y_unit_size(), stroke_color=color, stroke_width=stroke_width, fill_color=color, fill_opacity=opacity ) square.move_to(self.plane.coords_to_point(0, 0), DL) return square def add_unit_square(self, animate=False, **kwargs): square = self.get_unit_square(**kwargs) if animate: self.play( DrawBorderThenFill(square), Animation(Group(*self.moving_vectors)) ) self.add_transformable_mobject(square) self.bring_to_front(*self.moving_vectors) self.square = square return self def add_vector(self, vector, color=YELLOW, **kwargs): vector = VectorScene.add_vector( self, vector, color=color, **kwargs ) self.moving_vectors.append(vector) return vector def write_vector_coordinates(self, vector, **kwargs): coords = VectorScene.write_vector_coordinates(self, vector, **kwargs) self.add_foreground_mobject(coords) return coords def add_transformable_label( self, vector, label, transformation_name="L", new_label=None, **kwargs): label_mob = self.label_vector(vector, label, **kwargs) if new_label: label_mob.target_text = new_label else: label_mob.target_text = "%s(%s)" % ( transformation_name, label_mob.get_tex() ) label_mob.vector = vector label_mob.kwargs = kwargs if "animate" in label_mob.kwargs: label_mob.kwargs.pop("animate") self.transformable_labels.append(label_mob) return label_mob def add_title(self, title, scale_factor=1.5, animate=False): if not isinstance(title, Mobject): title = OldTexText(title).scale(scale_factor) title.to_edge(UP) title.add_background_rectangle() if animate: self.play(Write(title)) self.add_foreground_mobject(title) self.title = title return self def get_matrix_transformation(self, matrix): return self.get_transposed_matrix_transformation(np.array(matrix).T) def get_transposed_matrix_transformation(self, transposed_matrix): transposed_matrix = np.array(transposed_matrix) if transposed_matrix.shape == (2, 2): new_matrix = np.identity(3) new_matrix[:2, :2] = transposed_matrix transposed_matrix = new_matrix elif transposed_matrix.shape != (3, 3): raise Exception("Matrix has bad dimensions") return lambda point: np.dot(point, transposed_matrix) def get_piece_movement(self, pieces): start = VGroup(*pieces) target = VGroup(*[mob.target for mob in pieces]) if self.leave_ghost_vectors: self.add(start.copy().fade(0.7)) return Transform(start, target, lag_ratio=0) def get_moving_mobject_movement(self, func): for m in self.moving_mobjects: if m.target is None: m.target = m.copy() target_point = func(m.get_center()) m.target.move_to(target_point) return self.get_piece_movement(self.moving_mobjects) def get_vector_movement(self, func): for v in self.moving_vectors: v.target = Vector(func(v.get_end()), color=v.get_color()) norm = get_norm(v.target.get_end()) if norm < 0.1: v.target.get_tip().scale(norm) return self.get_piece_movement(self.moving_vectors) def get_transformable_label_movement(self): for l in self.transformable_labels: l.target = self.get_vector_label( l.vector.target, l.target_text, **l.kwargs ) return self.get_piece_movement(self.transformable_labels) def apply_matrix(self, matrix, **kwargs): self.apply_transposed_matrix(np.array(matrix).T, **kwargs) def apply_inverse(self, matrix, **kwargs): self.apply_matrix(np.linalg.inv(matrix), **kwargs) def apply_transposed_matrix(self, transposed_matrix, **kwargs): func = self.get_transposed_matrix_transformation(transposed_matrix) if "path_arc" not in kwargs: net_rotation = np.mean([ angle_of_vector(func(RIGHT)), angle_of_vector(func(UP)) - np.pi / 2 ]) kwargs["path_arc"] = net_rotation self.apply_function(func, **kwargs) def apply_inverse_transpose(self, t_matrix, **kwargs): t_inv = np.linalg.inv(np.array(t_matrix).T).T self.apply_transposed_matrix(t_inv, **kwargs) def apply_nonlinear_transformation(self, function, **kwargs): self.plane.prepare_for_nonlinear_transform() self.apply_function(function, **kwargs) def apply_function(self, function, added_anims=[], **kwargs): if "run_time" not in kwargs: kwargs["run_time"] = 3 anims = [ ApplyPointwiseFunction(function, t_mob) for t_mob in self.transformable_mobjects ] + [ self.get_vector_movement(function), self.get_transformable_label_movement(), self.get_moving_mobject_movement(function), ] + [ Animation(f_mob) for f_mob in self.foreground_mobjects ] + added_anims self.play(*anims, **kwargs)
videos_3b1b/custom/filler.py
from manimlib.scene.scene import Scene class ExternallyAnimatedScene(Scene): def construct(self): raise Exception("Don't actually run this class.")
videos_3b1b/custom/logo.py
from __future__ import annotations import numpy as np import itertools as it import random from manimlib.constants import * from manimlib.scene.scene import Scene from manimlib.mobject.geometry import AnnularSector from manimlib.mobject.geometry import Circle from manimlib.mobject.geometry import Polygon from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.bezier import interpolate from manimlib.utils.space_ops import angle_of_vector from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import smooth from manimlib.animation.animation import Animation from manimlib.animation.transform import Restore from manimlib.animation.transform import Transform from manimlib.animation.composition import AnimationGroup from manimlib.animation.composition import LaggedStartMap from manimlib.animation.creation import Write class Logo(VMobject): pupil_radius: float = 1.0 outer_radius: float = 2.0 iris_background_blue: ManimColor = "#74C0E3" iris_background_brown: ManimColor = "#8C6239" blue_spike_colors: list[ManimColor] = [ "#528EA3", "#3E6576", "#224C5B", BLACK, ] brown_spike_colors: list[ManimColor] = [ "#754C24", "#603813", "#42210b", BLACK, ] n_spike_layers: int = 4 n_spikes: int = 28 spike_angle: float = TAU / 28 def __init__(self, **kwargs): super().__init__(**kwargs) self.add_iris_back() self.add_spikes() self.add_pupil() def add_iris_back(self): blue_iris_back = AnnularSector( inner_radius=self.pupil_radius, outer_radius=self.outer_radius, angle=270 * DEGREES, start_angle=180 * DEGREES, fill_color=self.iris_background_blue, fill_opacity=1, stroke_width=0, ) brown_iris_back = AnnularSector( inner_radius=self.pupil_radius, outer_radius=self.outer_radius, angle=90 * DEGREES, start_angle=90 * DEGREES, fill_color=self.iris_background_brown, fill_opacity=1, stroke_width=0, ) self.iris_background = VGroup( blue_iris_back, brown_iris_back, ) self.add(self.iris_background) def add_spikes(self): layers = VGroup() radii = np.linspace( self.outer_radius, self.pupil_radius, self.n_spike_layers, endpoint=False, ) radii[:2] = radii[1::-1] # Swap first two if self.n_spike_layers > 2: radii[-1] = interpolate(radii[-1], self.pupil_radius, 0.25) for radius in radii: tip_angle = self.spike_angle half_base = radius * np.tan(tip_angle) triangle, right_half_triangle = [ Polygon( radius * UP, half_base * RIGHT, vertex3, fill_opacity=1, stroke_width=0, ) for vertex3 in (half_base * LEFT, ORIGIN,) ] left_half_triangle = right_half_triangle.copy() left_half_triangle.flip(UP, about_point=ORIGIN) n_spikes = self.n_spikes full_spikes = [ triangle.copy().rotate( -angle, about_point=ORIGIN ) for angle in np.linspace( 0, TAU, n_spikes, endpoint=False ) ] index = (3 * n_spikes) // 4 if radius == radii[0]: layer = VGroup(*full_spikes) layer.rotate( -TAU / n_spikes / 2, about_point=ORIGIN ) layer.brown_index = index else: half_spikes = [ right_half_triangle.copy(), left_half_triangle.copy().rotate( 90 * DEGREES, about_point=ORIGIN, ), right_half_triangle.copy().rotate( 90 * DEGREES, about_point=ORIGIN, ), left_half_triangle.copy() ] layer = VGroup(*it.chain( half_spikes[:1], full_spikes[1:index], half_spikes[1:3], full_spikes[index + 1:], half_spikes[3:], )) layer.brown_index = index + 1 layers.add(layer) # Color spikes blues = self.blue_spike_colors browns = self.brown_spike_colors for layer, blue, brown in zip(layers, blues, browns): index = layer.brown_index layer[:index].set_color(blue) layer[index:].set_color(brown) self.spike_layers = layers self.add(layers) def add_pupil(self): self.pupil = Circle( radius=self.pupil_radius, fill_color=BLACK, fill_opacity=1, stroke_width=0, stroke_color=BLACK, sheen=0.0, ) self.pupil.rotate(90 * DEGREES) self.add(self.pupil) def cut_pupil(self): pupil = self.pupil center = pupil.get_center() new_pupil = VGroup(*[ pupil.copy().pointwise_become_partial(pupil, a, b) for (a, b) in [(0.25, 1), (0, 0.25)] ]) for sector in new_pupil: sector.add_cubic_bezier_curve_to([ sector.get_points()[-1], *[center] * 3, *[sector.get_points()[0]] * 2 ]) self.remove(pupil) self.add(new_pupil) self.pupil = new_pupil def get_blue_part_and_brown_part(self): if len(self.pupil) == 1: self.cut_pupil() blue_part = VGroup( self.iris_background[0], *[ layer[:layer.brown_index] for layer in self.spike_layers ], self.pupil[0], ) brown_part = VGroup( self.iris_background[1], *[ layer[layer.brown_index:] for layer in self.spike_layers ], self.pupil[1], ) return blue_part, brown_part class LogoGenerationTemplate(Scene): def setup(self): super().setup() frame = self.camera.frame frame.shift(DOWN) self.logo = Logo() name = Text("3Blue1Brown") name.scale(2.5) name.next_to(self.logo, DOWN, buff=MED_LARGE_BUFF) name.set_gloss(0.2) self.channel_name = name def construct(self): logo = self.logo name = self.channel_name self.play( Write(name, run_time=3), *self.get_logo_animations(logo) ) self.wait() def get_logo_animations(self, logo): return [] # For subclasses class LogoGeneration(LogoGenerationTemplate): def construct(self): logo = self.logo name = self.channel_name layers = logo.spike_layers logo.save_state() for layer in layers: for spike in layer: spike.save_state() point = np.array(spike.get_points()[0]) angle = angle_of_vector(point) spike.rotate(-angle + 90 * DEGREES) spike.stretch_to_fit_width(0.2) spike.stretch_to_fit_height(0.5) spike.point = point for spike in layer[::2]: spike.rotate(180 * DEGREES) layer.arrange(LEFT, buff=0.1) layers.arrange(UP) layers.to_edge(DOWN) wrong_spike = layers[1][-5] wrong_spike.real_saved_state = wrong_spike.saved_state.copy() wrong_spike.saved_state.scale(0.25, about_point=wrong_spike.point) wrong_spike.saved_state.rotate(90 * DEGREES) self.wrong_spike = wrong_spike def get_spike_animation(spike, **kwargs): return Restore(spike, **kwargs) logo.iris_background.save_state() logo.iris_background.set_fill(opacity=0.0) logo.iris_background.scale(0.8) alt_name = name.copy() alt_name.set_stroke(BLACK, 5) self.play( Restore( logo.iris_background, rate_func=squish_rate_func(smooth, 1.0 / 3, 1), run_time=2, ), AnimationGroup(*( LaggedStartMap( get_spike_animation, layer, run_time=2, # rate_func=squish_rate_func(smooth, a / 3.0, (a + 0.9) / 3.0), lag_ratio=2 / len(layer), path_arc=-90 * DEGREES ) for layer, a in zip(layers, [0, 2, 1, 0]) )), Animation(logo.pupil), Write(alt_name), Write(name), run_time=3 ) self.wait(0.25) self.play( Transform( wrong_spike, wrong_spike.real_saved_state, ), Animation(self.logo), run_time=0.75 ) class SortingLogoGeneration(LogoGenerationTemplate): def get_logo_animations(self, logo): layers = logo.spike_layers for j, layer in enumerate(layers): for i, spike in enumerate(layer): spike.angle = (13 * (i + 1) * (j + 1) * TAU / 28) % TAU if spike.angle > PI: spike.angle -= TAU spike.save_state() spike.rotate( spike.angle, about_point=ORIGIN ) # spike.get_points()[1] = rotate_vector( # spike.get_points()[1], TAU/28, # ) # spike.get_points()[-1] = rotate_vector( # spike.get_points()[-1], -TAU/28, # ) def get_spike_animation(spike, **kwargs): return Restore( spike, path_arc=-spike.angle, **kwargs ) logo.iris_background.save_state() # logo.iris_background.scale(0.49) logo.iris_background.set_fill(GREY_D, 0.5) return [ Restore( logo.iris_background, rate_func=squish_rate_func(smooth, 2.0 / 3, 1), run_time=3, ), AnimationGroup(*[ LaggedStartMap( get_spike_animation, layer, run_time=2, # rate_func=squish_rate_func(smooth, a / 3.0, (a + 0.9) / 3.0), lag_ratio=0.2, ) for layer, a in zip(layers, [0, 2, 1, 0]) ]), Animation(logo.pupil), ] class LogoTest(Scene): def construct(self): n_range = list(range(4, 40, 4)) for n, denom in zip(n_range, np.linspace(14, 28, len(n_range))): logo = Logo(**{ "iris_background_blue": "#78C0E3", "iris_background_brown": "#8C6239", "blue_spike_colors": [ "#528EA3", "#3E6576", "#224C5B", BLACK, ], "brown_spike_colors": [ "#754C24", "#603813", "#42210b", BLACK, ], "n_spike_layers": 4, "n_spikes": n, "spike_angle": TAU / denom, }) self.add(logo) self.wait() self.clear() self.add(logo) class LogoGenerationFlurry(LogoGenerationTemplate): random_seed: int = 2 def get_logo_animations(self, logo): layers = logo.spike_layers for i, layer in enumerate(layers): random.shuffle(layer.submobjects) for spike in layer: spike.save_state() spike.scale(0.5) spike.apply_complex_function(np.log) spike.rotate(-90 * DEGREES, about_point=ORIGIN) spike.set_fill(opacity=0) layer.rotate(i * PI / 5) logo.iris_background.save_state() logo.iris_background.scale(0.25) logo.iris_background.fade(1) return [ Restore( logo.iris_background, run_time=3, ), AnimationGroup(*[ LaggedStartMap( Restore, layer, run_time=3, path_arc=180 * DEGREES, # rate_func=squish_rate_func(smooth, a / 3.0, (a + 1.9) / 3.0), lag_ratio=0.8, ) for layer, a in zip(layers, [0, 0.2, 0.1, 0]) ]), Animation(logo.pupil), ] class WrittenLogo(LogoGenerationTemplate): def get_logo_animations(self, logo): return [Write(logo, stroke_color=None, stroke_width=2, run_time=3, lag_ratio=5e-3)] class LogoGenerationFivefold(LogoGenerationTemplate): def construct(self): logo = self.logo iris, spike_layers, pupil = logo name = OldTexText("3Blue1Brown") name.scale(2.5) name.next_to(logo, DOWN, buff=MED_LARGE_BUFF) name.set_gloss(0.2) self.add(iris) anims = [] for layer in spike_layers: for n, spike in enumerate(layer): angle = (5 * (n + 1) * TAU / len(layer)) % TAU spike.rotate(angle, about_point=ORIGIN) anims.append(Rotate( spike, -angle, about_point=ORIGIN, run_time=5, # rate_func=rush_into, )) self.add(spike) self.add(pupil) def update(alpha): spike_layers.set_opacity(alpha) mid_alpha = 4.0 * (1.0 - alpha) * alpha spike_layers.set_stroke(WHITE, 1, opacity=mid_alpha) pupil.set_stroke(WHITE, 1, opacity=mid_alpha) iris.set_stroke(WHITE, 1, opacity=mid_alpha) name.flip().flip() self.play( *anims, VFadeIn(iris, run_time=3), UpdateFromAlphaFunc( Mobject(), lambda m, a: update(a), run_time=3, ), # FadeIn(name, run_time=3, lag_ratio=0.5, rate_func=linear), Write(name, run_time=3) ) self.wait(2) class Vertical3B1B(Scene): def construct(self): words = OldTexText( "3", "Blue", "1", "Brown", ) words.scale(2) words[::2].scale(1.2) buff = 0.2 words.arrange( DOWN, buff=buff, aligned_edge=LEFT, ) words[0].match_x(words[1][0]) words[2].match_x(words[3][0]) self.add(words) logo = Logo() logo.next_to(words, LEFT) self.add(logo) VGroup(logo, words).center()
videos_3b1b/custom/drawings.py
from manimlib import * # Related to pi creatures class Car(SVGMobject): file_name = "Car" height = 1 color = GREY_B light_colors = [BLACK, BLACK] def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) path = self.submobjects[0] subpaths = path.get_subpaths() path.clear_points() for indices in [(0, 1), (2, 3), (4, 6, 7), (5,), (8,)]: part = VMobject() for index in indices: part.append_points(subpaths[index]) path.add(part) self.set_height(self.height) self.set_stroke(color=WHITE, width=0) self.set_fill(self.color, opacity=1) from videos.characters.pi_creature import Randolph randy = Randolph(mode="happy") randy.set_height(0.6 * self.get_height()) randy.stretch(0.8, 0) randy.look(RIGHT) randy.move_to(self) randy.shift(0.07 * self.height * (RIGHT + UP)) self.randy = self.pi_creature = randy self.add_to_back(randy) orientation_line = Line(self.get_left(), self.get_right()) orientation_line.set_stroke(width=0) self.add(orientation_line) self.orientation_line = orientation_line for light, color in zip(self.get_lights(), self.light_colors): light.set_fill(color, 1) light.is_subpath = False self.add_treds_to_tires() def move_to(self, point_or_mobject): vect = rotate_vector( UP + LEFT, self.orientation_line.get_angle() ) self.next_to(point_or_mobject, vect, buff=0) return self def get_front_line(self): return DashedLine( self.get_corner(UP + RIGHT), self.get_corner(DOWN + RIGHT), color=DISTANCE_COLOR, dash_length=0.05, ) def add_treds_to_tires(self): for tire in self.get_tires(): radius = tire.get_width() / 2 center = tire.get_center() tred = Line( 0.7 * radius * RIGHT, 1.1 * radius * RIGHT, stroke_width=2, color=BLACK ) tred.rotate(PI / 5, about_point=tred.get_end()) for theta in np.arange(0, 2 * np.pi, np.pi / 4): new_tred = tred.copy() new_tred.rotate(theta, about_point=ORIGIN) new_tred.shift(center) tire.add(new_tred) return self def get_tires(self): return VGroup(self[1][0], self[1][1]) def get_lights(self): return VGroup(self.get_front_light(), self.get_rear_light()) def get_front_light(self): return self[1][3] def get_rear_light(self): return self[1][4] class MoveCar(ApplyMethod): def __init__(self, car, target_point, run_time=5, moving_forward=True, **kwargs): self.moving_forward = moving_forward self.check_if_input_is_car(car) self.target_point = target_point super().__init__( car.move_to, target_point, run_time=run_time, **kwargs ) def check_if_input_is_car(self, car): if not isinstance(car, Car): raise Exception("MoveCar must take in Car object") def begin(self): super().begin() car = self.mobject distance = get_norm(op.sub( self.target_mobject.get_right(), self.starting_mobject.get_right(), )) if not self.moving_forward: distance *= -1 tire_radius = car.get_tires()[0].get_width() / 2 self.total_tire_radians = -distance / tire_radius def interpolate_mobject(self, alpha): ApplyMethod.interpolate_mobject(self, alpha) if alpha == 0: return radians = alpha * self.total_tire_radians for tire in self.mobject.get_tires(): tire.rotate(radians) class PartyHat(SVGMobject): file_name = "party_hat" height = 1.5 pi_creature = None stroke_width = 0 fill_opacity = 1 frills_colors = [MAROON_B, PURPLE] cone_color = GREEN dots_colors = [YELLOW] NUM_FRILLS = 7 NUM_DOTS = 6 def __init__(self, **kwargs): SVGMobject.__init__(self, **kwargs) self.set_height(self.height) if self.pi_creature is not None: self.next_to(self.pi_creature.eyes, UP, buff=0) self.frills = VGroup(*self[:self.NUM_FRILLS]) self.cone = self[self.NUM_FRILLS] self.dots = VGroup(*self[self.NUM_FRILLS + 1:]) self.frills.set_color_by_gradient(*self.frills_colors) self.cone.set_color(self.cone_color) self.dots.set_color_by_gradient(*self.dots_colors) class SunGlasses(SVGMobject): file_name = "sunglasses" glasses_width_to_eyes_width = 1.1 def __init__(self, pi_creature, **kwargs): super().__init__(**kwargs) self.set_stroke(WHITE, width=0) self.set_fill(GREY, 1) self.set_width( self.glasses_width_to_eyes_width * pi_creature.eyes.get_width() ) self.move_to(pi_creature.eyes, UP) class Headphones(SVGMobject): file_name = "headphones" height = 2 y_stretch_factor = 0.5 color = GREY def __init__(self, pi_creature=None, **kwargs): super().__init__(file_name=self.file_name, **kwargs) self.stretch(self.y_stretch_factor, 1) self.set_height(self.height) self.set_stroke(width=0) self.set_fill(color=self.color) if pi_creature is not None: eyes = pi_creature.eyes self.set_height(3 * eyes.get_height()) self.move_to(eyes, DOWN) self.shift(DOWN * eyes.get_height() / 4) class Guitar(SVGMobject): file_name = "guitar" def __init__( self, height=2.5, fill_color=GREY_D, fill_opacity=1, stroke_color=WHITE, stroke_width=0.5, ): super().__init__( height=height, fill_color=fill_color, fill_opacity=fill_opacity, stroke_color=stroke_color, stroke_width=stroke_width, ) # Cards class DeckOfCards(VGroup): def __init__(self, **kwargs): possible_values = list(map(str, list(range(1, 11)))) + ["J", "Q", "K"] possible_suits = ["hearts", "diamonds", "spades", "clubs"] super().__init__(*( PlayingCard(value=value, suit=suit, **kwargs) for value in possible_values for suit in possible_suits )) class PlayingCard(VGroup): def __init__( self, key=None, # String like "8H" or "KS" value=None, suit=None, height=2, height_to_width=3.5 / 2.5, card_height_to_symbol_height=7, card_width_to_corner_num_width=10, card_height_to_corner_num_height=10, color=GREY_A, turned_over=False, possible_suits=["hearts", "diamonds", "spades", "clubs"], possible_values=list(map(str, list(range(2, 11)))) + ["J", "Q", "K", "A"], **kwargs, ): self.key = key self.value = value self.suit = suit self.height = height self.height_to_width = height_to_width self.card_height_to_symbol_height = card_height_to_symbol_height self.card_width_to_corner_num_width = card_width_to_corner_num_width self.card_height_to_corner_num_height = card_height_to_corner_num_height self.color = color self.turned_over = turned_over self.possible_suits = possible_suits self.possible_values = possible_values super().__init__(**kwargs) self.key = key self.add(Rectangle( height=self.height, width=self.height / self.height_to_width, stroke_color=WHITE, stroke_width=2, fill_color=self.color, fill_opacity=1, )) if self.turned_over: self.set_fill(GREY_D) self.set_stroke(GREY_B) contents = VectorizedPoint(self.get_center()) else: value = self.get_value() symbol = self.get_symbol() design = self.get_design(value, symbol) corner_numbers = self.get_corner_numbers(value, symbol) contents = VGroup(design, corner_numbers) self.design = design self.corner_numbers = corner_numbers self.add(contents) def get_value(self): value = self.value if value is None: if self.key is not None: value = self.key[:-1] else: value = random.choice(self.possible_values) value = str(value).upper() if value == "1": value = "A" if value not in self.possible_values: raise Exception("Invalid card value") face_card_to_value = { "J": 11, "Q": 12, "K": 13, "A": 14, } try: self.numerical_value = int(value) except Exception: self.numerical_value = face_card_to_value[value] return value def get_symbol(self): suit = self.suit if suit is None: if self.key is not None: suit = dict([ (s[0].upper(), s) for s in self.possible_suits ])[self.key[-1].upper()] else: suit = random.choice(self.possible_suits) if suit not in self.possible_suits: raise Exception("Invalud suit value") self.suit = suit symbol_height = float(self.height) / self.card_height_to_symbol_height symbol = SuitSymbol(suit, height=symbol_height) return symbol def get_design(self, value, symbol): if value == "A": return self.get_ace_design(symbol) if value in list(map(str, list(range(2, 11)))): return self.get_number_design(value, symbol) else: return self.get_face_card_design(value, symbol) def get_ace_design(self, symbol): design = symbol.copy().scale(1.5) design.move_to(self) return design def get_number_design(self, value, symbol): num = int(value) n_rows = { 2: 2, 3: 3, 4: 2, 5: 2, 6: 3, 7: 3, 8: 3, 9: 4, 10: 4, }[num] n_cols = 1 if num in [2, 3] else 2 insertion_indices = { 5: [0], 7: [0], 8: [0, 1], 9: [1], 10: [0, 2], }.get(num, []) top = self.get_top() + symbol.get_height() * DOWN bottom = self.get_bottom() + symbol.get_height() * UP column_points = [ interpolate(top, bottom, alpha) for alpha in np.linspace(0, 1, n_rows) ] design = VGroup(*[ symbol.copy().move_to(point) for point in column_points ]) if n_cols == 2: space = 0.2 * self.get_width() column_copy = design.copy().shift(space * RIGHT) design.shift(space * LEFT) design.add(*column_copy) design.add(*[ symbol.copy().move_to( center_of_mass(column_points[i:i + 2]) ) for i in insertion_indices ]) for symbol in design: if symbol.get_center()[1] < self.get_center()[1]: symbol.rotate(np.pi) return design def get_face_card_design(self, value, symbol): from videos.characters.pi_creature import PiCreature sub_rect = Rectangle( stroke_color=BLACK, fill_opacity=0, height=0.9 * self.get_height(), width=0.6 * self.get_width(), ) sub_rect.move_to(self) # pi_color = average_color(symbol.get_color(), GREY) pi_color = symbol.get_color() if Color(pi_color) == Color(BLACK): pi_color = GREY_D pi_mode = { "J": "plain", "Q": "thinking", "K": "hooray" }[value] pi_creature = PiCreature( mode=pi_mode, color=pi_color, ) pi_creature.set_width(0.8 * sub_rect.get_width()) if value in ["Q", "K"]: prefix = "king" if value == "K" else "queen" crown = SVGMobject(file_name=prefix + "_crown") crown.set_stroke(width=0) crown.set_fill(YELLOW, 1) crown.stretch_to_fit_width(0.5 * sub_rect.get_width()) crown.stretch_to_fit_height(0.17 * sub_rect.get_height()) crown.move_to(pi_creature.eyes.get_center(), DOWN) pi_creature.add_to_back(crown) to_top_buff = 0 else: to_top_buff = SMALL_BUFF * sub_rect.get_height() pi_creature.next_to(sub_rect.get_top(), DOWN, to_top_buff) # pi_creature.shift(0.05*sub_rect.get_width()*RIGHT) pi_copy = pi_creature.copy() pi_copy.rotate(np.pi, about_point=sub_rect.get_center()) return VGroup(sub_rect, pi_creature, pi_copy) def get_corner_numbers(self, value, symbol): value_mob = OldTexText(value) width = self.get_width() / self.card_width_to_corner_num_width height = self.get_height() / self.card_height_to_corner_num_height value_mob.set_width(width) value_mob.stretch_to_fit_height(height) value_mob.next_to( self.get_corner(UP + LEFT), DOWN + RIGHT, buff=MED_LARGE_BUFF * width ) value_mob.set_color(symbol.get_color()) corner_symbol = symbol.copy() corner_symbol.set_width(width) corner_symbol.next_to( value_mob, DOWN, buff=MED_SMALL_BUFF * width ) corner_group = VGroup(value_mob, corner_symbol) opposite_corner_group = corner_group.copy() opposite_corner_group.rotate( np.pi, about_point=self.get_center() ) return VGroup(corner_group, opposite_corner_group) class SuitSymbol(SVGMobject): def __init__(self, suit_name, **kwargs): suits = {"hearts", "diamonds", "spades", "clubs"} if suit_name not in suits: raise Exception("Invalid suit name") super().__init__(file_name=suit_name, **kwargs) # Logos class AoPSLogo(SVGMobject): file_name = "aops_logo" height = 1.5 def __init__(self, **kwargs): super().__init__(**kwargs) self.set_stroke(WHITE, width=0) colors = [BLUE_E, "#008445", GREEN_B] index_lists = [ (10, 11, 12, 13, 14, 21, 22, 23, 24, 27, 28, 29, 30), (0, 1, 2, 3, 4, 15, 16, 17, 26), (5, 6, 7, 8, 9, 18, 19, 20, 25) ] for color, index_list in zip(colors, index_lists): for i in index_list: self.submobjects[i].set_fill(color, opacity=1) self.set_height(self.height) self.center() class BitcoinLogo(SVGMobject): file_name = "Bitcoin_logo" height = 1
videos_3b1b/custom/backdrops.py
from manimlib.constants import WHITE from manimlib.constants import BLACK from manimlib.constants import DOWN from manimlib.constants import UP from manimlib.constants import BLUE from manimlib.scene.scene import Scene from manimlib.mobject.frame import FullScreenRectangle from manimlib.mobject.frame import ScreenRectangle from manimlib.mobject.changing import AnimatedBoundary from manimlib.mobject.svg.tex_mobject import TexText from manimlib.animation.creation import Write class Spotlight(Scene): title = "" title_font_size = 60 def construct(self): title = TexText(self.title, font_size=self.title_font_size) title.to_edge(UP) self.add(title) self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_height(6.0) screen.set_stroke(WHITE, 2) screen.set_fill(BLACK, 1) screen.to_edge(DOWN) animated_screen = AnimatedBoundary(screen) self.add(screen, animated_screen) self.wait(16) class VideoWrapper(Scene): animate_boundary = True animated_boundary_config = {"cycle_rate": 0.25} title = "" title_config = dict( font_size=60 ) wait_time = 32 screen_height = 6.25 def construct(self): self.add(FullScreenRectangle()) screen = ScreenRectangle() screen.set_fill(BLACK, 1) screen.set_stroke(BLUE, 0) screen.set_height(self.screen_height) screen.to_edge(DOWN) if self.animate_boundary: boundary = self.boundary = AnimatedBoundary(screen, **self.animated_boundary_config) self.add(boundary) wait_time = self.wait_time else: wait_time = 1 self.add(screen) if self.title: title_text = self.title_text = TexText( self.title, **self.title_config, ) title_text.set_max_width(screen.get_width()) title_text.next_to(screen, UP) self.play(Write(title_text)) self.wait(wait_time)
videos_3b1b/custom/end_screen.py
import random import os import json from tqdm import tqdm as ProgressDisplay from manimlib.animation.animation import Animation from manimlib.animation.composition import Succession from manimlib.animation.transform import ApplyMethod from manimlib.constants import * from manimlib.mobject.mobject import Mobject from manimlib.mobject.geometry import DashedLine from manimlib.mobject.geometry import Line from manimlib.mobject.geometry import Rectangle from manimlib.mobject.geometry import Square from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.scene import Scene from manimlib.utils.directories import get_directories from manimlib.utils.rate_functions import linear from custom.characters.pi_creature import Mortimer from custom.characters.pi_creature import Randolph from custom.characters.pi_creature_animations import Blink class PatreonEndScreen(Scene): title_text = "Clicky Stuffs" show_pis = True max_patron_group_size = 20 patron_scale_val = 0.8 n_patron_columns = 4 max_patron_width = 5 randomize_order = False capitalize = True name_y_spacing = 0.6 thanks_words = """ Instead of sponsor messages, these lessons are supported directly by viewers, such as those below | 3b1b.co/support """ scroll_time = 20 def construct(self): # Add title title = self.title = Text(self.title_text) title.scale(1.5) title.to_edge(UP, buff=MED_SMALL_BUFF) self.add(title) pi_creatures = VGroup(Randolph(), Mortimer()) for pi, vect in zip(pi_creatures, [LEFT, RIGHT]): pi.set_height(title.get_height()) pi.change_mode("thinking") pi.look(DOWN) pi.next_to(title, vect, buff=MED_LARGE_BUFF) self.add(pi_creatures) if not self.show_pis: pi_creatures.set_opacity(0) # Set the top of the screen logo_box = Square(side_length=2.5) logo_box.to_corner(DOWN + LEFT, buff=MED_LARGE_BUFF) black_rect = Rectangle( fill_color=BLACK, fill_opacity=1, stroke_width=3, stroke_color=BLACK, width=FRAME_WIDTH, height=FRAME_HEIGHT, ) black_rect.to_edge(UP, buff=0) line = DashedLine(FRAME_X_RADIUS * LEFT, FRAME_X_RADIUS * RIGHT) line.move_to(ORIGIN) # Add thanks thanks = Text(self.thanks_words) thanks.scale(0.8) thanks.next_to(line, DOWN, buff=MED_SMALL_BUFF) thanks.set_color(YELLOW) underline = Line(LEFT, RIGHT) underline.match_width(thanks) underline.scale(1.1) underline.next_to(thanks, DOWN, SMALL_BUFF) thanks.add(underline) black_rect.match_y(underline, DOWN) # Build name list names = self.get_names() name_labels = VGroup(*map( Text, ProgressDisplay(names, leave=False, desc="Writing names") )) name_labels.scale(self.patron_scale_val) for label in name_labels: label.set_max_width(self.max_patron_width) columns = VGroup(*[ VGroup(*name_labels[i::self.n_patron_columns]) for i in range(self.n_patron_columns) ]) column_x_spacing = 0.5 + max([c.get_width() for c in columns]) for i, column in enumerate(columns): for n, name in enumerate(column): name.shift(n * self.name_y_spacing * DOWN) name.align_to(ORIGIN, LEFT) column.move_to(i * column_x_spacing * RIGHT, UL) columns.center() max_width = FRAME_WIDTH - 1 if columns.get_width() > max_width: columns.set_width(max_width) underline.match_width(columns) columns.next_to(underline, DOWN, buff=3) # Set movement columns.generate_target() distance = columns.get_height() + 2 wait_time = self.scroll_time frame = self.camera.frame frame_shift = ApplyMethod( frame.shift, distance * DOWN, run_time=wait_time, rate_func=linear, ) blink_anims = [] blank_mob = Mobject() for x in range(wait_time): if random.random() < 0.25: blink_anims.append(Blink(random.choice(pi_creatures))) else: blink_anims.append(Animation(blank_mob)) blinks = Succession(*blink_anims) static_group = VGroup(black_rect, line, thanks, pi_creatures, title) static_group.fix_in_frame() self.add(columns, static_group) self.play(frame_shift, blinks) def get_names(self): patron_file = "patrons.txt" hardcoded_patron_file = "hardcoded_patrons.txt" names = [] for file in patron_file, hardcoded_patron_file: full_path = os.path.join(get_directories()["data"], file) with open(full_path, "r") as fp: names.extend([ self.modify_patron_name(name.strip()) for name in fp.readlines() ]) # Remove duplicates names = list(set(names)) # Make sure these aren't missed if self.randomize_order: random.shuffle(names) else: names.sort() return names def modify_patron_name(self, name): path = os.path.join( get_directories()['data'], "patron_name_replacements.json" ) with open(path) as fp: modification_map = json.load(fp) for n1, n2 in modification_map.items(): # name = name.replace("ā", "\\={a}") if name.lower() == n1.lower(): name = n2 if self.capitalize: name = " ".join(map( lambda s: s.capitalize(), name.split(" ") )) return name
videos_3b1b/custom/opening_quote.py
from manimlib.animation.creation import Write from manimlib.animation.fading import FadeIn from manimlib.constants import * from manimlib.mobject.svg.tex_mobject import TexText from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import linear class OpeningQuote(Scene): quote = [] quote_arg_separator = " " highlighted_quote_terms = {} author = "" fade_in_kwargs = { "lag_ratio": 0.5, "rate_func": linear, "run_time": 5, } text_size = R"\Large" use_quotation_marks = True top_buff = 1.0 author_buff = 1.0 def construct(self): self.quote = self.get_quote() self.author = self.get_author(self.quote) self.play(FadeIn(self.quote, **self.fade_in_kwargs)) self.wait(2) self.play(Write(self.author, run_time=3)) self.wait() def get_quote(self, max_width=FRAME_WIDTH - 1): text_mobject_kwargs = { "alignment": "", "arg_separator": self.quote_arg_separator, } if isinstance(self.quote, str): if self.use_quotation_marks: quote = OldTexText("``%s''" % self.quote.strip(), **text_mobject_kwargs) else: quote = OldTexText("%s" % self.quote.strip(), **text_mobject_kwargs) else: if self.use_quotation_marks: words = [self.text_size + " ``"] + list(self.quote) + ["''"] else: words = [self.text_size] + list(self.quote) quote = OldTexText(*words, **text_mobject_kwargs) # TODO, make less hacky if self.quote_arg_separator == " ": quote[0].shift(0.2 * RIGHT) quote[-1].shift(0.2 * LEFT) for term, color in self.highlighted_quote_terms: quote.set_color_by_tex(term, color) quote.to_edge(UP, buff=self.top_buff) if quote.get_width() > max_width: quote.set_width(max_width) return quote def get_author(self, quote): author = OldTexText(self.text_size + " --" + self.author) author.next_to(quote, DOWN, buff=self.author_buff) author.set_color(YELLOW) return author
videos_3b1b/custom/deprecated.py
# This file contains functions and classes which have been used in old # videos, but which have since been supplanted in manim. For example, # there were previously various specifically named classes for version # of fading which are now covered by arguments passed into FadeIn and # FadeOut from manimlib.animation.fading import FadeIn, FadeOut class FadeInFromDown(FadeIn): def __init__(self, mobject, **kwargs): super().__init__(mobject, UP, **kwargs) class FadeOutAndShiftDown(FadeOut): def __init__(self, mobject, **kwargs): super().__init__(mobject, DOWN, **kwargs) class FadeInFromLarge(FadeIn): def __init__(self, mobject, scale_factor=2, **kwargs): super().__init__(mobject, scale=(1 / scale_factor), **kwargs)
videos_3b1b/custom/banner.py
from __future__ import annotations from manimlib.constants import * from manimlib.mobject.coordinate_systems import NumberPlane from manimlib.mobject.svg.tex_mobject import TexText from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.frame import FullScreenFadeRectangle from manimlib.scene.scene import Scene from custom.characters.pi_creature import Mortimer from custom.characters.pi_creature import Randolph from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import Vect3 class Banner(Scene): camera_config = dict(pixel_height=1440, pixel_width=2560) pi_height = 1.25 pi_bottom = 0.25 * DOWN use_date = False message = "Animated Math" date = "Sunday, February 3rd" message_height = 0.4 add_supporter_note = False pre_date_text = "Next video on " def construct(self): # Background self.add(FullScreenFadeRectangle().set_fill(BLACK, 1)) plane = NumberPlane( (-7, 7), (-5, 5), height=10 * 1.5, width=14 * 1.5, axis_config=dict(stroke_color=BLUE_A), faded_line_style=dict( stroke_width=0.5, stroke_opacity=0.35, stroke_color=BLUE, ), faded_line_ratio=4, ) for line in plane.family_members_with_points(): line.set_stroke(width=line.get_stroke_width() / 2) self.add( plane, # FullScreenFadeRectangle().set_fill(BLACK, 0.25), ) # Pis pis = self.get_pis() pis.set_height(self.pi_height) pis.arrange(RIGHT, aligned_edge=DOWN) pis.move_to(self.pi_bottom, DOWN) self.pis = pis self.add(pis) plane.move_to(pis.get_bottom() + SMALL_BUFF * DOWN) # Message message = self.get_message() message.set_height(self.message_height) message.next_to(pis, DOWN) message.set_stroke(BLACK, 10, background=True) self.add(message) # Suppoerter note if self.add_supporter_note: note = self.get_supporter_note() note.scale(0.5) message.shift((MED_SMALL_BUFF - SMALL_BUFF) * UP) note.next_to(message, DOWN, SMALL_BUFF) self.add(note) yellow_parts = [sm for sm in message if sm.get_color() == YELLOW] for pi in pis: if yellow_parts: pi.look_at(yellow_parts[-1]) else: pi.look_at(message) def get_pis(self): return VGroup( Randolph(color=BLUE_E, mode="pondering"), Randolph(color=BLUE_D, mode="hooray"), Randolph(color=BLUE_C, mode="tease"), Mortimer(color=GREY_BROWN, mode="thinking") ) def get_message(self): if self.message: return Text(self.message) if self.use_date: return self.get_date_message() else: return self.get_probabalistic_message() def get_probabalistic_message(self): return Text( "New video every day " + \ "(with probability 0.05)", t2c={"Sunday": YELLOW}, ) def get_date_message(self): return Text( self.pre_date_text, self.date, t2c={self.date: YELLOW}, ) def get_supporter_note(self): return OldTexText( "(Available to supporters for review now)", color="#F96854", ) class CurrBanner(Banner): camera_config: dict = { "pixel_height": 1440, "pixel_width": 2560, } pi_height: float = 1.25 pi_bottom: Vect3 = 0.25 * DOWN use_date: bool = False date: str = "Wednesday, March 15th" message_scale_val: float = 0.9 add_supporter_note: bool = False pre_date_text: str = "Next video on " def construct(self): super().construct() for pi in self.pis: pi.set_gloss(0.1)
videos_3b1b/custom/characters/pi_creature_scene.py
from __future__ import annotations from collections.abc import Iterable import random from manimlib.animation.transform import ReplacementTransform from manimlib.animation.transform import Transform from manimlib.animation.transform import ApplyMethod from manimlib.animation.composition import LaggedStart from manimlib.animation.fading import FadeIn from manimlib.animation.fading import FadeTransform from manimlib.constants import * from manimlib.mobject.mobject import Group from manimlib.mobject.frame import ScreenRectangle from manimlib.mobject.frame import FullScreenFadeRectangle from manimlib.mobject.svg.drawings import SpeechBubble from manimlib.mobject.svg.drawings import ThoughtBubble from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.scene.interactive_scene import InteractiveScene from manimlib.scene.scene import Scene from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import there_and_back from manimlib.utils.space_ops import get_norm from custom.characters.pi_creature import Mortimer from custom.characters.pi_creature import PiCreature from custom.characters.pi_creature import Randolph from custom.characters.pi_creature_animations import Blink from custom.characters.pi_creature_animations import PiCreatureBubbleIntroduction from custom.characters.pi_creature_animations import RemovePiCreatureBubble from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Vect3 class PiCreatureScene(InteractiveScene): total_wait_time: float = 0 seconds_to_blink: float = 3 pi_creatures_start_on_screen: bool = True default_pi_creature_kwargs: dict = dict( color=BLUE, flip_at_start=False, ) default_pi_creature_start_corner: Vect3 = DL def setup(self): super().setup() self.pi_creatures = VGroup(*self.create_pi_creatures()) self.pi_creature = self.get_primary_pi_creature() if self.pi_creatures_start_on_screen: self.add(*self.pi_creatures) def create_pi_creatures(self) -> VGroup | Iterable[PiCreature]: """ Likely updated for subclasses """ return [self.create_pi_creature()] def create_pi_creature(self) -> PiCreature: pi_creature = PiCreature(**self.default_pi_creature_kwargs) pi_creature.to_corner(self.default_pi_creature_start_corner) return pi_creature def get_pi_creatures(self) -> VGroup: return self.pi_creatures def get_primary_pi_creature(self) -> PiCreature: return self.pi_creatures[0] def any_pi_creatures_on_screen(self): return len(self.get_on_screen_pi_creatures()) > 0 def get_on_screen_pi_creatures(self): mobjects = self.get_mobject_family_members() return VGroup(*( pi for pi in self.get_pi_creatures() if pi in mobjects )) def pi_changes(self, *modes, look_at=None, lag_ratio=0.5, run_time=1): return LaggedStart( *( pi.change(mode, look_at) for pi, mode in zip(self.pi_creatures, modes) if mode is not None ), lag_ratio=lag_ratio, run_time=1, ) def introduce_bubble( self, pi_creature, content, bubble_type=SpeechBubble, target_mode=None, look_at=None, bubble_config=dict(), bubble_removal_kwargs=dict(), added_anims=[], **kwargs ): if target_mode is None: target_mode = "thinking" if bubble_type is ThoughtBubble else "speaking" anims = [] on_screen_mobjects = self.get_mobject_family_members() pi_creatures_with_bubbles = [ pi for pi in self.get_pi_creatures() if pi.bubble in on_screen_mobjects ] if pi_creature in pi_creatures_with_bubbles: pi_creatures_with_bubbles.remove(pi_creature) old_bubble = pi_creature.bubble bubble = pi_creature.get_bubble( content, bubble_type=bubble_type, **bubble_config ) anims += [ ReplacementTransform(old_bubble, bubble), FadeTransform(old_bubble.content, bubble.content), pi_creature.change(target_mode, look_at) ] else: anims.append(PiCreatureBubbleIntroduction( pi_creature, content, target_mode=target_mode, bubble_type=bubble_type, bubble_config=bubble_config, **kwargs )) anims += [ RemovePiCreatureBubble(pi, **bubble_removal_kwargs) for pi in pi_creatures_with_bubbles ] anims += added_anims self.play(*anims, **kwargs) def pi_creature_says(self, pi_creature, content, **kwargs): self.introduce_bubble(pi_creature, content, bubble_type=SpeechBubble, **kwargs) def pi_creature_thinks(self, pi_creature, content, **kwargs): self.introduce_bubble(pi_creature, content, bubble_type=ThoughtBubble, **kwargs) def say(self, content, **kwargs): self.pi_creature_says(self.get_primary_pi_creature(), content, **kwargs) def think(self, content, **kwargs): self.pi_creature_thinks(self.get_primary_pi_creature(), content, **kwargs) def anims_from_play_args(self, *args, **kwargs): """ Add animations so that all pi creatures look at the first mobject being animated with each .play call """ animations = super().anims_from_play_args(*args, **kwargs) anim_mobjects = Group(*[a.mobject for a in animations]) all_movers = anim_mobjects.get_family() if not self.any_pi_creatures_on_screen(): return animations pi_creatures = self.get_on_screen_pi_creatures() non_pi_creature_anims = [ anim for anim in animations if len(set(anim.mobject.get_family()).intersection(pi_creatures)) == 0 ] if len(non_pi_creature_anims) == 0: return animations # Get pi creatures to look at whatever # is being animated first_anim = non_pi_creature_anims[0] if hasattr(first_anim, "target_mobject") and first_anim.target_mobject is not None: main_mobject = first_anim.target_mobject else: main_mobject = first_anim.mobject for pi_creature in pi_creatures: if pi_creature not in all_movers: animations.append(ApplyMethod(pi_creature.look_at, main_mobject)) return animations def blink(self): self.play(Blink(random.choice(self.get_on_screen_pi_creatures()))) def joint_blink(self, pi_creatures=None, shuffle=True, **kwargs): if pi_creatures is None: pi_creatures = self.get_on_screen_pi_creatures() creatures_list = list(pi_creatures) if shuffle: random.shuffle(creatures_list) def get_rate_func(pi): index = creatures_list.index(pi) proportion = float(index) / len(creatures_list) start_time = 0.8 * proportion return squish_rate_func( there_and_back, start_time, start_time + 0.2 ) self.play(*[ Blink(pi, rate_func=get_rate_func(pi), **kwargs) for pi in creatures_list ]) return self def wait(self, time=1, blink=True, **kwargs): if "stop_condition" in kwargs: self.non_blink_wait(time, **kwargs) return while time >= 1: time_to_blink = self.total_wait_time % self.seconds_to_blink == 0 if blink and self.any_pi_creatures_on_screen() and time_to_blink: self.blink() else: self.non_blink_wait(**kwargs) time -= 1 self.total_wait_time += 1 if time > 0: self.non_blink_wait(time, **kwargs) return self def non_blink_wait(self, time=1, **kwargs): Scene.wait(self, time, **kwargs) return self def change_mode(self, mode): self.play(self.get_primary_pi_creature().change_mode, mode) def look_at(self, thing_to_look_at, pi_creatures=None, added_anims=None, **kwargs): if pi_creatures is None: pi_creatures = self.get_pi_creatures() anims = [ pi.animate.look_at(thing_to_look_at) for pi in pi_creatures ] if added_anims is not None: anims.extend(added_anims) self.play(*anims, **kwargs) class MortyPiCreatureScene(PiCreatureScene): default_pi_creature_kwargs: dict = dict( color=GREY_BROWN, flip_at_start=True, ) default_pi_creature_start_corner: Vect3 = DR class TeacherStudentsScene(PiCreatureScene): student_colors: list[ManimColor] = [BLUE_D, BLUE_E, BLUE_C] teacher_color: ManimColor = GREY_BROWN background_color: ManimColor = GREY_E student_scale_factor: float = 0.8 seconds_to_blink: float = 2 screen_height: float = 4 def setup(self): super().setup() self.add_background(self.background_color) self.screen = ScreenRectangle( height=self.screen_height, fill_color=BLACK, fill_opacity=1.0, ) self.screen.to_corner(UP + LEFT) self.hold_up_spot = self.teacher.get_corner(UP + LEFT) + MED_LARGE_BUFF * UP def add_background(self, color: ManimColor): self.background = FullScreenFadeRectangle( fill_color=color, fill_opacity=1, ) self.disable_interaction(self.background) self.add(self.background) self.bring_to_back(self.background) def create_pi_creatures(self): self.teacher = Mortimer(color=self.teacher_color) self.teacher.to_corner(DOWN + RIGHT) self.teacher.look(DOWN + LEFT) self.students = VGroup(*[ Randolph(color=c) for c in self.student_colors ]) self.students.arrange(RIGHT) self.students.scale(self.student_scale_factor) self.students.to_corner(DOWN + LEFT) self.teacher.look_at(self.students[-1].eyes) for student in self.students: student.look_at(self.teacher.eyes) return [*self.students, self.teacher] def get_teacher(self): return self.teacher def get_students(self): return self.students def teacher_says(self, content, **kwargs): return self.pi_creature_says(self.get_teacher(), content, **kwargs) def student_says( self, content, target_mode=None, bubble_direction=LEFT, index=2, **kwargs ): if target_mode is None: target_mode = random.choice([ "raise_right_hand", "raise_left_hand", ]) return self.pi_creature_says( self.get_students()[index], content, target_mode=target_mode, bubble_direction=bubble_direction, **kwargs ) def teacher_thinks(self, content, **kwargs): return self.pi_creature_thinks(self.get_teacher(), content, **kwargs) def student_thinks(self, content, target_mode=None, index=2, **kwargs): return self.pi_creature_thinks( self.get_students()[index], content, target_mode=target_mode, **kwargs ) def play_all_student_changes(self, mode, **kwargs): self.play_student_changes(*[mode] * len(self.students), **kwargs) def play_student_changes(self, *modes, **kwargs): added_anims = kwargs.pop("added_anims", []) self.play( self.change_students(*modes, **kwargs), *added_anims ) def change_students(self, *modes, look_at=None, lag_ratio=0.5, run_time=1): return LaggedStart( *( student.change(mode, look_at) for student, mode in zip(self.get_students(), modes) if mode is not None ), lag_ratio=lag_ratio, run_time=1, ) def zoom_in_on_thought_bubble(self, bubble=None, radius=FRAME_Y_RADIUS + FRAME_X_RADIUS): if bubble is None: for pi in self.get_pi_creatures(): if isinstance(pi.bubble, ThoughtBubble): bubble = pi.bubble break if bubble is None: raise Exception("No pi creatures have a thought bubble") vect = -bubble.get_bubble_center() def func(point): centered = point + vect return radius * centered / get_norm(centered) self.play(*[ ApplyPointwiseFunction(func, mob) for mob in self.get_mobjects() ]) def teacher_holds_up(self, mobject, target_mode="raise_right_hand", added_anims=None, **kwargs): mobject.move_to(self.hold_up_spot, DOWN) mobject.shift_onto_screen() added_anims = added_anims or [] self.play( FadeIn(mobject, shift=UP), self.teacher.change(target_mode, mobject), *added_anims )
videos_3b1b/custom/characters/pi_creature.py
from __future__ import annotations import os import logging import numpy as np from manimlib.animation.animation import Animation from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeTransform from manimlib.animation.transform import ReplacementTransform from manimlib.constants import * from manimlib.mobject.mobject import _AnimationBuilder from manimlib.mobject.mobject import Mobject from manimlib.mobject.geometry import Circle from manimlib.mobject.svg.drawings import ThoughtBubble from manimlib.mobject.svg.drawings import SpeechBubble from manimlib.mobject.svg.svg_mobject import SVGMobject from manimlib.mobject.svg.text_mobject import Text from manimlib.mobject.types.vectorized_mobject import VGroup from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.directories import get_directories from manimlib.utils.space_ops import get_norm from manimlib.utils.space_ops import normalize from typing import TYPE_CHECKING if TYPE_CHECKING: from manimlib.typing import ManimColor, Vect3 PI_CREATURE_SCALE_FACTOR: float = 0.5 LEFT_EYE_INDEX: int = 0 RIGHT_EYE_INDEX: int = 1 LEFT_PUPIL_INDEX: int = 2 RIGHT_PUPIL_INDEX: int = 3 BODY_INDEX: int = 4 MOUTH_INDEX: int = 5 class PiCreature(SVGMobject): # Range of proportions along body where arms are right_arm_range: tuple[float, float] = (0.55, 0.7) left_arm_range: tuple[float, float] = (0.34, 0.462) pupil_to_eye_width_ratio: float = 0.4 pupil_dot_to_pupil_width_ratio: float = 0.3 def __init__( self, mode: str = "plain", color: ManimColor = BLUE_E, stroke_width: float = 0.0, stroke_color: ManimColor = BLACK, fill_opacity: float = 1.0, height: float = 3, flip_at_start: bool = False, start_corner: Vect3 | None = None, **kwargs ): self.mode = mode self.bubble = None self.body = VMobject() # Just to keep self.get_color happy super().__init__( file_name=self.get_svg_file_path(mode), color=None, stroke_width=stroke_width, stroke_color=stroke_color, fill_opacity=fill_opacity, height=height, **kwargs ) self.init_structure() self.set_color(color) if flip_at_start: self.flip() if start_corner is not None: self.to_corner(start_corner) self.refresh_triangulation() def get_svg_file_path(self, mode): folder = get_directories()["pi_creature_images"] path = os.path.join(folder, f"{mode}.svg") if os.path.exists(path): return path else: logging.log( logging.WARNING, f"No design with mode {mode}", ) folder = get_directories()["pi_creature_images"] return os.path.join(folder, "plain.svg") def init_structure(self): # Figma exports with superfluous parts, so this # hardcodes how to extract what we want. parts = self.submobjects self.eyes: VGroup = self.draw_eyes( original_irises=VGroup(parts[2], parts[6]), original_pupils=VGroup(parts[8], parts[9]) ) self.body: VMobject = parts[10] self.mouth: VMobject = parts[11] self.mouth.insert_n_curves(10) self.set_submobjects([self.eyes, self.body, self.mouth]) def draw_eyes(self, original_irises, original_pupils): # Instead of what is drawn, make new circles. # This is mostly because the paths associated # with the eyes in all the drawings got slightly # messed up. eyes = VGroup() for iris, ref_pupil in zip(original_irises, original_pupils): pupil_r = iris.get_width() / 2 pupil_r *= self.pupil_to_eye_width_ratio dot_r = pupil_r dot_r *= self.pupil_dot_to_pupil_width_ratio black = Circle(radius=pupil_r, color=BLACK) dot = Circle(radius=dot_r, color=WHITE) dot.shift(black.pfp(3 / 8) - dot.pfp(3 / 8)) pupil = VGroup(black, dot) pupil.set_style(fill_opacity=1, stroke_width=0) pupil.move_to(ref_pupil) eye = VGroup(iris, pupil) eye.pupil = pupil eye.iris = iris eyes.add(eye) return eyes def align_data_and_family(self, mobject): # This ensures that after a transform into a different mode, # the pi creatures mode will be updated appropriately SVGMobject.align_data_and_family(self, mobject) if isinstance(mobject, PiCreature): self.mode = mobject.get_mode() def set_color(self, color, recurse=True): self.body.set_fill(color, recurse=recurse) return self def get_color(self): return self.body.get_color() def change_mode(self, mode): new_self = self.__class__(mode=mode) new_self.match_style(self) new_self.match_height(self) if self.is_flipped() != new_self.is_flipped(): new_self.flip() new_self.shift(self.eyes.get_center() - new_self.eyes.get_center()) if hasattr(self, "purposeful_looking_direction"): new_self.look(self.purposeful_looking_direction) self.become(new_self) self.mode = mode return self def get_mode(self): return self.mode def look(self, direction): direction = normalize(direction) self.purposeful_looking_direction = direction for eye in self.eyes: iris, pupil = eye iris_center = iris.get_center() right = iris.get_right() - iris_center up = iris.get_top() - iris_center vect = direction[0] * right + direction[1] * up v_norm = get_norm(vect) pupil_radius = 0.5 * pupil.get_width() vect *= (v_norm - 0.75 * pupil_radius) / v_norm pupil.move_to(iris_center + vect) self.eyes[1].pupil.align_to(self.eyes[0].pupil, DOWN) return self def look_at(self, point_or_mobject): if isinstance(point_or_mobject, Mobject): point = point_or_mobject.get_center() else: point = point_or_mobject self.look(point - self.eyes.get_center()) return self def get_looking_direction(self): vect = self.eyes[0].pupil.get_center() - self.eyes[0].get_center() return normalize(vect) def get_look_at_spot(self): return self.eyes.get_center() + self.get_looking_direction() def is_flipped(self): return self.eyes.submobjects[0].get_center()[0] > \ self.eyes.submobjects[1].get_center()[0] def blink(self): eyes = self.eyes eye_bottom_y = eyes.get_y(DOWN) for eye_part in eyes.family_members_with_points(): new_points = eye_part.get_points() new_points[:, 1] = eye_bottom_y eye_part.set_points(new_points) return self def get_bubble(self, content, bubble_type=ThoughtBubble, **bubble_config): bubble = bubble_type(**bubble_config) if len(content) > 0: if isinstance(content[0], str): content_mob = Text(content) else: content_mob = content bubble.add_content(content_mob) bubble.resize_to_content() bubble.pin_to(self, auto_flip=("direction" not in bubble_config)) self.bubble = bubble return bubble def make_eye_contact(self, pi_creature): self.look_at(pi_creature.eyes) pi_creature.look_at(self.eyes) return self def shrug(self): self.change_mode("shruggie") points = self.mouth.get_points() top_mouth_point, bottom_mouth_point = [ points[np.argmax(points[:, 1])], points[np.argmin(points[:, 1])] ] self.look(top_mouth_point - bottom_mouth_point) return self def get_arm_copies(self): body = self.body return VGroup(*[ body.copy().pointwise_become_partial(body, *alpha_range) for alpha_range in (self.right_arm_range, self.left_arm_range) ]) # Overrides def become(self, mobject): super().become(mobject) if isinstance(mobject, PiCreature): self.bubble = mobject.bubble return self # Animations def change(self, new_mode, look_at=None) -> _AnimationBuilder: animation = self.animate.change_mode(new_mode) if look_at is not None: animation = animation.look_at(look_at) return animation def says(self, content, mode="speaking", look_at=None, **kwargs) -> Animation: from custom.characters.pi_creature_animations import PiCreatureBubbleIntroduction return PiCreatureBubbleIntroduction( self, content, target_mode=mode, look_at=look_at, bubble_type=SpeechBubble, **kwargs, ) def thinks(self, content, mode="thinking", look_at=None, **kwargs) -> Animation: from custom.characters.pi_creature_animations import PiCreatureBubbleIntroduction return PiCreatureBubbleIntroduction( self, content, target_mode=mode, look_at=look_at, bubble_type=ThoughtBubble, **kwargs, ) def replace_bubble(self, content, mode="pondering", look_at=None, **kwargs) -> Animation | _AnimationBuilder: if self.bubble is None: return self.change(mode, look_at) old_bubble = self.bubble new_bubble = self.get_bubble(content, bubble_type=old_bubble.__class__, **kwargs) self.bubble = new_bubble return AnimationGroup( ReplacementTransform(old_bubble, new_bubble), FadeTransform(old_bubble.content, new_bubble.content), self.change(mode, look_at) ) def debubble(self, mode="plain", look_at=None, **kwargs): if self.bubble is None: logging.log( logging.WARNING, f"Calling debubble on PiCreature with no bubble", ) return self.change(mode, look_at) from custom.characters.pi_creature_animations import RemovePiCreatureBubble result = RemovePiCreatureBubble( self, target_mode=mode, look_at=look_at, **kwargs ) self.bubble = None return result class Randolph(PiCreature): pass # Nothing more than an alternative name class Mortimer(PiCreature): def __init__( self, mode: str = "plain", color: ManimColor=GREY_BROWN, flip_at_start: bool = True, **kwargs, ): super().__init__(mode, color, flip_at_start=flip_at_start, **kwargs) class Mathematician(PiCreature): def __init__(self, mode: str = "plain", color: ManimColor = GREY, **kwargs): super().__init__(mode, color, **kwargs) class BabyPiCreature(PiCreature): def __init__( self, mode: str = "plain", height: float = 1.5, eye_scale_factor: float = 1.2, pupil_scale_factor: float = 1.3, **kwargs ): super().__init__(mode, height=height, **kwargs) eyes = self.eyes eyes_bottom = eyes.get_bottom() eyes.scale(eye_scale_factor) eyes.move_to(eyes_bottom, aligned_edge=DOWN) looking_direction = self.get_looking_direction() for eye in eyes: eye.pupil.scale(pupil_scale_factor) self.look(looking_direction) class TauCreature(PiCreature): # TODO, this currently does nothing file_name_prefix: str = "TauCreatures" class ThreeLeggedPiCreature(PiCreature): # TODO, this currently does nothing file_name_prefix: str = "ThreeLeggedPiCreatures" # TODO, it'd be better to rewrite this so that # the pi creature eyes from above are an instance # of this, rather than the logic going the other way # around class Eyes(VGroup): def __init__( self, body: VMobject, height: float = 0.3, mode: str = "plain", **kwargs ): super().__init__(**kwargs) self.create_eyes(mode, height, body.get_top()) def create_eyes( self, mode: str, height: float, bottom: Vect3, look_at: Vect3 | Mobject | None = None ): self.mode = mode pi = PiCreature(mode=mode) pi.eyes.set_height(height) pi.eyes.move_to(bottom, DOWN) if look_at is not None: pi.look_at(look_at) self.set_submobjects(list(pi.eyes)) def change_mode(self, mode, look_at=None): self.create_eyes(mode, self.get_height(), self.get_bottom(), look_at) return self def look_at(self, target): self.create_eyes(self.mode, self.get_height(), self.get_bottom(), target) def blink(self, **kwargs): # TODO, change Blink bottom_y = self.get_bottom()[1] for submob in self: submob.apply_function( lambda p: np.array([p[0], bottom_y, p[2]]) ) return self
videos_3b1b/custom/characters/pi_creature_animations.py
from __future__ import annotations from manimlib.animation.composition import AnimationGroup from manimlib.animation.fading import FadeOut from manimlib.animation.creation import DrawBorderThenFill from manimlib.animation.creation import Write from manimlib.animation.transform import ApplyMethod from manimlib.animation.transform import MoveToTarget from manimlib.constants import * from manimlib.mobject.mobject import Group from manimlib.mobject.mobject import Mobject from manimlib.mobject.svg.drawings import SpeechBubble from manimlib.utils.rate_functions import squish_rate_func from manimlib.utils.rate_functions import there_and_back from custom.characters.pi_creature import PiCreature from typing import TYPE_CHECKING if TYPE_CHECKING: from typing import Callable from manimlib.typing import Vect3 class Blink(ApplyMethod): def __init__( self, pi_creature: PiCreature, rate_func: Callable = squish_rate_func(there_and_back), **kwargs ): super().__init__(pi_creature.blink, rate_func=rate_func, **kwargs) class PiCreatureBubbleIntroduction(AnimationGroup): def __init__( self, pi_creature: PiCreature, content: str, target_mode: str = "speaking", look_at: Mobject | Vect3 | None = None, bubble_type: type = SpeechBubble, max_bubble_height: float | None = None, max_bubble_width: float | None = None, bubble_direction: Vect3 | None = None, bubble_config=dict(), bubble_creation_class: type = DrawBorderThenFill, bubble_creation_kwargs: dict = dict(), content_introduction_class: type = Write, content_introduction_kwargs: dict = dict(), **kwargs, ): bubble_config = dict(bubble_config) bubble_config["max_height"] = max_bubble_height bubble_config["max_width"] = max_bubble_width if bubble_direction is not None: bubble_config["direction"] = bubble_direction bubble = pi_creature.get_bubble( content, bubble_type=bubble_type, **bubble_config ) Group(bubble, bubble.content).shift_onto_screen() super().__init__( pi_creature.change(target_mode, look_at), bubble_creation_class(bubble, **bubble_creation_kwargs), content_introduction_class(bubble.content, **content_introduction_kwargs), **kwargs ) class PiCreatureSays(PiCreatureBubbleIntroduction): def __init__( self, pi_creature: PiCreature, content: str, target_mode: str = "speaking", bubble_type: type = SpeechBubble, **kwargs, ): super().__init__( pi_creature, content, target_mode=target_mode, bubble_type=bubble_type, **kwargs ) class RemovePiCreatureBubble(AnimationGroup): def __init__( self, pi_creature: PiCreature, target_mode: str = "plain", look_at: Mobject | Vect3 | None = None, remover: bool = True, **kwargs ): assert hasattr(pi_creature, "bubble") self.pi_creature = pi_creature pi_creature.generate_target() pi_creature.target.change_mode(target_mode) if look_at is not None: pi_creature.target.look_at(look_at) super().__init__( MoveToTarget(pi_creature), FadeOut(pi_creature.bubble), FadeOut(pi_creature.bubble.content), ) def clean_up_from_scene(self, scene=None): AnimationGroup.clean_up_from_scene(self, scene) self.pi_creature.bubble = None if scene is not None: scene.add(self.pi_creature)
videos_3b1b/_2016/zeta.py
from manim_imports_ext import * import mpmath mpmath.mp.dps = 7 def zeta(z): max_norm = FRAME_X_RADIUS try: return np.complex(mpmath.zeta(z)) except: return np.complex(max_norm, 0) def d_zeta(z): epsilon = 0.01 return (zeta(z + epsilon) - zeta(z))/epsilon class ComplexTransformationScene(Scene): def construct(self): pass class ZetaTransformationScene(ComplexTransformationScene): CONFIG = { "anchor_density" : 35, "min_added_anchors" : 10, "max_added_anchors" : 300, "num_anchors_to_add_per_line" : 75, "post_transformation_stroke_width" : 2, "default_apply_complex_function_kwargs" : { "run_time" : 5, }, "x_min" : 1, "x_max" : int(FRAME_X_RADIUS+2), "extra_lines_x_min" : -2, "extra_lines_x_max" : 4, "extra_lines_y_min" : -2, "extra_lines_y_max" : 2, } def prepare_for_transformation(self, mob): for line in mob.family_members_with_points(): #Find point of line cloest to 1 on C if not isinstance(line, Line): line.insert_n_curves(self.min_added_anchors) continue p1 = line.get_start()+LEFT p2 = line.get_end()+LEFT t = (-np.dot(p1, p2-p1))/(get_norm(p2-p1)**2) closest_to_one = interpolate( line.get_start(), line.get_end(), t ) #See how big this line will become diameter = abs(zeta(complex(*closest_to_one[:2]))) target_num_curves = np.clip( int(self.anchor_density*np.pi*diameter), self.min_added_anchors, self.max_added_anchors, ) num_curves = line.get_num_curves() if num_curves < target_num_curves: line.insert_n_curves(target_num_curves-num_curves) line.make_smooth() def add_extra_plane_lines_for_zeta(self, animate = False, **kwargs): dense_grid = self.get_dense_grid(**kwargs) if animate: self.play(ShowCreation(dense_grid)) self.plane.add(dense_grid) self.add(self.plane) def get_dense_grid(self, step_size = 1./16): epsilon = 0.1 x_range = np.arange( max(self.x_min, self.extra_lines_x_min), min(self.x_max, self.extra_lines_x_max), step_size ) y_range = np.arange( max(self.y_min, self.extra_lines_y_min), min(self.y_max, self.extra_lines_y_max), step_size ) vert_lines = VGroup(*[ Line( self.y_min*UP, self.y_max*UP, ).shift(x*RIGHT) for x in x_range if abs(x-1) > epsilon ]) vert_lines.set_color_by_gradient( self.vert_start_color, self.vert_end_color ) horiz_lines = VGroup(*[ Line( self.x_min*RIGHT, self.x_max*RIGHT, ).shift(y*UP) for y in y_range if abs(y) > epsilon ]) horiz_lines.set_color_by_gradient( self.horiz_start_color, self.horiz_end_color ) dense_grid = VGroup(horiz_lines, vert_lines) dense_grid.set_stroke(width = 1) return dense_grid def add_reflected_plane(self, animate = False): reflected_plane = self.get_reflected_plane() if animate: self.play(ShowCreation(reflected_plane, run_time = 5)) self.plane.add(reflected_plane) self.add(self.plane) def get_reflected_plane(self): reflected_plane = self.plane.copy() reflected_plane.rotate(np.pi, UP, about_point = RIGHT) for mob in reflected_plane.family_members_with_points(): mob.set_color( Color(rgb = 1-0.5*color_to_rgb(mob.get_color())) ) self.prepare_for_transformation(reflected_plane) reflected_plane.submobjects = list(reversed( reflected_plane.family_members_with_points() )) return reflected_plane def apply_zeta_function(self, **kwargs): transform_kwargs = dict(self.default_apply_complex_function_kwargs) transform_kwargs.update(kwargs) self.apply_complex_function(zeta, **kwargs) class TestZetaOnHalfPlane(ZetaTransformationScene): CONFIG = { "anchor_density" : 15, } def construct(self): self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() self.prepare_for_transformation(self.plane) print(sum([ mob.get_num_points() for mob in self.plane.family_members_with_points() ])) print(len(self.plane.family_members_with_points())) self.apply_zeta_function() self.wait() class TestZetaOnFullPlane(ZetaTransformationScene): def construct(self): self.add_transformable_plane(animate = True) self.add_extra_plane_lines_for_zeta(animate = True) self.add_reflected_plane(animate = True) self.apply_zeta_function() class TestZetaOnLine(ZetaTransformationScene): def construct(self): line = Line(UP+20*LEFT, UP+20*RIGHT) self.add_transformable_plane() self.plane.submobjects = [line] self.apply_zeta_function() self.wait(2) self.play(ShowCreation(line, run_time = 10)) self.wait(3) ###################### class IntroduceZeta(ZetaTransformationScene): CONFIG = { "default_apply_complex_function_kwargs" : { "run_time" : 8, } } def construct(self): title = OldTexText("Riemann zeta function") title.add_background_rectangle() title.to_corner(UP+LEFT) func_mob = VGroup( OldTex("\\zeta(s) = "), OldTex("\\sum_{n=1}^\\infty \\frac{1}{n^s}") ) func_mob.arrange(RIGHT, buff = 0) for submob in func_mob: submob.add_background_rectangle() func_mob.next_to(title, DOWN) randy = Randolph().flip() randy.to_corner(DOWN+RIGHT) self.add_foreground_mobjects(title, func_mob) self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() self.play(ShowCreation(self.plane, run_time = 2)) reflected_plane = self.get_reflected_plane() self.play(ShowCreation(reflected_plane, run_time = 2)) self.plane.add(reflected_plane) self.wait() self.apply_zeta_function() self.wait(2) self.play(FadeIn(randy)) self.play( randy.change_mode, "confused", randy.look_at, func_mob, ) self.play(Blink(randy)) self.wait() class WhyPeopleMayKnowIt(TeacherStudentsScene): def construct(self): title = OldTexText("Riemann zeta function") title.to_corner(UP+LEFT) func_mob = OldTex( "\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}" ) func_mob.next_to(title, DOWN, aligned_edge = LEFT) self.add(title, func_mob) mercenary_thought = VGroup( OldTex("\\$1{,}000{,}000").set_color_by_gradient(GREEN_B, GREEN_D), OldTex("\\zeta(s) = 0") ) mercenary_thought.arrange(DOWN) divergent_sum = VGroup( OldTex("1+2+3+4+\\cdots = -\\frac{1}{12}"), OldTex("\\zeta(-1) = -\\frac{1}{12}") ) divergent_sum.arrange(DOWN) divergent_sum[0].set_color_by_gradient(YELLOW, MAROON_B) divergent_sum[1].set_color(BLACK) #Thoughts self.play(*it.chain(*[ [pi.change_mode, "pondering", pi.look_at, func_mob] for pi in self.get_pi_creatures() ])) self.random_blink() self.student_thinks( mercenary_thought, index = 2, target_mode = "surprised", ) student = self.get_students()[2] self.random_blink() self.wait(2) self.student_thinks( divergent_sum, index = 1, added_anims = [student.change_mode, "plain"] ) student = self.get_students()[1] self.play( student.change_mode, "confused", student.look_at, divergent_sum, ) self.random_blink() self.play(*it.chain(*[ [pi.change_mode, "confused", pi.look_at, divergent_sum] for pi in self.get_pi_creatures() ])) self.wait() self.random_blink() divergent_sum[1].set_color(WHITE) self.play(Write(divergent_sum[1])) self.random_blink() self.wait() #Ask about continuation self.student_says( OldTexText("Can you explain \\\\" , "``analytic continuation''?"), index = 1, target_mode = "raise_right_hand" ) self.play_student_changes( "raise_left_hand", "raise_right_hand", "raise_left_hand", ) self.play( self.get_teacher().change_mode, "happy", self.get_teacher().look_at, student.eyes, ) self.random_blink() self.wait(2) self.random_blink() self.wait() class ComplexValuedFunctions(ComplexTransformationScene): def construct(self): title = OldTexText("Complex-valued function") title.scale(1.5) title.add_background_rectangle() title.to_edge(UP) self.add(title) z_in = Dot(UP+RIGHT, color = YELLOW) z_out = Dot(4*RIGHT + 2*UP, color = MAROON_B) arrow = Arrow(z_in, z_out, buff = 0.1) arrow.set_color(WHITE) z = OldTex("z").next_to(z_in, DOWN+LEFT, buff = SMALL_BUFF) z.set_color(z_in.get_color()) f_z = OldTex("f(z)").next_to(z_out, UP+RIGHT, buff = SMALL_BUFF) f_z.set_color(z_out.get_color()) self.add(z_in, z) self.wait() self.play(ShowCreation(arrow)) self.play( ShowCreation(z_out), Write(f_z) ) self.wait(2) class PreviewZetaAndContinuation(ZetaTransformationScene): CONFIG = { "default_apply_complex_function_kwargs" : { "run_time" : 4, } } def construct(self): self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() reflected_plane = self.get_reflected_plane() titles = [ OldTexText( "What does", "%s"%s, "look like?", alignment = "", ) for s in [ "$\\displaystyle \\sum_{n=1}^\\infty \\frac{1}{n^s}$", "analytic continuation" ] ] for mob in titles: mob[1].set_color(YELLOW) mob.to_corner(UP+LEFT, buff = 0.7) mob.add_background_rectangle() self.remove(self.plane) self.play(Write(titles[0], run_time = 2)) self.add_foreground_mobjects(titles[0]) self.play(FadeIn(self.plane)) self.apply_zeta_function() reflected_plane.apply_complex_function(zeta) reflected_plane.make_smooth() reflected_plane.set_stroke(width = 2) self.wait() self.play(Transform(*titles)) self.wait() self.play(ShowCreation( reflected_plane, lag_ratio = 0, run_time = 2 )) self.wait() class AssumeKnowledgeOfComplexNumbers(ComplexTransformationScene): def construct(self): z = complex(5, 2) dot = Dot(z.real*RIGHT + z.imag*UP, color = YELLOW) line = Line(ORIGIN, dot.get_center(), color = dot.get_color()) x_line = Line(ORIGIN, z.real*RIGHT, color = GREEN_B) y_line = Line(ORIGIN, z.imag*UP, color = RED) y_line.shift(z.real*RIGHT) complex_number_label = OldTex( "%d+%di"%(int(z.real), int(z.imag)) ) complex_number_label[0].set_color(x_line.get_color()) complex_number_label[2].set_color(y_line.get_color()) complex_number_label.next_to(dot, UP) text = VGroup( OldTexText("Assumed knowledge:"), OldTexText("1) What complex numbers are."), OldTexText("2) How to work with them."), OldTexText("3) Maybe derivatives?"), ) text.arrange(DOWN, aligned_edge = LEFT) for words in text: words.add_background_rectangle() text[0].shift(LEFT) text[-1].set_color(PINK) text.to_corner(UP+LEFT) self.play(Write(text[0])) self.wait() self.play(FadeIn(text[1])) self.play( ShowCreation(x_line), ShowCreation(y_line), ShowCreation(VGroup(line, dot)), Write(complex_number_label), ) self.play(Write(text[2])) self.wait(2) self.play(Write(text[3])) self.wait() self.play(text[3].fade) class DefineForRealS(PiCreatureScene): def construct(self): zeta_def, s_group = self.get_definition("s") self.initial_definition(zeta_def) self.plug_in_two(zeta_def) self.plug_in_three_and_four(zeta_def) self.plug_in_negative_values(zeta_def) def initial_definition(self, zeta_def): zeta_s, sum_terms, brace, sigma = zeta_def self.say("Let's define $\\zeta(s)$") self.blink() pre_zeta_s = VGroup( *self.pi_creature.bubble.content.copy()[-4:] ) pre_zeta_s.add(VectorizedPoint(pre_zeta_s.get_right())) self.play( Transform(pre_zeta_s, zeta_s), *self.get_bubble_fade_anims() ) self.remove(pre_zeta_s) self.add(zeta_s) self.wait() for count, term in enumerate(sum_terms): self.play(FadeIn(term), run_time = 0.5) if count%2 == 0: self.wait() self.play( GrowFromCenter(brace), Write(sigma), self.pi_creature.change_mode, "pondering" ) self.wait() def plug_in_two(self, zeta_def): two_def = self.get_definition("2")[0] number_line = NumberLine( x_min = 0, x_max = 3, tick_frequency = 0.25, numbers_with_elongated_ticks = list(range(4)), unit_size = 3, ) number_line.add_numbers() number_line.next_to(self.pi_creature, LEFT) number_line.to_edge(LEFT) self.number_line = number_line lines, braces, dots, pi_dot = self.get_sum_lines(2) fracs = VGroup(*[ OldTex("\\frac{1}{%d}"%((d+1)**2)).scale(0.7) for d, brace in enumerate(braces) ]) for frac, brace, line in zip(fracs, braces, lines): frac.set_color(line.get_color()) frac.next_to(brace, UP, buff = SMALL_BUFF) if frac is fracs[-1]: frac.shift(0.5*RIGHT + 0.2*UP) arrow = Arrow( frac.get_bottom(), brace.get_top(), tip_length = 0.1, buff = 0.1 ) arrow.set_color(line.get_color()) frac.add(arrow) pi_term = OldTex("= \\frac{\\pi^2}{6}") pi_term.next_to(zeta_def[1], RIGHT) pi_arrow = Arrow( pi_term[-1].get_bottom(), pi_dot, color = pi_dot.get_color() ) approx = OldTex("\\approx 1.645") approx.next_to(pi_term) self.play(Transform(zeta_def, two_def)) self.wait() self.play(ShowCreation(number_line)) for frac, brace, line in zip(fracs, braces, lines): self.play( Write(frac), GrowFromCenter(brace), ShowCreation(line), run_time = 0.7 ) self.wait(0.7) self.wait() self.play( ShowCreation(VGroup(*lines[4:])), Write(dots) ) self.wait() self.play( Write(pi_term), ShowCreation(VGroup(pi_arrow, pi_dot)), self.pi_creature.change_mode, "hooray" ) self.wait() self.play( Write(approx), self.pi_creature.change_mode, "happy" ) self.wait(3) self.play(*list(map(FadeOut, [ fracs, pi_arrow, pi_dot, approx, ]))) self.lines = lines self.braces = braces self.dots = dots self.final_dot = pi_dot self.final_sum = pi_term def plug_in_three_and_four(self, zeta_def): final_sums = ["1.202\\dots", "\\frac{\\pi^4}{90}"] sum_terms, brace, sigma = zeta_def[1:] for exponent, final_sum in zip([3, 4], final_sums): self.transition_to_new_input(zeta_def, exponent, final_sum) self.wait() arrow = Arrow(sum_terms.get_left(), sum_terms.get_right()) arrow.next_to(sum_terms, DOWN) smaller_words = OldTexText("Getting smaller") smaller_words.next_to(arrow, DOWN) self.arrow, self.smaller_words = arrow, smaller_words self.wait() self.play( ShowCreation(arrow), Write(smaller_words) ) self.change_mode("happy") self.wait(2) def plug_in_negative_values(self, zeta_def): zeta_s, sum_terms, brace, sigma = zeta_def arrow = self.arrow smaller_words = self.smaller_words bigger_words = OldTexText("Getting \\emph{bigger}?") bigger_words.move_to(self.smaller_words) #plug in -1 self.transition_to_new_input(zeta_def, -1, "-\\frac{1}{12}") self.play( Transform(self.smaller_words, bigger_words), self.pi_creature.change_mode, "confused" ) new_sum_terms = OldTex( list("1+2+3+4+") + ["\\cdots"] ) new_sum_terms.move_to(sum_terms, LEFT) arrow.target = arrow.copy().next_to(new_sum_terms, DOWN) arrow.target.stretch_to_fit_width(new_sum_terms.get_width()) bigger_words.next_to(arrow.target, DOWN) new_brace = Brace(new_sum_terms, UP) self.play( Transform(sum_terms, new_sum_terms), Transform(brace, new_brace), sigma.next_to, new_brace, UP, MoveToTarget(arrow), Transform(smaller_words, bigger_words), self.final_sum.next_to, new_sum_terms, RIGHT ) self.wait(3) #plug in -2 new_sum_terms = OldTex( list("1+4+9+16+") + ["\\cdots"] ) new_sum_terms.move_to(sum_terms, LEFT) new_zeta_def, ignore = self.get_definition("-2") zeta_minus_two, ignore, ignore, new_sigma = new_zeta_def new_sigma.next_to(brace, UP) new_final_sum = OldTex("=0") new_final_sum.next_to(new_sum_terms) lines, braces, dots, final_dot = self.get_sum_lines(-2) self.play( Transform(zeta_s, zeta_minus_two), Transform(sum_terms, new_sum_terms), Transform(sigma, new_sigma), Transform(self.final_sum, new_final_sum), Transform(self.lines, lines), Transform(self.braces, braces), ) self.wait() self.change_mode("pleading") self.wait(2) def get_definition(self, input_string, input_color = YELLOW): inputs = VGroup() num_shown_terms = 4 n_input_chars = len(input_string) zeta_s_eq = OldTex("\\zeta(%s) = "%input_string) zeta_s_eq.to_edge(LEFT, buff = LARGE_BUFF) zeta_s_eq.shift(0.5*UP) inputs.add(*zeta_s_eq[2:2+n_input_chars]) sum_terms = OldTex(*it.chain(*list(zip( [ "\\frac{1}{%d^{%s}}"%(d, input_string) for d in range(1, 1+num_shown_terms) ], it.cycle(["+"]) )))) sum_terms.add(OldTex("\\cdots").next_to(sum_terms)) sum_terms.next_to(zeta_s_eq, RIGHT) for x in range(num_shown_terms): inputs.add(*sum_terms[2*x][-n_input_chars:]) brace = Brace(sum_terms, UP) sigma = OldTex( "\\sum_{n=1}^\\infty \\frac{1}{n^{%s}}"%input_string ) sigma.next_to(brace, UP) inputs.add(*sigma[-n_input_chars:]) inputs.set_color(input_color) group = VGroup(zeta_s_eq, sum_terms, brace, sigma) return group, inputs def get_sum_lines(self, exponent, line_thickness = 6): num_lines = 100 if exponent > 0 else 6 powers = [0] + [x**(-exponent) for x in range(1, num_lines)] power_sums = np.cumsum(powers) lines = VGroup(*[ Line( self.number_line.number_to_point(s1), self.number_line.number_to_point(s2), ) for s1, s2 in zip(power_sums, power_sums[1:]) ]) lines.set_stroke(width = line_thickness) # VGroup(*lines[:4]).set_color_by_gradient(RED, GREEN_B) # VGroup(*lines[4:]).set_color_by_gradient(GREEN_B, MAROON_B) VGroup(*lines[::2]).set_color(MAROON_B) VGroup(*lines[1::2]).set_color(RED) braces = VGroup(*[ Brace(line, UP) for line in lines[:4] ]) dots = OldTex("...") dots.stretch_to_fit_width( 0.8 * VGroup(*lines[4:]).get_width() ) dots.next_to(braces, RIGHT, buff = SMALL_BUFF) final_dot = Dot( self.number_line.number_to_point(power_sums[-1]), color = GREEN_B ) return lines, braces, dots, final_dot def transition_to_new_input(self, zeta_def, exponent, final_sum): new_zeta_def = self.get_definition(str(exponent))[0] lines, braces, dots, final_dot = self.get_sum_lines(exponent) final_sum = OldTex("=" + final_sum) final_sum.next_to(new_zeta_def[1][-1]) final_sum.shift(SMALL_BUFF*UP) self.play( Transform(zeta_def, new_zeta_def), Transform(self.lines, lines), Transform(self.braces, braces), Transform(self.dots, dots), Transform(self.final_dot, final_dot), Transform(self.final_sum, final_sum), self.pi_creature.change_mode, "pondering" ) class ReadIntoZetaFunction(Scene): CONFIG = { "statement" : "$\\zeta(-1) = -\\frac{1}{12}$", "target_mode" : "frustrated", } def construct(self): randy = Randolph(mode = "pondering") randy.shift(3*LEFT+DOWN) paper = Rectangle(width = 4, height = 5) paper.next_to(randy, RIGHT, aligned_edge = DOWN) paper.set_color(WHITE) max_width = 0.8*paper.get_width() title = OldTexText("$\\zeta(s)$ manual") title.next_to(paper.get_top(), DOWN) title.set_color(YELLOW) paper.add(title) paragraph_lines = VGroup( Line(LEFT, RIGHT), Line(LEFT, RIGHT).shift(0.2*DOWN), Line(LEFT, ORIGIN).shift(0.4*DOWN) ) paragraph_lines.set_width(max_width) paragraph_lines.next_to(title, DOWN, MED_LARGE_BUFF) paper.add(paragraph_lines) max_height = 1.5*paragraph_lines.get_height() statement = OldTexText(self.statement) if statement.get_width() > max_width: statement.set_width(max_width) if statement.get_height() > max_height: statement.set_height(max_height) statement.next_to(paragraph_lines, DOWN) statement.set_color(GREEN_B) paper.add(paragraph_lines.copy().next_to(statement, DOWN, MED_LARGE_BUFF)) randy.look_at(statement) self.add(randy, paper) self.play(Write(statement)) self.play( randy.change_mode, self.target_mode, randy.look_at, title ) self.play(Blink(randy)) self.play(randy.look_at, statement) self.wait() class ReadIntoZetaFunctionTrivialZero(ReadIntoZetaFunction): CONFIG = { "statement" : "$\\zeta(-2n) = 0$" } class ReadIntoZetaFunctionAnalyticContinuation(ReadIntoZetaFunction): CONFIG = { "statement" : "...analytic \\\\ continuation...", "target_mode" : "confused", } class IgnoreNegatives(TeacherStudentsScene): def construct(self): definition = OldTex(""" \\zeta(s) = \\sum_{n=1}^{\\infty} \\frac{1}{n^s} """) VGroup(definition[2], definition[-1]).set_color(YELLOW) definition.to_corner(UP+LEFT) self.add(definition) brace = Brace(definition, DOWN) only_s_gt_1 = brace.get_text(""" Only defined for $s > 1$ """) only_s_gt_1[-3].set_color(YELLOW) self.play_student_changes(*["confused"]*3) words = OldTexText( "Ignore $s \\le 1$ \\dots \\\\", "For now." ) words[0][6].set_color(YELLOW) words[1].set_color(BLACK) self.teacher_says(words) self.play(words[1].set_color, WHITE) self.play_student_changes(*["happy"]*3) self.play( GrowFromCenter(brace), Write(only_s_gt_1), *it.chain(*[ [pi.look_at, definition] for pi in self.get_pi_creatures() ]) ) self.random_blink(3) class RiemannFatherOfComplex(ComplexTransformationScene): def construct(self): name = OldTexText( "Bernhard Riemann $\\rightarrow$ Complex analysis" ) name.to_corner(UP+LEFT) name.shift(0.25*DOWN) name.add_background_rectangle() # photo = Square() photo = ImageMobject("Riemann", invert = False) photo.set_width(5) photo.next_to(name, DOWN, aligned_edge = LEFT) self.add(photo) self.play(Write(name)) self.wait() input_dot = Dot(2*RIGHT+UP, color = YELLOW) arc = Arc(-2*np.pi/3) arc.rotate(-np.pi) arc.add_tip() arc.shift(input_dot.get_top()-arc.get_points()[0]+SMALL_BUFF*UP) output_dot = Dot( arc.get_points()[-1] + SMALL_BUFF*(2*RIGHT+DOWN), color = MAROON_B ) for dot, tex in (input_dot, "z"), (output_dot, "f(z)"): dot.label = OldTex(tex) dot.label.add_background_rectangle() dot.label.next_to(dot, DOWN+RIGHT, buff = SMALL_BUFF) dot.label.set_color(dot.get_color()) self.play( ShowCreation(input_dot), Write(input_dot.label) ) self.play(ShowCreation(arc)) self.play( ShowCreation(output_dot), Write(output_dot.label) ) self.wait() class FromRealToComplex(ComplexTransformationScene): CONFIG = { "plane_config" : { "space_unit_to_x_unit" : 2, "space_unit_to_y_unit" : 2, }, "background_label_scale_val" : 0.7, "output_color" : GREEN_B, "num_lines_in_spiril_sum" : 1000, } def construct(self): self.handle_background() self.show_real_to_real() self.transition_to_complex() self.single_out_complex_exponent() ##Fade to several scenes defined below self.show_s_equals_two_lines() self.transition_to_spiril_sum() self.vary_complex_input() self.show_domain_of_convergence() self.ask_about_visualizing_all() def handle_background(self): self.remove(self.background) #Oh yeah, this is great practice... self.background[-1].remove(*self.background[-1][-3:]) def show_real_to_real(self): zeta = self.get_zeta_definition("2", "\\frac{\\pi^2}{6}") number_line = NumberLine( unit_size = 2, tick_frequency = 0.5, numbers_with_elongated_ticks = list(range(-2, 3)) ) number_line.add_numbers() input_dot = Dot(number_line.number_to_point(2)) input_dot.set_color(YELLOW) output_dot = Dot(number_line.number_to_point(np.pi**2/6)) output_dot.set_color(self.output_color) arc = Arc( 2*np.pi/3, start_angle = np.pi/6, ) arc.stretch_to_fit_width( (input_dot.get_center()-output_dot.get_center())[0] ) arc.stretch_to_fit_height(0.5) arc.next_to(input_dot.get_center(), UP, aligned_edge = RIGHT) arc.add_tip() two = zeta[1][2].copy() sum_term = zeta[-1] self.add(number_line, *zeta[:-1]) self.wait() self.play(Transform(two, input_dot)) self.remove(two) self.add(input_dot) self.play(ShowCreation(arc)) self.play(ShowCreation(output_dot)) self.play(Transform(output_dot.copy(), sum_term)) self.remove(*self.get_mobjects_from_last_animation()) self.add(sum_term) self.wait(2) self.play( ShowCreation( self.background, run_time = 2 ), FadeOut(VGroup(arc, output_dot, number_line)), Animation(zeta), Animation(input_dot) ) self.wait(2) self.zeta = zeta self.input_dot = input_dot def transition_to_complex(self): complex_zeta = self.get_zeta_definition("2+i", "???") input_dot = self.input_dot input_dot.generate_target() input_dot.target.move_to( self.background.num_pair_to_point((2, 1)) ) input_label = OldTex("2+i") input_label.set_color(YELLOW) input_label.next_to(input_dot.target, DOWN+RIGHT, buff = SMALL_BUFF) input_label.add_background_rectangle() input_label.save_state() input_label.replace(VGroup(*complex_zeta[1][2:5])) input_label.background_rectangle.scale(0.01) self.input_label = input_label self.play(Transform(self.zeta, complex_zeta)) self.wait() self.play( input_label.restore, MoveToTarget(input_dot) ) self.wait(2) def single_out_complex_exponent(self): frac_scale_factor = 1.2 randy = Randolph() randy.to_corner() bubble = randy.get_bubble(height = 4) bubble.set_fill(BLACK, opacity = 1) frac = VGroup( VectorizedPoint(self.zeta[2][3].get_left()), self.zeta[2][3], VectorizedPoint(self.zeta[2][3].get_right()), self.zeta[2][4], ).copy() frac.generate_target() frac.target.scale(frac_scale_factor) bubble.add_content(frac.target) new_frac = OldTex( "\\Big(", "\\frac{1}{2}", "\\Big)", "^{2+i}" ) new_frac[-1].set_color(YELLOW) new_frac.scale(frac_scale_factor) new_frac.move_to(frac.target) new_frac.shift(LEFT+0.2*UP) words = OldTexText("Not repeated \\\\", " multiplication") words.scale(0.8) words.set_color(RED) words.next_to(new_frac, RIGHT) new_words = OldTexText("Not \\emph{super} \\\\", "crucial to know...") new_words.replace(words) new_words.scale(1.3) self.play(FadeIn(randy)) self.play( randy.change_mode, "confused", randy.look_at, bubble, ShowCreation(bubble), MoveToTarget(frac) ) self.play(Blink(randy)) self.play(Transform(frac, new_frac)) self.play(Write(words)) for x in range(2): self.wait(2) self.play(Blink(randy)) self.play( Transform(words, new_words), randy.change_mode, "maybe" ) self.wait() self.play(Blink(randy)) self.play(randy.change_mode, "happy") self.wait() self.play(*list(map(FadeOut, [randy, bubble, frac, words]))) def show_s_equals_two_lines(self): self.input_label.save_state() zeta = self.get_zeta_definition("2", "\\frac{\\pi^2}{6}") lines, output_dot = self.get_sum_lines(2) sum_terms = self.zeta[2][:-1:3] dots_copy = zeta[2][-1].copy() pi_copy = zeta[3].copy() def transform_and_replace(m1, m2): self.play(Transform(m1, m2)) self.remove(m1) self.add(m2) self.play( self.input_dot.shift, 2*DOWN, self.input_label.fade, 0.7, ) self.play(Transform(self.zeta, zeta)) for term, line in zip(sum_terms, lines): line.save_state() line.next_to(term, DOWN) term_copy = term.copy() transform_and_replace(term_copy, line) self.play(line.restore) later_lines = VGroup(*lines[4:]) transform_and_replace(dots_copy, later_lines) self.wait() transform_and_replace(pi_copy, output_dot) self.wait() self.lines = lines self.output_dot = output_dot def transition_to_spiril_sum(self): zeta = self.get_zeta_definition("2+i", "1.15 - 0.44i") zeta.set_width(FRAME_WIDTH-1) zeta.to_corner(UP+LEFT) lines, output_dot = self.get_sum_lines(complex(2, 1)) self.play( self.input_dot.shift, 2*UP, self.input_label.restore, ) self.wait() self.play(Transform(self.zeta, zeta)) self.wait() self.play( Transform(self.lines, lines), Transform(self.output_dot, output_dot), run_time = 2, path_arc = -np.pi/6, ) self.wait() def vary_complex_input(self): zeta = self.get_zeta_definition("s", "") zeta[3].set_color(BLACK) self.play(Transform(self.zeta, zeta)) self.play(FadeOut(self.input_label)) self.wait(2) inputs = [ complex(1.5, 1.8), complex(1.5, -1), complex(3, -1), complex(1.5, 1.8), complex(1.5, -1.8), complex(1.4, -1.8), complex(1.5, 0), complex(2, 1), ] for s in inputs: input_point = self.z_to_point(s) lines, output_dot = self.get_sum_lines(s) self.play( self.input_dot.move_to, input_point, Transform(self.lines, lines), Transform(self.output_dot, output_dot), run_time = 2 ) self.wait() self.wait() def show_domain_of_convergence(self, opacity = 0.2): domain = Rectangle( width = FRAME_X_RADIUS-2, height = FRAME_HEIGHT, stroke_width = 0, fill_color = YELLOW, fill_opacity = opacity, ) domain.to_edge(RIGHT, buff = 0) anti_domain = Rectangle( width = FRAME_X_RADIUS+2, height = FRAME_HEIGHT, stroke_width = 0, fill_color = RED, fill_opacity = opacity, ) anti_domain.to_edge(LEFT, buff = 0) domain_words = OldTexText(""" $\\zeta(s)$ happily converges and makes sense """) domain_words.to_corner(UP+RIGHT, buff = MED_LARGE_BUFF) anti_domain_words = OldTexText(""" Not so much... """) anti_domain_words.next_to(ORIGIN, LEFT, buff = LARGE_BUFF) anti_domain_words.shift(1.5*DOWN) self.play(FadeIn(domain)) self.play(Write(domain_words)) self.wait() self.play(FadeIn(anti_domain)) self.play(Write(anti_domain_words)) self.wait(2) self.play(*list(map(FadeOut, [ anti_domain, anti_domain_words, ]))) self.domain_words = domain_words def ask_about_visualizing_all(self): morty = Mortimer().flip() morty.scale(0.7) morty.to_corner(DOWN+LEFT) bubble = morty.get_bubble(SpeechBubble, height = 4) bubble.set_fill(BLACK, opacity = 0.5) bubble.write(""" How can we visualize this for all inputs? """) self.play(FadeIn(morty)) self.play( morty.change_mode, "speaking", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.wait(3) self.play( morty.change_mode, "pondering", morty.look_at, self.input_dot, *list(map(FadeOut, [ bubble, bubble.content, self.domain_words ])) ) arrow = Arrow(self.input_dot, self.output_dot, buff = SMALL_BUFF) arrow.set_color(WHITE) self.play(ShowCreation(arrow)) self.play(Blink(morty)) self.wait() def get_zeta_definition(self, input_string, output_string, input_color = YELLOW): inputs = VGroup() num_shown_terms = 4 n_input_chars = len(input_string) zeta_s_eq = OldTex("\\zeta(%s) = "%input_string) zeta_s_eq.to_edge(LEFT, buff = LARGE_BUFF) zeta_s_eq.shift(0.5*UP) inputs.add(*zeta_s_eq[2:2+n_input_chars]) raw_sum_terms = OldTex(*[ "\\frac{1}{%d^{%s}} + "%(d, input_string) for d in range(1, 1+num_shown_terms) ]) sum_terms = VGroup(*it.chain(*[ [ VGroup(*term[:3]), VGroup(*term[3:-1]), term[-1], ] for term in raw_sum_terms ])) sum_terms.add(OldTex("\\cdots").next_to(sum_terms[-1])) sum_terms.next_to(zeta_s_eq, RIGHT) for x in range(num_shown_terms): inputs.add(*sum_terms[3*x+1]) output = OldTex("= \\," + output_string) output.next_to(sum_terms, RIGHT) output.set_color(self.output_color) inputs.set_color(input_color) group = VGroup(zeta_s_eq, sum_terms, output) group.to_edge(UP) group.add_to_back(BackgroundRectangle(group)) return group def get_sum_lines(self, exponent, line_thickness = 6): powers = [0] + [ x**(-exponent) for x in range(1, self.num_lines_in_spiril_sum) ] power_sums = np.cumsum(powers) lines = VGroup(*[ Line(*list(map(self.z_to_point, z_pair))) for z_pair in zip(power_sums, power_sums[1:]) ]) widths = np.linspace(line_thickness, 0, len(list(lines))) for line, width in zip(lines, widths): line.set_stroke(width = width) VGroup(*lines[::2]).set_color(MAROON_B) VGroup(*lines[1::2]).set_color(RED) final_dot = Dot( # self.z_to_point(power_sums[-1]), self.z_to_point(zeta(exponent)), color = self.output_color ) return lines, final_dot class TerritoryOfExponents(ComplexTransformationScene): def construct(self): self.add_title() familiar_territory = OldTexText("Familiar territory") familiar_territory.set_color(YELLOW) familiar_territory.next_to(ORIGIN, UP+RIGHT) familiar_territory.shift(2*UP) real_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) real_line.set_color(YELLOW) arrow1 = Arrow(familiar_territory.get_bottom(), real_line.get_left()) arrow2 = Arrow(familiar_territory.get_bottom(), real_line.get_right()) VGroup(arrow1, arrow2).set_color(WHITE) extended_realm = OldTexText("Extended realm") extended_realm.move_to(familiar_territory) full_plane = Rectangle( width = FRAME_WIDTH, height = FRAME_HEIGHT, fill_color = YELLOW, fill_opacity = 0.3 ) self.add(familiar_territory) self.play(ShowCreation(arrow1)) self.play( Transform(arrow1, arrow2), ShowCreation(real_line) ) self.play(FadeOut(arrow1)) self.play( FadeIn(full_plane), Transform(familiar_territory, extended_realm), Animation(real_line) ) def add_title(self): exponent = OldTex( "\\left(\\frac{1}{2}\\right)^s" ) exponent[-1].set_color(YELLOW) exponent.next_to(ORIGIN, LEFT, MED_LARGE_BUFF).to_edge(UP) self.add_foreground_mobjects(exponent) class ComplexExponentiation(Scene): def construct(self): self.extract_pure_imaginary_part() self.add_on_planes() self.show_imaginary_powers() def extract_pure_imaginary_part(self): original = OldTex( "\\left(\\frac{1}{2}\\right)", "^{2+i}" ) split = OldTex( "\\left(\\frac{1}{2}\\right)", "^{2}", "\\left(\\frac{1}{2}\\right)", "^{i}", ) VGroup(original[-1], split[1], split[3]).set_color(YELLOW) VGroup(original, split).shift(UP) real_part = VGroup(*split[:2]) imag_part = VGroup(*split[2:]) brace = Brace(real_part) we_understand = brace.get_text( "We understand this" ) VGroup(brace, we_understand).set_color(GREEN_B) self.add(original) self.wait() self.play(*[ Transform(*pair) for pair in [ (original[0], split[0]), (original[1][0], split[1]), (original[0].copy(), split[2]), (VGroup(*original[1][1:]), split[3]), ] ]) self.remove(*self.get_mobjects_from_last_animation()) self.add(real_part, imag_part) self.wait() self.play( GrowFromCenter(brace), FadeIn(we_understand), real_part.set_color, GREEN_B ) self.wait() self.play( imag_part.move_to, imag_part.get_left(), *list(map(FadeOut, [brace, we_understand, real_part])) ) self.wait() self.imag_exponent = imag_part def add_on_planes(self): left_plane = NumberPlane(x_radius = (FRAME_X_RADIUS-1)/2) left_plane.to_edge(LEFT, buff = 0) imag_line = Line(DOWN, UP).scale(FRAME_Y_RADIUS) imag_line.set_color(YELLOW).fade(0.3) imag_line.move_to(left_plane.get_center()) left_plane.add(imag_line) left_title = OldTexText("Input space") left_title.add_background_rectangle() left_title.set_color(YELLOW) left_title.next_to(left_plane.get_top(), DOWN) right_plane = NumberPlane(x_radius = (FRAME_X_RADIUS-1)/2) right_plane.to_edge(RIGHT, buff = 0) unit_circle = Circle() unit_circle.set_color(MAROON_B).fade(0.3) unit_circle.shift(right_plane.get_center()) right_plane.add(unit_circle) right_title = OldTexText("Output space") right_title.add_background_rectangle() right_title.set_color(MAROON_B) right_title.next_to(right_plane.get_top(), DOWN) for plane in left_plane, right_plane: labels = VGroup() for x in range(-2, 3): label = OldTex(str(x)) label.move_to(plane.num_pair_to_point((x, 0))) labels.add(label) for y in range(-3, 4): if y == 0: continue label = OldTex(str(y) + "i") label.move_to(plane.num_pair_to_point((0, y))) labels.add(label) for label in labels: label.scale(0.5) label.next_to( label.get_center(), DOWN+RIGHT, buff = SMALL_BUFF ) plane.add(labels) arrow = Arrow(LEFT, RIGHT) self.play( ShowCreation(left_plane), Write(left_title), run_time = 3 ) self.play( ShowCreation(right_plane), Write(right_title), run_time = 3 ) self.play(ShowCreation(arrow)) self.wait() self.left_plane = left_plane self.right_plane = right_plane def show_imaginary_powers(self): i = complex(0, 1) input_dot = Dot(self.z_to_point(i)) input_dot.set_color(YELLOW) output_dot = Dot(self.z_to_point(0.5**(i), is_input = False)) output_dot.set_color(MAROON_B) output_dot.save_state() output_dot.move_to(input_dot) output_dot.set_color(input_dot.get_color()) curr_base = 0.5 def output_dot_update(ouput_dot): y = input_dot.get_center()[1] output_dot.move_to(self.z_to_point( curr_base**complex(0, y), is_input = False )) return output_dot def walk_up_and_down(): for vect in 3*DOWN, 5*UP, 5*DOWN, 2*UP: self.play( input_dot.shift, vect, UpdateFromFunc(output_dot, output_dot_update), run_time = 3 ) exp = self.imag_exponent[-1] new_exp = OldTex("ti") new_exp.set_color(exp.get_color()) new_exp.set_height(exp.get_height()) new_exp.move_to(exp, LEFT) nine = OldTex("9") nine.set_color(BLUE) denom = self.imag_exponent[0][3] denom.save_state() nine.replace(denom) self.play(Transform(exp, new_exp)) self.play(input_dot.shift, 2*UP) self.play(input_dot.shift, 2*DOWN) self.wait() self.play(output_dot.restore) self.wait() walk_up_and_down() self.wait() curr_base = 1./9 self.play(Transform(denom, nine)) walk_up_and_down() self.wait() def z_to_point(self, z, is_input = True): if is_input: plane = self.left_plane else: plane = self.right_plane return plane.num_pair_to_point((z.real, z.imag)) class SizeAndRotationBreakdown(Scene): def construct(self): original = OldTex( "\\left(\\frac{1}{2}\\right)", "^{2+i}" ) split = OldTex( "\\left(\\frac{1}{2}\\right)", "^{2}", "\\left(\\frac{1}{2}\\right)", "^{i}", ) VGroup(original[-1], split[1], split[3]).set_color(YELLOW) VGroup(original, split).shift(UP) real_part = VGroup(*split[:2]) imag_part = VGroup(*split[2:]) size_brace = Brace(real_part) size = size_brace.get_text("Size") rotation_brace = Brace(imag_part, UP) rotation = rotation_brace.get_text("Rotation") self.add(original) self.wait() self.play(*[ Transform(*pair) for pair in [ (original[0], split[0]), (original[1][0], split[1]), (original[0].copy(), split[2]), (VGroup(*original[1][1:]), split[3]), ] ]) self.play( GrowFromCenter(size_brace), Write(size) ) self.play( GrowFromCenter(rotation_brace), Write(rotation) ) self.wait() class SeeLinksInDescription(TeacherStudentsScene): def construct(self): self.teacher_says(""" See links in the description for more. """) self.play(*it.chain(*[ [pi.change_mode, "hooray", pi.look, DOWN] for pi in self.get_students() ])) self.random_blink(3) class ShowMultiplicationOfRealAndImaginaryExponentialParts(FromRealToComplex): def construct(self): self.break_up_exponent() self.show_multiplication() def break_up_exponent(self): original = OldTex( "\\left(\\frac{1}{2}\\right)", "^{2+i}" ) split = OldTex( "\\left(\\frac{1}{2}\\right)", "^{2}", "\\left(\\frac{1}{2}\\right)", "^{i}", ) VGroup(original[-1], split[1], split[3]).set_color(YELLOW) VGroup(original, split).to_corner(UP+LEFT) rect = BackgroundRectangle(split) real_part = VGroup(*split[:2]) imag_part = VGroup(*split[2:]) self.add(rect, original) self.wait() self.play(*[ Transform(*pair) for pair in [ (original[0], split[0]), (original[1][0], split[1]), (original[0].copy(), split[2]), (VGroup(*original[1][1:]), split[3]), ] ]) self.remove(*self.get_mobjects_from_last_animation()) self.add(real_part, imag_part) self.wait() self.real_part = real_part self.imag_part = imag_part def show_multiplication(self): real_part = self.real_part.copy() imag_part = self.imag_part.copy() for part in real_part, imag_part: part.add_to_back(BackgroundRectangle(part)) fourth_point = self.z_to_point(0.25) fourth_line = Line(ORIGIN, fourth_point) brace = Brace(fourth_line, UP, buff = SMALL_BUFF) fourth_dot = Dot(fourth_point) fourth_group = VGroup(fourth_line, brace, fourth_dot) fourth_group.set_color(RED) circle = Circle(radius = 2, color = MAROON_B) circle.fade(0.3) imag_power_point = self.z_to_point(0.5**complex(0, 1)) imag_power_dot = Dot(imag_power_point) imag_power_line = Line(ORIGIN, imag_power_point) VGroup(imag_power_dot, imag_power_line).set_color(MAROON_B) full_power_tex = OldTex( "\\left(\\frac{1}{2}\\right)", "^{2+i}" ) full_power_tex[-1].set_color(YELLOW) full_power_tex.add_background_rectangle() full_power_tex.scale(0.7) full_power_tex.next_to( 0.5*self.z_to_point(0.5**complex(2, 1)), UP+RIGHT ) self.play( real_part.scale, 0.7, real_part.next_to, brace, UP, SMALL_BUFF, LEFT, ShowCreation(fourth_dot) ) self.play( GrowFromCenter(brace), ShowCreation(fourth_line), ) self.wait() self.play( imag_part.scale, 0.7, imag_part.next_to, imag_power_dot, DOWN+RIGHT, SMALL_BUFF, ShowCreation(imag_power_dot) ) self.play(ShowCreation(circle), Animation(imag_power_dot)) self.play(ShowCreation(imag_power_line)) self.wait(2) self.play( fourth_group.rotate, imag_power_line.get_angle() ) real_part.generate_target() imag_part.generate_target() real_part.target.next_to(brace, UP+RIGHT, buff = 0) imag_part.target.next_to(real_part.target, buff = 0) self.play(*list(map(MoveToTarget, [real_part, imag_part]))) self.wait() class ComplexFunctionsAsTransformations(ComplexTransformationScene): def construct(self): self.add_title() input_dots, output_dots, arrows = self.get_dots() self.play(FadeIn( input_dots, run_time = 2, lag_ratio = 0.5 )) for in_dot, out_dot, arrow in zip(input_dots, output_dots, arrows): self.play( Transform(in_dot.copy(), out_dot), ShowCreation(arrow) ) self.wait() self.wait() def add_title(self): title = OldTexText("Complex functions as transformations") title.add_background_rectangle() title.to_edge(UP) self.add(title) def get_dots(self): input_points = [ RIGHT+2*UP, 4*RIGHT+DOWN, 2*LEFT+2*UP, LEFT+DOWN, 6*LEFT+DOWN, ] output_nudges = [ DOWN+RIGHT, 2*UP+RIGHT, 2*RIGHT+2*DOWN, 2*RIGHT+DOWN, RIGHT+2*UP, ] input_dots = VGroup(*list(map(Dot, input_points))) input_dots.set_color(YELLOW) output_dots = VGroup(*[ Dot(ip + on) for ip, on in zip(input_points, output_nudges) ]) output_dots.set_color(MAROON_B) arrows = VGroup(*[ Arrow(in_dot, out_dot, buff = 0.1, color = WHITE) for in_dot, out_dot, in zip(input_dots, output_dots) ]) for i, dot in enumerate(input_dots): label = OldTex("s_%d"%i) label.set_color(dot.get_color()) label.next_to(dot, DOWN+LEFT, buff = SMALL_BUFF) dot.add(label) for i, dot in enumerate(output_dots): label = OldTex("f(s_%d)"%i) label.set_color(dot.get_color()) label.next_to(dot, UP+RIGHT, buff = SMALL_BUFF) dot.add(label) return input_dots, output_dots, arrows class VisualizingSSquared(ComplexTransformationScene): CONFIG = { "num_anchors_to_add_per_line" : 100, "horiz_end_color" : GOLD, "y_min" : 0, } def construct(self): self.add_title() self.plug_in_specific_values() self.show_transformation() self.comment_on_two_dimensions() def add_title(self): title = OldTex("f(", "s", ") = ", "s", "^2") title.set_color_by_tex("s", YELLOW) title.add_background_rectangle() title.scale(1.5) title.to_corner(UP+LEFT) self.play(Write(title)) self.add_foreground_mobject(title) self.wait() self.title = title def plug_in_specific_values(self): inputs = list(map(complex, [2, -1, complex(0, 1)])) input_dots = VGroup(*[ Dot(self.z_to_point(z), color = YELLOW) for z in inputs ]) output_dots = VGroup(*[ Dot(self.z_to_point(z**2), color = BLUE) for z in inputs ]) arrows = VGroup() VGroup(*[ ParametricCurve( lambda t : self.z_to_point(z**(1.1+0.8*t)) ) for z in inputs ]) for z, dot in zip(inputs, input_dots): path = ParametricCurve( lambda t : self.z_to_point(z**(1+t)) ) dot.path = path arrow = ParametricCurve( lambda t : self.z_to_point(z**(1.1+0.8*t)) ) stand_in_arrow = Arrow( arrow.get_points()[-2], arrow.get_points()[-1], tip_length = 0.2 ) arrow.add(stand_in_arrow.tip) arrows.add(arrow) arrows.set_color(WHITE) for input_dot, output_dot, arrow in zip(input_dots, output_dots, arrows): input_dot.save_state() input_dot.move_to(self.title[1][1]) input_dot.set_fill(opacity = 0) self.play(input_dot.restore) self.wait() self.play(ShowCreation(arrow)) self.play(ShowCreation(output_dot)) self.wait() self.add_foreground_mobjects(arrows, output_dots, input_dots) self.input_dots = input_dots self.output_dots = output_dots def add_transformable_plane(self, **kwargs): ComplexTransformationScene.add_transformable_plane(self, **kwargs) self.plane.next_to(ORIGIN, UP, buff = 0.01) self.plane.add(self.plane.copy().rotate(np.pi, RIGHT)) self.plane.add( Line(ORIGIN, FRAME_X_RADIUS*RIGHT, color = self.horiz_end_color), Line(ORIGIN, FRAME_X_RADIUS*LEFT, color = self.horiz_end_color), ) self.add(self.plane) def show_transformation(self): self.add_transformable_plane() self.play(ShowCreation(self.plane, run_time = 3)) self.wait() self.apply_complex_homotopy( lambda z, t : z**(1+t), added_anims = [ MoveAlongPath(dot, dot.path, run_time = 5) for dot in self.input_dots ], run_time = 5 ) self.wait(2) def comment_on_two_dimensions(self): morty = Mortimer().flip() morty.scale(0.7) morty.to_corner(DOWN+LEFT) bubble = morty.get_bubble(SpeechBubble, height = 2, width = 4) bubble.set_fill(BLACK, opacity = 0.9) bubble.write(""" It all happens in two dimensions! """) self.foreground_mobjects = [] self.play(FadeIn(morty)) self.play( morty.change_mode, "hooray", ShowCreation(bubble), Write(bubble.content), ) self.play(Blink(morty)) self.wait(2) class ShowZetaOnHalfPlane(ZetaTransformationScene): CONFIG = { "x_min" : 1, "x_max" : int(FRAME_X_RADIUS+2), } def construct(self): self.add_title() self.initial_transformation() self.react_to_transformation() self.show_cutoff() self.set_color_i_line() self.show_continuation() self.emphsize_sum_doesnt_make_sense() def add_title(self): zeta = OldTex( "\\zeta(", "s", ")=", *[ "\\frac{1}{%d^s} + "%d for d in range(1, 5) ] + ["\\cdots"] ) zeta[1].set_color(YELLOW) for mob in zeta[3:3+4]: mob[-2].set_color(YELLOW) zeta.add_background_rectangle() zeta.scale(0.8) zeta.to_corner(UP+LEFT) self.add_foreground_mobjects(zeta) self.zeta = zeta def initial_transformation(self): self.add_transformable_plane() self.wait() self.add_extra_plane_lines_for_zeta(animate = True) self.wait(2) self.plane.save_state() self.apply_zeta_function() self.wait(2) def react_to_transformation(self): morty = Mortimer().flip() morty.to_corner(DOWN+LEFT) bubble = morty.get_bubble(SpeechBubble) bubble.set_fill(BLACK, 0.5) bubble.write("\\emph{Damn}!") bubble.resize_to_content() bubble.pin_to(morty) self.play(FadeIn(morty)) self.play( morty.change_mode, "surprised", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.play(morty.look_at, self.plane.get_top()) self.wait() self.play( morty.look_at, self.plane.get_bottom(), *list(map(FadeOut, [bubble, bubble.content])) ) self.play(Blink(morty)) self.play(FadeOut(morty)) def show_cutoff(self): words = OldTexText("Such an abrupt stop...") words.add_background_rectangle() words.next_to(ORIGIN, UP+LEFT) words.shift(LEFT+UP) line = Line(*list(map(self.z_to_point, [ complex(np.euler_gamma, u*FRAME_Y_RADIUS) for u in (1, -1) ]))) line.set_color(YELLOW) arrows = [ Arrow(words.get_right(), point) for point in line.get_start_and_end() ] self.play(Write(words, run_time = 2)) self.play(ShowCreation(arrows[0])) self.play( Transform(*arrows), ShowCreation(line), run_time = 2 ) self.play(FadeOut(arrows[0])) self.wait(2) self.play(*list(map(FadeOut, [words, line]))) def set_color_i_line(self): right_i_lines, left_i_lines = [ VGroup(*[ Line( vert_vect+RIGHT, vert_vect+(FRAME_X_RADIUS+1)*horiz_vect ) for vert_vect in (UP, DOWN) ]) for horiz_vect in (RIGHT, LEFT) ] right_i_lines.set_color(YELLOW) left_i_lines.set_color(BLUE) for lines in right_i_lines, left_i_lines: self.prepare_for_transformation(lines) self.restore_mobjects(self.plane) self.plane.add(*right_i_lines) colored_plane = self.plane.copy() right_i_lines.set_stroke(width = 0) self.play( self.plane.set_stroke, GREY, 1, ) right_i_lines.set_stroke(YELLOW, width = 3) self.play(ShowCreation(right_i_lines)) self.plane.save_state() self.wait(2) self.apply_zeta_function() self.wait(2) left_i_lines.save_state() left_i_lines.apply_complex_function(zeta) self.play(ShowCreation(left_i_lines, run_time = 5)) self.wait() self.restore_mobjects(self.plane, left_i_lines) self.play(Transform(self.plane, colored_plane)) self.wait() self.left_i_lines = left_i_lines def show_continuation(self): reflected_plane = self.get_reflected_plane() self.play(ShowCreation(reflected_plane, run_time = 2)) self.plane.add(reflected_plane) self.remove(self.left_i_lines) self.wait() self.apply_zeta_function() self.wait(2) self.play(ShowCreation( reflected_plane, run_time = 6, rate_func = lambda t : 1-there_and_back(t) )) self.wait(2) def emphsize_sum_doesnt_make_sense(self): brace = Brace(VGroup(*self.zeta[1][3:])) words = brace.get_text(""" Still fails to converge when Re$(s) < 1$ """, buff = SMALL_BUFF) words.add_background_rectangle() words.scale(0.8) divergent_sum = OldTex("1+2+3+4+\\cdots") divergent_sum.next_to(ORIGIN, UP) divergent_sum.to_edge(LEFT) divergent_sum.add_background_rectangle() self.play( GrowFromCenter(brace), Write(words) ) self.wait(2) self.play(Write(divergent_sum)) self.wait(2) def restore_mobjects(self, *mobjects): self.play(*it.chain(*[ [m.restore, m.make_smooth] for m in mobjects ]), run_time = 2) for m in mobjects: self.remove(m) m.restore() self.add(m) class ShowConditionalDefinition(Scene): def construct(self): zeta = OldTex("\\zeta(s)=") zeta[2].set_color(YELLOW) sigma = OldTex("\\sum_{n=1}^\\infty \\frac{1}{n^s}") sigma[-1].set_color(YELLOW) something_else = OldTexText("Something else...") conditions = VGroup(*[ OldTexText("if Re$(s) %s 1$"%s) for s in (">", "\\le") ]) definitions = VGroup(sigma, something_else) definitions.arrange(DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT) conditions.arrange(DOWN, buff = LARGE_BUFF) definitions.shift(2*LEFT+2*UP) conditions.next_to(definitions, RIGHT, buff = LARGE_BUFF, aligned_edge = DOWN) brace = Brace(definitions, LEFT) zeta.next_to(brace, LEFT) sigma.save_state() sigma.next_to(zeta) self.add(zeta, sigma) self.wait() self.play( sigma.restore, GrowFromCenter(brace), FadeIn(something_else) ) self.play(Write(conditions)) self.wait() underbrace = Brace(something_else) question = underbrace.get_text(""" What to put here? """) VGroup(underbrace, question).set_color(GREEN_B) self.play( GrowFromCenter(underbrace), Write(question), something_else.set_color, GREEN_B ) self.wait(2) class SquiggleOnExtensions(ZetaTransformationScene): CONFIG = { "x_min" : 1, "x_max" : int(FRAME_X_RADIUS+2), } def construct(self): self.show_negative_one() self.cycle_through_options() self.lock_into_place() def show_negative_one(self): self.add_transformable_plane() thin_plane = self.plane.copy() thin_plane.add(self.get_reflected_plane()) self.remove(self.plane) self.add_extra_plane_lines_for_zeta() reflected_plane = self.get_reflected_plane() self.plane.add(reflected_plane) self.remove(self.plane) self.add(thin_plane) dot = self.note_point(-1, "-1") self.play( ShowCreation(self.plane, run_time = 2), Animation(dot), run_time = 2 ) self.remove(thin_plane) self.apply_zeta_function(added_anims = [ ApplyMethod( dot.move_to, self.z_to_point(-1./12), run_time = 5 ) ]) dot_to_remove = self.note_point(-1./12, "-\\frac{1}{12}") self.remove(dot_to_remove) self.left_plane = reflected_plane self.dot = dot def note_point(self, z, label_tex): dot = Dot(self.z_to_point(z)) dot.set_color(YELLOW) label = OldTex(label_tex) label.add_background_rectangle() label.next_to(dot, UP+LEFT, buff = SMALL_BUFF) label.shift(LEFT) arrow = Arrow(label.get_right(), dot, buff = SMALL_BUFF) self.play(Write(label, run_time = 1)) self.play(*list(map(ShowCreation, [arrow, dot]))) self.wait() self.play(*list(map(FadeOut, [arrow, label]))) return dot def cycle_through_options(self): gamma = np.euler_gamma def shear(point): x, y, z = point return np.array([ x, y+0.25*(1-x)**2, 0 ]) def mixed_scalar_func(point): x, y, z = point scalar = 1 + (gamma-x)/(gamma+FRAME_X_RADIUS) return np.array([ (scalar**2)*x, (scalar**3)*y, 0 ]) def alt_mixed_scalar_func(point): x, y, z = point scalar = 1 + (gamma-x)/(gamma+FRAME_X_RADIUS) return np.array([ (scalar**5)*x, (scalar**2)*y, 0 ]) def sinusoidal_func(point): x, y, z = point freq = np.pi/gamma return np.array([ x-0.2*np.sin(x*freq)*np.sin(y), y-0.2*np.sin(x*freq)*np.sin(y), 0 ]) funcs = [ shear, mixed_scalar_func, alt_mixed_scalar_func, sinusoidal_func, ] for mob in self.left_plane.family_members_with_points(): if np.all(np.abs(mob.get_points()[:,1]) < 0.1): self.left_plane.remove(mob) new_left_planes = [ self.left_plane.copy().apply_function(func) for func in funcs ] new_dots = [ self.dot.copy().move_to(func(self.dot.get_center())) for func in funcs ] self.left_plane.save_state() for plane, dot in zip(new_left_planes, new_dots): self.play( Transform(self.left_plane, plane), Transform(self.dot, dot), run_time = 3 ) self.wait() self.play(FadeOut(self.dot)) #Squiggle on example self.wait() self.play(FadeOut(self.left_plane)) self.play(ShowCreation( self.left_plane, run_time = 5, rate_func=linear )) self.wait() def lock_into_place(self): words = OldTexText( """Only one extension has a """, "\\emph{derivative}", "everywhere", alignment = "" ) words.to_corner(UP+LEFT) words.set_color_by_tex("\\emph{derivative}", YELLOW) words.add_background_rectangle() self.play(Write(words)) self.add_foreground_mobjects(words) self.play(self.left_plane.restore) self.wait() class DontKnowDerivatives(TeacherStudentsScene): def construct(self): self.student_says( """ You said we don't need derivatives! """, target_mode = "pleading" ) self.random_blink(2) self.student_says( """ I get $\\frac{df}{dx}$, just not for complex functions """, target_mode = "confused", index = 2 ) self.random_blink(2) self.teacher_says( """ Luckily, there's a purely geometric intuition here. """, target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.random_blink(3) class IntroduceAnglePreservation(VisualizingSSquared): CONFIG = { "num_anchors_to_add_per_line" : 50, "use_homotopy" : True, } def construct(self): self.add_title() self.show_initial_transformation() self.talk_about_derivative() self.cycle_through_line_pairs() self.note_grid_lines() self.name_analytic() def add_title(self): title = OldTex("f(", "s", ")=", "s", "^2") title.set_color_by_tex("s", YELLOW) title.scale(1.5) title.to_corner(UP+LEFT) title.add_background_rectangle() self.title = title self.add_transformable_plane() self.play(Write(title)) self.add_foreground_mobjects(title) self.wait() def show_initial_transformation(self): self.apply_function() self.wait(2) self.reset() def talk_about_derivative(self): randy = Randolph().scale(0.8) randy.to_corner(DOWN+LEFT) morty = Mortimer() morty.to_corner(DOWN+RIGHT) randy.make_eye_contact(morty) for pi, words in (randy, "$f'(s) = 2s$"), (morty, "Here's some \\\\ related geometry..."): pi.bubble = pi.get_bubble(SpeechBubble) pi.bubble.set_fill(BLACK, opacity = 0.7) pi.bubble.write(words) pi.bubble.resize_to_content() pi.bubble.pin_to(pi) for index in 3, 7: randy.bubble.content[index].set_color(YELLOW) self.play(*list(map(FadeIn, [randy, morty]))) self.play( randy.change_mode, "speaking", ShowCreation(randy.bubble), Write(randy.bubble.content) ) self.play(Blink(morty)) self.wait() self.play( morty.change_mode, "speaking", randy.change_mode, "pondering", ShowCreation(morty.bubble), Write(morty.bubble.content), ) self.play(Blink(randy)) self.wait() self.play(*list(map(FadeOut, [ randy, morty, randy.bubble, randy.bubble.content, morty.bubble, morty.bubble.content, ]))) def cycle_through_line_pairs(self): line_pairs = [ ( Line(3*DOWN+3*RIGHT, 2*UP), Line(DOWN+RIGHT, 3*UP+4*RIGHT) ), ( Line(RIGHT+3.5*DOWN, RIGHT+2.5*UP), Line(3*LEFT+0.5*UP, 3*RIGHT+0.5*UP), ), ( Line(4*RIGHT+4*DOWN, RIGHT+2*UP), Line(4*DOWN+RIGHT, 2*UP+2*RIGHT) ), ] for lines in line_pairs: self.show_angle_preservation_between_lines(*lines) self.reset() def note_grid_lines(self): intersection_inputs = [ complex(x, y) for x in np.arange(-5, 5, 0.5) for y in np.arange(0, 3, 0.5) if not (x <= 0 and y == 0) ] brackets = VGroup(*list(map( self.get_right_angle_bracket, intersection_inputs ))) self.apply_function() self.wait() self.play( ShowCreation(brackets, run_time = 5), Animation(self.plane) ) self.wait() def name_analytic(self): equiv = OldTexText("``Analytic'' $\\Leftrightarrow$ Angle-preserving") kind_of = OldTexText("...kind of") for text in equiv, kind_of: text.scale(1.2) text.add_background_rectangle() equiv.set_color(YELLOW) kind_of.set_color(RED) kind_of.next_to(equiv, RIGHT) VGroup(equiv, kind_of).next_to(ORIGIN, UP, buff = 1) self.play(Write(equiv)) self.wait(2) self.play(Write(kind_of, run_time = 1)) self.wait(2) def reset(self, faded = True): self.play(FadeOut(self.plane)) self.add_transformable_plane() if faded: self.plane.fade() self.play(FadeIn(self.plane)) def apply_function(self, **kwargs): if self.use_homotopy: self.apply_complex_homotopy( lambda z, t : z**(1+t), run_time = 5, **kwargs ) else: self.apply_complex_function( lambda z : z**2, **kwargs ) def show_angle_preservation_between_lines(self, *lines): R2_endpoints = [ [l.get_start()[:2], l.get_end()[:2]] for l in lines ] R2_intersection_point = intersection(*R2_endpoints) intersection_point = np.array(list(R2_intersection_point) + [0]) angle1, angle2 = [l.get_angle() for l in lines] arc = Arc( start_angle = angle1, angle = angle2-angle1, radius = 0.4, color = YELLOW ) arc.shift(intersection_point) arc.insert_n_curves(10) arc.generate_target() input_z = complex(*arc.get_center()[:2]) scale_factor = abs(2*input_z) arc.target.scale_about_point(1./scale_factor, intersection_point) arc.target.apply_complex_function(lambda z : z**2) angle_tex = OldTex( "%d^\\circ"%abs(int((angle2-angle1)*180/np.pi)) ) angle_tex.set_color(arc.get_color()) angle_tex.add_background_rectangle() self.put_angle_tex_next_to_arc(angle_tex, arc) angle_arrow = Arrow( angle_tex, arc, color = arc.get_color(), buff = 0.1, ) angle_group = VGroup(angle_tex, angle_arrow) self.play(*list(map(ShowCreation, lines))) self.play( Write(angle_tex), ShowCreation(angle_arrow), ShowCreation(arc) ) self.wait() self.play(FadeOut(angle_group)) self.plane.add(*lines) self.apply_function(added_anims = [ MoveToTarget(arc, run_time = 5) ]) self.put_angle_tex_next_to_arc(angle_tex, arc) arrow = Arrow(angle_tex, arc, buff = 0.1) arrow.set_color(arc.get_color()) self.play( Write(angle_tex), ShowCreation(arrow) ) self.wait(2) self.play(*list(map(FadeOut, [arc, angle_tex, arrow]))) def put_angle_tex_next_to_arc(self, angle_tex, arc): vect = arc.point_from_proportion(0.5)-interpolate( arc.get_points()[0], arc.get_points()[-1], 0.5 ) unit_vect = vect/get_norm(vect) angle_tex.move_to(arc.get_center() + 1.7*unit_vect) def get_right_angle_bracket(self, input_z): output_z = input_z**2 derivative = 2*input_z rotation = np.log(derivative).imag brackets = VGroup( Line(RIGHT, RIGHT+UP), Line(RIGHT+UP, UP) ) brackets.scale(0.15) brackets.set_stroke(width = 2) brackets.set_color(YELLOW) brackets.shift(0.02*UP) ##Why??? brackets.rotate(rotation, about_point = ORIGIN) brackets.shift(self.z_to_point(output_z)) return brackets class AngleAtZeroDerivativePoints(IntroduceAnglePreservation): CONFIG = { "use_homotopy" : True } def construct(self): self.add_title() self.is_before_transformation = True self.add_transformable_plane() self.plane.fade() line = Line(3*LEFT+0.5*UP, 3*RIGHT+0.5*DOWN) self.show_angle_preservation_between_lines( line, line.copy().rotate(np.pi/5) ) self.wait() def add_title(self): title = OldTex("f(", "s", ")=", "s", "^2") title.set_color_by_tex("s", YELLOW) title.scale(1.5) title.to_corner(UP+LEFT) title.add_background_rectangle() derivative = OldTex("f'(0) = 0") derivative.set_color(RED) derivative.scale(1.2) derivative.add_background_rectangle() derivative.next_to(title, DOWN) self.add_foreground_mobjects(title, derivative) def put_angle_tex_next_to_arc(self, angle_tex, arc): IntroduceAnglePreservation.put_angle_tex_next_to_arc( self, angle_tex, arc ) if not self.is_before_transformation: two_dot = OldTex("2 \\times ") two_dot.set_color(angle_tex.get_color()) two_dot.next_to(angle_tex, LEFT, buff = SMALL_BUFF) two_dot.add_background_rectangle() center = angle_tex.get_center() angle_tex.add_to_back(two_dot) angle_tex.move_to(center) else: self.is_before_transformation = False class AnglePreservationAtAnyPairOfPoints(IntroduceAnglePreservation): def construct(self): self.add_transformable_plane() self.plane.fade() line_pairs = self.get_line_pairs() line_pair = line_pairs[0] for target_pair in line_pairs[1:]: self.play(Transform( line_pair, target_pair, run_time = 2, path_arc = np.pi )) self.wait() self.show_angle_preservation_between_lines(*line_pair) self.show_example_analytic_functions() def get_line_pairs(self): return list(it.starmap(VGroup, [ ( Line(3*DOWN, 3*LEFT+2*UP), Line(2*LEFT+DOWN, 3*UP+RIGHT) ), ( Line(2*RIGHT+DOWN, 3*LEFT+2*UP), Line(LEFT+3*DOWN, 4*RIGHT+3*UP), ), ( Line(LEFT+3*DOWN, LEFT+3*UP), Line(5*LEFT+UP, 3*RIGHT+UP) ), ( Line(4*RIGHT+3*DOWN, RIGHT+2*UP), Line(3*DOWN+RIGHT, 2*UP+2*RIGHT) ), ])) def show_example_analytic_functions(self): words = OldTexText("Examples of analytic functions:") words.shift(2*UP) words.set_color(YELLOW) words.add_background_rectangle() words.next_to(UP, UP).to_edge(LEFT) functions = OldTexText( "$e^x$, ", "$\\sin(x)$, ", "any polynomial, " "$\\log(x)$, ", "\\dots", ) functions.next_to(ORIGIN, UP).to_edge(LEFT) for function in functions: function.add_to_back(BackgroundRectangle(function)) self.play(Write(words)) for function in functions: self.play(FadeIn(function)) self.wait() class NoteZetaFunctionAnalyticOnRightHalf(ZetaTransformationScene): CONFIG = { "anchor_density" : 35, } def construct(self): self.add_title() self.add_transformable_plane(animate = False) self.add_extra_plane_lines_for_zeta(animate = True) self.apply_zeta_function() self.note_right_angles() def add_title(self): title = OldTex( "\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}" ) title[2].set_color(YELLOW) title[-1].set_color(YELLOW) title.add_background_rectangle() title.to_corner(UP+LEFT) self.add_foreground_mobjects(title) def note_right_angles(self): intersection_inputs = [ complex(x, y) for x in np.arange(1+2./16, 1.4, 1./16) for y in np.arange(-0.5, 0.5, 1./16) if abs(y) > 1./16 ] brackets = VGroup(*list(map( self.get_right_angle_bracket, intersection_inputs ))) self.play(ShowCreation(brackets, run_time = 3)) self.wait() def get_right_angle_bracket(self, input_z): output_z = zeta(input_z) derivative = d_zeta(input_z) rotation = np.log(derivative).imag brackets = VGroup( Line(RIGHT, RIGHT+UP), Line(RIGHT+UP, UP) ) brackets.scale(0.1) brackets.set_stroke(width = 2) brackets.set_color(YELLOW) brackets.rotate(rotation, about_point = ORIGIN) brackets.shift(self.z_to_point(output_z)) return brackets class InfiniteContinuousJigsawPuzzle(ZetaTransformationScene): CONFIG = { "anchor_density" : 35, } def construct(self): self.set_stage() self.add_title() self.show_jigsaw() self.name_analytic_continuation() def set_stage(self): self.plane = self.get_dense_grid() left_plane = self.get_reflected_plane() self.plane.add(left_plane) self.apply_zeta_function(run_time = 0) self.remove(left_plane) lines_per_piece = 5 pieces = [ VGroup(*left_plane[lines_per_piece*i:lines_per_piece*(i+1)]) for i in range(len(list(left_plane))/lines_per_piece) ] random.shuffle(pieces) self.pieces = pieces def add_title(self): title = OldTexText("Infinite ", "continuous ", "jigsaw puzzle") title.scale(1.5) title.to_edge(UP) for word in title: word.add_to_back(BackgroundRectangle(word)) self.play(FadeIn(word)) self.wait() self.add_foreground_mobjects(title) self.title = title def show_jigsaw(self): for piece in self.pieces: self.play(FadeIn(piece, run_time = 0.5)) self.wait() def name_analytic_continuation(self): words = OldTexText("``Analytic continuation''") words.set_color(YELLOW) words.scale(1.5) words.next_to(self.title, DOWN, buff = LARGE_BUFF) words.add_background_rectangle() self.play(Write(words)) self.wait() class ThatsHowZetaIsDefined(TeacherStudentsScene): def construct(self): self.add_zeta_definition() self.teacher_says(""" So that's how $\\zeta(s)$ is defined """) self.play_student_changes(*["hooray"]*3) self.random_blink(2) def add_zeta_definition(self): zeta = OldTex( "\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}" ) VGroup(zeta[2], zeta[-1]).set_color(YELLOW) zeta.to_corner(UP+LEFT) self.add(zeta) class ManyIntersectingLinesPreZeta(ZetaTransformationScene): CONFIG = { "apply_zeta" : False, "lines_center" : RIGHT, "nudge_size" : 0.9, "function" : zeta, "angle" : np.pi/5, "arc_scale_factor" : 0.3, "shift_directions" : [LEFT, RIGHT], } def construct(self): self.establish_plane() self.add_title() line = Line(DOWN+2*LEFT, UP+2*RIGHT) lines = VGroup(line, line.copy().rotate(self.angle)) arc = Arc(start_angle = line.get_angle(), angle = self.angle) arc.scale(self.arc_scale_factor) arc.set_color(YELLOW) lines.add(arc) # lines.set_stroke(WHITE, width = 5) lines.shift(self.lines_center + self.nudge_size*RIGHT) if self.apply_zeta: self.apply_zeta_function(run_time = 0) lines.set_stroke(width = 0) added_anims = self.get_modified_line_anims(lines) for vect in self.shift_directions: self.play( ApplyMethod(lines.shift, 2*self.nudge_size*vect, path_arc = np.pi), *added_anims, run_time = 3 ) def establish_plane(self): self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() self.add_reflected_plane() self.plane.fade() def add_title(self): if self.apply_zeta: title = OldTexText("After \\\\ transformation") else: title = OldTexText("Before \\\\ transformation") title.add_background_rectangle() title.to_edge(UP) self.add_foreground_mobjects(title) def get_modified_line_anims(self, lines): return [] class ManyIntersectingLinesPostZeta(ManyIntersectingLinesPreZeta): CONFIG = { "apply_zeta" : True, # "anchor_density" : 5 } def get_modified_line_anims(self, lines): n_inserted_points = 30 new_lines = lines.copy() new_lines.set_stroke(width = 5) def update_new_lines(lines_to_update): transformed = lines.copy() self.prepare_for_transformation(transformed) transformed.apply_complex_function(self.function) transformed.make_smooth() transformed.set_stroke(width = 5) for start, end in zip(lines_to_update, transformed): if start.get_num_points() > 0: start.points = np.array(end.points) return [UpdateFromFunc(new_lines, update_new_lines)] class ManyIntersectingLinesPreSSquared(ManyIntersectingLinesPreZeta): CONFIG = { "x_min" : -int(FRAME_X_RADIUS), "apply_zeta" : False, "lines_center" : ORIGIN, "nudge_size" : 0.9, "function" : lambda z : z**2, "shift_directions" : [LEFT, RIGHT, UP, DOWN, DOWN+LEFT, UP+RIGHT], } def establish_plane(self): self.add_transformable_plane() self.plane.fade() def apply_zeta_function(self, **kwargs): self.apply_complex_function(self.function, **kwargs) class ManyIntersectingLinesPostSSquared(ManyIntersectingLinesPreSSquared): CONFIG = { "apply_zeta" : True, } def get_modified_line_anims(self, lines): n_inserted_points = 30 new_lines = lines.copy() new_lines.set_stroke(width = 5) def update_new_lines(lines_to_update): transformed = lines.copy() self.prepare_for_transformation(transformed) transformed.apply_complex_function(self.function) transformed.make_smooth() transformed.set_stroke(width = 5) for start, end in zip(lines_to_update, transformed): if start.get_num_points() > 0: start.points = np.array(end.points) return [UpdateFromFunc(new_lines, update_new_lines)] class ButWhatIsTheExensions(TeacherStudentsScene): def construct(self): self.student_says( """ But what exactly \\emph{is} that continuation? """, target_mode = "sassy" ) self.play_student_changes("confused", "sassy", "confused") self.random_blink(2) self.teacher_says(""" You're $\\$1{,}000{,}000$ richer if you can answer that fully """, target_mode = "shruggie") self.play_student_changes(*["pondering"]*3) self.random_blink(3) class MathematiciansLookingAtFunctionEquation(Scene): def construct(self): equation = OldTex( "\\zeta(s)", "= 2^s \\pi ^{s-1}", "\\sin\\left(\\frac{\\pi s}{2}\\right)", "\\Gamma(1-s)", "\\zeta(1-s)", ) equation.shift(UP) mathy = Mathematician().to_corner(DOWN+LEFT) mathys = VGroup(mathy) for x in range(2): mathys.add(Mathematician().next_to(mathys)) for mathy in mathys: mathy.change_mode("pondering") mathy.look_at(equation) self.add(mathys) self.play(Write(VGroup(*equation[:-1]))) self.play(Transform( equation[0].copy(), equation[-1], path_arc = -np.pi/3, run_time = 2 )) for mathy in mathys: self.play(Blink(mathy)) self.wait() class DiscussZeros(ZetaTransformationScene): def construct(self): self.establish_plane() self.ask_about_zeros() self.show_trivial_zeros() self.show_critical_strip() self.transform_bit_of_critical_line() self.extend_transformed_critical_line() def establish_plane(self): self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() self.add_reflected_plane() self.plane.fade() def ask_about_zeros(self): dots = VGroup(*[ Dot( (2+np.sin(12*alpha))*\ rotate_vector(RIGHT, alpha+nudge) ) for alpha in np.arange(3*np.pi/20, 2*np.pi, 2*np.pi/5) for nudge in [random.random()*np.pi/6] ]) dots.set_color(YELLOW) q_marks = VGroup(*[ OldTex("?").next_to(dot, UP) for dot in dots ]) arrows = VGroup(*[ Arrow(dot, ORIGIN, buff = 0.2, tip_length = 0.1) for dot in dots ]) question = OldTexText("Which numbers go to $0$?") question.add_background_rectangle() question.to_edge(UP) for mob in dots, arrows, q_marks: self.play(ShowCreation(mob)) self.play(Write(question)) self.wait(2) dots.generate_target() for i, dot in enumerate(dots.target): dot.move_to(2*(i+1)*LEFT) self.play( FadeOut(arrows), FadeOut(q_marks), FadeOut(question), MoveToTarget(dots), ) self.wait() self.dots = dots def show_trivial_zeros(self): trivial_zero_words = OldTexText("``Trivial'' zeros") trivial_zero_words.next_to(ORIGIN, UP) trivial_zero_words.to_edge(LEFT) randy = Randolph().flip() randy.to_corner(DOWN+RIGHT) bubble = randy.get_bubble() bubble.set_fill(BLACK, opacity = 0.8) bubble.write("$1^1 + 2^2 + 3^2 + \\cdots = 0$") bubble.resize_to_content() bubble.pin_to(randy) self.plane.save_state() self.dots.save_state() for dot in self.dots.target: dot.move_to(ORIGIN) self.apply_zeta_function( added_anims = [MoveToTarget(self.dots, run_time = 3)], run_time = 3 ) self.wait(3) self.play( self.plane.restore, self.plane.make_smooth, self.dots.restore, run_time = 2 ) self.remove(*self.get_mobjects_from_last_animation()) self.plane.restore() self.dots.restore() self.add(self.plane, self.dots) self.play(Write(trivial_zero_words)) self.wait() self.play(FadeIn(randy)) self.play( randy.change_mode, "confused", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(randy)) self.wait() self.play(Blink(randy)) self.play(*list(map(FadeOut, [ randy, bubble, bubble.content, trivial_zero_words ]))) def show_critical_strip(self): strip = Rectangle( height = FRAME_HEIGHT, width = 1 ) strip.next_to(ORIGIN, RIGHT, buff = 0) strip.set_stroke(width = 0) strip.set_fill(YELLOW, opacity = 0.3) name = OldTexText("Critical strip") name.add_background_rectangle() name.next_to(ORIGIN, LEFT) name.to_edge(UP) arrow = Arrow(name.get_bottom(), 0.5*RIGHT+UP) primes = OldTex("2, 3, 5, 7, 11, 13, 17, \\dots") primes.to_corner(UP+RIGHT) # photo = Square() photo = ImageMobject("Riemann", invert = False) photo.set_width(5) photo.to_corner(UP+LEFT) new_dots = VGroup(*[ Dot(0.5*RIGHT + y*UP) for y in np.linspace(-2.5, 3.2, 5) ]) new_dots.set_color(YELLOW) critical_line = Line( 0.5*RIGHT+FRAME_Y_RADIUS*DOWN, 0.5*RIGHT+FRAME_Y_RADIUS*UP, color = YELLOW ) self.give_dots_wandering_anims() self.play(FadeIn(strip), *self.get_dot_wandering_anims()) self.play( Write(name, run_time = 1), ShowCreation(arrow), *self.get_dot_wandering_anims() ) self.play(*self.get_dot_wandering_anims()) self.play( FadeIn(primes), *self.get_dot_wandering_anims() ) for x in range(7): self.play(*self.get_dot_wandering_anims()) self.play( GrowFromCenter(photo), FadeOut(name), FadeOut(arrow), *self.get_dot_wandering_anims() ) self.play(Transform(self.dots, new_dots)) self.play(ShowCreation(critical_line)) self.wait(3) self.play( photo.shift, 7*LEFT, *list(map(FadeOut, [ primes, self.dots, strip ])) ) self.remove(photo) self.critical_line = critical_line def give_dots_wandering_anims(self): def func(t): result = (np.sin(6*2*np.pi*t) + 1)*RIGHT/2 result += 3*np.cos(2*2*np.pi*t)*UP return result self.wandering_path = ParametricCurve(func) for i, dot in enumerate(self.dots): dot.target = dot.copy() q_mark = OldTex("?") q_mark.next_to(dot.target, UP) dot.target.add(q_mark) dot.target.move_to(self.wandering_path.point_from_proportion( (float(2+2*i)/(4*len(list(self.dots))))%1 )) self.dot_anim_count = 0 def get_dot_wandering_anims(self): self.dot_anim_count += 1 if self.dot_anim_count == 1: return list(map(MoveToTarget, self.dots)) denom = 4*(len(list(self.dots))) def get_rate_func(index): return lambda t : (float(self.dot_anim_count + 2*index + t)/denom)%1 return [ MoveAlongPath( dot, self.wandering_path, rate_func = get_rate_func(i) ) for i, dot in enumerate(self.dots) ] def transform_bit_of_critical_line(self): self.play( self.plane.scale, 0.8, self.critical_line.scale, 0.8, rate_func = there_and_back, run_time = 2 ) self.wait() self.play( self.plane.set_stroke, GREY, 1, Animation(self.critical_line) ) self.plane.add(self.critical_line) self.apply_zeta_function() self.wait(2) self.play( self.plane.fade, Animation(self.critical_line) ) def extend_transformed_critical_line(self): def func(t): z = zeta(complex(0.5, t)) return z.real*RIGHT + z.imag*UP full_line = VGroup(*[ ParametricCurve(func, t_min = t0, t_max = t0+1) for t0 in range(100) ]) full_line.set_color_by_gradient( YELLOW, BLUE, GREEN, RED, YELLOW, BLUE, GREEN, RED, ) self.play(ShowCreation(full_line, run_time = 20, rate_func=linear)) self.wait() class AskAboutRelationToPrimes(TeacherStudentsScene): def construct(self): self.student_says(""" Whoa! Where the heck do primes come in here? """, target_mode = "confused") self.random_blink(3) self.teacher_says(""" Perhaps in a different video. """, target_mode = "hesitant") self.random_blink(3) class HighlightCriticalLineAgain(DiscussZeros): def construct(self): self.establish_plane() title = OldTex("\\zeta(", "s", ") = 0") title.set_color_by_tex("s", YELLOW) title.add_background_rectangle() title.to_corner(UP+LEFT) self.add(title) strip = Rectangle( height = FRAME_HEIGHT, width = 1 ) strip.next_to(ORIGIN, RIGHT, buff = 0) strip.set_stroke(width = 0) strip.set_fill(YELLOW, opacity = 0.3) line = Line( 0.5*RIGHT+FRAME_Y_RADIUS*UP, 0.5*RIGHT+FRAME_Y_RADIUS*DOWN, color = YELLOW ) randy = Randolph().to_corner(DOWN+LEFT) million = OldTex("\\$1{,}000{,}000") million.set_color(GREEN_B) million.next_to(ORIGIN, UP+LEFT) million.shift(2*LEFT) arrow1 = Arrow(million.get_right(), line.get_top()) arrow2 = Arrow(million.get_right(), line.get_bottom()) self.add(randy, strip) self.play(Write(million)) self.play( randy.change_mode, "pondering", randy.look_at, line.get_top(), ShowCreation(arrow1), run_time = 3 ) self.play( randy.look_at, line.get_bottom(), ShowCreation(line), Transform(arrow1, arrow2) ) self.play(FadeOut(arrow1)) self.play(Blink(randy)) self.wait() self.play(randy.look_at, line.get_center()) self.play(randy.change_mode, "confused") self.play(Blink(randy)) self.wait() self.play(randy.change_mode, "pondering") self.wait() class DiscussSumOfNaturals(Scene): def construct(self): title = OldTex( "\\zeta(s) = \\sum_{n=1}^\\infty \\frac{1}{n^s}" ) VGroup(title[2], title[-1]).set_color(YELLOW) title.to_corner(UP+LEFT) neg_twelfth, eq, zeta_neg_1, sum_naturals = equation = OldTex( "-\\frac{1}{12}", "=", "\\zeta(-1)", "= 1 + 2 + 3 + 4 + \\cdots" ) neg_twelfth.set_color(GREEN_B) VGroup(*zeta_neg_1[2:4]).set_color(YELLOW) q_mark = OldTex("?").next_to(sum_naturals[0], UP) q_mark.set_color(RED) randy = Randolph() randy.to_corner(DOWN+LEFT) analytic_continuation = OldTexText("Analytic continuation") analytic_continuation.next_to(title, RIGHT, 3*LARGE_BUFF) sum_to_zeta = Arrow(title.get_corner(DOWN+RIGHT), zeta_neg_1) sum_to_ac = Arrow(title.get_right(), analytic_continuation) ac_to_zeta = Arrow(analytic_continuation.get_bottom(), zeta_neg_1.get_top()) cross = OldTex("\\times") cross.scale(2) cross.set_color(RED) cross.rotate(np.pi/6) cross.move_to(sum_to_zeta.get_center()) brace = Brace(VGroup(zeta_neg_1, sum_naturals)) words = OldTexText( "If not equal, at least connected", "\\\\(see links in description)" ) words.next_to(brace, DOWN) self.add(neg_twelfth, eq, zeta_neg_1, randy, title) self.wait() self.play( Write(sum_naturals), Write(q_mark), randy.change_mode, "confused" ) self.play(Blink(randy)) self.wait() self.play(randy.change_mode, "angry") self.play( ShowCreation(sum_to_zeta), Write(cross) ) self.play(Blink(randy)) self.wait() self.play( Transform(sum_to_zeta, sum_to_ac), FadeOut(cross), Write(analytic_continuation), randy.change_mode, "pondering", randy.look_at, analytic_continuation, ) self.play(ShowCreation(ac_to_zeta)) self.play(Blink(randy)) self.wait() self.play( GrowFromCenter(brace), Write(words[0]), randy.look_at, words[0], ) self.wait() self.play(FadeIn(words[1])) self.play(Blink(randy)) self.wait() class InventingMathPreview(Scene): def construct(self): rect = Rectangle(height = 9, width = 16) rect.set_height(4) title = OldTexText("What does it feel like to invent math?") title.next_to(rect, UP) sum_tex = OldTex("1+2+4+8+\\cdots = -1") sum_tex.set_width(rect.get_width()-1) self.play( ShowCreation(rect), Write(title) ) self.play(Write(sum_tex)) self.wait() class FinalAnimationTease(Scene): def construct(self): morty = Mortimer().shift(2*(DOWN+RIGHT)) bubble = morty.get_bubble(SpeechBubble) bubble.write(""" Want to know what $\\zeta'(s)$ looks like? """) self.add(morty) self.play( morty.change_mode, "hooray", morty.look_at, bubble.content, ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.wait() class PatreonThanks(Scene): CONFIG = { "specific_patrons" : [ "CrypticSwarm", "Ali Yahya", "Damion Kistler", "Juan Batiz-Benet", "Yu Jun", "Othman Alikhan", "Markus Persson", "Joseph John Cox", "Luc Ritchie", "Shimin Kuang", "Einar Johansen", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) n_patrons = len(self.specific_patrons) special_thanks = OldTexText("Special thanks to:") special_thanks.set_color(YELLOW) special_thanks.shift(3*UP) patreon_logo = ImageMobject("patreon", invert = False) patreon_logo.set_height(1.5) patreon_logo.next_to(special_thanks, DOWN) left_patrons = VGroup(*list(map(TexText, self.specific_patrons[:n_patrons/2] ))) right_patrons = VGroup(*list(map(TexText, self.specific_patrons[n_patrons/2:] ))) for patrons, vect in (left_patrons, LEFT), (right_patrons, RIGHT): patrons.arrange(DOWN, aligned_edge = LEFT) patrons.next_to(special_thanks, DOWN) patrons.to_edge(vect, buff = LARGE_BUFF) self.add(patreon_logo) self.play(morty.change_mode, "gracious") self.play(Write(special_thanks, run_time = 1)) self.play( Write(left_patrons), morty.look_at, left_patrons ) self.play( Write(right_patrons), morty.look_at, right_patrons ) self.play(Blink(morty)) for patrons in left_patrons, right_patrons: for index in 0, -1: self.play(morty.look_at, patrons[index]) self.wait() class CreditTwo(Scene): def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) morty.to_edge(RIGHT) brother = PiCreature(color = GOLD_E) brother.next_to(morty, LEFT) brother.look_at(morty.eyes) headphones = Headphones(height = 1) headphones.move_to(morty.eyes, aligned_edge = DOWN) headphones.shift(0.1*DOWN) url = OldTexText("www.audible.com/3blue1brown") url.to_corner(UP+RIGHT, buff = LARGE_BUFF) self.add(morty) self.play(Blink(morty)) self.play( FadeIn(headphones), Write(url), Animation(morty) ) self.play(morty.change_mode, "happy") for x in range(4): self.wait() self.play(Blink(morty)) self.wait() self.play( FadeIn(brother), morty.look_at, brother.eyes ) self.play(brother.change_mode, "surprised") self.play(Blink(brother)) self.wait() self.play( morty.look, LEFT, brother.change_mode, "happy", brother.look, LEFT ) for x in range(10): self.play(Blink(morty)) self.wait() self.play(Blink(brother)) self.wait() class FinalAnimation(ZetaTransformationScene): CONFIG = { "min_added_anchors" : 100, } def construct(self): self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() self.add_reflected_plane() title = OldTex("s", "\\to \\frac{d\\zeta}{ds}(", "s", ")") title.set_color_by_tex("s", YELLOW) title.add_background_rectangle() title.scale(1.5) title.to_corner(UP+LEFT) self.play(Write(title)) self.add_foreground_mobjects(title) self.wait() self.apply_complex_function(d_zeta, run_time = 8) self.wait() class Thumbnail(ZetaTransformationScene): CONFIG = { "anchor_density" : 35 } def construct(self): self.y_min = -4 self.y_max = 4 self.x_min = 1 self.x_max = int(FRAME_X_RADIUS+2) self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() self.add_reflected_plane() # self.apply_zeta_function() self.plane.set_stroke(width = 4) div_sum = OldTex("-\\frac{1}{12} = ", "1+2+3+4+\\cdots") div_sum.set_width(FRAME_WIDTH-1) div_sum.to_edge(DOWN) div_sum.set_color(YELLOW) div_sum.set_background_stroke(width=8) # for mob in div_sum.submobjects: # mob.add_to_back(BackgroundRectangle(mob)) zeta = OldTex("\\zeta(s)") zeta.set_height(FRAME_Y_RADIUS-1) zeta.to_corner(UP+LEFT) million = OldTex("\\$1{,}000{,}000") million.set_width(FRAME_X_RADIUS+1) million.to_edge(UP+RIGHT) million.set_color(GREEN_B) million.set_background_stroke(width=8) self.add(div_sum, million, zeta) class ZetaThumbnail(Scene): def construct(self): plane = ComplexPlane( x_range=(-5, 5), y_range=(-3, 3), background_line_style={ "stroke_width": 2, "stroke_opacity": 0.75, } ) plane.set_height(FRAME_HEIGHT) plane.scale(3 / 2.5) plane.add_coordinate_labels(font_size=12) # self.add(plane) lines = VGroup( *( Line(plane.c2p(-7, y), plane.c2p(7, y)) for y in np.arange(-2, 2, 0.1) if y != 0 ), *( Line(plane.c2p(x, -4), plane.c2p(x, 4)) for x in np.arange(-2, 2, 0.1) if x != 0 ), ) lines.insert_n_curves(200) lines.apply_function(lambda p: plane.n2p(zeta(plane.p2n(p)))) lines.make_smooth() lines.set_stroke(GREY_B, 1, opacity=0.5) # self.add(lines) c_line = Line(plane.c2p(0.5, 0), plane.c2p(0.5, 35)) c_line.insert_n_curves(1000) c_line.apply_function(lambda p: plane.n2p(zeta(plane.p2n(p)))) c_line.make_smooth() c_line.set_stroke([TEAL, YELLOW], width=[7, 3]) shadow = VGroup() for w in np.linspace(25, 0, 50): cc = c_line.copy() cc.set_stroke(BLACK, width=w, opacity=0.025) shadow.add(cc) self.add(shadow) self.add(c_line) sym = OldTex("\\zeta\\left(s\\right)") sym.set_height(1.5) sym.move_to(FRAME_WIDTH * LEFT / 4 + FRAME_HEIGHT * UP / 4) shadow = VGroup() for w in np.linspace(50, 0, 50): sc = sym.copy() sc.set_fill(opacity=0) sc.set_stroke(BLACK, width=w, opacity=0.05) shadow.add(sc) # self.add(shadow) # self.add(sym) class ZetaPartialSums(ZetaTransformationScene): CONFIG = { "anchor_density" : 35, "num_partial_sums" : 12, } def construct(self): self.add_transformable_plane() self.add_extra_plane_lines_for_zeta() self.prepare_for_transformation(self.plane) N_list = [2**k for k in range(self.num_partial_sums)] sigma = OldTex( "\\sum_{n = 1}^N \\frac{1}{n^s}" ) sigmas = [] for N in N_list + ["\\infty"]: tex = OldTex(str(N)) tex.set_color(YELLOW) new_sigma = sigma.copy() top = new_sigma[0] tex.move_to(top, DOWN) new_sigma.remove(top) new_sigma.add(tex) new_sigma.to_corner(UP+LEFT) sigmas.append(new_sigma) def get_partial_sum_func(n_terms): return lambda s : sum([1./(n**s) for n in range(1, n_terms+1)]) interim_planes = [ self.plane.copy().apply_complex_function( get_partial_sum_func(N) ) for N in N_list ] interim_planes.append(self.plane.copy().apply_complex_function(zeta)) symbol = VGroup(OldTex("s")) symbol.scale(2) symbol.set_color(YELLOW) symbol.to_corner(UP+LEFT) for plane, sigma in zip(interim_planes, sigmas): self.play( Transform(self.plane, plane), Transform(symbol, sigma) ) self.wait()
videos_3b1b/_2016/patreon.py
from manim_imports_ext import * class SideGigToFullTime(Scene): def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) self.add(morty) self.side_project(morty) self.income(morty) self.full_time(morty) def side_project(self, morty): rect = PictureInPictureFrame() rect.next_to(morty, UP+LEFT) side_project = OldTexText("Side project") side_project.next_to(rect, UP) dollar_sign = OldTex("\\$") cross = VGroup(*[ Line(vect, -vect, color = RED) for vect in (UP+RIGHT, UP+LEFT) ]) cross.set_height(dollar_sign.get_height()) no_money = VGroup(dollar_sign, cross) no_money.next_to(rect, DOWN) self.play( morty.change_mode, "raise_right_hand", morty.look_at, rect ) self.play( Write(side_project), ShowCreation(rect) ) self.wait() self.play(Blink(morty)) self.wait() self.play(Write(dollar_sign)) self.play(ShowCreation(cross)) self.screen_title = side_project self.cross = cross def income(self, morty): dollar_signs = VGroup(*[ OldTex("\\$") for x in range(10) ]) dollar_signs.arrange(RIGHT, buff = LARGE_BUFF) dollar_signs.set_color(BLACK) dollar_signs.next_to(morty.eyes, RIGHT, buff = 2*LARGE_BUFF) self.play( morty.change_mode, "happy", morty.look_at, dollar_signs, dollar_signs.shift, LEFT, dollar_signs.set_color, GREEN ) for x in range(5): last_sign = dollar_signs[0] dollar_signs.remove(last_sign) self.play( FadeOut(last_sign), dollar_signs.shift, LEFT ) random.shuffle(dollar_signs.submobjects) self.play( ApplyMethod( dollar_signs.shift, (FRAME_Y_RADIUS+1)*DOWN, lag_ratio = 0.5 ), morty.change_mode, "guilty", morty.look, DOWN+RIGHT ) self.play(Blink(morty)) def full_time(self, morty): new_title = OldTexText("Full time") new_title.move_to(self.screen_title) q_mark = OldTex("?") q_mark.next_to(self.cross) q_mark.set_color(GREEN) self.play(morty.look_at, q_mark) self.play(Transform(self.screen_title, new_title)) self.play( Transform(self.cross, q_mark), morty.change_mode, "confused" ) self.play(Blink(morty)) self.wait() self.play( morty.change_mode, "happy", morty.look, UP+RIGHT ) self.play(Blink(morty)) self.wait() class TakesTime(Scene): def construct(self): rect = PictureInPictureFrame(height = 4) rect.to_edge(RIGHT, buff = LARGE_BUFF) clock = Clock() clock.hour_hand.set_color(BLUE_C) clock.minute_hand.set_color(BLUE_D) clock.next_to(rect, LEFT, buff = LARGE_BUFF) self.add(rect) self.play(ShowCreation(clock)) for x in range(3): self.play(ClockPassesTime(clock)) class GrowingToDoList(Scene): def construct(self): morty = Mortimer() morty.flip() morty.next_to(ORIGIN, DOWN+LEFT) title = OldTexText("3blue1brown to-do list") title.next_to(ORIGIN, RIGHT) title.to_edge(UP) underline = Line(title.get_left(), title.get_right()) underline.next_to(title, DOWN) lines = VGroup(*list(map(TexText, [ "That one on topology", "Something with quaternions", "Solving puzzles with binary counting", "Tatoos on math", "Laplace stuffs", "The role of memorization in math", "Strangeness of the axiom of choice", "Tensors", "Different view of $e^{\\pi i}$", "Quadratic reciprocity", "Fourier stuffs", "$1+2+3+\\cdots = -\\frac{1}{12}$", "Understanding entropy", ]))) lines.scale(0.65) lines.arrange(DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT) lines.set_color_by_gradient(BLUE_C, YELLOW) lines.next_to(title, DOWN, buff = LARGE_BUFF/2.) lines.to_edge(RIGHT) self.play( Write(title), morty.look_at, title ) self.play( Write(lines[0]), morty.change_mode, "erm", run_time = 1 ) for line in lines[1:3]: self.play( Write(line), morty.look_at, line, run_time = 1 ) self.play( morty.change_mode, "pleading", morty.look_at, lines, Write( VGroup(*lines[3:]), ) ) class TwoTypesOfVideos(Scene): def construct(self): morty = Mortimer().shift(2*DOWN) stand_alone = OldTexText("Standalone videos") stand_alone.shift(FRAME_X_RADIUS*LEFT/2) stand_alone.to_edge(UP) series = OldTexText("Series") series.shift(FRAME_X_RADIUS*RIGHT/2) series.to_edge(UP) box = Rectangle(width = 16, height = 9, color = WHITE) box.set_height(3) box.next_to(stand_alone, DOWN) series_list = VGroup(*[ OldTexText("Essence of %s"%s) for s in [ "linear algebra", "calculus", "probability", "real analysis", "complex analysis", "ODEs", ] ]) series_list.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) series_list.set_width(FRAME_X_RADIUS-2) series_list.next_to(series, DOWN, buff = MED_SMALL_BUFF) series_list.to_edge(RIGHT) fridays = OldTexText("Every other friday") when_done = OldTexText("When series is done") for words, vect in (fridays, LEFT), (when_done, RIGHT): words.set_color(YELLOW) words.next_to( morty, vect, buff = MED_SMALL_BUFF, aligned_edge = UP ) unless = OldTexText(""" Unless you're a patron \\dots """) unless.next_to(when_done, DOWN, buff = MED_SMALL_BUFF) self.add(morty) self.play(Blink(morty)) self.play( morty.change_mode, "raise_right_hand", morty.look_at, stand_alone, Write(stand_alone, run_time = 2), ) self.play( morty.change_mode, "raise_left_hand", morty.look_at, series, Write(series, run_time = 2), ) self.play(Blink(morty)) self.wait() self.play( morty.change_mode, "raise_right_hand", morty.look_at, box, ShowCreation(box) ) for x in range(3): self.wait(2) self.play(Blink(morty)) self.play( morty.change_mode, "raise_left_hand", morty.look_at, series ) for i, words in enumerate(series_list): self.play(Write(words), run_time = 1) self.play(Blink(morty)) self.wait() self.play(series_list[1].set_color, BLUE) self.wait(2) self.play(Blink(morty)) self.wait() pairs = [ (fridays, "speaking"), (when_done, "wave_2") , (unless, "surprised"), ] for words, mode in pairs: self.play( Write(words), morty.change_mode, mode, morty.look_at, words ) self.wait() class ClassWatching(TeacherStudentsScene): def construct(self): rect = PictureInPictureFrame(height = 4) rect.next_to(self.get_teacher(), UP, buff = LARGE_BUFF/2.) rect.to_edge(RIGHT) self.add(rect) for pi in self.get_students(): pi.look_at(rect) self.random_blink(5) self.play_student_changes( "raise_left_hand", "raise_right_hand", "sassy", ) self.play(self.get_teacher().change_mode, "pondering") self.random_blink(3) class RandolphWatching(Scene): def construct(self): randy = Randolph() randy.shift(2*LEFT) randy.look(RIGHT) self.add(randy) self.wait() self.play(Blink(randy)) self.wait() self.play( randy.change_mode, "pondering", randy.look, RIGHT ) self.play(Blink(randy)) self.wait() class RandolphWatchingWithLaptop(Scene): pass class GrowRonaksSierpinski(Scene): CONFIG = { "colors" : [BLUE, YELLOW, BLUE_C, BLUE_E], "dot_radius" : 0.08, "n_layers" : 64, } def construct(self): sierp = self.get_ronaks_sierpinski(self.n_layers) dots = self.get_dots(self.n_layers) self.triangle = VGroup(sierp, dots) self.triangle.scale(1.5) self.triangle.shift(3*UP) sierp_layers = sierp.submobjects dot_layers = dots.submobjects last_dot_layer = dot_layers[0] self.play(ShowCreation(last_dot_layer)) run_time = 1 for n, sierp_layer, dot_layer in zip(it.count(1), sierp_layers, dot_layers[1:]): self.play( ShowCreation(sierp_layer, lag_ratio=1), Animation(last_dot_layer), run_time = run_time ) self.play(ShowCreation( dot_layer, run_time = run_time, lag_ratio=1, )) # if n == 2: # dot = dot_layer[1] # words = OldTexText("Stop growth at pink") # words.next_to(dot, DOWN, 2) # arrow = Arrow(words, dot) # self.play( # Write(words), # ShowCreation(arrow) # ) # self.wait() # self.play(*map(FadeOut, [words, arrow])) log2 = np.log2(n) if n > 2 and log2-np.round(log2) == 0 and n < self.n_layers: self.wait() self.rescale() run_time /= 1.3 last_dot_layer = dot_layer def rescale(self): shown_mobs = VGroup(*self.get_mobjects()) shown_mobs_copy = shown_mobs.copy() self.remove(shown_mobs) self.add(shown_mobs_copy) top = shown_mobs.get_top() self.triangle.scale(0.5) self.triangle.move_to(top, aligned_edge = UP) self.play(Transform(shown_mobs_copy, shown_mobs)) self.remove(shown_mobs_copy) self.add(shown_mobs) def get_pascal_point(self, n, k): return n*rotate_vector(RIGHT, -2*np.pi/3) + k*RIGHT def get_lines_at_layer(self, n): lines = VGroup() for k in range(n+1): if choose(n, k)%2 == 1: p1 = self.get_pascal_point(n, k) p2 = self.get_pascal_point(n+1, k) p3 = self.get_pascal_point(n+1, k+1) lines.add(Line(p1, p2), Line(p1, p3)) return lines def get_dot_layer(self, n): dots = VGroup() for k in range(n+1): p = self.get_pascal_point(n, k) dot = Dot(p, radius = self.dot_radius) if choose(n, k)%2 == 0: if choose(n-1, k)%2 == 0: continue dot.set_color(PINK) else: dot.set_color(WHITE) dots.add(dot) return dots def get_ronaks_sierpinski(self, n_layers): ronaks_sierpinski = VGroup() for n in range(n_layers): ronaks_sierpinski.add(self.get_lines_at_layer(n)) ronaks_sierpinski.set_color_by_gradient(*self.colors) ronaks_sierpinski.set_stroke(width = 0)##TODO return ronaks_sierpinski def get_dots(self, n_layers): dots = VGroup() for n in range(n_layers+1): dots.add(self.get_dot_layer(n)) return dots class PatreonLogo(Scene): def construct(self): words1 = OldTexText( "Support future\\\\", "3blue1brown videos" ) words2 = OldTexText( "Early access to\\\\", "``Essence of'' series" ) for words in words1, words2: words.scale(2) words.to_edge(DOWN) self.play(Write(words1)) self.wait(2) self.play(Transform(words1, words2)) self.wait(2) class PatreonLogin(Scene): pass class PythagoreanTransformation(Scene): def construct(self): tri1 = VGroup( Line(ORIGIN, 2*RIGHT, color = BLUE), Line(2*RIGHT, 3*UP, color = YELLOW), Line(3*UP, ORIGIN, color = MAROON_B), ) tri1.shift(2.5*(DOWN+LEFT)) tri2, tri3, tri4 = copies = [ tri1.copy().rotate(-i*np.pi/2) for i in range(1, 4) ] a = OldTex("a").next_to(tri1[0], DOWN, buff = MED_SMALL_BUFF) b = OldTex("b").next_to(tri1[2], LEFT, buff = MED_SMALL_BUFF) c = OldTex("c").next_to(tri1[1].get_center(), UP+RIGHT) c_square = Polygon(*[ tri[1].get_end() for tri in [tri1] + copies ]) c_square.set_stroke(width = 0) c_square.set_fill(color = YELLOW, opacity = 0.5) c_square_tex = OldTex("c^2") big_square = Polygon(*[ tri[0].get_start() for tri in [tri1] + copies ]) big_square.set_color(WHITE) a_square = Square(side_length = 2) a_square.shift(1.5*(LEFT+UP)) a_square.set_stroke(width = 0) a_square.set_fill(color = BLUE, opacity = 0.5) a_square_tex = OldTex("a^2") a_square_tex.move_to(a_square) b_square = Square(side_length = 3) b_square.move_to( a_square.get_corner(DOWN+RIGHT), aligned_edge = UP+LEFT ) b_square.set_stroke(width = 0) b_square.set_fill(color = MAROON_B, opacity = 0.5) b_square_tex = OldTex("b^2") b_square_tex.move_to(b_square) self.play(ShowCreation(tri1, run_time = 2)) self.play(*list(map(Write, [a, b, c]))) self.wait() self.play( FadeIn(c_square), Animation(c) ) self.play(Transform(c, c_square_tex)) self.wait(2) mover = tri1.copy() for copy in copies: self.play(Transform( mover, copy, path_arc = -np.pi/2 )) self.add(copy) self.remove(mover) self.add(big_square, *[tri1]+copies) self.wait(2) self.play(*list(map(FadeOut, [a, b, c, c_square]))) self.play( tri3.shift, tri1.get_corner(UP+LEFT) -\ tri3.get_corner(UP+LEFT) ) self.play(tri2.shift, 2*RIGHT) self.play(tri4.shift, 3*UP) self.wait() self.play(FadeIn(a_square)) self.play(FadeIn(b_square)) self.play(Write(a_square_tex)) self.play(Write(b_square_tex)) self.wait(2) class KindWordsOnEoLA(TeacherStudentsScene): def construct(self): rect = Rectangle(width = 16, height = 9, color = WHITE) rect.set_height(4) title = OldTexText("Essence of linear algebra") title.to_edge(UP) rect.next_to(title, DOWN) self.play( Write(title), ShowCreation(rect), *[ ApplyMethod(pi.look_at, rect) for pi in self.get_pi_creatures() ], run_time = 2 ) self.random_blink() self.play_student_changes(*["hooray"]*3) self.random_blink() self.play(self.get_teacher().change_mode, "happy") self.random_blink() class MakeALotOfPiCreaturesHappy(Scene): def construct(self): width = 7 height = 4 pis = VGroup(*[ VGroup(*[ Randolph() for x in range(7) ]).arrange(RIGHT, buff = MED_LARGE_BUFF) for x in range(4) ]).arrange(DOWN, buff = MED_LARGE_BUFF) pi_list = list(it.chain(*[ layer.submobjects for layer in pis.submobjects ])) random.shuffle(pi_list) colors = color_gradient([BLUE_D, GREY_BROWN], len(pi_list)) for pi, color in zip(pi_list, colors): pi.set_color(color) pis = VGroup(*pi_list) pis.set_height(6) self.add(pis) pis.generate_target() self.wait() for pi, color in zip(pis.target, colors): pi.change_mode("hooray") # pi.scale(1) pi.set_color(color) self.play( MoveToTarget( pis, run_time = 2, lag_ratio = 0.5, ) ) for x in range(10): pi = random.choice(pi_list) self.play(Blink(pi)) class IntegrationByParts(Scene): def construct(self): rect = Rectangle(width = 5, height = 3) # f = lambda t : 4*np.sin(t*np.pi/2) f = lambda t : 4*t g = lambda t : 3*smooth(t) curve = ParametricCurve(lambda t : f(t)*RIGHT + g(t)*DOWN) curve.set_color(YELLOW) curve.center() rect = Rectangle() rect.replace(curve, stretch = True) regions = [] for vect, color in (UP+RIGHT, BLUE), (DOWN+LEFT, GREEN): region = curve.copy() region.add_line_to(rect.get_corner(vect)) region.set_stroke(width = 0) region.set_fill(color = color, opacity = 0.5) regions.append(region) upper_right, lower_left = regions v_lines, h_lines = VGroup(), VGroup() for alpha in np.linspace(0, 1, 30): point = curve.point_from_proportion(alpha) top_point = curve.get_points()[0][1]*UP + point[0]*RIGHT left_point = curve.get_points()[0][0]*RIGHT + point[1]*UP v_lines.add(Line(top_point, point)) h_lines.add(Line(left_point, point)) v_lines.set_color(BLUE_E) h_lines.set_color(GREEN_E) equation = OldTex( "\\int_0^1 g\\,df", "+\\int_0^1 f\\,dg", "= \\big(fg \\big)_0^1" ) equation.to_edge(UP) equation.set_color_by_tex( "\\int_0^1 g\\,df", upper_right.get_color() ) equation.set_color_by_tex( "+\\int_0^1 f\\,dg", lower_left.get_color() ) left_brace = Brace(rect, LEFT) down_brace = Brace(rect, DOWN) g_T = left_brace.get_text("$g(t)\\big|_0^1$") f_T = down_brace.get_text("$f(t)\\big|_0^1$") self.draw_curve(curve) self.play(ShowCreation(rect)) self.play(*list(map(Write, [down_brace, left_brace, f_T, g_T]))) self.wait() self.play(FadeIn(upper_right)) self.play( ShowCreation( v_lines, run_time = 2 ), Animation(curve), Animation(rect) ) self.play(Write(equation[0])) self.wait() self.play(FadeIn(lower_left)) self.play( ShowCreation( h_lines, run_time = 2 ), Animation(curve), Animation(rect) ) self.play(Write(equation[1])) self.wait() self.play(Write(equation[2])) self.wait() def draw_curve(self, curve): lp, lnum, comma, rnum, rp = coords = OldTex( "\\big(f(", "t", "), g(", "t", ")\\big)" ) coords.set_color_by_tex("0.00", BLACK) dot = Dot(radius = 0.1) dot.move_to(curve.get_points()[0]) coords.next_to(dot, UP+RIGHT) self.play( ShowCreation(curve), UpdateFromFunc( dot, lambda d : d.move_to(curve.get_points()[-1]) ), MaintainPositionRelativeTo(coords, dot), run_time = 5, rate_func=linear ) self.wait() self.play(*list(map(FadeOut, [coords, dot]))) class EndScreen(TeacherStudentsScene): def construct(self): self.teacher_says( """ See you every other friday! """, target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.random_blink()
videos_3b1b/_2016/wcat.py
from manim_imports_ext import * class ClosedLoopScene(Scene): CONFIG = { "loop_anchor_points" : [ 3*RIGHT, 2*RIGHT+UP, 3*RIGHT + 3*UP, UP, 2*UP+LEFT, 2*LEFT + 2*UP, 3*LEFT, 2*LEFT+DOWN, 3*LEFT+2*DOWN, 2*DOWN+RIGHT, LEFT+DOWN, ], "square_vertices" : [ 2*RIGHT+UP, 2*UP+LEFT, 2*LEFT+DOWN, 2*DOWN+RIGHT ], "rect_vertices" : [ 0*RIGHT + 1*UP, -1*RIGHT + 2*UP, -3*RIGHT + 0*UP, -2*RIGHT + -1*UP, ], "dot_color" : YELLOW, "connecting_lines_color" : BLUE, "pair_colors" : [MAROON_B, PURPLE_B], } def setup(self): self.dots = VGroup() self.connecting_lines = VGroup() self.add_loop() def add_loop(self): self.loop = self.get_default_loop() self.add(self.loop) def get_default_loop(self): loop = VMobject() loop.set_points_smoothly( self.loop_anchor_points + [self.loop_anchor_points[0]] ) return loop def get_square(self): return Polygon(*self.square_vertices) def get_rect_vertex_dots(self, square = False): if square: vertices = self.square_vertices else: vertices = self.rect_vertices dots = VGroup(*[Dot(v) for v in vertices]) dots.set_color(self.dot_color) return dots def get_rect_alphas(self, square = False): #Inefficient and silly, but whatever. dots = self.get_rect_vertex_dots(square = square) return self.get_dot_alphas(dots) def add_dot(self, dot): self.add_dots(dot) def add_dots(self, *dots): self.dots.add(*dots) self.add(self.dots) def add_rect_dots(self, square = False): self.add_dots(*self.get_rect_vertex_dots(square = square)) def add_dots_at_alphas(self, *alphas): self.add_dots(*[ Dot( self.loop.point_from_proportion(alpha), color = self.dot_color ) for alpha in alphas ]) def add_connecting_lines(self, cyclic = False): if cyclic: pairs = adjacent_pairs(self.dots) else: n_pairs = len(list(self.dots))/2 pairs = list(zip(self.dots[:n_pairs], self.dots[n_pairs:])) for d1, d2 in pairs: line = Line(d1.get_center(), d2.get_center()) line.start_dot = d1 line.end_dot = d2 line.update_anim = UpdateFromFunc( line, lambda l : l.put_start_and_end_on( l.start_dot.get_center(), l.end_dot.get_center() ) ) line.set_color(d1.get_color()) self.connecting_lines.add(line) if cyclic: self.connecting_lines.set_color(self.connecting_lines_color) self.connecting_lines.set_stroke(width = 6) self.add(self.connecting_lines, self.dots) def get_line_anims(self): return [ line.update_anim for line in self.connecting_lines ] + [Animation(self.dots)] def get_dot_alphas(self, dots = None, precision = 0.005): if dots == None: dots = self.dots alphas = [] alpha_range = np.arange(0, 1, precision) loop_points = np.array(list(map(self.loop.point_from_proportion, alpha_range))) for dot in dots: vects = loop_points - dot.get_center() norms = np.apply_along_axis(get_norm, 1, vects) index = np.argmin(norms) alphas.append(alpha_range[index]) return alphas def let_dots_wonder(self, run_time = 5, random_seed = None, added_anims = []): if random_seed is not None: np.random.seed(random_seed) start_alphas = self.get_dot_alphas() alpha_rates = 0.05 + 0.1*np.random.random(len(list(self.dots))) def generate_rate_func(start, rate): return lambda t : (start + t*rate*run_time)%1 anims = [ MoveAlongPath( dot, self.loop, rate_func = generate_rate_func(start, rate) ) for dot, start, rate in zip(self.dots, start_alphas, alpha_rates) ] anims += self.get_line_anims() anims += added_anims self.play(*anims, run_time = run_time) def move_dots_to_alphas(self, alphas, run_time = 3): assert(len(alphas) == len(list(self.dots))) start_alphas = self.get_dot_alphas() def generate_rate_func(start_alpha, alpha): return lambda t : interpolate(start_alpha, alpha, smooth(t)) anims = [ MoveAlongPath( dot, self.loop, rate_func = generate_rate_func(sa, a), run_time = run_time, ) for dot, sa, a in zip(self.dots, start_alphas, alphas) ] anims += self.get_line_anims() self.play(*anims) def transform_loop(self, target_loop, added_anims = [], **kwargs): alphas = self.get_dot_alphas() dot_anims = [] for dot, alpha in zip(self.dots, alphas): dot.generate_target() dot.target.move_to(target_loop.point_from_proportion(alpha)) dot_anims.append(MoveToTarget(dot)) self.play( Transform(self.loop, target_loop), *dot_anims + self.get_line_anims() + added_anims, **kwargs ) def set_color_dots_by_pair(self): n_pairs = len(list(self.dots))/2 for d1, d2, c in zip(self.dots[:n_pairs], self.dots[n_pairs:], self.pair_colors): VGroup(d1, d2).set_color(c) def find_square(self): alpha_quads = list(it.combinations( np.arange(0, 1, 0.02) , 4 )) quads = np.array([ [ self.loop.point_from_proportion(alpha) for alpha in quad ] for quad in alpha_quads ]) scores = self.square_scores(quads) index = np.argmin(scores) return quads[index] def square_scores(self, all_quads): midpoint_diffs = np.apply_along_axis( get_norm, 1, 0.5*(all_quads[:,0] + all_quads[:,2]) - 0.5*(all_quads[:,1] + all_quads[:,3]) ) vects1 = all_quads[:,0] - all_quads[:,2] vects2 = all_quads[:,1] - all_quads[:,3] distances1 = np.apply_along_axis(get_norm, 1, vects1) distances2 = np.apply_along_axis(get_norm, 1, vects2) distance_diffs = np.abs(distances1 - distances2) midpoint_diffs /= distances1 distance_diffs /= distances2 buffed_d1s = np.repeat(distances1, 3).reshape(vects1.shape) buffed_d2s = np.repeat(distances2, 3).reshape(vects2.shape) unit_v1s = vects1/buffed_d1s unit_v2s = vects2/buffed_d2s dots = np.abs(unit_v1s[:,0]*unit_v2s[:,0] + unit_v1s[:,1]*unit_v2s[:,1] + unit_v1s[:,2]*unit_v2s[:,2]) return midpoint_diffs + distance_diffs + dots ############################# class Introduction(TeacherStudentsScene): def construct(self): self.play(self.get_teacher().change_mode, "hooray") self.random_blink() self.teacher_says("") for pi in self.get_students(): pi.generate_target() pi.target.change_mode("happy") pi.target.look_at(self.get_teacher().bubble) self.play(*list(map(MoveToTarget, self.get_students()))) self.random_blink(3) self.teacher_says( "Here's why \\\\ I'm excited...", target_mode = "hooray" ) for pi in self.get_students(): pi.target.look_at(self.get_teacher().eyes) self.play(*list(map(MoveToTarget, self.get_students()))) self.wait() class WhenIWasAKid(TeacherStudentsScene): def construct(self): children = self.get_children() speaker = self.get_speaker() self.prepare_everyone(children, speaker) self.state_excitement(children, speaker) self.students = children self.teacher = speaker self.run_class() self.grow_up() def state_excitement(self, children, speaker): self.teacher_says( """ Here's why I'm excited! """, target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.wait() speaker.look_at(children) me = children[-1] self.play( FadeOut(self.get_students()), FadeOut(self.get_teacher().bubble), FadeOut(self.get_teacher().bubble.content), Transform(self.get_teacher(), me) ) self.remove(self.get_teacher()) self.add(me) self.play(*list(map(FadeIn, children[:-1] + [speaker]))) self.random_blink() def run_class(self): children = self.students speaker = self.teacher title = OldTexText("Topology") title.to_edge(UP) pi1, pi2, pi3, me = children self.random_blink() self.teacher_says( """ Math! Excitement! You are the future! """, target_mode = "hooray" ) self.play( pi1.look_at, pi2.eyes, pi1.change_mode, "erm", pi2.look_at, pi1.eyes, pi2.change_mode, "surprised", ) self.play( pi3.look_at, me.eyes, pi3.change_mode, "sassy", me.look_at, pi3.eyes, ) self.random_blink(2) self.play( self.teacher.change_mode, "speaking", FadeOut(self.teacher.bubble), FadeOut(self.teacher.bubble.content), ) self.play(Write(title)) self.random_blink() self.play(pi1.change_mode, "raise_right_hand") self.random_blink() self.play( pi2.change_mode, "confused", pi3.change_mode, "happy", pi2.look_at, pi3.eyes, pi3.look_at, pi2.eyes, ) self.random_blink() self.play(me.change_mode, "pondering") self.wait() self.random_blink(2) self.play(pi1.change_mode, "raise_left_hand") self.wait() self.play(pi2.change_mode, "erm") self.random_blink() self.student_says( "How is this math?", index = -1, target_mode = "pleading", width = 5, height = 3, direction = RIGHT ) self.play( pi1.change_mode, "pondering", pi2.change_mode, "pondering", pi3.change_mode, "pondering", ) self.play(speaker.change_mode, "pondering") self.random_blink() def grow_up(self): me = self.students[-1] self.students.remove(me) morty = Mortimer(mode = "pondering") morty.flip() morty.move_to(me, aligned_edge = DOWN) morty.to_edge(LEFT) morty.look(RIGHT) self.play( Transform(me, morty), *list(map(FadeOut, [ self.students, self.teacher, me.bubble, me.bubble.content ])) ) self.remove(me) self.add(morty) self.play(Blink(morty)) self.wait() self.play(morty.change_mode, "hooray") self.wait() def prepare_everyone(self, children, speaker): self.everyone = list(children) + [speaker] for pi in self.everyone: pi.bubble = None def get_children(self): colors = [MAROON_E, YELLOW_D, PINK, GREY_BROWN] children = VGroup(*[ BabyPiCreature(color = color) for color in colors ]) children.arrange(RIGHT) children.to_edge(DOWN, buff = LARGE_BUFF) children.to_edge(LEFT) return children def get_speaker(self): speaker = Mathematician(mode = "happy") speaker.flip() speaker.to_edge(DOWN, buff = LARGE_BUFF) speaker.to_edge(RIGHT) return speaker def get_pi_creatures(self): if hasattr(self, "everyone"): return self.everyone else: return TeacherStudentsScene.get_pi_creatures(self) class FormingTheMobiusStrip(Scene): def construct(self): pass class DrawLineOnMobiusStrip(Scene): def construct(self): pass class MugIntoTorus(Scene): def construct(self): pass class DefineInscribedSquareProblem(ClosedLoopScene): def construct(self): self.draw_loop() self.cycle_through_shapes() self.ask_about_rectangles() def draw_loop(self): self.title = OldTexText("Inscribed", "square", "problem") self.title.to_edge(UP) #Draw loop self.remove(self.loop) self.play(Write(self.title)) self.wait() self.play(ShowCreation( self.loop, run_time = 5, rate_func=linear )) self.wait() self.add_rect_dots(square = True) self.play(ShowCreation(self.dots, run_time = 2)) self.wait() self.add_connecting_lines(cyclic = True) self.play( ShowCreation( self.connecting_lines, lag_ratio = 0, run_time = 2 ), Animation(self.dots) ) self.wait(2) def cycle_through_shapes(self): circle = Circle(radius = 2.5, color = WHITE) ellipse = circle.copy() ellipse.stretch(1.5, 0) ellipse.stretch(0.7, 1) ellipse.rotate(-np.pi/2) ellipse.set_height(4) pi_loop = OldTex("\\pi")[0] pi_loop.set_fill(opacity = 0) pi_loop.set_stroke( color = WHITE, width = DEFAULT_STROKE_WIDTH ) pi_loop.set_height(4) randy = Randolph() randy.look(DOWN) randy.set_width(pi_loop.get_width()) randy.move_to(pi_loop, aligned_edge = DOWN) randy.body.set_fill(opacity = 0) randy.mouth.set_stroke(width = 0) self.transform_loop(circle) self.remove(self.loop) self.loop = circle self.add(self.loop, self.connecting_lines, self.dots) self.wait() odd_eigths = np.linspace(1./8, 7./8, 4) self.move_dots_to_alphas(odd_eigths) self.wait() for nudge in 0.1, -0.1, 0: self.move_dots_to_alphas(odd_eigths+nudge) self.wait() self.transform_loop(ellipse) self.wait() nudge = 0.055 self.move_dots_to_alphas( odd_eigths + [nudge, -nudge, nudge, -nudge] ) self.wait(2) self.transform_loop(pi_loop) self.let_dots_wonder() randy_anims = [ FadeIn(randy), Animation(randy), Blink(randy), Animation(randy), Blink(randy), Animation(randy), Blink(randy, rate_func = smooth) ] for anim in randy_anims: self.let_dots_wonder( run_time = 1.5, random_seed = 0, added_anims = [anim] ) self.remove(randy) self.transform_loop(self.get_default_loop()) def ask_about_rectangles(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) morty.to_edge(RIGHT) new_title = OldTexText("Inscribed", "rectangle", "problem") new_title.set_color_by_tex("rectangle", YELLOW) new_title.to_edge(UP) rect_dots = self.get_rect_vertex_dots() rect_alphas = self.get_dot_alphas(rect_dots) self.play(FadeIn(morty)) self.play(morty.change_mode, "speaking") self.play(Transform(self.title, new_title)) self.move_dots_to_alphas(rect_alphas) self.wait() self.play(morty.change_mode, "hooray") self.play(Blink(morty)) self.wait() self.play(FadeOut(self.connecting_lines)) self.connecting_lines = VGroup() self.play(morty.change_mode, "plain") dot_pairs = [ VGroup(self.dots[i], self.dots[j]) for i, j in [(0, 2), (1, 3)] ] pair_colors = MAROON_B, PURPLE_B diag_lines = [ Line(d1.get_center(), d2.get_center(), color = c) for (d1, d2), c in zip(dot_pairs, pair_colors) ] for pair, line in zip(dot_pairs, diag_lines): self.play( FadeIn(line), pair.set_color, line.get_color(), ) class RectangleProperties(Scene): def construct(self): rect = Rectangle(color = BLUE) vertex_dots = VGroup(*[ Dot(anchor, color = YELLOW) for anchor in rect.get_anchors_and_handles()[0] ]) dot_pairs = [ VGroup(vertex_dots[i], vertex_dots[j]) for i, j in [(0, 2), (1, 3)] ] colors = [MAROON_B, PURPLE_B] diag_lines = [ Line(d1.get_center(), d2.get_center(), color = c) for (d1, d2), c in zip(dot_pairs, colors) ] braces = [Brace(rect).next_to(ORIGIN, DOWN) for x in range(2)] for brace, line in zip(braces, diag_lines): brace.stretch_to_fit_width(line.get_length()) brace.rotate(line.get_angle()) a, b, c, d = labels = VGroup(*[ OldTex(s).next_to(dot, dot.get_center(), buff = SMALL_BUFF) for s, dot in zip("abcd", vertex_dots) ]) midpoint = Dot(ORIGIN, color = RED) self.play(ShowCreation(rect)) self.wait() self.play( ShowCreation(vertex_dots), Write(labels) ) self.wait() mob_lists = [ (a, c, dot_pairs[0]), (b, d, dot_pairs[1]), ] for color, mob_list in zip(colors, mob_lists): self.play(*[ ApplyMethod(mob.set_color, color) for mob in mob_list ]) self.wait() for line, brace in zip(diag_lines, braces): self.play( ShowCreation(line), GrowFromCenter(brace) ) self.wait() self.play(FadeOut(brace)) self.play(FadeIn(midpoint)) self.wait() class PairOfPairBecomeRectangle(Scene): def construct(self): dots = VGroup( Dot(4*RIGHT+0.5*DOWN, color = MAROON_B), Dot(5*RIGHT+3*UP, color = MAROON_B), Dot(LEFT+0.1*DOWN, color = PURPLE_B), Dot(2*LEFT+UP, color = PURPLE_B) ) labels = VGroup() for dot, char in zip(dots, "acbd"): label = OldTex(char) y_coord = dot.get_center()[1] label.next_to(dot, np.sign(dot.get_center()[1])*UP) label.set_color(dot.get_color()) labels.add(label) lines = [ Line( dots[i].get_center(), dots[j].get_center(), color = dots[i].get_color() ) for i, j in [(0, 1), (2, 3)] ] groups = [ VGroup(dots[0], dots[1], labels[0], labels[1], lines[0]), VGroup(dots[2], dots[3], labels[2], labels[3], lines[1]), ] midpoint = Dot(LEFT, color = RED) words = VGroup(*list(map(TexText, [ "Common midpoint", "Same distance apart", "$\\Downarrow$", "Rectangle", ]))) words.arrange(DOWN) words.to_edge(RIGHT) words[-1].set_color(BLUE) self.play( ShowCreation(dots), Write(labels) ) self.play(*list(map(ShowCreation, lines))) self.wait() self.play(*[ ApplyMethod( group.shift, -group[-1].get_center()+midpoint.get_center() ) for group in groups ]) self.play( ShowCreation(midpoint), Write(words[0]) ) factor = lines[0].get_length()/lines[1].get_length() grower = groups[1].copy() new_line = grower[-1] new_line.scale(factor) grower[0].move_to(new_line.get_start()) grower[2].next_to(grower[0], DOWN) grower[1].move_to(new_line.get_end()) grower[3].next_to(grower[1], UP) self.play(Transform(groups[1], grower)) self.play(Write(words[1])) self.wait() rectangle = Polygon(*[ dots[i].get_center() for i in (0, 2, 1, 3) ]) rectangle.set_color(BLUE) self.play( ShowCreation(rectangle), Animation(dots) ) self.play(*list(map(Write, words[2:]))) self.wait() class SearchForRectangleOnLoop(ClosedLoopScene): def construct(self): self.add_dots_at_alphas(*np.linspace(0.2, 0.8, 4)) self.set_color_dots_by_pair() rect_alphas = self.get_rect_alphas() self.play(ShowCreation(self.dots)) self.add_connecting_lines() self.play(ShowCreation(self.connecting_lines)) self.let_dots_wonder(2) self.move_dots_to_alphas(rect_alphas) midpoint = Dot( center_of_mass([d.get_center() for d in self.dots]), color = RED ) self.play(ShowCreation(midpoint)) self.wait() angles = [line.get_angle() for line in self.connecting_lines] angle_mean = np.mean(angles) self.play( *[ ApplyMethod(line.rotate, angle_mean-angle) for line, angle in zip(self.connecting_lines, angles) ] + [Animation(midpoint)], rate_func = there_and_back ) self.add(self.connecting_lines.copy(), midpoint) self.connecting_lines = VGroup() self.wait() self.add_connecting_lines(cyclic = True) self.play( ShowCreation(self.connecting_lines), Animation(self.dots) ) self.wait() class DeclareFunction(ClosedLoopScene): def construct(self): self.add_dots_at_alphas(0.2, 0.8) self.set_color_dots_by_pair() self.add_connecting_lines() VGroup( self.loop, self.dots, self.connecting_lines ).scale(0.7).to_edge(LEFT).shift(DOWN) arrow = Arrow(LEFT, RIGHT).next_to(self.loop) self.add(arrow) self.add_tex() self.let_dots_wonder(10) def add_tex(self): tex = OldTex("f", "(A, B)", "=", "(x, y, z)") tex.to_edge(UP) tex.shift(LEFT) ab_brace = Brace(tex[1]) xyz_brace = Brace(tex[-1], RIGHT) ab_brace.add(ab_brace.get_text("Pair of points on the loop")) xyz_brace.add(xyz_brace.get_text("Point in 3d space")) ab_brace.set_color_by_gradient(MAROON_B, PURPLE_B) xyz_brace.set_color(BLUE) self.add(tex) self.play(Write(ab_brace)) self.wait() self.play(Write(xyz_brace)) self.wait() class DefinePairTo3dFunction(Scene): def construct(self): pass class LabelMidpoint(Scene): def construct(self): words = OldTexText("Midpoint $M$") words.set_color(RED) words.scale(2) self.play(Write(words, run_time = 1)) self.wait() class LabelDistance(Scene): def construct(self): words = OldTexText("Distance $d$") words.set_color(MAROON_B) words.scale(2) self.play(Write(words, run_time = 1)) self.wait() class DrawingOneLineOfTheSurface(Scene): def construct(self): pass class FunctionSurface(Scene): def construct(self): pass class PointPairApprocahingEachother3D(Scene): def construct(self): pass class InputPairToFunction(Scene): def construct(self): tex = OldTex("f(X, X)", "=X") tex.set_color_by_tex("=X", BLUE) tex.scale(2) self.play(Write(tex[0])) self.wait(2) self.play(Write(tex[1])) self.wait(2) class WigglePairUnderSurface(Scene): def construct(self): pass class WriteContinuous(Scene): def construct(self): self.play(Write(OldTexText("Continuous").scale(2))) self.wait(2) class DistinctPairCollisionOnSurface(Scene): def construct(self): pass class PairsOfPointsOnLoop(ClosedLoopScene): def construct(self): self.add_dots_at_alphas(0.2, 0.5) self.dots.set_color(MAROON_B) self.add_connecting_lines() self.let_dots_wonder(run_time = 10) class PairOfRealsToPlane(Scene): def construct(self): r1, r2 = numbers = -3, 2 colors = GREEN, RED dot1, dot2 = dots = VGroup(*[Dot(color = c) for c in colors]) for dot, number in zip(dots, numbers): dot.move_to(number*RIGHT) pair_label = OldTex("(", str(r1), ",", str(r2), ")") for number, color in zip(numbers, colors): pair_label.set_color_by_tex(str(number), color) pair_label.next_to(dots, UP, buff = 2) arrows = VGroup(*[ Arrow(pair_label[i], dot, color = dot.get_color()) for i, dot in zip([1, 3], dots) ]) two_d_point = Dot(r1*RIGHT + r2*UP, color = YELLOW) pair_label.add_background_rectangle() x_axis = NumberLine(color = BLUE) y_axis = NumberLine(color = BLUE) plane = NumberPlane().fade() self.add(x_axis, y_axis, dots, pair_label) self.play(ShowCreation(arrows, run_time = 2)) self.wait() self.play( pair_label.next_to, two_d_point, UP+LEFT, SMALL_BUFF, Rotate(y_axis, np.pi/2), Rotate(dot2, np.pi/2), FadeOut(arrows) ) lines = VGroup(*[ DashedLine(dot, two_d_point, color = dot.get_color()) for dot in dots ]) self.play(*list(map(ShowCreation, lines))) self.play(ShowCreation(two_d_point)) everything = VGroup(*self.get_mobjects()) self.play( FadeIn(plane), Animation(everything), Animation(dot2) ) self.wait() class SeekSurfaceForPairs(ClosedLoopScene): def construct(self): self.loop.to_edge(LEFT) self.add_dots_at_alphas(0.2, 0.3) self.set_color_dots_by_pair() self.add_connecting_lines() arrow = Arrow(LEFT, RIGHT).next_to(self.loop) words = OldTexText("Some 2d surface") words.next_to(arrow, RIGHT) anims = [ ShowCreation(arrow), Write(words) ] for anim in anims: self.let_dots_wonder( random_seed = 1, added_anims = [anim], run_time = anim.run_time ) self.let_dots_wonder(random_seed = 1, run_time = 10) class AskAbouPairType(TeacherStudentsScene): def construct(self): self.student_says(""" Do you mean ordered or unordered pairs? """) self.play(*[ ApplyMethod(self.get_students()[i].change_mode, "confused") for i in (0, 2) ]) self.random_blink(3) class DefineOrderedPair(ClosedLoopScene): def construct(self): title = OldTexText("Ordered pairs") title.to_edge(UP) subtitle = OldTex( "(", "a", ",", "b", ")", "\\ne", "(", "b", ",", "a", ")" ) labels_start = VGroup(subtitle[1], subtitle[3]) labels_end = VGroup(subtitle[9], subtitle[7]) subtitle.next_to(title, DOWN) colors = GREEN, RED for char, color in zip("ab", colors): subtitle.set_color_by_tex(char, color) self.loop.next_to(subtitle, DOWN) self.add(title, subtitle) self.add_dots_at_alphas(0.5, 0.6) dots = self.dots for dot, color, char in zip(dots, colors, "ab"): dot.set_color(color) label = OldTex(char) label.set_color(color) label.next_to(dot, RIGHT, buff = SMALL_BUFF) dot.label = label self.dots[1].label.shift(0.3*UP) first = OldTexText("First") first.next_to(self.dots[0], UP+2*LEFT, LARGE_BUFF) arrow = Arrow(first.get_bottom(), self.dots[0], color = GREEN) self.wait() self.play(*[ Transform(label.copy(), dot.label) for label, dot in zip(labels_start, dots) ]) self.remove(*self.get_mobjects_from_last_animation()) self.add(*[d.label for d in dots]) self.wait() self.play( Write(first), ShowCreation(arrow) ) self.wait() class DefineUnorderedPair(ClosedLoopScene): def construct(self): title = OldTexText("Unordered pairs") title.to_edge(UP) subtitle = OldTex( "\\{a,b\\}", "=", "\\{b,a\\}", ) subtitle.next_to(title, DOWN) for char in "ab": subtitle.set_color_by_tex(char, PURPLE_B) self.loop.next_to(subtitle, DOWN) self.add(title, subtitle) self.add_dots_at_alphas(0.5, 0.6) dots = self.dots dots.set_color(PURPLE_B) labels = VGroup(*[subtitle[i].copy() for i in (0, 2)]) for label, vect in zip(labels, [LEFT, RIGHT]): label.next_to(dots, vect, LARGE_BUFF) arrows = [ Arrow(*pair, color = PURPLE_B) for pair in it.product(labels, dots) ] arrow_pairs = [VGroup(*arrows[:2]), VGroup(*arrows[2:])] for label, arrow_pair in zip(labels, arrow_pairs): self.play(*list(map(FadeIn, [label, arrow_pair]))) self.wait() for x in range(2): self.play( dots[0].move_to, dots[1], dots[1].move_to, dots[0], path_arc = np.pi/2 ) self.wait() class BeginWithOrdered(TeacherStudentsScene): def construct(self): self.teacher_says(""" One must know order before he can ignore it. """) self.random_blink(3) class DeformToInterval(ClosedLoopScene): def construct(self): interval = UnitInterval(color = WHITE) interval.shift(2*DOWN) numbers = interval.get_number_mobjects(0, 1) line = Line(interval.get_left(), interval.get_right()) line.insert_n_curves(self.loop.get_num_curves()) line.make_smooth() self.loop.scale(0.7) self.loop.to_edge(UP) original_loop = self.loop.copy() cut_loop = self.loop.copy() cut_loop.get_points()[0] += 0.3*(UP+RIGHT) cut_loop.get_points()[-1] += 0.3*(DOWN+RIGHT) #Unwrap loop self.transform_loop(cut_loop, path_arc = np.pi) self.wait() self.transform_loop( line, run_time = 3, path_arc = np.pi/2 ) self.wait() self.play(ShowCreation(interval)) self.play(Write(numbers)) self.wait() #Follow points self.loop = original_loop.copy() self.play(FadeIn(self.loop)) self.add(original_loop) self.add_dots_at_alphas(*np.linspace(0, 1, 20)) self.dots.set_color_by_gradient(BLUE, MAROON_C, BLUE) dot_at_1 = self.dots[-1] dot_at_1.generate_target() dot_at_1.target.move_to(interval.get_right()) dots_copy = self.dots.copy() fading_dots = VGroup(*list(self.dots)+list(dots_copy)) end_dots = VGroup( self.dots[0], self.dots[-1], dots_copy[0], dots_copy[-1] ) fading_dots.remove(*end_dots) self.play(Write(self.dots)) self.add(dots_copy) self.wait() self.transform_loop( line, added_anims = [MoveToTarget(dot_at_1)], run_time = 3 ) self.wait() self.loop = original_loop self.dots = dots_copy dot_at_1 = self.dots[-1] dot_at_1.target.move_to(cut_loop.get_points()[-1]) self.transform_loop( cut_loop, added_anims = [MoveToTarget(dot_at_1)] ) self.wait() fading_dots.generate_target() fading_dots.target.set_fill(opacity = 0.3) self.play(MoveToTarget(fading_dots)) self.play( end_dots.shift, 0.2*UP, rate_func = wiggle ) self.wait() class RepresentPairInUnitSquare(ClosedLoopScene): def construct(self): interval = UnitInterval(color = WHITE) interval.shift(2.5*DOWN) interval.shift(LEFT) numbers = interval.get_number_mobjects(0, 1) line = Line(interval.get_left(), interval.get_right()) line.insert_n_curves(self.loop.get_num_curves()) line.make_smooth() vert_interval = interval.copy() square = Square() square.set_width(interval.get_width()) square.set_stroke(width = 0) square.set_fill(color = BLUE, opacity = 0.3) square.move_to( interval.get_left(), aligned_edge = DOWN+LEFT ) right_words = VGroup(*[ OldTexText("Pair of\\\\ loop points"), OldTex("\\Downarrow"), OldTexText("Point in \\\\ unit square") ]) right_words.arrange(DOWN) right_words.to_edge(RIGHT) dot_coords = (0.3, 0.7) self.loop.scale(0.7) self.loop.to_edge(UP) self.add_dots_at_alphas(*dot_coords) self.dots.set_color_by_gradient(GREEN, RED) self.play( Write(self.dots), Write(right_words[0]) ) self.wait() self.transform_loop(line) self.play( ShowCreation(interval), Write(numbers), Animation(self.dots) ) self.wait() self.play(*[ Rotate(mob, np.pi/2, about_point = interval.get_left()) for mob in (vert_interval, self.dots[1]) ]) #Find interior point point = self.dots[0].get_center()[0]*RIGHT point += self.dots[1].get_center()[1]*UP inner_dot = Dot(point, color = YELLOW) dashed_lines = VGroup(*[ DashedLine(dot, inner_dot, color = dot.get_color()) for dot in self.dots ]) self.play(ShowCreation(dashed_lines)) self.play(ShowCreation(inner_dot)) self.play( FadeIn(square), Animation(self.dots), *list(map(Write, right_words[1:])) ) self.wait() #Shift point in square movers = list(dashed_lines)+list(self.dots)+[inner_dot] for mob in movers: mob.generate_target() shift_vals = [ RIGHT+DOWN, LEFT+DOWN, LEFT+2*UP, 3*DOWN, 2*RIGHT+UP, RIGHT+UP, 3*LEFT+3*DOWN ] for shift_val in shift_vals: inner_dot.target.shift(shift_val) self.dots[0].target.shift(shift_val[0]*RIGHT) self.dots[1].target.shift(shift_val[1]*UP) for line, dot in zip(dashed_lines, self.dots): line.target.put_start_and_end_on( dot.target.get_center(), inner_dot.target.get_center() ) self.play(*list(map(MoveToTarget, movers))) self.wait() self.play(*list(map(FadeOut, [dashed_lines, self.dots]))) class EdgesOfSquare(Scene): def construct(self): square = self.add_square() x_edges, y_edges = self.get_edges(square) label_groups = self.get_coordinate_labels(square) arrow_groups = self.get_arrows(x_edges, y_edges) for edge in list(x_edges) + list(y_edges): self.play(ShowCreation(edge)) self.wait() for label_group in label_groups: for label in label_group[:3]: self.play(FadeIn(label)) self.wait() self.play(Write(VGroup(*label_group[3:]))) self.wait() self.play(FadeOut(VGroup(*label_groups))) for arrows in arrow_groups: self.play(ShowCreation(arrows, run_time = 2)) self.wait() self.play(*[ ApplyMethod( n.next_to, square.get_corner(vect+LEFT), LEFT, MED_SMALL_BUFF, path_arc = np.pi/2 ) for n, vect in zip(self.numbers, [DOWN, UP]) ]) self.wait() def add_square(self): interval = UnitInterval(color = WHITE) interval.shift(2.5*DOWN) bottom_left = interval.get_left() for tick in interval.tick_marks: height = tick.get_height() tick.scale(0.5) tick.shift(height*DOWN/4.) self.numbers = interval.get_number_mobjects(0, 1) vert_interval = interval.copy() vert_interval.rotate(np.pi, axis = UP+RIGHT, about_point = bottom_left) square = Square() square.set_width(interval.get_width()) square.set_stroke(width = 0) square.set_fill(color = BLUE, opacity = 0.3) square.move_to( bottom_left, aligned_edge = DOWN+LEFT ) self.add(interval, self.numbers, vert_interval, square) return square def get_edges(self, square): y_edges = VGroup(*[ Line( square.get_corner(vect+LEFT), square.get_corner(vect+RIGHT), ) for vect in (DOWN, UP) ]) y_edges.set_color(BLUE) x_edges = VGroup(*[ Line( square.get_corner(vect+DOWN), square.get_corner(vect+UP), ) for vect in (LEFT, RIGHT) ]) x_edges.set_color(MAROON_B) return x_edges, y_edges def get_coordinate_labels(self, square): alpha_range = np.arange(0, 1.1, 0.1) dot_groups = [ VGroup(*[ Dot(interpolate( square.get_corner(DOWN+vect), square.get_corner(UP+vect), alpha )) for alpha in alpha_range ]) for vect in (LEFT, RIGHT) ] for group in dot_groups: group.set_color_by_gradient(YELLOW, PURPLE_B) label_groups = [ VGroup(*[ OldTex("(%s, %s)"%(a, b)).scale(0.7) for b in alpha_range ]) for a in (0, 1) ] for dot_group, label_group in zip(dot_groups, label_groups): for dot, label in zip(dot_group, label_group): label[1].set_color(MAROON_B) label.next_to(dot, RIGHT*np.sign(dot.get_center()[0])) label.add(dot) return label_groups def get_arrows(self, x_edges, y_edges): alpha_range = np.linspace(0, 1, 4) return [ VGroup(*[ VGroup(*[ Arrow( edge.point_from_proportion(a1), edge.point_from_proportion(a2), buff = 0 ) for a1, a2 in zip(alpha_range, alpha_range[1:]) ]) for edge in edges ]).set_color(edges.get_color()) for edges in (x_edges, y_edges) ] class EndpointsGluedTogether(ClosedLoopScene): def construct(self): interval = UnitInterval(color = WHITE) interval.shift(2*DOWN) numbers = interval.get_number_mobjects(0, 1) line = Line(interval.get_left(), interval.get_right()) line.insert_n_curves(self.loop.get_num_curves()) line.make_smooth() self.loop.scale(0.7) self.loop.to_edge(UP) original_loop = self.loop self.remove(original_loop) self.loop = line dots = VGroup(*[ Dot(line.get_bounding_box_point(vect)) for vect in (LEFT, RIGHT) ]) dots.set_color(BLUE) self.add(interval, dots) self.play(dots.rotate, np.pi/20, rate_func = wiggle) self.wait() self.transform_loop( original_loop, added_anims = [ ApplyMethod(dot.move_to, original_loop.get_points()[0]) for dot in dots ], run_time = 3 ) self.wait() class WrapUpToTorus(Scene): def construct(self): pass class TorusPlaneAnalogy(ClosedLoopScene): def construct(self): top_arrow = DoubleArrow(LEFT, RIGHT) top_arrow.to_edge(UP, buff = 2*LARGE_BUFF) single_pointed_top_arrow = Arrow(LEFT, RIGHT) single_pointed_top_arrow.to_edge(UP, buff = 2*LARGE_BUFF) low_arrow = DoubleArrow(LEFT, RIGHT).shift(2*DOWN) self.loop.scale(0.5) self.loop.next_to(top_arrow, RIGHT) self.loop.shift_onto_screen() self.add_dots_at_alphas(0.3, 0.5) self.dots.set_color_by_gradient(GREEN, RED) plane = NumberPlane() plane.scale(0.3).next_to(low_arrow, LEFT) number_line = NumberLine() number_line.scale(0.3) number_line.next_to(low_arrow, RIGHT) number_line.add( Dot(number_line.number_to_point(3), color = GREEN), Dot(number_line.number_to_point(-2), color = RED), ) self.wait() self.play(ShowCreation(single_pointed_top_arrow)) self.wait() self.play(ShowCreation(top_arrow)) self.wait() self.play(ShowCreation(plane)) self.play(ShowCreation(low_arrow)) self.play(ShowCreation(number_line)) self.wait() class WigglingPairOfPoints(ClosedLoopScene): def construct(self): alpha_pairs = [ (0.4, 0.6), (0.42, 0.62), ] self.add_dots_at_alphas(*alpha_pairs[-1]) self.add_connecting_lines() self.dots.set_color_by_gradient(GREEN, RED) self.connecting_lines.set_color(YELLOW) for x, pair in zip(list(range(20)), it.cycle(alpha_pairs)): self.move_dots_to_alphas(pair, run_time = 0.3) class WigglingTorusPoint(Scene): def construct(self): pass class WhatAboutUnordered(TeacherStudentsScene): def construct(self): self.student_says( "What about \\\\ unordered pairs?" ) self.play(self.get_teacher().change_mode, "pondering") self.random_blink(2) class TrivialPairCollision(ClosedLoopScene): def construct(self): self.loop.to_edge(RIGHT) self.add_dots_at_alphas(0.35, 0.55) self.dots.set_color_by_gradient(BLUE, YELLOW) a, b = self.dots a_label = OldTex("a").next_to(a, RIGHT) a_label.set_color(a.get_color()) b_label = OldTex("b").next_to(b, LEFT) b_label.set_color(b.get_color()) line = Line( a.get_corner(DOWN+LEFT), b.get_corner(UP+RIGHT), color = MAROON_B ) midpoint = Dot(self.dots.get_center(), color = RED) randy = Randolph(mode = "pondering") randy.next_to(self.loop, LEFT, aligned_edge = DOWN) randy.look_at(b) self.add(randy) for label in a_label, b_label: self.play( Write(label, run_time = 1), randy.look_at, label ) self.play(Blink(randy)) self.wait() swappers = [a, b, a_label, b_label] for mob in swappers: mob.save_state() self.play( a.move_to, b, b.move_to, a, a_label.next_to, b, LEFT, b_label.next_to, a, RIGHT, randy.look_at, a, path_arc = np.pi ) self.play(ShowCreation(midpoint)) self.play(ShowCreation(line), Animation(midpoint)) self.play(randy.change_mode, "erm", randy.look_at, b) self.play( randy.look_at, a, *[m.restore for m in swappers], path_arc = -np.pi ) self.play(Blink(randy)) self.wait() class NotHelpful(Scene): def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) bubble = morty.get_bubble(SpeechBubble, width = 4, height = 3) bubble.write("Not helpful!") self.add(morty) self.play( FadeIn(bubble), FadeIn(bubble.content), morty.change_mode, "angry", morty.look, OUT ) self.play(Blink(morty)) self.wait() class FoldUnitSquare(EdgesOfSquare): def construct(self): self.add_triangles() self.add_arrows() self.show_points_to_glue() self.perform_fold() self.show_singleton_pairs() self.ask_about_gluing() self.clarify_edge_gluing() def add_triangles(self): square = self.add_square() triangles = VGroup(*[ Polygon(*[square.get_corner(vect) for vect in vects]) for vects in [ (DOWN+LEFT, UP+RIGHT, UP+LEFT), (DOWN+LEFT, UP+RIGHT, DOWN+RIGHT), ] ]) triangles.set_stroke(width = 0) triangles.set_fill( color = square.get_color(), opacity = square.get_fill_opacity() ) self.remove(square) self.square = square self.add(triangles) self.triangles = triangles def add_arrows(self): start_arrows = VGroup() end_arrows = VGroup() colors = MAROON_B, BLUE for a in 0, 1: for color in colors: b_range = np.linspace(0, 1, 4) for b1, b2 in zip(b_range, b_range[1:]): arrow = Arrow( self.get_point_from_coords(a, b1), self.get_point_from_coords(a, b2), buff = 0, color = color ) if color is BLUE: arrow.rotate( -np.pi/2, about_point = self.square.get_center() ) if (a is 0): start_arrows.add(arrow) else: end_arrows.add(arrow) self.add(start_arrows, end_arrows) self.start_arrows = start_arrows self.end_arrows = VGroup(*list(end_arrows[3:])+list(end_arrows[:3])).copy() self.end_arrows.set_color( color_gradient([MAROON_B, BLUE], 3)[1] ) def show_points_to_glue(self): colors = YELLOW, MAROON_B, PINK pairs = [(0.2, 0.3), (0.5, 0.7), (0.25, 0.6)] unit = self.square.get_width() start_dots = VGroup() end_dots = VGroup() for (x, y), color in zip(pairs, colors): old_x_line, old_y_line = None, None for (a, b) in (x, y), (y, x): point = self.get_point_from_coords(a, b) dot = Dot(point) dot.set_color(color) if color == colors[-1]: s = "(x, y)" if a < b else "(y, x)" label = OldTex(s) else: label = OldTex("(%.01f, %.01f)"%(a, b)) vect = UP+RIGHT if a < b else DOWN+RIGHT label.next_to(dot, vect, buff = SMALL_BUFF) self.play(*list(map(FadeIn, [dot, label]))) x_line = Line(point+a*unit*LEFT, point) y_line = Line(point+b*unit*DOWN, point) x_line.set_color(GREEN) y_line.set_color(RED) if old_x_line is None: self.play(ShowCreation(x_line), Animation(dot)) self.play(ShowCreation(y_line), Animation(dot)) old_x_line, old_y_line = y_line, x_line else: self.play(Transform(old_x_line, x_line), Animation(dot)) self.play(Transform(old_y_line, y_line), Animation(dot)) self.remove(old_x_line, old_y_line) self.add(x_line, y_line, dot) self.wait(2) self.play(FadeOut(label)) if a < b: start_dots.add(dot) else: end_dots.add(dot) self.play(*list(map(FadeOut, [x_line, y_line]))) self.start_dots, self.end_dots = start_dots, end_dots def perform_fold(self): diag_line = DashedLine( self.square.get_corner(DOWN+LEFT), self.square.get_corner(UP+RIGHT), color = RED ) self.play(ShowCreation(diag_line)) self.wait() self.play( Transform(*self.triangles), Transform(self.start_dots, self.end_dots), Transform(self.start_arrows, self.end_arrows), ) self.wait() self.diag_line = diag_line def show_singleton_pairs(self): xs = [0.7, 0.4, 0.5] old_label = None old_dot = None for x in xs: point = self.get_point_from_coords(x, x) dot = Dot(point) if x is xs[-1]: label = OldTex("(x, x)") else: label = OldTex("(%.1f, %.1f)"%(x, x)) label.next_to(dot, UP+LEFT, buff = SMALL_BUFF) VGroup(dot, label).set_color(RED) if old_label is None: self.play( ShowCreation(dot), Write(label) ) old_label = label old_dot = dot else: self.play( Transform(old_dot, dot), Transform(old_label, label), ) self.wait() #Some strange bug necesitating this self.remove(old_label) self.add(label) def ask_about_gluing(self): keepers = VGroup( self.triangles[0], self.start_arrows, self.diag_line ).copy() faders = VGroup(*self.get_mobjects()) randy = Randolph() randy.next_to(ORIGIN, DOWN) bubble = randy.get_bubble(height = 4, width = 6) bubble.write("How do you \\\\ glue those arrows?") self.play( FadeOut(faders), Animation(keepers) ) self.play( keepers.scale, 0.6, keepers.shift, 4*RIGHT + UP, FadeIn(randy) ) self.play( randy.change_mode, "pondering", randy.look_at, keepers, ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(randy)) self.wait() self.randy = randy def clarify_edge_gluing(self): dots = VGroup(*[ Dot(self.get_point_from_coords(*coords), radius = 0.1) for coords in [ (0.1, 0), (1, 0.1), (0.9, 0), (1, 0.9), ] ]) dots.scale(0.6) dots.shift(4*RIGHT + UP) for dot in dots[:2]: dot.set_color(YELLOW) self.play( ShowCreation(dot), self.randy.look_at, dot ) self.wait() for dot in dots[2:]: dot.set_color(MAROON_B) self.play( ShowCreation(dot), self.randy.look_at, dot ) self.play(Blink(self.randy)) self.wait() def get_point_from_coords(self, x, y): left, right, bottom, top = [ self.triangles.get_edge_center(vect) for vect in (LEFT, RIGHT, DOWN, UP) ] x_point = interpolate(left, right, x) y_point = interpolate(bottom, top, y) return x_point[0]*RIGHT + y_point[1]*UP class PrepareForMobiusStrip(Scene): def construct(self): self.add_triangles() self.perform_cut() self.rearrange_pieces() def add_triangles(self): triangles = VGroup( Polygon( DOWN+LEFT, DOWN+RIGHT, ORIGIN, ), Polygon( DOWN+RIGHT, UP+RIGHT, ORIGIN, ), ) triangles.set_fill(color = BLUE, opacity = 0.6) triangles.set_stroke(width = 0) triangles.center() triangles.scale(2) arrows_color = color_gradient([PINK, BLUE], 3)[1] for tri in triangles: anchors = tri.get_anchors_and_handles()[0] alpha_range = np.linspace(0, 1, 4) arrows = VGroup(*[ Arrow( interpolate(anchors[0], anchors[1], a), interpolate(anchors[0], anchors[1], b), buff = 0, color = arrows_color ) for a, b in zip(alpha_range, alpha_range[1:]) ]) tri.original_arrows = arrows tri.add(arrows) i, j, k = (0, 2, 1) if tri is triangles[0] else (1, 2, 0) dashed_line = DashedLine( anchors[i], anchors[j], color = RED ) tri.add(dashed_line) #Add but don't draw cut_arrows start, end = anchors[j], anchors[k] cut_arrows = VGroup(*[ Arrow( interpolate(start, end, a), interpolate(start, end, b), buff = 0, color = YELLOW ) for a, b in zip(alpha_range, alpha_range[1:]) ]) tri.cut_arrows = cut_arrows self.add(triangles) self.triangles = triangles def perform_cut(self): tri1, tri2 = self.triangles self.play(ShowCreation(tri1.cut_arrows)) for tri in self.triangles: tri.add(tri.cut_arrows) self.wait() self.play( tri1.shift, (DOWN+LEFT)/2., tri2.shift, (UP+RIGHT)/2., ) self.wait() def rearrange_pieces(self): tri1, tri2 = self.triangles self.play( tri1.rotate, np.pi, UP+RIGHT, tri1.next_to, ORIGIN, RIGHT, tri2.next_to, ORIGIN, LEFT, ) self.wait() self.play(*[ ApplyMethod(tri.shift, tri.get_points()[0][0]*LEFT) for tri in self.triangles ]) self.play(*[ FadeOut(tri.original_arrows) for tri in self.triangles ]) for tri in self.triangles: tri.remove(tri.original_arrows) self.wait() # self.play(*[ # ApplyMethod(tri.rotate, -np.pi/4) # for tri in self.triangles # ]) # self.wait() class FoldToMobius(Scene): def construct(self): pass class MobiusPlaneAnalogy(ClosedLoopScene): def construct(self): top_arrow = Arrow(LEFT, RIGHT) top_arrow.to_edge(UP, buff = 2*LARGE_BUFF) low_arrow = Arrow(LEFT, RIGHT).shift(2*DOWN) self.loop.scale(0.5) self.loop.next_to(top_arrow, RIGHT) self.loop.shift_onto_screen() self.add_dots_at_alphas(0.3, 0.5) self.dots.set_color(PURPLE_B) plane = NumberPlane() plane.scale(0.3).next_to(low_arrow, LEFT) number_line = NumberLine() number_line.scale(0.3) number_line.next_to(low_arrow, RIGHT) number_line.add( Dot(number_line.number_to_point(3), color = GREEN), Dot(number_line.number_to_point(-2), color = RED), ) self.wait() self.play(ShowCreation(top_arrow)) self.wait() self.play(ShowCreation(plane)) self.play(ShowCreation(low_arrow)) self.play(ShowCreation(number_line)) self.wait() class DrawRightArrow(Scene): CONFIG = { "tex" : "\\Rightarrow" } def construct(self): arrow = OldTex(self.tex) arrow.scale(4) self.play(Write(arrow)) self.wait() class DrawLeftrightArrow(DrawRightArrow): CONFIG = { "tex" : "\\Leftrightarrow" } class MobiusToPairToSurface(ClosedLoopScene): def construct(self): self.loop.scale(0.5) self.loop.next_to(ORIGIN, RIGHT) self.loop.to_edge(UP) self.add_dots_at_alphas(0.4, 0.6) self.dots.set_color(MAROON_B) self.add_connecting_lines() strip_dot = Dot().next_to(self.loop, LEFT, buff = 2*LARGE_BUFF) surface_dot = Dot().next_to(self.loop, DOWN, buff = 2*LARGE_BUFF) top_arrow = Arrow(strip_dot, self.loop) right_arrow = Arrow(self.loop, surface_dot) diag_arrow = Arrow(strip_dot, surface_dot) randy = self.randy = Randolph(mode = "pondering") randy.next_to(ORIGIN, DOWN+LEFT) self.look_at(strip_dot) self.play( ShowCreation(top_arrow), randy.look_at, self.loop ) self.wait() self.look_at(strip_dot, surface_dot) self.play(ShowCreation(diag_arrow)) self.play(Blink(randy)) self.look_at(strip_dot, self.loop) self.wait() self.play( ShowCreation(right_arrow), randy.look_at, surface_dot ) self.play(Blink(randy)) self.play(randy.change_mode, "happy") self.play(Blink(randy)) self.wait() def look_at(self, *things): for thing in things: self.play(self.randy.look_at, thing) class MapMobiusStripOntoSurface(Scene): def construct(self): pass class StripMustIntersectItself(TeacherStudentsScene): def construct(self): self.teacher_says( """ The strip must intersect itself during this process """, width = 4 ) dot = Dot(2*UP + 4*LEFT) for student in self.get_students(): student.generate_target() student.target.change_mode("pondering") student.target.look_at(dot) self.play(*list(map(MoveToTarget, self.get_students()))) self.random_blink(4) class PairOfMobiusPointsLandOnEachother(Scene): def construct(self): pass class ThatsTheProof(TeacherStudentsScene): def construct(self): self.teacher_says( """ Bada boom bada bang! """, target_mode = "hooray", width = 4 ) self.play_student_changes(*["hooray"]*3) self.random_blink() self.play_student_changes( "confused", "sassy", "erm" ) self.teacher_says( """ If you trust the mobius strip fact... """, target_mode = "guilty", width = 4, ) self.random_blink() class TryItYourself(TeacherStudentsScene): def construct(self): self.teacher_says(""" It's actually an edifying exercise. """) self.random_blink() self.play_student_changes(*["pondering"]*3) self.random_blink(2) pi = self.get_students()[1] bubble = pi.get_bubble( "thought", width = 4, height = 4, direction = RIGHT ) bubble.set_fill(BLACK, opacity = 1) bubble.write("Orientation seem\\\\ to matter...") self.play( FadeIn(bubble), Write(bubble.content) ) self.random_blink(3) class OneMoreAnimation(TeacherStudentsScene): def construct(self): self.teacher_says(""" One more animation, but first... """) self.play_student_changes(*["happy"]*3) self.random_blink() class PatreonThanks(Scene): CONFIG = { "specific_patrons" : [ "Loo Yu Jun", "Tom", "Othman Alikhan", "Juan Batiz-Benet", "Markus Persson", "Joseph John Cox", "Achille Brighton", "Kirk Werklund", "Luc Ritchie", "Ripta Pasay", "PatrickJMT ", "Felipe Diniz", ] } def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) n_patrons = len(self.specific_patrons) special_thanks = OldTexText("Special thanks to:") special_thanks.set_color(YELLOW) special_thanks.shift(2*UP) left_patrons = VGroup(*list(map(TexText, self.specific_patrons[:n_patrons/2] ))) right_patrons = VGroup(*list(map(TexText, self.specific_patrons[n_patrons/2:] ))) for patrons, vect in (left_patrons, LEFT), (right_patrons, RIGHT): patrons.arrange(DOWN, aligned_edge = LEFT) patrons.next_to(special_thanks, DOWN) patrons.to_edge(vect, buff = LARGE_BUFF) self.play(morty.change_mode, "gracious") self.play(Write(special_thanks, run_time = 1)) self.play( Write(left_patrons), morty.look_at, left_patrons ) self.play( Write(right_patrons), morty.look_at, right_patrons ) self.play(Blink(morty)) for patrons in left_patrons, right_patrons: for index in 0, -1: self.play(morty.look_at, patrons[index]) self.wait() class CreditTWo(Scene): def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) morty.to_edge(RIGHT) brother = PiCreature(color = GOLD_E) brother.next_to(morty, LEFT) brother.look_at(morty.eyes) headphones = Headphones(height = 1) headphones.move_to(morty.eyes, aligned_edge = DOWN) headphones.shift(0.1*DOWN) url = OldTexText("www.audible.com/3b1b") url.to_corner(UP+RIGHT, buff = LARGE_BUFF) self.add(morty) self.play(Blink(morty)) self.play( FadeIn(headphones), Write(url), Animation(morty) ) self.play(morty.change_mode, "happy") self.wait() self.play(Blink(morty)) self.wait() self.play( FadeIn(brother), morty.look_at, brother.eyes ) self.play(brother.change_mode, "surprised") self.play(Blink(brother)) self.wait() self.play( morty.look, LEFT, brother.change_mode, "happy", brother.look, LEFT ) self.play(Blink(morty)) self.wait() class CreditThree(Scene): def construct(self): logo_dot = Dot().to_edge(UP).shift(3*RIGHT) randy = Randolph() randy.next_to(ORIGIN, DOWN) randy.to_edge(LEFT) randy.look(RIGHT) self.add(randy) bubble = randy.get_bubble(width = 2, height = 2) domains = VGroup(*list(map(TexText, [ "visualnumbertheory.com", "buymywidgets.com", "learnwhatilearn.com", ]))) domains.arrange(DOWN, aligned_edge = LEFT) domains.next_to(randy, UP, buff = LARGE_BUFF) domains.shift_onto_screen() promo_code = OldTexText("Promo code: TOPOLOGY") promo_code.shift(3*RIGHT) self.add(promo_code) whois = OldTexText("Free WHOIS privacy") whois.next_to(promo_code, DOWN, buff = LARGE_BUFF) self.play(Blink(randy)) self.play( randy.change_mode, "happy", randy.look_at, logo_dot ) self.wait() self.play( ShowCreation(bubble), randy.change_mode, "pondering", run_time = 2 ) self.play(Blink(randy)) self.play( Transform(bubble, VectorizedPoint(randy.get_corner(UP+LEFT))), randy.change_mode, "sad" ) self.wait() self.play( Write(domains, run_time = 5), randy.look_at, domains ) self.wait() self.play(Blink(randy)) self.play( randy.change_mode, "hooray", randy.look_at, logo_dot, FadeOut(domains) ) self.wait() self.play( Write(whois), randy.change_mode, "confused", randy.look_at, whois ) self.wait(2) self.play(randy.change_mode, "sassy") self.wait(2) self.play( randy.change_mode, "happy", randy.look_at, logo_dot ) self.play(Blink(randy)) self.wait() class ShiftingLoopPairSurface(Scene): def construct(self): pass class ThumbnailImage(ClosedLoopScene): def construct(self): self.add_rect_dots(square = True) for dot in self.dots: dot.scale(1.5) self.add_connecting_lines(cyclic = True) self.connecting_lines.set_stroke(width = 10) self.loop.add(self.connecting_lines, self.dots) title = OldTexText("Unsolved") title.scale(2.5) title.to_edge(UP) title.set_color_by_gradient(YELLOW, MAROON_B) self.add(title) self.loop.next_to(title, DOWN, buff = MED_SMALL_BUFF) self.loop.shift(2*LEFT)
videos_3b1b/_2016/hanoi.py
from manim_imports_ext import * class CountingScene(Scene): CONFIG = { "base" : 10, "power_colors" : [YELLOW, MAROON_B, RED, GREEN, BLUE, PURPLE_D], "counting_dot_starting_position" : (FRAME_X_RADIUS-1)*RIGHT + (FRAME_Y_RADIUS-1)*UP, "count_dot_starting_radius" : 0.5, "dot_configuration_height" : 2, "ones_configuration_location" : UP+2*RIGHT, "num_scale_factor" : 2, "num_start_location" : 2*DOWN, } def setup(self): self.dots = VGroup() self.number = 0 self.number_mob = VGroup(OldTex(str(self.number))) self.number_mob.scale(self.num_scale_factor) self.number_mob.shift(self.num_start_location) self.digit_width = self.number_mob.get_width() self.initialize_configurations() self.arrows = VGroup() self.add(self.number_mob) def get_template_configuration(self): #This should probably be replaced for non-base-10 counting scenes down_right = (0.5)*RIGHT + (np.sqrt(3)/2)*DOWN result = [] for down_right_steps in range(5): for left_steps in range(down_right_steps): result.append( down_right_steps*down_right + left_steps*LEFT ) return reversed(result[:self.base]) def get_dot_template(self): #This should be replaced for non-base-10 counting scenes down_right = (0.5)*RIGHT + (np.sqrt(3)/2)*DOWN dots = VGroup(*[ Dot( point, radius = 0.25, fill_opacity = 0, stroke_width = 2, stroke_color = WHITE, ) for point in self.get_template_configuration() ]) dots[-1].set_stroke(width = 0) dots.set_height(self.dot_configuration_height) return dots def initialize_configurations(self): self.dot_templates = [] self.dot_template_iterators = [] self.curr_configurations = [] def add_configuration(self): new_template = self.get_dot_template() new_template.move_to(self.ones_configuration_location) left_vect = (new_template.get_width()+LARGE_BUFF)*LEFT new_template.shift( left_vect*len(self.dot_templates) ) self.dot_templates.append(new_template) self.dot_template_iterators.append( it.cycle(new_template) ) self.curr_configurations.append(VGroup()) def count(self, max_val, run_time_per_anim = 1): for x in range(max_val): self.increment(run_time_per_anim) def increment(self, run_time_per_anim = 1, added_anims = [], total_run_time = None): run_all_at_once = (total_run_time is not None) if run_all_at_once: num_rollovers = self.get_num_rollovers() run_time_per_anim = float(total_run_time)/(num_rollovers+1) moving_dot = Dot( self.counting_dot_starting_position, radius = self.count_dot_starting_radius, color = self.power_colors[0], ) moving_dot.generate_target() moving_dot.set_fill(opacity = 0) continue_rolling_over = True place = 0 self.number += 1 added_anims = list(added_anims) #Silly python objects... added_anims += self.get_new_configuration_animations() while continue_rolling_over: moving_dot.target.replace( next(self.dot_template_iterators[place]) ) if run_all_at_once: denom = float(num_rollovers+1) start_t = place/denom def get_modified_rate_func(anim): return lambda t : anim.original_rate_func( start_t + t/denom ) for anim in added_anims: if not hasattr(anim, "original_rate_func"): anim.original_rate_func = anim.rate_func anim.rate_func = get_modified_rate_func(anim) self.play( MoveToTarget(moving_dot), *added_anims, run_time = run_time_per_anim ) self.curr_configurations[place].add(moving_dot) if not run_all_at_once: added_anims = [] if len(self.curr_configurations[place].split()) == self.base: full_configuration = self.curr_configurations[place] self.curr_configurations[place] = VGroup() place += 1 center = full_configuration.get_center_of_mass() radius = 0.6*max( full_configuration.get_width(), full_configuration.get_height(), ) circle = Circle( radius = radius, stroke_width = 0, fill_color = self.power_colors[place], fill_opacity = 0.5, ) circle.move_to(center) moving_dot = VGroup(circle, full_configuration) moving_dot.generate_target() moving_dot[0].set_fill(opacity = 0) else: continue_rolling_over = False self.play(*self.get_digit_increment_animations()) def get_new_configuration_animations(self): if self.is_perfect_power(): self.add_configuration() return [FadeIn(self.dot_templates[-1])] else: return [] def get_digit_increment_animations(self): result = [] new_number_mob = self.get_number_mob(self.number) new_number_mob.move_to(self.number_mob, RIGHT) if self.is_perfect_power(): place = len(new_number_mob.split())-1 arrow = Arrow( new_number_mob[place].get_top(), self.dot_templates[place].get_bottom(), color = self.power_colors[place] ) self.arrows.add(arrow) result.append(ShowCreation(arrow)) result.append(Transform( self.number_mob, new_number_mob, lag_ratio = 0.5 )) return result def get_number_mob(self, num): result = VGroup() place = 0 while num > 0: digit = OldTex(str(num % self.base)) if place >= len(self.power_colors): self.power_colors += self.power_colors digit.set_color(self.power_colors[place]) digit.scale(self.num_scale_factor) digit.move_to(result, RIGHT) digit.shift(place*(self.digit_width+SMALL_BUFF)*LEFT) result.add(digit) num /= self.base place += 1 return result def is_perfect_power(self): number = self.number while number > 1: if number%self.base != 0: return False number /= self.base return True def get_num_rollovers(self): next_number = self.number + 1 result = 0 while next_number%self.base == 0: result += 1 next_number /= self.base return result class BinaryCountingScene(CountingScene): CONFIG = { "base" : 2, "dot_configuration_height" : 1, "ones_configuration_location" : UP+5*RIGHT } def get_template_configuration(self): return [ORIGIN, UP] class CountInDecimal(CountingScene): def construct(self): for x in range(11): self.increment() for x in range(85): self.increment(0.25) for x in range(20): self.increment() class CountInTernary(CountingScene): CONFIG = { "base" : 3, "dot_configuration_height" : 1, "ones_configuration_location" : UP+4*RIGHT } def construct(self): self.count(27) # def get_template_configuration(self): # return [ORIGIN, UP] class CountTo27InTernary(CountInTernary): def construct(self): for x in range(27): self.increment() self.wait() class CountInBinaryTo256(BinaryCountingScene): def construct(self): self.count(256, 0.25) class TowersOfHanoiScene(Scene): CONFIG = { "disk_start_and_end_colors" : [BLUE_E, BLUE_A], "num_disks" : 5, "peg_width" : 0.25, "peg_height" : 2.5, "peg_spacing" : 4, "include_peg_labels" : True, "middle_peg_bottom" : 0.5*DOWN, "disk_height" : 0.4, "disk_min_width" : 1, "disk_max_width" : 3, "default_disk_run_time_off_peg" : 1, "default_disk_run_time_on_peg" : 2, } def setup(self): self.add_pegs() self.add_disks() def add_pegs(self): peg = Rectangle( height = self.peg_height, width = self.peg_width, stroke_width = 0, fill_color = GREY_BROWN, fill_opacity = 1, ) peg.move_to(self.middle_peg_bottom, DOWN) self.pegs = VGroup(*[ peg.copy().shift(vect) for vect in (self.peg_spacing*LEFT, ORIGIN, self.peg_spacing*RIGHT) ]) self.add(self.pegs) if self.include_peg_labels: self.peg_labels = VGroup(*[ OldTex(char).next_to(peg, DOWN) for char, peg in zip("ABC", self.pegs) ]) self.add(self.peg_labels) def add_disks(self): self.disks = VGroup(*[ Rectangle( height = self.disk_height, width = width, fill_color = color, fill_opacity = 0.8, stroke_width = 0, ) for width, color in zip( np.linspace( self.disk_min_width, self.disk_max_width, self.num_disks ), color_gradient( self.disk_start_and_end_colors, self.num_disks ) ) ]) for number, disk in enumerate(self.disks): label = OldTex(str(number)) label.set_color(BLACK) label.set_height(self.disk_height/2) label.move_to(disk) disk.add(label) disk.label = label self.reset_disks(run_time = 0) self.add(self.disks) def reset_disks(self, **kwargs): self.disks.generate_target() self.disks.target.arrange(DOWN, buff = 0) self.disks.target.move_to(self.pegs[0], DOWN) self.play( MoveToTarget(self.disks), **kwargs ) self.disk_tracker = [ set(range(self.num_disks)), set([]), set([]) ] def disk_index_to_peg_index(self, disk_index): for index, disk_set in enumerate(self.disk_tracker): if disk_index in disk_set: return index raise Exception("Somehow this disk wasn't accounted for...") def min_disk_index_on_peg(self, peg_index): disk_index_set = self.disk_tracker[peg_index] if disk_index_set: return min(self.disk_tracker[peg_index]) else: return self.num_disks def bottom_point_for_next_disk(self, peg_index): min_disk_index = self.min_disk_index_on_peg(peg_index) if min_disk_index >= self.num_disks: return self.pegs[peg_index].get_bottom() else: return self.disks[min_disk_index].get_top() def get_next_disk_0_peg(self): curr_peg_index = self.disk_index_to_peg_index(0) return (curr_peg_index+1)%3 def get_available_peg(self, disk_index): if disk_index == 0: return self.get_next_disk_0_peg() for index in range(len(list(self.pegs))): if self.min_disk_index_on_peg(index) > disk_index: return index raise Exception("Tower's of Honoi rule broken: No available disks") def set_disk_config(self, peg_indices): assert(len(peg_indices) == self.num_disks) self.disk_tracker = [set([]) for x in range(3)] for n, peg_index in enumerate(peg_indices): disk_index = self.num_disks - n - 1 disk = self.disks[disk_index] peg = self.pegs[peg_index] disk.move_to(peg.get_bottom(), DOWN) n_disks_here = len(self.disk_tracker[peg_index]) disk.shift(disk.get_height()*n_disks_here*UP) self.disk_tracker[peg_index].add(disk_index) def move_disk(self, disk_index, **kwargs): next_peg_index = self.get_available_peg(disk_index) self.move_disk_to_peg(disk_index, next_peg_index, **kwargs) def move_subtower_to_peg(self, num_disks, next_peg_index, **kwargs): disk_indices = list(range(num_disks)) peg_indices = list(map(self.disk_index_to_peg_index, disk_indices)) if len(set(peg_indices)) != 1: warnings.warn("These disks don't make up a tower right now") self.move_disks_to_peg(disk_indices, next_peg_index, **kwargs) def move_disk_to_peg(self, disk_index, next_peg_index, **kwargs): self.move_disks_to_peg([disk_index], next_peg_index, **kwargs) def move_disks_to_peg(self, disk_indices, next_peg_index, run_time = None, stay_on_peg = True, added_anims = []): if run_time is None: if stay_on_peg is True: run_time = self.default_disk_run_time_on_peg else: run_time = self.default_disk_run_time_off_peg disks = VGroup(*[self.disks[index] for index in disk_indices]) max_disk_index = max(disk_indices) next_peg = self.pegs[next_peg_index] curr_peg_index = self.disk_index_to_peg_index(max_disk_index) curr_peg = self.pegs[curr_peg_index] if self.min_disk_index_on_peg(curr_peg_index) != max_disk_index: warnings.warn("Tower's of Hanoi rule broken: disk has crap on top of it") target_bottom_point = self.bottom_point_for_next_disk(next_peg_index) path_arc = np.sign(curr_peg_index-next_peg_index)*np.pi/3 if stay_on_peg: self.play( Succession( ApplyMethod(disks.next_to, curr_peg, UP, 0), ApplyMethod(disks.next_to, next_peg, UP, 0, path_arc = path_arc), ApplyMethod(disks.move_to, target_bottom_point, DOWN), ), *added_anims, run_time = run_time, rate_func = lambda t : smooth(t, 2) ) else: self.play( ApplyMethod(disks.move_to, target_bottom_point, DOWN), *added_anims, path_arc = path_arc*2, run_time = run_time, rate_func = lambda t : smooth(t, 2) ) for disk_index in disk_indices: self.disk_tracker[curr_peg_index].remove(disk_index) self.disk_tracker[next_peg_index].add(disk_index) class ConstrainedTowersOfHanoiScene(TowersOfHanoiScene): def get_next_disk_0_peg(self): if not hasattr(self, "total_disk_0_movements"): self.total_disk_0_movements = 0 curr_peg_index = self.disk_index_to_peg_index(0) if (self.total_disk_0_movements/2)%2 == 0: result = curr_peg_index + 1 else: result = curr_peg_index - 1 self.total_disk_0_movements += 1 return result def get_ruler_sequence(order = 4): if order == -1: return [] else: smaller = get_ruler_sequence(order - 1) return smaller + [order] + smaller def get_ternary_ruler_sequence(order = 4): if order == -1: return [] else: smaller = get_ternary_ruler_sequence(order-1) return smaller+[order]+smaller+[order]+smaller class SolveHanoi(TowersOfHanoiScene): def construct(self): self.wait() for x in get_ruler_sequence(self.num_disks-1): self.move_disk(x, stay_on_peg = False) self.wait() class SolveConstrainedHanoi(ConstrainedTowersOfHanoiScene): def construct(self): self.wait() for x in get_ternary_ruler_sequence(self.num_disks-1): self.move_disk(x, run_time = 0.5, stay_on_peg = False) self.wait() class Keith(PiCreature): CONFIG = { "color" : GREEN_D } def get_binary_tex_mobs(num_list): result = VGroup() zero_width = OldTex("0").get_width() nudge = zero_width + SMALL_BUFF for num in num_list: bin_string = bin(num)[2:]#Strip off the "0b" prefix bits = VGroup(*list(map(Tex, bin_string))) for n, bit in enumerate(bits): bit.shift(n*nudge*RIGHT) bits.move_to(ORIGIN, RIGHT) result.add(bits) return result def get_base_b_tex_mob(number, base, n_digits): assert(number < base**n_digits) curr_digit = n_digits - 1 zero = OldTex("0") zero_width = zero.get_width() zero_height = zero.get_height() result = VGroup() for place in range(n_digits): remainder = number%base digit_mob = OldTex(str(remainder)) digit_mob.set_height(zero_height) digit_mob.shift(place*(zero_width+SMALL_BUFF)*LEFT) result.add(digit_mob) number = (number - remainder)/base return result.center() def get_binary_tex_mob(number, n_bits = 4): return get_base_b_tex_mob(number, 2, n_bits) def get_ternary_tex_mob(number, n_trits = 4): return get_base_b_tex_mob(number, 3, n_trits) #################### class IntroduceKeith(Scene): def construct(self): morty = Mortimer(mode = "happy") keith = Keith(mode = "dance_kick") keith_image = ImageMobject("keith_schwarz", invert = False) # keith_image = Rectangle() keith_image.set_height(FRAME_HEIGHT - 2) keith_image.next_to(ORIGIN, LEFT) keith.move_to(keith_image, DOWN+RIGHT) morty.next_to(keith, buff = LARGE_BUFF, aligned_edge = DOWN) morty.make_eye_contact(keith) randy = Randolph().next_to(keith, LEFT, LARGE_BUFF, aligned_edge = DOWN) randy.shift_onto_screen() bubble = keith.get_bubble(SpeechBubble, width = 7) bubble.write("01101011 $\\Rightarrow$ Towers of Hanoi") zero_width = bubble.content[0].get_width() one_width = bubble.content[1].get_width() for mob in bubble.content[:8]: if abs(mob.get_width() - zero_width) < 0.01: mob.set_color(GREEN) else: mob.set_color(YELLOW) bubble.resize_to_content() bubble.pin_to(keith) VGroup(bubble, bubble.content).shift(DOWN) randy.bubble = randy.get_bubble(SpeechBubble, height = 3) randy.bubble.write("Wait, what's \\\\ Towers of Hanoi?") title = OldTexText("Keith Schwarz (Computer scientist)") title.to_edge(UP) self.add(keith_image, morty) self.play(Write(title)) self.play(FadeIn(keith, run_time = 2)) self.play(FadeOut(keith_image), Animation(keith)) self.play(Blink(morty)) self.play( keith.change_mode, "speaking", keith.set_height, morty.get_height(), keith.next_to, morty, LEFT, LARGE_BUFF, run_time = 1.5 ) self.play( ShowCreation(bubble), Write(bubble.content) ) self.play( morty.change_mode, "pondering", morty.look_at, bubble ) self.play(Blink(keith)) self.wait() original_content = bubble.content bubble.write("I'm usually meh \\\\ on puzzles") self.play( keith.change_mode, "hesitant", Transform(original_content, bubble.content), ) self.play( morty.change_mode, "happy", morty.look_at, keith.eyes ) self.play(Blink(keith)) bubble.write("But \\emph{analyzing} puzzles!") VGroup(*bubble.content[3:12]).set_color(YELLOW) self.play( keith.change_mode, "hooray", Transform(original_content, bubble.content) ) self.play(Blink(morty)) self.wait() self.play(FadeIn(randy)) self.play( randy.change_mode, "confused", randy.look_at, keith.eyes, keith.change_mode, "plain", keith.look_at, randy.eyes, morty.change_mode, "plain", morty.look_at, randy.eyes, FadeOut(bubble), FadeOut(original_content), ShowCreation(randy.bubble), Write(randy.bubble.content) ) self.play(Blink(keith)) self.play( keith.change_mode, "hooray", keith.look_at, randy.eyes ) self.wait() class IntroduceTowersOfHanoi(TowersOfHanoiScene): def construct(self): self.clear() self.add_title() self.show_setup() self.note_disk_labels() self.show_more_disk_possibility() self.move_full_tower() self.move_single_disk() self.cannot_move_disk_onto_smaller_disk() def add_title(self): title = OldTexText("Towers of Hanoi") title.to_edge(UP) self.add(title) self.title = title def show_setup(self): self.pegs.save_state() bottom = self.pegs.get_bottom() self.pegs.stretch_to_fit_height(0) self.pegs.move_to(bottom) self.play( ApplyMethod( self.pegs.restore, lag_ratio = 0.5, run_time = 2 ), Write(self.peg_labels) ) self.wait() self.bring_in_disks() self.wait() def bring_in_disks(self): peg = self.pegs[0] disk_groups = VGroup() for disk in self.disks: top = Circle(radius = disk.get_width()/2) inner = Circle(radius = self.peg_width/2) inner.flip() top.add_subpath(inner.points) top.set_stroke(width = 0) top.set_fill(disk.get_color()) top.rotate(np.pi/2, RIGHT) top.move_to(disk, UP) bottom = top.copy() bottom.move_to(disk, DOWN) group = VGroup(disk, top, bottom) group.truly_original_state = group.copy() group.next_to(peg, UP, 0) group.rotate(-np.pi/24, RIGHT) group.save_state() group.rotate(-11*np.pi/24, RIGHT) disk.set_fill(opacity = 0) disk_groups.add(group) disk_groups.arrange() disk_groups.next_to(self.peg_labels, DOWN) self.play(FadeIn( disk_groups, run_time = 2, lag_ratio = 0.5 )) for group in reversed(list(disk_groups)): self.play(group.restore) self.play(Transform(group, group.truly_original_state)) self.remove(disk_groups) self.add(self.disks) def note_disk_labels(self): labels = [disk.label for disk in self.disks] last = VGroup().save_state() for label in labels: label.save_state() self.play( label.scale, 2, label.set_color, YELLOW, last.restore, run_time = 0.5 ) last = label self.play(last.restore) self.wait() def show_more_disk_possibility(self): original_num_disks = self.num_disks original_disk_height = self.disk_height original_disks = self.disks original_disks_copy = original_disks.copy() #Hacky self.num_disks = 10 self.disk_height = 0.3 self.add_disks() new_disks = self.disks self.disks = original_disks self.remove(new_disks) self.play(Transform(self.disks, new_disks)) self.wait() self.play(Transform(self.disks, original_disks_copy)) self.remove(self.disks) self.disks = original_disks_copy self.add(self.disks) self.wait() self.num_disks = original_num_disks self.disk_height = original_disk_height def move_full_tower(self): self.move_subtower_to_peg(self.num_disks, 1, run_time = 2) self.wait() self.reset_disks(run_time = 1, lag_ratio = 0.5) self.wait() def move_single_disk(self): for x in 0, 1, 0: self.move_disk(x) self.wait() def cannot_move_disk_onto_smaller_disk(self): also_not_allowed = OldTexText("Not allowed") also_not_allowed.to_edge(UP) also_not_allowed.set_color(RED) cross = OldTex("\\times") cross.set_fill(RED, opacity = 0.5) disk = self.disks[2] disk.save_state() self.move_disks_to_peg([2], 2, added_anims = [ Transform(self.title, also_not_allowed, run_time = 1) ]) cross.replace(disk) self.play(FadeIn(cross)) self.wait() self.play( FadeOut(cross), FadeOut(self.title), disk.restore ) self.wait() class ExampleFirstMoves(TowersOfHanoiScene): def construct(self): ruler_sequence = get_ruler_sequence(4) cross = OldTex("\\times") cross.set_fill(RED, 0.7) self.wait() self.play( self.disks[0].set_fill, YELLOW, self.disks[0].label.set_color, BLACK ) self.wait() self.move_disk(0) self.wait() self.play( self.disks[1].set_fill, YELLOW_D, self.disks[1].label.set_color, BLACK ) self.move_disk_to_peg(1, 1) cross.replace(self.disks[1]) self.play(FadeIn(cross)) self.wait() self.move_disk_to_peg(1, 2, added_anims = [FadeOut(cross)]) self.wait() for x in ruler_sequence[2:9]: self.move_disk(x) for x in ruler_sequence[9:]: self.move_disk(x, run_time = 0.5, stay_on_peg = False) self.wait() class KeithShowingBinary(Scene): def construct(self): keith = Keith() morty = Mortimer() morty.to_corner(DOWN+RIGHT) keith.next_to(morty, LEFT, buff = 2*LARGE_BUFF) randy = Randolph() randy.next_to(keith, LEFT, buff = 2*LARGE_BUFF) randy.bubble = randy.get_bubble(SpeechBubble) randy.bubble.set_fill(BLACK, opacity = 1) randy.bubble.write("Hold on...how does \\\\ binary work again?") binary_tex_mobs = get_binary_tex_mobs(list(range(16))) binary_tex_mobs.shift(keith.get_corner(UP+LEFT)) binary_tex_mobs.shift(0.5*(UP+RIGHT)) bits_list = binary_tex_mobs.split() bits = bits_list.pop(0) def get_bit_flip(): return Transform( bits, bits_list.pop(0), rate_func = squish_rate_func(smooth, 0, 0.7) ) self.play( keith.change_mode, "wave_1", keith.look_at, bits, morty.look_at, bits, Write(bits) ) for x in range(2): self.play(get_bit_flip()) self.play( morty.change_mode, "pondering", morty.look_at, bits, get_bit_flip() ) while bits_list: added_anims = [] if random.random() < 0.2: if random.random() < 0.5: added_anims.append(Blink(keith)) else: added_anims.append(Blink(morty)) self.play(get_bit_flip(), *added_anims) self.wait() self.play( FadeIn(randy), morty.change_mode, "plain", morty.look_at, randy.eyes, keith.change_mode, "plain", keith.look_at, randy.eyes, ) self.play( randy.change_mode, "confused", ShowCreation(randy.bubble), Write(randy.bubble.content) ) self.play(Blink(randy)) self.wait() self.play(morty.change_mode, "hooray") self.play(Blink(morty)) self.wait() class FocusOnRhythm(Scene): def construct(self): title = OldTexText("Focus on rhythm") title.scale(1.5) letters = list(reversed(title[-6:])) self.play(Write(title, run_time = 1)) sequence = get_ruler_sequence(5) for x in sequence: movers = VGroup(*letters[:x+1]) self.play( movers.shift, 0.2*DOWN, rate_func = there_and_back, run_time = 0.25 ) class IntroduceBase10(Scene): def construct(self): self.expand_example_number() self.list_digits() def expand_example_number(self): title = OldTexText("``Base 10''") title.to_edge(UP) number = OldTex("137") number.next_to(title, DOWN) number.shift(2*LEFT) colors = [RED, MAROON_B, YELLOW] expansion = OldTex( "1(100) + ", "3(10) + ", "7" ) expansion.next_to(number, DOWN, buff = LARGE_BUFF, aligned_edge = RIGHT) arrows = VGroup() number.generate_target() for color, digit, term in zip(colors, number.target, expansion): digit.set_color(color) term.set_color(color) arrow = Arrow(digit, term.get_top()) arrow.set_color(color) arrows.add(arrow) expansion.save_state() for digit, term in zip(number, expansion): Transform(term, digit).update(1) self.play( MoveToTarget(number), ShowCreation(arrows), ApplyMethod( expansion.restore, lag_ratio = 0.5), run_time = 2 ) self.play(Write(title)) self.wait() self.title = title def list_digits(self): digits = OldTexText(""" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 """) digits.next_to(self.title, DOWN, buff = LARGE_BUFF) digits.shift(2*RIGHT) self.play(Write(digits)) self.wait() class RhythmOfDecimalCounting(CountingScene): CONFIG = { "ones_configuration_location" : 2*UP+2*RIGHT, "num_start_location" : DOWN } def construct(self): for x in range(10): self.increment() brace = Brace(self.number_mob) two_digits = brace.get_text("Two digits") one_brace = Brace(self.number_mob[-1]) tens_place = one_brace.get_text("Ten's place") ten_group = self.curr_configurations[1][0] self.play( GrowFromCenter(brace), Write(two_digits, run_time = 1) ) self.wait(2) self.play( Transform(brace, one_brace), Transform(two_digits, tens_place) ) self.wait() ten_group.save_state() self.play( ten_group.scale, 7, ten_group.shift, 2*(DOWN+LEFT), ) self.wait() self.play( ten_group.restore, *list(map(FadeOut, [brace, two_digits])) ) for x in range(89): self.increment(run_time_per_anim = 0.25) self.increment(run_time_per_anim = 1) self.wait() hundred_group = self.curr_configurations[2][0] hundred_group.save_state() self.play( hundred_group.scale, 14, hundred_group.to_corner, DOWN+LEFT ) self.wait() self.play(hundred_group.restore) self.wait() groups = [ VGroup(*pair) for pair in zip(self.dot_templates, self.curr_configurations) ] self.play( groups[2].to_edge, RIGHT, MaintainPositionRelativeTo(groups[1], groups[2]), MaintainPositionRelativeTo(groups[0], groups[2]), self.number_mob.to_edge, RIGHT, LARGE_BUFF, FadeOut(self.arrows) ) class DecimalCountingAtHundredsScale(CountingScene): CONFIG = { "power_colors" : [RED, GREEN, BLUE, PURPLE_D], "counting_dot_starting_position" : (FRAME_X_RADIUS+1)*RIGHT + (FRAME_Y_RADIUS-2)*UP, "ones_configuration_location" : 2*UP+5.7*RIGHT, "num_start_location" : DOWN + 3*RIGHT } def construct(self): added_zeros = OldTex("00") added_zeros.scale(self.num_scale_factor) added_zeros.next_to(self.number_mob, RIGHT, SMALL_BUFF, aligned_edge = DOWN) added_zeros.set_color_by_gradient(MAROON_B, YELLOW) self.add(added_zeros) self.increment(run_time_per_anim = 0) VGroup(self.number_mob, added_zeros).to_edge(RIGHT, buff = LARGE_BUFF) VGroup(self.dot_templates[0], self.curr_configurations[0]).to_edge(RIGHT) Transform( self.arrows[0], Arrow(self.number_mob, self.dot_templates[0], color = self.power_colors[0]) ).update(1) for x in range(10): this_range = list(range(8)) if x == 0 else list(range(9)) for y in this_range: self.increment(run_time_per_anim = 0.25) self.increment(run_time_per_anim = 1) class IntroduceBinaryCounting(BinaryCountingScene): CONFIG = { "ones_configuration_location" : UP+5*RIGHT, "num_start_location" : DOWN+2*RIGHT } def construct(self): self.introduce_name() self.initial_counting() self.show_self_similarity() def introduce_name(self): title = OldTexText("Binary (base 2):", "0, 1") title.to_edge(UP) self.add(title) self.number_mob.set_fill(opacity = 0) brace = Brace(title[1], buff = SMALL_BUFF) bits = OldTexText("bi", "ts", arg_separator = "") bits.submobjects.insert(1, VectorizedPoint(bits.get_center())) binary_digits = OldTexText("bi", "nary digi", "ts", arg_separator = "") for mob in bits, binary_digits: mob.next_to(brace, DOWN, buff = SMALL_BUFF) VGroup(brace, bits, binary_digits).set_color(BLUE) binary_digits[1].set_color(BLUE_E) self.play( GrowFromCenter(brace), Write(bits) ) self.wait() bits.save_state() self.play(Transform(bits, binary_digits)) self.wait() self.play(bits.restore) self.wait() def initial_counting(self): randy = Randolph().to_corner(DOWN+LEFT) bubble = randy.get_bubble(ThoughtBubble, height = 3.4, width = 5) bubble.write( "Not ten, not ten \\\\", "\\quad not ten, not ten..." ) self.play(self.number_mob.set_fill, self.power_colors[0], 1) self.increment() self.wait() self.start_dot = self.curr_configurations[0][0] ##Up to 10 self.increment() brace = Brace(self.number_mob[1]) twos_place = brace.get_text("Two's place") self.play( GrowFromCenter(brace), Write(twos_place) ) self.play( FadeIn(randy), ShowCreation(bubble) ) self.play( randy.change_mode, "hesitant", randy.look_at, self.number_mob, Write(bubble.content) ) self.wait() curr_content = bubble.content bubble.write("$1 \\! \\cdot \\! 2+$", "$0$") bubble.content[0][0].set_color(self.power_colors[1]) self.play( Transform(curr_content, bubble.content), randy.change_mode, "pondering", randy.look_at, self.number_mob ) self.remove(curr_content) self.add(bubble.content) #Up to 11 zero = bubble.content[-1] zero.set_color(self.power_colors[0]) one = OldTex("1").replace(zero, dim_to_match = 1) one.set_color(zero.get_color()) self.play(Blink(randy)) self.increment(added_anims = [Transform(zero, one)]) self.wait() #Up to 100 curr_content = bubble.content bubble.write( "$1 \\!\\cdot\\! 4 + $", "$0 \\!\\cdot\\! 2 + $", "$0$", ) colors = reversed(self.power_colors[:3]) for piece, color in zip(bubble.content.submobjects, colors): piece[0].set_color(color) self.increment(added_anims = [Transform(curr_content, bubble.content)]) four_brace = Brace(self.number_mob[-1]) fours_place = four_brace.get_text("Four's place") self.play( Transform(brace, four_brace), Transform(twos_place, fours_place), ) self.play(Blink(randy)) self.play(*list(map(FadeOut, [bubble, curr_content]))) #Up to 1000 for x in range(4): self.increment() brace.target = Brace(self.number_mob[-1]) twos_place.target = brace.get_text("Eight's place") self.play( randy.change_mode, "happy", randy.look_at, self.number_mob, *list(map(MoveToTarget, [brace, twos_place])) ) for x in range(8): self.increment(total_run_time = 1) self.wait() for x in range(8): self.increment(total_run_time = 1.5) def show_self_similarity(self): cover_rect = Rectangle() cover_rect.set_width(FRAME_WIDTH) cover_rect.set_height(FRAME_HEIGHT) cover_rect.set_stroke(width = 0) cover_rect.set_fill(BLACK, opacity = 0.85) big_dot = self.curr_configurations[-1][0].copy() self.play( FadeIn(cover_rect), Animation(big_dot) ) self.play( big_dot.center, big_dot.set_height, FRAME_HEIGHT-2, big_dot.to_edge, LEFT, run_time = 5 ) class BinaryCountingAtEveryScale(Scene): CONFIG = { "num_bits" : 4, "show_title" : False, } def construct(self): title = OldTexText("Count to %d (which is %s in binary)"%( 2**self.num_bits-1, bin(2**self.num_bits-1)[2:] )) title.to_edge(UP) if self.show_title: self.add(title) bit_mobs = [ get_binary_tex_mob(n, self.num_bits) for n in range(2**self.num_bits) ] curr_bits = bit_mobs[0] lower_brace = Brace(VGroup(*curr_bits[1:])) do_a_thing = lower_brace.get_text("Do a thing") VGroup(lower_brace, do_a_thing).set_color(YELLOW) upper_brace = Brace(curr_bits, UP) roll_over = upper_brace.get_text("Roll over") VGroup(upper_brace, roll_over).set_color(MAROON_B) again = OldTexText("again") again.next_to(do_a_thing, RIGHT, 2*SMALL_BUFF) again.set_color(YELLOW) self.add(curr_bits, lower_brace, do_a_thing) def get_run_through(mobs): return Succession(*[ Transform( curr_bits, mob, rate_func = squish_rate_func(smooth, 0, 0.5) ) for mob in mobs ], run_time = 1) for bit_mob in bit_mobs: curr_bits.align_data_and_family(bit_mob) bit_mob.set_color(YELLOW) bit_mob[0].set_color(MAROON_B) self.play(get_run_through(bit_mobs[1:2**(self.num_bits-1)])) self.play(*list(map(FadeIn, [upper_brace, roll_over]))) self.play(Transform( VGroup(*reversed(list(curr_bits))), VGroup(*reversed(list(bit_mobs[2**(self.num_bits-1)]))), lag_ratio = 0.5, )) self.wait() self.play( get_run_through(bit_mobs[2**(self.num_bits-1)+1:]), Write(again) ) self.wait() class BinaryCountingAtSmallestScale(BinaryCountingAtEveryScale): CONFIG = { "num_bits" : 2, "show_title" : True, } class BinaryCountingAtMediumScale(BinaryCountingAtEveryScale): CONFIG = { "num_bits" : 4, "show_title" : True, } class BinaryCountingAtLargeScale(BinaryCountingAtEveryScale): CONFIG = { "num_bits" : 8, "show_title" : True, } class IntroduceSolveByCounting(TowersOfHanoiScene): CONFIG = { "num_disks" : 4 } def construct(self): self.initialize_bit_mobs() for disk in self.disks: disk.original_fill_color = disk.get_color() braces = [ Brace(VGroup(*self.curr_bit_mob[:n])) for n in range(1, self.num_disks+1) ] word_list = [ brace.get_text(text) for brace, text in zip(braces, [ "Only flip last bit", "Roll over once", "Roll over twice", "Roll over three times", ]) ] brace = braces[0].copy() words = word_list[0].copy() ##First increment self.play(self.get_increment_animation()) self.play( GrowFromCenter(brace), Write(words, run_time = 1) ) disk = self.disks[0] last_bit = self.curr_bit_mob[0] last_bit.save_state() self.play( disk.set_fill, YELLOW, disk[1].set_fill, BLACK, last_bit.set_fill, YELLOW, ) self.wait() self.move_disk(0, run_time = 2) self.play( last_bit.restore, disk.set_fill, disk.original_fill_color, self.disks[0][1].set_fill, BLACK ) ##Second increment self.play( self.get_increment_animation(), Transform(words, word_list[1]), Transform(brace, braces[1]), ) disk = self.disks[1] twos_bit = self.curr_bit_mob[1] twos_bit.save_state() self.play( disk.set_fill, MAROON_B, disk[1].set_fill, BLACK, twos_bit.set_fill, MAROON_B, ) self.move_disk(1, run_time = 2) self.wait() self.move_disk_to_peg(1, 1, stay_on_peg = False) cross = OldTex("\\times") cross.replace(disk) cross.set_fill(RED, opacity = 0.5) self.play(FadeIn(cross)) self.wait() self.move_disk_to_peg( 1, 2, stay_on_peg = False, added_anims = [FadeOut(cross)] ) self.play( disk.set_fill, disk.original_fill_color, disk[1].set_fill, BLACK, twos_bit.restore, Transform(brace, braces[0]), Transform(words, word_list[0]), ) self.move_disk( 0, added_anims = [self.get_increment_animation()], run_time = 2 ) self.wait() ##Fourth increment self.play( Transform(brace, braces[2]), Transform(words, word_list[2]), ) self.play(self.get_increment_animation()) disk = self.disks[2] fours_bit = self.curr_bit_mob[2] fours_bit.save_state() self.play( disk.set_fill, RED, disk[1].set_fill, BLACK, fours_bit.set_fill, RED ) self.move_disk(2, run_time = 2) self.play( disk.set_fill, disk.original_fill_color, disk[1].set_fill, BLACK, fours_bit.restore, FadeOut(brace), FadeOut(words) ) self.wait() for disk_index in 0, 1, 0: self.play(self.get_increment_animation()) self.move_disk(disk_index) self.wait() ##Eighth incremement brace = braces[3] words = word_list[3] self.play( self.get_increment_animation(), GrowFromCenter(brace), Write(words, run_time = 1) ) disk = self.disks[3] eights_bit = self.curr_bit_mob[3] eights_bit.save_state() self.play( disk.set_fill, GREEN, disk[1].set_fill, BLACK, eights_bit.set_fill, GREEN ) self.move_disk(3, run_time = 2) self.play( disk.set_fill, disk.original_fill_color, disk[1].set_fill, BLACK, eights_bit.restore, ) self.play(*list(map(FadeOut, [brace, words]))) for disk_index in get_ruler_sequence(2): self.play(self.get_increment_animation()) self.move_disk(disk_index, stay_on_peg = False) self.wait() def initialize_bit_mobs(self): bit_mobs = VGroup(*[ get_binary_tex_mob(n, self.num_disks) for n in range(2**(self.num_disks)) ]) bit_mobs.scale(2) self.bit_mobs_iter = it.cycle(bit_mobs) self.curr_bit_mob = next(self.bit_mobs_iter) for bit_mob in bit_mobs: bit_mob.align_data_and_family(self.curr_bit_mob) for bit, disk in zip(bit_mob, reversed(list(self.disks))): bit.set_color(disk.get_color()) bit_mobs.next_to(self.peg_labels, DOWN) self.add(self.curr_bit_mob) def get_increment_animation(self): return Succession( Transform( self.curr_bit_mob, next(self.bit_mobs_iter), lag_ratio = 0.5, path_arc = -np.pi/3 ), Animation(self.curr_bit_mob) ) class SolveSixDisksByCounting(IntroduceSolveByCounting): CONFIG = { "num_disks" : 6, "stay_on_peg" : False, "run_time_per_move" : 0.5, } def construct(self): self.initialize_bit_mobs() for disk_index in get_ruler_sequence(self.num_disks-1): self.play( self.get_increment_animation(), run_time = self.run_time_per_move, ) self.move_disk( disk_index, stay_on_peg = self.stay_on_peg, run_time = self.run_time_per_move, ) self.wait() class RecursionTime(Scene): def construct(self): keith = Keith().shift(2*DOWN+3*LEFT) morty = Mortimer().shift(2*DOWN+3*RIGHT) keith.make_eye_contact(morty) keith_kick = keith.copy().change_mode("dance_kick") keith_kick.scale(1.3) keith_kick.shift(0.5*LEFT) keith_kick.look_at(morty.eyes) keith_hooray = keith.copy().change_mode("hooray") self.add(keith, morty) bubble = keith.get_bubble(SpeechBubble, height = 2) bubble.write("Recursion time!!!") VGroup(bubble, bubble.content).shift(UP) self.play( Transform(keith, keith_kick), morty.change_mode, "happy", ShowCreation(bubble), Write(bubble.content, run_time = 1) ) self.play( morty.change_mode, "hooray", Transform(keith, keith_hooray), bubble.content.set_color_by_gradient, BLUE_A, BLUE_E ) self.play(Blink(morty)) self.wait() class RecursiveSolution(TowersOfHanoiScene): CONFIG = { "num_disks" : 4, "middle_peg_bottom" : 2*DOWN, } def construct(self): # VGroup(*self.get_mobjects()).shift(1.5*DOWN) big_disk = self.disks[-1] self.eyes = Eyes(big_disk) title = OldTexText("Move 4-tower") sub_steps = OldTexText( "Move 3-tower,", "Move disk 3,", "Move 3-tower", ) sub_steps[1].set_color(GREEN) sub_step_brace = Brace(sub_steps, UP) sub_sub_steps = OldTexText( "Move 2-tower,", "Move disk 2,", "Move 2-tower", ) sub_sub_steps[1].set_color(RED) sub_sub_steps_brace = Brace(sub_sub_steps, UP) steps = VGroup( title, sub_step_brace, sub_steps, sub_sub_steps_brace, sub_sub_steps ) steps.arrange(DOWN) steps.scale(0.7) steps.to_edge(UP) VGroup(sub_sub_steps_brace, sub_sub_steps).next_to(sub_steps[-1], DOWN) self.add(title) ##Big disk is frustrated self.play( FadeIn(self.eyes), big_disk.set_fill, GREEN, big_disk.label.set_fill, BLACK, ) big_disk.add(self.eyes) self.blink() self.wait() self.change_mode("angry") for x in range(2): self.wait() self.shake(big_disk) self.blink() self.wait() self.change_mode("plain") self.look_at(self.peg_labels[2]) self.look_at(self.disks[0]) self.blink() #Subtower move self.move_subtower_to_peg(3, 1, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[1]), FadeIn(sub_step_brace), Write(sub_steps[0], run_time = 1) ]) self.wait() self.move_disk_to_peg(0, 0, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[0].get_top()) ]) self.shake(big_disk) self.move_disk_to_peg(0, 2, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[2].get_bottom()) ]) self.change_mode("angry") self.move_disk_to_peg(0, 1, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.disks[1].get_top()) ]) self.blink() #Final moves for big case self.move_disk(3, run_time = 2, added_anims = [ Write(sub_steps[1]) ]) self.look_at(self.disks[1]) self.blink() bubble = SpeechBubble() bubble.write("I'm set!") bubble.resize_to_content() bubble.pin_to(big_disk) bubble.add_content(bubble.content) bubble.set_fill(BLACK, opacity = 0.7) self.play( ShowCreation(bubble), Write(bubble.content) ) self.wait() self.blink() self.play(*list(map(FadeOut, [bubble, bubble.content]))) big_disk.remove(self.eyes) self.move_subtower_to_peg(3, 2, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[2].get_top()), Write(sub_steps[2]) ]) self.play(FadeOut(self.eyes)) self.wait() #Highlight subproblem self.play( VGroup(*self.disks[:3]).move_to, self.pegs[1], DOWN ) self.disk_tracker = [set([]), set([0, 1, 2]), set([3])] arc = Arc(-5*np.pi/6, start_angle = 5*np.pi/6) arc.add_tip() arc.set_color(YELLOW) arc.set_width( VGroup(*self.pegs[1:]).get_width()*0.8 ) arc.next_to(self.disks[0], UP+RIGHT, buff = SMALL_BUFF) q_mark = OldTexText("?") q_mark.next_to(arc, UP) self.play( ShowCreation(arc), Write(q_mark), sub_steps[-1].set_color, YELLOW ) self.wait() self.play( GrowFromCenter(sub_sub_steps_brace), *list(map(FadeOut, [arc, q_mark])) ) #Disk 2 frustration big_disk = self.disks[2] self.eyes.move_to(big_disk.get_top(), DOWN) self.play( FadeIn(self.eyes), big_disk.set_fill, RED, big_disk.label.set_fill, BLACK ) big_disk.add(self.eyes) self.change_mode("sad") self.look_at(self.pegs[1].get_top()) self.shake(big_disk) self.blink() #Move sub-sub-tower self.move_subtower_to_peg(2, 0, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[0].get_bottom()), Write(sub_sub_steps[0]) ]) self.blink() self.move_disk_to_peg(2, 2, run_time = 2, added_anims = [ Write(sub_sub_steps[1]) ]) self.look_at(self.disks[0]) big_disk.remove(self.eyes) self.move_subtower_to_peg(2, 2, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[2].get_top()), Write(sub_sub_steps[2]) ]) self.blink() self.look_at(self.disks[-1]) #Move eyes self.play(FadeOut(self.eyes)) self.eyes.move_to(self.disks[1].get_top(), DOWN) self.play(FadeIn(self.eyes)) self.blink() self.play(FadeOut(self.eyes)) self.eyes.move_to(self.disks[3].get_top(), DOWN) self.play(FadeIn(self.eyes)) #Show process one last time big_disk = self.disks[3] big_disk.add(self.eyes) self.move_subtower_to_peg(3, 1, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[0]) ]) self.move_disk_to_peg(3, 0, run_time = 2) big_disk.remove(self.eyes) self.move_subtower_to_peg(3, 0, run_time = 2, added_anims = [ self.eyes.look_at_anim(self.pegs[0].get_top()) ]) self.blink() def shake(self, mobject, direction = UP, added_anims = []): self.play( mobject.shift, 0.2*direction, rate_func = wiggle, *added_anims ) def blink(self): self.play(self.eyes.blink_anim()) def look_at(self, point_or_mobject): self.play(self.eyes.look_at_anim(point_or_mobject)) def change_mode(self, mode): self.play(self.eyes.change_mode_anim(mode)) class KeithSaysBigToSmall(Scene): def construct(self): keith = Keith() keith.shift(2.5*DOWN + 3*LEFT) bubble = keith.get_bubble(SpeechBubble, height = 4.5) bubble.write(""" Big problem $\\Downarrow$ Smaller problem """) self.add(keith) self.play(Blink(keith)) self.play( keith.change_mode, "speaking", ShowCreation(bubble), Write(bubble.content) ) self.wait() self.play(Blink(keith)) self.wait() class CodeThisUp(Scene): def construct(self): keith = Keith() keith.shift(2*DOWN+3*LEFT) morty = Mortimer() morty.shift(2*DOWN+3*RIGHT) keith.make_eye_contact(morty) point = 2*UP+3*RIGHT bubble = keith.get_bubble(SpeechBubble, width = 4.5, height = 3) bubble.write("This is the \\\\ most efficient") self.add(morty, keith) self.play( keith.change_mode, "speaking", keith.look_at, point ) self.play( morty.change_mode, "pondering", morty.look_at, point ) self.play(Blink(keith)) self.wait(2) self.play(Blink(morty)) self.wait() self.play( keith.change_mode, "hooray", keith.look_at, morty.eyes ) self.play(Blink(keith)) self.wait() self.play( keith.change_mode, "speaking", keith.look_at, morty.eyes, ShowCreation(bubble), Write(bubble.content), morty.change_mode, "happy", morty.look_at, keith.eyes, ) self.wait() self.play(Blink(morty)) self.wait() class HanoiSolutionCode(Scene): def construct(self): pass class NoRoomForInefficiency(Scene): def construct(self): morty = Mortimer().flip() morty.shift(2.5*DOWN+3*LEFT) bubble = morty.get_bubble(SpeechBubble, width = 4) bubble.write("No room for \\\\ inefficiency") VGroup(morty, bubble, bubble.content).to_corner(DOWN+RIGHT) self.add(morty) self.play( morty.change_mode, "speaking", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.wait() class WhyDoesBinaryAchieveThis(Scene): def construct(self): keith = Keith() keith.shift(2*DOWN+3*LEFT) morty = Mortimer() morty.shift(2*DOWN+3*RIGHT) keith.make_eye_contact(morty) bubble = morty.get_bubble(SpeechBubble, width = 5, height = 3) bubble.write(""" Why does counting in binary work? """) self.add(morty, keith) self.play( morty.change_mode, "confused", morty.look_at, keith.eyes, ShowCreation(bubble), Write(bubble.content) ) self.play(keith.change_mode, "happy") self.wait() self.play(Blink(morty)) self.wait() class BothAreSelfSimilar(Scene): def construct(self): morty = Mortimer().flip() morty.shift(2.5*DOWN+3*LEFT) bubble = morty.get_bubble(SpeechBubble) bubble.write("Both are self-similar") self.add(morty) self.play( morty.change_mode, "hooray", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.wait() class LargeScaleHanoiDecomposition(TowersOfHanoiScene): CONFIG = { "num_disks" : 8, "peg_height" : 3.5, "middle_peg_bottom" : 2*DOWN, "disk_max_width" : 4, } def construct(self): self.move_subtower_to_peg(7, 1, stay_on_peg = False) self.wait() self.move_disk(7, stay_on_peg = False) self.wait() self.move_subtower_to_peg(7, 2, stay_on_peg = False) self.wait() class SolveTwoDisksByCounting(SolveSixDisksByCounting): CONFIG = { "num_disks" : 2, "stay_on_peg" : False, "run_time_per_move" : 1, "disk_max_width" : 1.5, } def construct(self): self.initialize_bit_mobs() for disk_index in 0, 1, 0: self.play(self.get_increment_animation()) self.move_disk( disk_index, stay_on_peg = False, ) self.wait() class ShowFourDiskFourBitsParallel(IntroduceSolveByCounting): CONFIG = { "num_disks" : 4, "subtask_run_time" : 1, } def construct(self): self.initialize_bit_mobs() self.counting_subtask() self.wait() self.disk_subtask() self.wait() self.play(self.get_increment_animation()) self.move_disk( self.num_disks-1, stay_on_peg = False, ) self.wait() self.counting_subtask() self.wait() self.disk_subtask() self.wait() def disk_subtask(self): sequence = get_ruler_sequence(self.num_disks-2) run_time = float(self.subtask_run_time)/len(sequence) for disk_index in get_ruler_sequence(self.num_disks-2): self.move_disk( disk_index, run_time = run_time, stay_on_peg = False, ) # curr_peg = self.disk_index_to_peg_index(0) # self.move_subtower_to_peg(self.num_disks-1, curr_peg+1) def counting_subtask(self): num_tasks = 2**(self.num_disks-1)-1 run_time = float(self.subtask_run_time)/num_tasks # for x in range(num_tasks): # self.play( # self.get_increment_animation(), # run_time = run_time # ) self.play( Succession(*[ self.get_increment_animation() for x in range(num_tasks) ]), rate_func=linear, run_time = self.subtask_run_time ) def get_increment_animation(self): return Transform( self.curr_bit_mob, next(self.bit_mobs_iter), path_arc = -np.pi/3, ) class ShowThreeDiskThreeBitsParallel(ShowFourDiskFourBitsParallel): CONFIG = { "num_disks" : 3, "subtask_run_time" : 1 } class ShowFiveDiskFiveBitsParallel(ShowFourDiskFourBitsParallel): CONFIG = { "num_disks" : 5, "subtask_run_time" : 2 } class ShowSixDiskSixBitsParallel(ShowFourDiskFourBitsParallel): CONFIG = { "num_disks" : 6, "subtask_run_time" : 2 } class CoolRight(Scene): def construct(self): morty = Mortimer() morty.shift(2*DOWN) bubble = SpeechBubble() bubble.write("Cool! right?") bubble.resize_to_content() bubble.pin_to(morty) self.play( morty.change_mode, "surprised", morty.look, OUT, ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.wait() curr_content = bubble.content bubble.write("It gets \\\\ better...") self.play( Transform(curr_content, bubble.content), morty.change_mode, "hooray", morty.look, OUT ) self.wait() self.play(Blink(morty)) self.wait() ############ Part 2 ############ class MentionLastVideo(Scene): def construct(self): keith = Keith() keith.shift(2*DOWN+3*LEFT) morty = Mortimer() morty.shift(2*DOWN+3*RIGHT) keith.make_eye_contact(morty) point = 2*UP name = OldTexText(""" Keith Schwarz (Computer Scientist) """) name.to_corner(UP+LEFT) arrow = Arrow(name.get_bottom(), keith.get_top()) self.add(morty, keith) self.play( keith.change_mode, "raise_right_hand", keith.look_at, point, morty.change_mode, "pondering", morty.look_at, point ) self.play(Blink(keith)) self.play(Write(name)) self.play(ShowCreation(arrow)) self.play(Blink(morty)) self.wait(2) self.play( morty.change_mode, "confused", morty.look_at, point ) self.play(Blink(keith)) self.wait(2) self.play( morty.change_mode, "surprised" ) self.wait() class IntroduceConstrainedTowersOfHanoi(ConstrainedTowersOfHanoiScene): CONFIG = { "middle_peg_bottom" : 2*DOWN, } def construct(self): title = OldTexText("Constrained", "Towers of Hanoi") title.set_color_by_tex("Constrained", YELLOW) title.to_edge(UP) self.play(Write(title)) self.add_arcs() self.disks.save_state() for index in 0, 0, 1, 0: self.move_disk(index) self.wait() self.wait() self.play(self.disks.restore) self.disk_tracker = [set(range(self.num_disks)), set([]), set([])] self.wait() self.move_disk_to_peg(0, 1) self.move_disk_to_peg(1, 2) self.play(ShowCreation(self.big_curved_arrow)) cross = OldTex("\\times") cross.scale(2) cross.set_fill(RED) cross.move_to(self.big_curved_arrow.get_top()) big_cross = cross.copy() big_cross.replace(self.disks[1]) big_cross.set_fill(opacity = 0.5) self.play(FadeIn(cross)) self.play(FadeIn(big_cross)) self.wait() def add_arcs(self): arc = Arc(start_angle = np.pi/6, angle = 2*np.pi/3) curved_arrow1 = VGroup(arc, arc.copy().flip()) curved_arrow2 = curved_arrow1.copy() curved_arrows = [curved_arrow1, curved_arrow2] for curved_arrow in curved_arrows: for arc in curved_arrow: arc.add_tip(tip_length = 0.15) arc.set_color(YELLOW) peg_sets = (self.pegs[:2], self.pegs[1:]) for curved_arrow, pegs in zip(curved_arrows, peg_sets): peg_group = VGroup(*pegs) curved_arrow.set_width(0.7*peg_group.get_width()) curved_arrow.next_to(peg_group, UP) self.play(ShowCreation(curved_arrow1)) self.play(ShowCreation(curved_arrow2)) self.wait() big_curved_arrow = Arc(start_angle = 5*np.pi/6, angle = -2*np.pi/3) big_curved_arrow.set_width(0.9*self.pegs.get_width()) big_curved_arrow.next_to(self.pegs, UP) big_curved_arrow.add_tip(tip_length = 0.4) big_curved_arrow.set_color(WHITE) self.big_curved_arrow = big_curved_arrow class StillRecruse(Scene): def construct(self): keith = Keith() keith.shift(2*DOWN+3*LEFT) morty = Mortimer() morty.shift(2*DOWN+3*RIGHT) keith.make_eye_contact(morty) point = 2*UP+3*RIGHT bubble = keith.get_bubble(SpeechBubble, width = 4.5, height = 3) bubble.write("You can still\\\\ use recursion") self.add(morty, keith) self.play( keith.change_mode, "speaking", ShowCreation(bubble), Write(bubble.content) ) self.play(morty.change_mode, "hooray") self.play(Blink(keith)) self.wait() self.play(Blink(morty)) self.wait() class RecursiveSolutionToConstrained(RecursiveSolution): CONFIG = { "middle_peg_bottom" : 2*DOWN, "num_disks" : 4, } def construct(self): big_disk = self.disks[-1] self.eyes = Eyes(big_disk) #Define steps breakdown text title = OldTexText("Move 4-tower") subdivisions = [ OldTexText( "\\tiny Move %d-tower,"%d, "Move disk %d,"%d, "\\, Move %d-tower, \\,"%d, "Move disk %d,"%d, "Move %d-tower"%d, ).set_color_by_tex("Move disk %d,"%d, color) for d, color in [(3, GREEN), (2, RED), (1, BLUE_C)] ] sub_steps, sub_sub_steps = subdivisions[:2] for steps in subdivisions: steps.set_width(FRAME_WIDTH-1) subdivisions.append( OldTexText("\\tiny Move disk 0, Move disk 0").set_color(BLUE) ) braces = [ Brace(steps, UP) for steps in subdivisions ] sub_steps_brace, sub_sub_steps_brace = braces[:2] steps = VGroup(title, *it.chain(*list(zip( braces, subdivisions )))) steps.arrange(DOWN) steps.to_edge(UP) steps_to_fade = VGroup( title, sub_steps_brace, *list(sub_steps[:2]) + list(sub_steps[3:]) ) self.add(title) #Initially move big disk self.play( FadeIn(self.eyes), big_disk.set_fill, GREEN, big_disk.label.set_fill, BLACK ) big_disk.add(self.eyes) big_disk.save_state() self.blink() self.look_at(self.pegs[2]) self.move_disk_to_peg(self.num_disks-1, 2, stay_on_peg = False) self.look_at(self.pegs[0]) self.blink() self.play(big_disk.restore, path_arc = np.pi/3) self.disk_tracker = [set(range(self.num_disks)), set([]), set([])] self.look_at(self.pegs[0].get_top()) self.change_mode("angry") self.shake(big_disk) self.wait() #Talk about tower blocking tower = VGroup(*self.disks[:self.num_disks-1]) blocking = OldTexText("Still\\\\", "Blocking") blocking.set_color(RED) blocking.to_edge(LEFT) blocking.shift(2*UP) arrow = Arrow(blocking.get_bottom(), tower.get_top(), buff = SMALL_BUFF) new_arrow = Arrow(blocking.get_bottom(), self.pegs[1], buff = SMALL_BUFF) VGroup(arrow, new_arrow).set_color(RED) self.play( Write(blocking[1]), ShowCreation(arrow) ) self.shake(tower, RIGHT, added_anims = [Animation(big_disk)]) self.blink() self.shake(big_disk) self.wait() self.move_subtower_to_peg(self.num_disks-1, 1, added_anims = [ Transform(arrow, new_arrow), self.eyes.look_at_anim(self.pegs[1]) ]) self.play(Write(blocking[0])) self.shake(big_disk, RIGHT) self.wait() self.blink() self.wait() self.play(FadeIn(sub_steps_brace)) self.move_subtower_to_peg(self.num_disks-1, 2, added_anims = [ FadeOut(blocking), FadeOut(arrow), self.eyes.change_mode_anim("plain", thing_to_look_at = self.pegs[2]), Write(sub_steps[0], run_time = 1), ]) self.blink() #Proceed through actual process self.move_disk_to_peg(self.num_disks-1, 1, added_anims = [ Write(sub_steps[1], run_time = 1), ]) self.wait() self.move_subtower_to_peg(self.num_disks-1, 0, added_anims = [ self.eyes.look_at_anim(self.pegs[0]), Write(sub_steps[2], run_time = 1), ]) self.blink() self.move_disk_to_peg(self.num_disks-1, 2, added_anims = [ Write(sub_steps[3], run_time = 1), ]) self.wait() big_disk.remove(self.eyes) self.move_subtower_to_peg(self.num_disks-1, 2, added_anims = [ self.eyes.look_at_anim(self.pegs[2].get_top()), Write(sub_steps[4], run_time = 1), ]) self.blink() self.play(FadeOut(self.eyes)) #Ask about subproblem sub_sub_steps_brace.set_color(WHITE) self.move_subtower_to_peg(self.num_disks-1, 0, added_anims = [ steps_to_fade.fade, 0.7, sub_steps[2].set_color, WHITE, sub_steps[2].scale, 1.2, FadeIn(sub_sub_steps_brace) ]) num_disks = self.num_disks-1 big_disk = self.disks[num_disks-1] self.eyes.move_to(big_disk.get_top(), DOWN) self.play( FadeIn(self.eyes), big_disk.set_fill, RED, big_disk.label.set_fill, BLACK, ) big_disk.add(self.eyes) self.blink() #Solve subproblem self.move_subtower_to_peg(num_disks-1, 2, added_anims = [ self.eyes.look_at_anim(self.pegs[2]), Write(sub_sub_steps[0], run_time = 1) ]) self.blink() self.move_disk_to_peg(num_disks-1, 1, added_anims = [ Write(sub_sub_steps[1], run_time = 1) ]) self.wait() self.move_subtower_to_peg(num_disks-1, 0, added_anims = [ self.eyes.look_at_anim(self.pegs[0]), Write(sub_sub_steps[2], run_time = 1) ]) self.blink() self.move_disk_to_peg(num_disks-1, 2, added_anims = [ Write(sub_sub_steps[3], run_time = 1) ]) self.wait() big_disk.remove(self.eyes) self.move_subtower_to_peg(num_disks-1, 2, added_anims = [ self.eyes.look_at_anim(self.pegs[2].get_top()), Write(sub_sub_steps[4], run_time = 1) ]) self.wait() #Show smallest subdivisions smaller_subdivision = VGroup( *list(subdivisions[2:]) + \ list(braces[2:]) ) last_subdivisions = [VGroup(braces[-1], subdivisions[-1])] for vect in LEFT, RIGHT: group = last_subdivisions[0].copy() group.to_edge(vect) steps.add(group) smaller_subdivision.add(group) last_subdivisions.append(group) smaller_subdivision.set_fill(opacity = 0) self.play( steps.shift, (FRAME_Y_RADIUS-sub_sub_steps.get_top()[1]-MED_SMALL_BUFF)*UP, self.eyes.look_at_anim(steps) ) self.play(ApplyMethod( VGroup(VGroup(braces[-2], subdivisions[-2])).set_fill, None, 1, run_time = 3, lag_ratio = 0.5, )) self.blink() for mob in last_subdivisions: self.play( ApplyMethod(mob.set_fill, None, 1), self.eyes.look_at_anim(mob) ) self.blink() self.play(FadeOut(self.eyes)) self.wait() #final movements movements = [ (0, 1), (0, 0), (1, 1), (0, 1), (0, 2), (1, 0), (0, 1), (0, 0), ] for disk_index, peg_index in movements: self.move_disk_to_peg( disk_index, peg_index, stay_on_peg = False ) self.wait() class SimpleConstrainedBreakdown(TowersOfHanoiScene): CONFIG = { "num_disks" : 4 } def construct(self): self.move_subtower_to_peg(self.num_disks-1, 2) self.wait() self.move_disk(self.num_disks-1) self.wait() self.move_subtower_to_peg(self.num_disks-1, 0) self.wait() self.move_disk(self.num_disks-1) self.wait() self.move_subtower_to_peg(self.num_disks-1, 2) self.wait() class SolveConstrainedByCounting(ConstrainedTowersOfHanoiScene): CONFIG = { "num_disks" : 5, "ternary_mob_scale_factor" : 2, } def construct(self): ternary_mobs = VGroup() for num in range(3**self.num_disks): ternary_mob = get_ternary_tex_mob(num, self.num_disks) ternary_mob.scale(self.ternary_mob_scale_factor) ternary_mob.set_color_by_gradient(*self.disk_start_and_end_colors) ternary_mobs.add(ternary_mob) ternary_mobs.next_to(self.peg_labels, DOWN) self.ternary_mob_iter = it.cycle(ternary_mobs) self.curr_ternary_mob = next(self.ternary_mob_iter) self.add(self.curr_ternary_mob) for index in get_ternary_ruler_sequence(self.num_disks-1): self.move_disk(index, stay_on_peg = False, added_anims = [ self.increment_animation() ]) def increment_animation(self): return Succession( Transform( self.curr_ternary_mob, next(self.ternary_mob_iter), lag_ratio = 0.5, path_arc = np.pi/6, ), Animation(self.curr_ternary_mob), ) class CompareNumberSystems(Scene): def construct(self): base_ten = OldTexText("Base ten") base_ten.to_corner(UP+LEFT).shift(RIGHT) binary = OldTexText("Binary") binary.to_corner(UP+RIGHT).shift(LEFT) ternary = OldTexText("Ternary") ternary.to_edge(UP) ternary.set_color(YELLOW) titles = [base_ten, binary, ternary] zero_to_nine = OldTexText(""" 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 """) zero_to_nine.next_to(base_ten, DOWN, buff = LARGE_BUFF) zero_one = OldTexText("0, 1") zero_one.next_to(binary, DOWN, buff = LARGE_BUFF) zero_one_two = OldTexText("0, 1, 2") zero_one_two.next_to(ternary, DOWN, buff = LARGE_BUFF) zero_one_two.set_color_by_gradient(BLUE, GREEN) symbols = [zero_to_nine, zero_one, zero_one_two] names = ["Digits", "Bits", "Trits?"] for mob, text in zip(symbols, names): mob.brace = Brace(mob) mob.name = mob.brace.get_text(text) zero_one_two.name.set_color_by_gradient(BLUE, GREEN) dots = OldTex("\\dots") dots.next_to(zero_one.name, RIGHT, aligned_edge = DOWN, buff = SMALL_BUFF) keith = Keith() keith.shift(2*DOWN+3*LEFT) keith.look_at(zero_one_two) morty = Mortimer() morty.shift(2*DOWN+3*RIGHT) for title, symbol in zip(titles, symbols): self.play(FadeIn(title)) added_anims = [] if title is not ternary: added_anims += [ FadeIn(symbol.brace), FadeIn(symbol.name) ] self.play(Write(symbol, run_time = 2), *added_anims) self.wait() self.play(FadeIn(keith)) self.play(keith.change_mode, "confused") self.play(keith.look_at, zero_to_nine) self.play(keith.look_at, zero_one) self.play( GrowFromCenter(zero_one_two.brace), Write(zero_one_two.name), keith.look_at, zero_one_two, ) self.play(keith.change_mode, "sassy") self.play(Blink(keith)) self.play(FadeIn(morty)) self.play( morty.change_mode, "sassy", morty.look_at, zero_one_two ) self.play(Blink(morty)) self.wait() self.play( morty.shrug, morty.look_at, keith.eyes, keith.shrug, keith.look_at, morty.eyes ) self.wait() self.play( morty.change_mode, "hesitant", morty.look_at, zero_one.name, keith.change_mode, "erm", keith.look_at, zero_one.name ) self.play(Blink(morty)) self.play(Write(dots, run_time = 3)) self.wait() class IntroduceTernaryCounting(CountingScene): CONFIG = { "base" : 3, "counting_dot_starting_position" : (FRAME_X_RADIUS-1)*RIGHT + (FRAME_Y_RADIUS-1)*UP, "count_dot_starting_radius" : 0.5, "dot_configuration_height" : 1, "ones_configuration_location" : UP+2*RIGHT, "num_scale_factor" : 2, "num_start_location" : DOWN+RIGHT, } def construct(self): for x in range(2): self.increment() self.wait() self.increment() brace = Brace(self.number_mob[-1]) threes_place = brace.get_text("Three's place") self.play( GrowFromCenter(brace), Write(threes_place) ) self.wait() for x in range(6): self.increment() self.wait() new_brace = Brace(self.number_mob[-1]) nines_place = new_brace.get_text("Nine's place") self.play( Transform(brace, new_brace), Transform(threes_place, nines_place), ) self.wait() for x in range(9): self.increment() class TernaryCountingSelfSimilarPattern(Scene): CONFIG = { "num_trits" : 3, "colors" : CountingScene.CONFIG["power_colors"][:3], } def construct(self): colors = self.colors title = OldTexText("Count to " + "2"*self.num_trits) for i, color in enumerate(colors): title[-i-1].set_color(color) steps = VGroup(*list(map(TexText, [ "Count to %s,"%("2"*(self.num_trits-1)), "Roll over,", "Count to %s,"%("2"*(self.num_trits-1)), "Roll over,", "Count to %s,"%("2"*(self.num_trits-1)), ]))) steps.arrange(RIGHT) for step in steps[::2]: for i, color in enumerate(colors[:-1]): step[-i-2].set_color(color) VGroup(*steps[1::2]).set_color(colors[-1]) steps.set_width(FRAME_WIDTH-1) brace = Brace(steps, UP) word_group = VGroup(title, brace, steps) word_group.arrange(DOWN) word_group.to_edge(UP) ternary_mobs = VGroup(*[ get_ternary_tex_mob(n, n_trits = self.num_trits) for n in range(3**self.num_trits) ]) ternary_mobs.scale(2) ternary_mob_iter = it.cycle(ternary_mobs) curr_ternary_mob = next(ternary_mob_iter) for trits in ternary_mobs: trits.align_data_and_family(curr_ternary_mob) for trit, color in zip(trits, colors): trit.set_color(color) def get_increment(): return Transform( curr_ternary_mob, next(ternary_mob_iter), lag_ratio = 0.5, path_arc = -np.pi/3 ) self.add(curr_ternary_mob, title) self.play(GrowFromCenter(brace)) for i, step in enumerate(steps): self.play(Write(step, run_time = 1)) if i%2 == 0: self.play( Succession(*[ get_increment() for x in range(3**(self.num_trits-1)-1) ]), run_time = 1 ) else: self.play(get_increment()) self.wait() class TernaryCountingSelfSimilarPatternFiveTrits(TernaryCountingSelfSimilarPattern): CONFIG = { "num_trits" : 5, "colors" : color_gradient([YELLOW, PINK, RED], 5), } class CountInTernary(IntroduceTernaryCounting): def construct(self): for x in range(9): self.increment() self.wait() class SolveConstrainedWithTernaryCounting(ConstrainedTowersOfHanoiScene): CONFIG = { "num_disks" : 4, } def construct(self): for x in range(3**self.num_disks-1): self.increment(run_time = 0.75) self.wait() def setup(self): ConstrainedTowersOfHanoiScene.setup(self) ternary_mobs = VGroup(*[ get_ternary_tex_mob(x) for x in range(3**self.num_disks) ]) ternary_mobs.scale(2) ternary_mobs.next_to(self.peg_labels, DOWN) for trits in ternary_mobs: trits.align_data_and_family(ternary_mobs[0]) trits.set_color_by_gradient(*self.disk_start_and_end_colors) self.ternary_mob_iter = it.cycle(ternary_mobs) self.curr_ternary_mob = self.ternary_mob_iter.next().copy() self.disk_index_iter = it.cycle( get_ternary_ruler_sequence(self.num_disks-1) ) self.ternary_mobs = ternary_mobs def increment(self, run_time = 1, stay_on_peg = False): self.increment_number(run_time) self.move_next_disk(run_time, stay_on_peg) def increment_number(self, run_time = 1): self.play(Transform( self.curr_ternary_mob, next(self.ternary_mob_iter), path_arc = -np.pi/3, lag_ratio = 0.5, run_time = run_time, )) def move_next_disk(self, run_time = None, stay_on_peg = False): self.move_disk( next(self.disk_index_iter), run_time = run_time, stay_on_peg = stay_on_peg ) class DescribeSolutionByCountingToConstrained(SolveConstrainedWithTernaryCounting): def construct(self): braces = [ Brace(VGroup(*self.curr_ternary_mob[:n+1])) for n in range(self.num_disks) ] words = [ brace.get_text(text) for brace, text in zip(braces, [ "Only flip last trit", "Roll over once", "Roll over twice", "Roll over three times", ]) ] #Count 1, 2 color = YELLOW brace = braces[0] word = words[0] words[0].set_color(color) self.increment_number() self.play( FadeIn(brace), Write(word, run_time = 1), self.curr_ternary_mob[0].set_color, color ) self.wait() self.play( self.disks[0].set_fill, color, self.disks[0].label.set_fill, BLACK, ) self.move_next_disk(stay_on_peg = True) self.wait() self.ternary_mobs[2][0].set_color(color) self.increment_number() self.move_next_disk(stay_on_peg = True) self.wait() #Count 10 color = MAROON_B words[1].set_color(color) self.increment_number() self.play( Transform(brace, braces[1]), Transform(word, words[1]), self.curr_ternary_mob[1].set_color, color ) self.wait() self.play( self.disks[1].set_fill, color, self.disks[1].label.set_fill, BLACK, ) self.move_next_disk(stay_on_peg = True) self.wait() self.play(*list(map(FadeOut, [brace, word]))) #Count up to 22 for x in range(5): self.increment() self.wait() #Count to 100 color = RED words[2].set_color(color) self.wait() self.increment_number() self.play( FadeIn(braces[2]), Write(words[2], run_time = 1), self.curr_ternary_mob[2].set_fill, color, self.disks[2].set_fill, color, self.disks[2].label.set_fill, BLACK, ) self.wait() self.move_next_disk(stay_on_peg = True) self.wait() self.play(*list(map(FadeOut, [braces[2], words[2]]))) for x in range(20): self.increment() class Describe2222(Scene): def construct(self): ternary_mob = OldTex("2222").scale(1.5) brace = Brace(ternary_mob) description = brace.get_text("$3^4 - 1 = 80$") VGroup(ternary_mob, brace, description).scale(1.5) self.add(ternary_mob) self.wait() self.play(GrowFromCenter(brace)) self.play(Write(description)) self.wait() class KeithAsksAboutConfigurations(Scene): def construct(self): keith = Keith().shift(2*DOWN+3*LEFT) morty = Mortimer().shift(2*DOWN+3*RIGHT) keith.make_eye_contact(morty) bubble = keith.get_bubble(SpeechBubble) bubble.write("Think about how many \\\\ configurations there are.") self.add(keith, morty) self.play(Blink(keith)) self.play( keith.change_mode, "speaking", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.play(morty.change_mode, "pondering") self.wait() class AskAboutConfigurations(SolveConstrainedWithTernaryCounting): def construct(self): question = OldTexText("How many configurations?") question.scale(1.5) question.to_edge(UP) self.add(question) for x in range(15): self.remove(self.curr_ternary_mob) self.wait(2) for y in range(7): self.increment(run_time = 0) class AnswerConfigurationsCount(TowersOfHanoiScene): CONFIG = { "middle_peg_bottom" : 2.5*DOWN, "num_disks" : 4, "peg_height" : 1.5, } def construct(self): answer = OldTexText("$3^4 = 81$ configurations") answer.to_edge(UP) self.add(answer) parentheticals = self.get_parentheticals(answer) self.prepare_disks() for parens, disk in zip(parentheticals, reversed(list(self.disks))): VGroup(parens, parens.brace, parens.three).set_color(disk.get_color()) self.play( Write(parens, run_time = 1), FadeIn(disk) ) self.play( ApplyMethod( disk.next_to, self.pegs[2], UP, run_time = 2 ), GrowFromCenter(parens.brace), Write(parens.three, run_time = 1) ) x_diff = disk.saved_state.get_center()[0]-disk.get_center()[0] self.play( disk.shift, x_diff*RIGHT ) self.play(disk.restore) self.wait() def get_parentheticals(self, top_mob): parentheticals = VGroup(*reversed([ OldTex(""" \\left( \\begin{array}{c} \\text{Choices for} \\\\ \\text{disk %d} \\end{array} \\right) """%d) for d in range(self.num_disks) ])) parentheticals.arrange() parentheticals.set_width(FRAME_WIDTH-1) parentheticals.next_to(top_mob, DOWN) for parens in parentheticals: brace = Brace(parens) three = brace.get_text("$3$") parens.brace = brace parens.three = three return parentheticals def prepare_disks(self): configuration = [1, 2, 1, 0] for n, peg_index in enumerate(configuration): disk_index = self.num_disks-n-1 disk = self.disks[disk_index] top = Circle(radius = disk.get_width()/2) inner = Circle(radius = self.peg_width/2) inner.flip() top.add_subpath(inner.points) top.set_stroke(width = 0) top.set_fill(disk.get_color()) top.rotate(np.pi/2, RIGHT) top.move_to(disk, UP) bottom = top.copy() bottom.move_to(disk, DOWN) disk.remove(disk.label) disk.add(top, bottom, disk.label) self.move_disk_to_peg(disk_index, peg_index, run_time = 0) if disk_index == 0: disk.move_to(self.pegs[peg_index].get_bottom(), DOWN) for disk in self.disks: disk.save_state() disk.rotate(np.pi/30, RIGHT) disk.next_to(self.pegs[0], UP) self.remove(self.disks) class ThisIsMostEfficientText(Scene): def construct(self): text = OldTexText("This is the most efficient solution") text.set_width(FRAME_WIDTH - 1) text.to_edge(DOWN) self.play(Write(text)) self.wait(2) class RepeatingConfiguraiton(Scene): def construct(self): dots = VGroup(*[Dot() for x in range(10)]) arrows = VGroup(*[Arrow(LEFT, RIGHT) for x in range(9)]) arrows.add(VGroup()) arrows.scale(0.5) group = VGroup(*it.chain(*list(zip(dots, arrows)))) group.arrange() title = OldTexText("Same state twice") title.shift(3*UP) special_dots = VGroup(dots[2], dots[6]) special_arrows = VGroup(*[ Arrow(title.get_bottom(), dot, color = RED) for dot in special_dots ]) mid_mobs = VGroup(*group[5:14]) mid_arrow = Arrow(dots[2], dots[7], tip_length = 0.125) more_efficient = OldTexText("More efficient") more_efficient.next_to(mid_arrow, UP) self.play(ShowCreation(group, run_time = 2)) self.play(Write(title)) self.play( ShowCreation(special_arrows), special_dots.set_color, RED ) self.wait() self.play( mid_mobs.shift, 2*DOWN, FadeOut(special_arrows) ) self.play( ShowCreation(mid_arrow), Write(more_efficient) ) self.wait() class ShowSomeGraph(Scene): def construct(self): title = OldTexText("Graphs") title.scale(2) title.to_edge(UP) nodes = VGroup(*list(map(Dot, [ 2*LEFT, UP, DOWN, 2*RIGHT, 2*RIGHT+2*UP, 2*RIGHT+2*DOWN, 4*RIGHT+2*UP, ]))) edge_pairs = [ (0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (3, 5), (4, 6), ] edges = VGroup() for i, j in edge_pairs: edges.add(Line( nodes[i].get_center(), nodes[j].get_center(), )) self.play(Write(title)) for mob in nodes, edges: mob.set_color_by_gradient(YELLOW, MAROON_B) self.play(ShowCreation( mob, lag_ratio = 0.5, run_time = 2, )) self.wait() class SierpinskiGraphScene(Scene): CONFIG = { "num_disks" : 3, "towers_config" : { "num_disks" : 3, "peg_height" : 1.5, "peg_spacing" : 2, "include_peg_labels" : False, "disk_min_width" : 1, "disk_max_width" : 2, }, "preliminary_node_radius" : 1, "center_to_island_length" : 2.0, "include_towers" : True, "start_color" : RED, "end_color" : GREEN, "graph_stroke_width" : 2, } def setup(self): self.initialize_nodes() self.add(self.nodes) self.initialize_edges() self.add(self.edges) def initialize_nodes(self): circles = self.get_node_circles(self.num_disks) circles.set_color_by_gradient(self.start_color, self.end_color) circles.set_fill(BLACK, opacity = 0.7) circles.set_stroke(width = self.graph_stroke_width) self.nodes = VGroup() for circle in circles.get_family(): if not isinstance(circle, Circle): continue node = VGroup() node.add(circle) node.circle = circle self.nodes.add(node) if self.include_towers: self.add_towers_to_nodes() self.nodes.set_height(FRAME_HEIGHT-2) self.nodes.to_edge(UP) def get_node_circles(self, order = 3): if order == 0: return Circle(radius = self.preliminary_node_radius) islands = [self.get_node_circles(order-1) for x in range(3)] for island, angle in (islands[0], np.pi/6), (islands[2], 5*np.pi/6): island.rotate( np.pi, rotate_vector(RIGHT, angle), about_point = island.get_center_of_mass() ) for n, island in enumerate(islands): vect = rotate_vector(RIGHT, -5*np.pi/6-n*2*np.pi/3) island.scale(0.5) island.shift(vect) return VGroup(*islands) def add_towers_to_nodes(self): towers_scene = ConstrainedTowersOfHanoiScene(**self.towers_config) tower_scene_group = VGroup(*towers_scene.get_mobjects()) ruler_sequence = get_ternary_ruler_sequence(self.num_disks-1) self.disks = VGroup(*[VGroup() for x in range(self.num_disks)]) for disk_index, node in zip(ruler_sequence+[0], self.nodes): towers = tower_scene_group.copy() for mob in towers: if hasattr(mob, "label"): self.disks[int(mob.label.tex_string)].add(mob) towers.set_width(0.85*node.get_width()) towers.move_to(node) node.towers = towers node.add(towers) towers_scene.move_disk(disk_index, run_time = 0) def distance_between_nodes(self, i, j): return get_norm( self.nodes[i].get_center()-\ self.nodes[j].get_center() ) def initialize_edges(self): edges = VGroup() self.edge_dict = {} min_distance = self.distance_between_nodes(0, 1) min_distance *= 1.1 ##Just a little buff to be sure node_radius = self.nodes[0].get_width()/2 for i, j in it.combinations(list(range(3**self.num_disks)), 2): center1 = self.nodes[i].get_center() center2 = self.nodes[j].get_center() vect = center1-center2 distance = get_norm(center1 - center2) if distance < min_distance: edge = Line( center1 - (vect/distance)*node_radius, center2 + (vect/distance)*node_radius, color = self.nodes[i].circle.get_stroke_color(), stroke_width = self.graph_stroke_width, ) edges.add(edge) self.edge_dict[self.node_indices_to_key(i, j)] = edge self.edges = edges def node_indices_to_key(self, i, j): return ",".join(map(str, sorted([i, j]))) def node_indices_to_edge(self, i, j): key = self.node_indices_to_key(i, j) if key not in self.edge_dict: warnings.warn("(%d, %d) is not an edge"%(i, j)) return VGroup() return self.edge_dict[key] def zoom_into_node(self, node_index, order = 0): start_index = node_index - node_index%(3**order) node_indices = [start_index + r for r in range(3**order)] self.zoom_into_nodes(node_indices) def zoom_into_nodes(self, node_indices): nodes = VGroup(*[ self.nodes[index].circle for index in node_indices ]) everything = VGroup(*self.get_mobjects()) if nodes.get_width()/nodes.get_height() > FRAME_X_RADIUS/FRAME_Y_RADIUS: scale_factor = (FRAME_WIDTH-2)/nodes.get_width() else: scale_factor = (FRAME_HEIGHT-2)/nodes.get_height() self.play( everything.shift, -nodes.get_center(), everything.scale, scale_factor ) self.remove(everything) self.add(*everything) self.wait() class IntroduceGraphStructure(SierpinskiGraphScene): CONFIG = { "include_towers" : True, "graph_stroke_width" : 3, "num_disks" : 3, } def construct(self): self.remove(self.nodes, self.edges) self.introduce_nodes() self.define_edges() self.tour_structure() def introduce_nodes(self): self.play(FadeIn( self.nodes, run_time = 3, lag_ratio = 0.5, )) vect = LEFT for index in 3, 21, 8, 17, 10, 13: node = self.nodes[index] node.save_state() self.play( node.set_height, FRAME_HEIGHT-2, node.next_to, ORIGIN, vect ) self.wait() self.play(node.restore) node.saved_state = None vect = -vect def define_edges(self): nodes = [self.nodes[i] for i in (12, 14)] for node, vect in zip(nodes, [LEFT, RIGHT]): node.save_state() node.generate_target() node.target.set_height(5) node.target.center() node.target.to_edge(vect) arc = Arc(angle = -2*np.pi/3, start_angle = 5*np.pi/6) if vect is RIGHT: arc.flip() arc.set_width(0.8*node.target.towers.get_width()) arc.next_to(node.target.towers, UP) arc.add_tip() arc.set_color(YELLOW) node.arc = arc self.play(*list(map(MoveToTarget, nodes))) edge = Line( nodes[0].get_right(), nodes[1].get_left(), color = YELLOW, stroke_width = 6, ) edge.target = self.node_indices_to_edge(12, 14) self.play(ShowCreation(edge)) self.wait() for node in nodes: self.play(ShowCreation(node.arc)) self.wait() self.play(*[ FadeOut(node.arc) for node in nodes ]) self.play( MoveToTarget(edge), *[node.restore for node in nodes] ) self.wait() self.play(ShowCreation(self.edges, run_time = 3)) self.wait() def tour_structure(self): for n in range(3): self.zoom_into_node(n) self.zoom_into_node(0, 1) self.play( self.disks[0].set_color, YELLOW, *[ ApplyMethod(disk.label.set_color, BLACK) for disk in self.disks[0] ] ) self.wait() self.zoom_into_node(0, 3) self.zoom_into_node(15, 1) self.wait() self.zoom_into_node(20, 1) self.wait() class DescribeTriforcePattern(SierpinskiGraphScene): CONFIG = { "index_pairs" : [(7, 1), (2, 3), (5, 6)], "scale" : 2, "disk_color" : MAROON_B, "include_towers" : True, "first_connect_0_and_2_islands" : True, #Dumb that I have to do this } def construct(self): index_pair = self.index_pairs[0] self.zoom_into_node(index_pair[0], self.scale) self.play( self.disks[self.scale-1].set_color, self.disk_color, *[ ApplyMethod(disk.label.set_color, BLACK) for disk in self.disks[self.scale-1] ] ) nodes = [self.nodes[i] for i in index_pair] for node, vect in zip(nodes, [LEFT, RIGHT]): node.save_state() node.generate_target() node.target.set_height(6) node.target.center().next_to(ORIGIN, vect) self.play(*list(map(MoveToTarget, nodes))) self.wait() self.play(*[node.restore for node in nodes]) bold_edges = [ self.node_indices_to_edge(*pair).copy().set_stroke(self.disk_color, 6) for pair in self.index_pairs ] self.play(ShowCreation(bold_edges[0])) self.wait() self.play(*list(map(ShowCreation, bold_edges[1:]))) self.wait() power_of_three = 3**(self.scale-1) index_sets = [ list(range(0, power_of_three)), list(range(power_of_three, 2*power_of_three)), list(range(2*power_of_three, 3*power_of_three)), ] if self.first_connect_0_and_2_islands: index_sets = [index_sets[0], index_sets[2], index_sets[1]] islands = [ VGroup(*[self.nodes[i] for i in index_set]) for index_set in index_sets ] def wiggle_island(island): return ApplyMethod( island.rotate, np.pi/12, run_time = 1, rate_func = wiggle ) self.play(*list(map(wiggle_island, islands[:2]))) self.wait() self.play(wiggle_island(islands[2])) self.wait() for index_set in index_sets: self.zoom_into_nodes(index_set) self.zoom_into_nodes(list(it.chain(*index_sets))) self.wait() class TriforcePatternWord(Scene): def construct(self): word = OldTexText("Triforce \\\\ pattern") word.scale(2) word.to_corner(DOWN+RIGHT) self.play(Write(word)) self.wait(2) class DescribeOrderTwoPattern(DescribeTriforcePattern): CONFIG = { "index_pairs" : [(8, 9), (17, 18), (4, 22)], "scale" : 3, "disk_color" : RED, "first_connect_0_and_2_islands" : False, } class BiggerTowers(SierpinskiGraphScene): CONFIG = { "num_disks" : 6, "include_towers" : False } def construct(self): for order in range(3, 7): self.zoom_into_node(0, order) class ShowPathThroughGraph(SierpinskiGraphScene): CONFIG = { "include_towers" : True } def construct(self): arrows = VGroup(*[ Arrow( n1.get_center(), n2.get_center(), tip_length = 0.15, buff = 0.15 ) for n1, n2 in zip(self.nodes, self.nodes[1:]) ]) self.wait() self.play(ShowCreation( arrows, rate_func=linear, run_time = 5 )) self.wait(2) for index in range(9): self.zoom_into_node(index) class MentionFinalAnimation(Scene): def construct(self): morty = Mortimer() morty.shift(2*DOWN+3*RIGHT) bubble = morty.get_bubble(SpeechBubble, width = 6) bubble.write("Before the final\\\\ animation...") self.add(morty) self.wait() self.play( morty.change_mode, "speaking", morty.look_at, bubble.content, ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(morty)) self.wait(2) self.play(Blink(morty)) self.wait(2) class PatreonThanks(Scene): CONFIG = { "specific_patrons" : [ "CrypticSwarm", "Ali Yahya", "Juan Batiz-Benet", "Yu Jun", "Othman Alikhan", "Joseph John Cox", "Luc Ritchie", "Einar Johansen", "Rish Kundalia", "Achille Brighton", "Kirk Werklund", "Ripta Pasay", "Felipe Diniz", ] } def construct(self): morty = Mortimer() morty.next_to(ORIGIN, DOWN) n_patrons = len(self.specific_patrons) special_thanks = OldTexText("Special thanks to:") special_thanks.set_color(YELLOW) special_thanks.shift(3*UP) left_patrons = VGroup(*list(map(TexText, self.specific_patrons[:n_patrons/2] ))) right_patrons = VGroup(*list(map(TexText, self.specific_patrons[n_patrons/2:] ))) for patrons, vect in (left_patrons, LEFT), (right_patrons, RIGHT): patrons.arrange(DOWN, aligned_edge = LEFT) patrons.next_to(special_thanks, DOWN) patrons.to_edge(vect, buff = LARGE_BUFF) self.play(morty.change_mode, "gracious") self.play(Write(special_thanks, run_time = 1)) self.play( Write(left_patrons), morty.look_at, left_patrons ) self.play( Write(right_patrons), morty.look_at, right_patrons ) self.play(Blink(morty)) for patrons in left_patrons, right_patrons: for index in 0, -1: self.play(morty.look_at, patrons[index]) self.wait() class MortyLookingAtRectangle(Scene): def construct(self): morty = Mortimer() morty.to_corner(DOWN+RIGHT) url = OldTexText("www.desmos.com/careers") url.to_corner(UP+LEFT) rect = Rectangle(height = 9, width = 16) rect.set_height(5) rect.next_to(url, DOWN) rect.shift_onto_screen() url.save_state() url.next_to(morty.get_corner(UP+LEFT), UP) self.play(morty.change_mode, "raise_right_hand") self.play(Write(url)) self.play(Blink(morty)) self.wait() self.play( url.restore, morty.change_mode, "happy" ) self.play(ShowCreation(rect)) self.wait() self.play(Blink(morty)) self.wait() class ShowSierpinskiCurvesOfIncreasingOrder(Scene): CONFIG = { "sierpinski_graph_scene_config" :{ "include_towers" : False }, "min_order" : 2, "max_order" : 7, "path_stroke_width" : 7, } def construct(self): graph_scenes = [ SierpinskiGraphScene( num_disks = order, **self.sierpinski_graph_scene_config ) for order in range(self.min_order, self.max_order+1) ] paths = [self.get_path(scene) for scene in graph_scenes] graphs = [] for scene in graph_scenes: graphs.append(scene.nodes) for graph in graphs: graph.set_fill(opacity = 0) graph, path = graphs[0], paths[0] self.add(graph) self.wait() self.play(ShowCreation(path, run_time = 3, rate_func=linear)) self.wait() self.play(graph.fade, 0.5, Animation(path)) for other_graph in graphs[1:]: other_graph.fade(0.5) self.wait() for new_graph, new_path in zip(graphs[1:], paths[1:]): self.play( Transform(graph, new_graph), Transform(path, new_path), run_time = 2 ) self.wait() self.path = path def get_path(self, graph_scene): path = VGroup() nodes = graph_scene.nodes for n1, n2, n3 in zip(nodes, nodes[1:], nodes[2:]): segment = VMobject() segment.set_points_as_corners([ n1.get_center(), n2.get_center(), n3.get_center(), ]) path.add(segment) path.set_color_by_gradient( graph_scene.start_color, graph_scene.end_color, ) path.set_stroke( width = self.path_stroke_width - graph_scene.num_disks/2 ) return path class Part1Thumbnail(Scene): CONFIG = { "part_number" : 1, "sierpinski_order" : 5 } def construct(self): toh_scene = TowersOfHanoiScene( peg_spacing = 2, part_number = 1, ) toh_scene.remove(toh_scene.peg_labels) toh_scene.pegs[2].set_fill(opacity = 0.5) toh = VGroup(*toh_scene.get_mobjects()) toh.scale(2) toh.to_edge(DOWN) self.add(toh) sierpinski_scene = ShowSierpinskiCurvesOfIncreasingOrder( min_order = self.sierpinski_order, max_order = self.sierpinski_order, skip_animations = True, ) sierpinski_scene.path.set_stroke(width = 10) sierpinski = VGroup(*sierpinski_scene.get_mobjects()) sierpinski.scale(0.9) sierpinski.to_corner(DOWN+RIGHT) self.add(sierpinski) binary = OldTex("01011") binary.set_color_by_tex("0", GREEN) binary.set_color_by_tex("1", BLUE) binary.set_color_by_gradient(GREEN, RED) binary.add_background_rectangle() binary.background_rectangle.set_fill(opacity = 0.5) # binary.set_fill(opacity = 0.5) binary.scale(4) binary.to_corner(UP+LEFT) self.add(binary) part = OldTexText("Part %d"%self.part_number) part.scale(4) part.to_corner(UP+RIGHT) part.add_background_rectangle() self.add(part) class Part2Thumbnail(Part1Thumbnail): CONFIG = { "part_number" : 2 }
videos_3b1b/_2016/fractal_charm.py
from manim_imports_ext import * class FractalCreation(Scene): CONFIG = { "fractal_class" : PentagonalFractal, "max_order" : 5, "transform_kwargs" : { "path_arc" : np.pi/6, "lag_ratio" : 0.5, "run_time" : 2, }, "fractal_kwargs" : {}, } def construct(self): fractal = self.fractal_class(order = 0, **self.fractal_kwargs) self.play(FadeIn(fractal)) for order in range(1, self.max_order+1): new_fractal = self.fractal_class( order = order, **self.fractal_kwargs ) fractal.align_data_and_family(new_fractal) self.play(Transform( fractal, new_fractal, **self.transform_kwargs )) self.wait() self.wait() self.fractal = fractal class PentagonalFractalCreation(FractalCreation): pass class DiamondFractalCreation(FractalCreation): CONFIG = { "fractal_class" : DiamondFractal, "max_order" : 6, "fractal_kwargs" : {"height" : 6} } class PiCreatureFractalCreation(FractalCreation): CONFIG = { "fractal_class" : PiCreatureFractal, "max_order" : 6, "fractal_kwargs" : {"height" : 6}, "transform_kwargs" : { "lag_ratio" : 0, "run_time" : 2, }, } def construct(self): FractalCreation.construct(self) fractal = self.fractal smallest_pi = fractal[0][0] zoom_factor = 0.1/smallest_pi.get_height() fractal.generate_target() fractal.target.shift(-smallest_pi.get_corner(UP+LEFT)) fractal.target.scale(zoom_factor) self.play(MoveToTarget(fractal, run_time = 10)) self.wait() class QuadraticKochFractalCreation(FractalCreation): CONFIG = { "fractal_class" : QuadraticKoch, "max_order" : 5, "fractal_kwargs" : {"radius" : 10}, # "transform_kwargs" : { # "lag_ratio" : 0, # "run_time" : 2, # }, } class KochSnowFlakeFractalCreation(FractalCreation): CONFIG = { "fractal_class" : KochSnowFlake, "max_order" : 6, "fractal_kwargs" : { "radius" : 6, "num_submobjects" : 100, }, "transform_kwargs" : { "lag_ratio" : 0.5, "path_arc" : np.pi/6, "run_time" : 2, }, } class WonkyHexagonFractalCreation(FractalCreation): CONFIG = { "fractal_class" : WonkyHexagonFractal, "max_order" : 5, "fractal_kwargs" : {"height" : 6}, } class SierpinskiFractalCreation(FractalCreation): CONFIG = { "fractal_class" : Sierpinski, "max_order" : 6, "fractal_kwargs" : {"height" : 6}, "transform_kwargs" : { "path_arc" : 0, }, } class CircularFractalCreation(FractalCreation): CONFIG = { "fractal_class" : CircularFractal, "max_order" : 5, "fractal_kwargs" : {"height" : 6}, }
videos_3b1b/_2016/triangle_of_power/triangle.py
import numbers from manim_imports_ext import * from functools import reduce OPERATION_COLORS = [YELLOW, GREEN, BLUE_B] def get_equation(index, x = 2, y = 3, z = 8, expression_only = False): assert(index in [0, 1, 2]) if index == 0: tex1 = "\\sqrt[%d]{%d}"%(y, z), tex2 = " = %d"%x elif index == 1: tex1 = "\\log_%d(%d)"%(x, z), tex2 = " = %d"%y elif index == 2: tex1 = "%d^%d"%(x, y), tex2 = " = %d"%z if expression_only: tex = tex1 else: tex = tex1+tex2 return OldTex(tex).set_color(OPERATION_COLORS[index]) def get_inverse_rules(): return list(map(Tex, [ "x^{\\log_x(z)} = z", "\\log_x\\left(x^y \\right) = y", "\\sqrt[y]{x^y} = x", "\\left(\\sqrt[y]{z}\\right)^y = z", "\\sqrt[\\log_x(z)]{z} = x", "\\log_{\\sqrt[y]{z}}(z) = y", ])) def get_top_inverse_rules(): result = [] pairs = [#Careful of order here! (0, 2), (0, 1), (1, 0), (1, 2), (2, 0), (2, 1), ] for i, j in pairs: top = get_top_inverse(i, j) char = ["x", "y", "z"][j] eq = OldTex("= %s"%char) eq.scale(2) eq.next_to(top, RIGHT) diff = eq.get_center() - top.triangle.get_center() eq.shift(diff[1]*UP) result.append(VMobject(top, eq)) return result def get_top_inverse(i, j): args = [None]*3 k = set([0, 1, 2]).difference([i, j]).pop() args[i] = ["x", "y", "z"][i] big_top = TOP(*args) args[j] = ["x", "y", "z"][j] lil_top = TOP(*args, triangle_height_to_number_height = 1.5) big_top.set_value(k, lil_top) return big_top class TOP(VMobject): CONFIG = { "triangle_height_to_number_height" : 3, "offset_multiple" : 1.5, "radius" : 1.5, } def __init__(self, x = None, y = None, z = None, **kwargs): digest_config(self, kwargs, locals()) VMobject.__init__(self, **kwargs) def init_points(self): vertices = [ self.radius*rotate_vector(RIGHT, 7*np.pi/6 - i*2*np.pi/3) for i in range(3) ] self.triangle = Polygon( *vertices, color = WHITE, stroke_width = 5 ) self.values = [VMobject()]*3 self.set_values(self.x, self.y, self.z) def set_values(self, x, y, z): for i, mob in enumerate([x, y, z]): self.set_value(i, mob) def set_value(self, index, value): self.values[index] = self.put_on_vertex(index, value) self.reset_submobjects() def put_on_vertex(self, index, value): assert(index in [0, 1, 2]) if value is None: value = VectorizedPoint() if isinstance(value, numbers.Number): value = str(value) if isinstance(value, str): value = OldTex(value) if isinstance(value, TOP): return self.put_top_on_vertix(index, value) self.rescale_corner_mobject(value) value.center() if index == 0: offset = -value.get_corner(UP+RIGHT) elif index == 1: offset = -value.get_bottom() elif index == 2: offset = -value.get_corner(UP+LEFT) value.shift(self.offset_multiple*offset) anchors = self.triangle.get_anchors_and_handles()[0] value.shift(anchors[index]) return value def put_top_on_vertix(self, index, top): top.set_height(2*self.get_value_height()) vertices = np.array(top.get_vertices()) vertices[index] = 0 start = reduce(op.add, vertices)/2 end = self.triangle.get_anchors_and_handles()[0][index] top.shift(end-start) return top def put_in_vertex(self, index, mobject): self.rescale_corner_mobject(mobject) mobject.center() mobject.shift(interpolate( self.get_center(), self.get_vertices()[index], 0.7 )) return mobject def get_surrounding_circle(self, color = YELLOW): return Circle( radius = 1.7*self.radius, color = color ).shift( self.triangle.get_center(), (self.triangle.get_height()/6)*DOWN ) def rescale_corner_mobject(self, mobject): mobject.set_height(self.get_value_height()) return self def get_value_height(self): return self.triangle.get_height()/self.triangle_height_to_number_height def get_center(self): return center_of_mass(self.get_vertices()) def get_vertices(self): return self.triangle.get_anchors_and_handles()[0][:3] def reset_submobjects(self): self.submobjects = [self.triangle] + self.values return self class IntroduceNotation(Scene): def construct(self): top = TOP() equation = OldTex("2^3 = 8") equation.to_corner(UP+LEFT) two, three, eight = [ top.put_on_vertex(i, num) for i, num in enumerate([2, 3, 8]) ] self.play(FadeIn(equation)) self.wait() self.play(ShowCreation(top)) for num in two, three, eight: self.play(ShowCreation(num), run_time=2) self.wait() class ShowRule(Scene): args_list = [(0,), (1,), (2,)] @staticmethod def args_to_string(index): return str(index) @staticmethod def string_to_args(index_string): result = int(index_string) assert(result in [0, 1, 2]) return result def construct(self, index): equation = get_equation(index) equation.to_corner(UP+LEFT) top = TOP(2, 3, 8) new_top = top.copy() equals = OldTex("=").scale(1.5) new_top.next_to(equals, LEFT, buff = 1) new_top.values[index].next_to(equals, RIGHT, buff = 1) circle = Circle( radius = 1.7*top.radius, color = OPERATION_COLORS[index] ) self.add(equation, top) self.wait() self.play( Transform(top, new_top), ShowCreation(equals) ) circle.shift(new_top.triangle.get_center_of_mass()) new_circle = circle.copy() new_top.put_on_vertex(index, new_circle) self.wait() self.play(ShowCreation(circle)) self.wait() self.play( Transform(circle, new_circle), ApplyMethod(new_top.values[index].set_color, circle.color) ) self.wait() class AllThree(Scene): def construct(self): tops = [] equations = [] args = (2, 3, 8) for i in 2, 1, 0: new_args = list(args) new_args[i] = None top = TOP(*new_args, triangle_height_to_number_height = 2) # top.set_color(OPERATION_COLORS[i]) top.shift(i*4.5*LEFT) equation = get_equation(i, expression_only = True) equation.scale(3) equation.next_to(top, DOWN, buff = 0.7) tops.append(top) equations.append(equation) VMobject(*tops+equations).center() # name = OldTexText("Triangle of Power") # name.to_edge(UP) for top, eq in zip(tops, equations): self.play(FadeIn(top), FadeIn(eq)) self.wait(3) # self.play(Write(name)) self.wait() class SixDifferentInverses(Scene): def construct(self): rules = get_inverse_rules() vects = it.starmap(op.add, it.product( [3*UP, 0.5*UP, 2*DOWN], [2*LEFT, 2*RIGHT] )) for rule, vect in zip(rules, vects): rule.shift(vect) general_idea = OldTex("f(f^{-1}(a)) = a") self.play(Write(VMobject(*rules))) self.wait() for s, color in (rules[:4], GREEN), (rules[4:], RED): mob = VMobject(*s) self.play(ApplyMethod(mob.set_color, color)) self.wait() self.play(ApplyMethod(mob.set_color, WHITE)) self.play( ApplyMethod(VMobject(*rules[::2]).to_edge, LEFT), ApplyMethod(VMobject(*rules[1::2]).to_edge, RIGHT), GrowFromCenter(general_idea) ) self.wait() top_rules = get_top_inverse_rules() for rule, top_rule in zip(rules, top_rules): top_rule.set_height(1.5) top_rule.center() top_rule.shift(rule.get_center()) self.play(*list(map(FadeOut, rules))) self.remove(*rules) self.play(*list(map(GrowFromCenter, top_rules))) self.wait() self.remove(general_idea) rules = get_inverse_rules() original = None for i, (top_rule, rule) in enumerate(zip(top_rules, rules)): rule.center().to_edge(UP) rule.set_color(GREEN if i < 4 else RED) self.add(rule) new_top_rule = top_rule.copy().center().scale(1.5) anims = [Transform(top_rule, new_top_rule)] if original is not None: anims.append(FadeIn(original)) original = top_rule.copy() self.play(*anims) self.wait() self.animate_top_rule(top_rule) self.remove(rule) def animate_top_rule(self, top_rule): lil_top, lil_symbol, symbol_index = None, None, None big_top = top_rule.submobjects[0] equals, right_symbol = top_rule.submobjects[1].split() for i, value in enumerate(big_top.values): if isinstance(value, TOP): lil_top = value elif isinstance(value, Tex): symbol_index = i else: lil_symbol_index = i lil_symbol = lil_top.values[lil_symbol_index] assert(lil_top is not None and lil_symbol is not None) cancel_parts = [ VMobject(top.triangle, top.values[symbol_index]) for top in (lil_top, big_top) ] new_symbol = lil_symbol.copy() new_symbol.replace(right_symbol) vect = equals.get_center() - right_symbol.get_center() new_symbol.shift(2*vect[0]*RIGHT) self.play( Transform(*cancel_parts, rate_func = rush_into) ) self.play( FadeOut(VMobject(*cancel_parts)), Transform(lil_symbol, new_symbol, rate_func = rush_from) ) self.wait() self.remove(lil_symbol, top_rule, VMobject(*cancel_parts)) class SixSixSix(Scene): def construct(self): randy = Randolph(mode = "pondering").to_corner() bubble = ThoughtBubble().pin_to(randy) rules = get_inverse_rules() sixes = OldTex(["6", "6", "6"], next_to_buff = 1) sixes.to_corner(UP+RIGHT) sixes = sixes.split() speech_bubble = SpeechBubble() speech_bubble.pin_to(randy) speech_bubble.write("I'll just study art!") self.add(randy) self.play(ShowCreation(bubble)) bubble.add_content(VectorizedPoint()) for i, rule in enumerate(rules): if i%2 == 0: anim = ShowCreation(sixes[i/2]) else: anim = Blink(randy) self.play( ApplyMethod(bubble.add_content, rule), anim ) self.wait() self.wait() words = speech_bubble.content equation = bubble.content speech_bubble.clear() bubble.clear() self.play( ApplyMethod(randy.change_mode, "angry"), Transform(bubble, speech_bubble), Transform(equation, words), FadeOut(VMobject(*sixes)) ) self.wait() class AdditiveProperty(Scene): def construct(self): exp_rule, log_rule = self.write_old_style_rules() t_exp_rule, t_log_rule = self.get_new_style_rules() self.play( ApplyMethod(exp_rule.to_edge, UP), ApplyMethod(log_rule.to_edge, DOWN, 1.5) ) t_exp_rule.next_to(exp_rule, DOWN) t_exp_rule.set_color(GREEN) t_log_rule.next_to(log_rule, UP) t_log_rule.set_color(RED) self.play( FadeIn(t_exp_rule), FadeIn(t_log_rule), ApplyMethod(exp_rule.set_color, GREEN), ApplyMethod(log_rule.set_color, RED), ) self.wait() all_tops = [m for m in t_exp_rule.split()+t_log_rule.split() if isinstance(m, TOP)] self.put_in_circles(all_tops) self.set_color_appropriate_parts(t_exp_rule, t_log_rule) def write_old_style_rules(self): start = OldTex("a^x a^y = a^{x+y}") end = OldTex("\\log_a(xy) = \\log_a(x) + \\log_a(y)") start.shift(UP) end.shift(DOWN) a1, x1, a2, y1, eq1, a3, p1, x2, y2 = start.split() a4, x3, y3, eq2, a5, x4, p2, a6, y4 = np.array(end.split())[ [3, 5, 6, 8, 12, 14, 16, 20, 22] ] start_copy = start.copy() self.play(Write(start_copy)) self.wait() self.play(Transform( VMobject(a1, x1, a2, y1, eq1, a3, p1, x2, a3.copy(), y2), VMobject(a4, x3, a4.copy(), y3, eq2, a5, p2, x4, a6, y4) )) self.play(Write(end)) self.clear() self.add(start_copy, end) self.wait() return start_copy, end def get_new_style_rules(self): upper_mobs = [ TOP("a", "x", "R"), Dot(), TOP("a", "y", "R"), OldTex("="), TOP("a", "x+y") ] lower_mobs = [ TOP("a", None, "xy"), OldTex("="), TOP("a", None, "x"), OldTex("+"), TOP("a", None, "y"), ] for mob in upper_mobs + lower_mobs: if isinstance(mob, TOP): mob.scale(0.5) for group in upper_mobs, lower_mobs: for m1, m2 in zip(group, group[1:]): m2.next_to(m1) for top in upper_mobs[0], upper_mobs[2]: top.set_value(2, None) upper_mobs = VMobject(*upper_mobs).center().shift(2*UP) lower_mobs = VMobject(*lower_mobs).center().shift(2*DOWN) return upper_mobs, lower_mobs def put_in_circles(self, tops): anims = [] for top in tops: for i, value in enumerate(top.values): if isinstance(value, VectorizedPoint): index = i circle = top.put_on_vertex(index, Circle(color = WHITE)) anims.append( Transform(top.copy().set_color(YELLOW), circle) ) self.add(*[anim.mobject for anim in anims]) self.wait() self.play(*anims) self.wait() def set_color_appropriate_parts(self, t_exp_rule, t_log_rule): #Horribly hacky circle1 = t_exp_rule.split()[0].put_on_vertex( 2, Circle() ) top_dot = t_exp_rule.split()[1] circle2 = t_exp_rule.split()[2].put_on_vertex( 2, Circle() ) top_plus = t_exp_rule.split()[4].values[1] bottom_times = t_log_rule.split()[0].values[2] circle3 = t_log_rule.split()[2].put_on_vertex( 1, Circle() ) bottom_plus = t_log_rule.split()[3] circle4 = t_log_rule.split()[4].put_on_vertex( 1, Circle() ) mob_lists = [ [circle1, top_dot, circle2], [top_plus], [bottom_times], [circle3, bottom_plus, circle4] ] for mobs in mob_lists: copies = VMobject(*mobs).copy() self.play(ApplyMethod( copies.set_color, YELLOW, run_time = 0.5 )) self.play(ApplyMethod( copies.scale, 1.2, rate_func = there_and_back )) self.wait() self.remove(copies) class DrawInsideTriangle(Scene): def construct(self): top = TOP() top.scale(2) dot = top.put_in_vertex(0, Dot()) plus = top.put_in_vertex(1, OldTex("+")) times = top.put_in_vertex(2, OldTex("\\times")) plus.set_color(GREEN) times.set_color(YELLOW) self.add(top) self.wait() for mob in dot, plus, times: self.play(Write(mob, run_time = 1)) self.wait() class ConstantOnTop(Scene): def construct(self): top = TOP() dot = top.put_in_vertex(1, Dot()) times1 = top.put_in_vertex(0, OldTex("\\times")) times2 = top.put_in_vertex(2, OldTex("\\times")) times1.set_color(YELLOW) times2.set_color(YELLOW) three = top.put_on_vertex(1, "3") lower_left_x = top.put_on_vertex(0, "x") lower_right_x = top.put_on_vertex(2, "x") x_cubed = OldTex("x^3").to_edge(UP) x_cubed.submobjects.reverse() #To align better cube_root_x = OldTex("\\sqrt[3]{x}").to_edge(UP) self.add(top) self.play(ShowCreation(three)) self.play( FadeIn(lower_left_x), Write(x_cubed), run_time = 1 ) self.wait() self.play(*[ Transform(*pair, path_arc = np.pi) for pair in [ (lower_left_x, lower_right_x), (x_cubed, cube_root_x), ] ]) self.wait(2) for mob in dot, times1, times2: self.play(ShowCreation(mob)) self.wait() def get_const_top_TOP(*args): top = TOP(*args) dot = top.put_in_vertex(1, Dot()) times1 = top.put_in_vertex(0, OldTex("\\times")) times2 = top.put_in_vertex(2, OldTex("\\times")) times1.set_color(YELLOW) times2.set_color(YELLOW) top.add(dot, times1, times2) return top class MultiplyWithConstantTop(Scene): def construct(self): top1 = get_const_top_TOP("x", "3") top2 = get_const_top_TOP("y", "3") top3 = get_const_top_TOP("xy", "3") times = OldTex("\\times") equals = OldTex("=") top_exp_equation = VMobject( top1, times, top2, equals, top3 ) top_exp_equation.arrange() old_style_exp = OldTex("(x^3)(y^3) = (xy)^3") old_style_exp.to_edge(UP) old_style_exp.set_color(GREEN) old_style_rad = OldTex("\\sqrt[3]{x} \\sqrt[3]{y} = \\sqrt[3]{xy}") old_style_rad.to_edge(UP) old_style_rad.set_color(RED) self.add(top_exp_equation, old_style_exp) self.wait(3) old_tops = [top1, top2, top3] new_tops = [] for top in old_tops: new_top = top.copy() new_top.put_on_vertex(2, new_top.values[0]) new_top.shift(0.5*LEFT) new_tops.append(new_top) self.play( Transform(old_style_exp, old_style_rad), Transform( VMobject(*old_tops), VMobject(*new_tops), path_arc = np.pi/2 ) ) self.wait(3) class RightStaysConstantQ(Scene): def construct(self): top1, top2, top3 = old_tops = [ TOP(None, s, "8") for s in ("x", "y", OldTex("x?y")) ] q_mark = OldTex("?").scale(2) equation = VMobject( top1, q_mark, top2, OldTex("="), top3 ) equation.arrange(buff = 0.7) symbols_at_top = VMobject(*[ top.values[1] for top in (top1, top2, top3) ]) symbols_at_lower_right = VMobject(*[ top.put_on_vertex(0, top.values[1].copy()) for top in (top1, top2, top3) ]) old_style_eq1 = OldTex("\\sqrt[x]{8} ? \\sqrt[y]{8} = \\sqrt[x?y]{8}") old_style_eq1.set_color(BLUE) old_style_eq2 = OldTex("\\log_x(8) ? \\log_y(8) = \\log_{x?y}(8)") old_style_eq2.set_color(YELLOW) for eq in old_style_eq1, old_style_eq2: eq.to_edge(UP) randy = Randolph() randy.to_corner() bubble = ThoughtBubble().pin_to(randy) bubble.add_content(TOP(None, None, "8")) self.add(randy, bubble) self.play(ApplyMethod(randy.change_mode, "pondering")) self.wait(3) triangle = bubble.content.triangle eight = bubble.content.values[2] bubble.clear() self.play( Transform(triangle, equation), FadeOut(eight), ApplyPointwiseFunction( lambda p : (p+2*DOWN)*15/get_norm(p+2*DOWN), bubble ), FadeIn(old_style_eq1), ApplyMethod(randy.shift, 3*DOWN + 3*LEFT), run_time = 2 ) self.remove(triangle) self.add(equation) self.wait(4) self.play( Transform( symbols_at_top, symbols_at_lower_right, path_arc = np.pi/2 ), Transform(old_style_eq1, old_style_eq2) ) self.wait(2) class AOplusB(Scene): def construct(self): self.add(OldTex( "a \\oplus b = \\dfrac{1}{\\frac{1}{a} + \\frac{1}{b}}" ).scale(2)) self.wait() class ConstantLowerRight(Scene): def construct(self): top = TOP() times = top.put_in_vertex(0, OldTex("\\times")) times.set_color(YELLOW) oplus = top.put_in_vertex(1, OldTex("\\oplus")) oplus.set_color(BLUE) dot = top.put_in_vertex(2, Dot()) eight = top.put_on_vertex(2, OldTex("8")) self.add(top) self.play(ShowCreation(eight)) for mob in dot, oplus, times: self.play(ShowCreation(mob)) self.wait() top.add(eight) top.add(times, oplus, dot) top1, top2, top3 = tops = [ top.copy() for i in range(3) ] big_oplus = OldTex("\\oplus").scale(2).set_color(BLUE) equals = OldTex("=") equation = VMobject( top1, big_oplus, top2, equals, top3 ) equation.arrange() top3.shift(0.5*RIGHT) x, y, xy = [ t.put_on_vertex(0, s) for t, s in zip(tops, ["x", "y", "xy"]) ] old_style_eq = OldTex( "\\dfrac{1}{\\frac{1}{\\log_x(8)} + \\frac{1}{\\log_y(8)}} = \\log_{xy}(8)" ) old_style_eq.to_edge(UP).set_color(RED) triple_top_copy = VMobject(*[ top.copy() for i in range(3) ]) self.clear() self.play( Transform(triple_top_copy, VMobject(*tops)), FadeIn(VMobject(x, y, xy, big_oplus, equals)) ) self.remove(triple_top_copy) self.add(*tops) self.play(Write(old_style_eq)) self.wait(3) syms = VMobject(x, y, xy) new_syms = VMobject(*[ t.put_on_vertex(1, s) for t, s in zip(tops, ["x", "y", "x \\oplus y"]) ]) new_old_style_eq = OldTex( "\\sqrt[x]{8} \\sqrt[y]{8} = \\sqrt[X]{8}" ) X = new_old_style_eq.split()[-4] frac = OldTex("\\frac{1}{\\frac{1}{x} + \\frac{1}{y}}") frac.replace(X) frac_lower_right = frac.get_corner(DOWN+RIGHT) frac.scale(2) frac.shift(frac_lower_right - frac.get_corner(DOWN+RIGHT)) new_old_style_eq.submobjects[-4] = frac new_old_style_eq.to_edge(UP) new_old_style_eq.set_color(RED) big_times = OldTex("\\times").set_color(YELLOW) big_times.shift(big_oplus.get_center()) self.play( Transform(old_style_eq, new_old_style_eq), Transform(syms, new_syms, path_arc = np.pi/2), Transform(big_oplus, big_times) ) self.wait(4) class TowerExponentFrame(Scene): def construct(self): words = OldTexText(""" Consider an expression like $3^{3^3}$. It's ambiguous whether this means $27^3$ or $3^{27}$, which is the difference between $19{,}683$ and $7{,}625{,}597{,}484{,}987$. But with the triangle of power, the difference is crystal clear: """) words.set_width(FRAME_WIDTH-1) words.to_edge(UP) top1 = TOP(TOP(3, 3), 3) top2 = TOP(3, (TOP(3, 3))) for top in top1, top2: top.next_to(words, DOWN) top1.shift(3*LEFT) top2.shift(3*RIGHT) self.add(words, top1, top2) self.wait() class ExponentialGrowth(Scene): def construct(self): words = OldTexText(""" Let's say you are studying a certain growth rate, and you come across an expression like $T^a$. It matters a lot whether you consider $T$ or $a$ to be the variable, since exponential growth and polynomial growth have very different flavors. The nice thing about having a triangle that you can write inside is that you can clarify this kind of ambiguity by writing a little dot next to the constant and a ``$\\sim$'' next to the variable. """) words.scale(0.75) words.to_edge(UP) top = TOP("T", "a") top.next_to(words, DOWN) dot = top.put_in_vertex(0, OldTex("\\cdot")) sim = top.put_in_vertex(1, OldTex("\\sim")) self.add(words, top, dot, sim) self.show_frame() self.wait() class GoExplore(Scene): def construct(self): explore = OldTexText("Go explore!") by_the_way = OldTexText("by the way \\dots") by_the_way.shift(20*RIGHT) self.play(Write(explore)) self.wait(4) self.play( ApplyMethod( VMobject(explore, by_the_way).shift, 20*LEFT ) ) self.wait(3)
videos_3b1b/_2016/triangle_of_power/end.py
from manim_imports_ext import * from _2016.triangle_of_power.triangle import TOP, OPERATION_COLORS class DontLearnFromSymbols(Scene): def construct(self): randy = Randolph().to_corner() bubble = randy.get_bubble() bubble.content_scale_factor = 0.6 bubble.add_content(TOP(2, 3, 8).scale(0.7)) equation = VMobject( TOP(2, "x"), OldTex("\\times"), TOP(2, "y"), OldTex("="), TOP(2, "x+y") ) equation.arrange() q_marks = OldTexText("???") q_marks.set_color(YELLOW) q_marks.next_to(randy, UP) self.add(randy) self.play(FadeIn(bubble)) self.wait() top = bubble.content bubble.add_content(equation) self.play( FadeOut(top), ApplyMethod(randy.change_mode, "sassy"), Write(bubble.content), Write(q_marks), run_time = 1 ) self.wait(3) class NotationReflectsMath(Scene): def construct(self): top_expr = OldTexText("Notation $\\Leftrightarrow$ Math") top_expr.shift(2*UP) better_questions = OldTexText("Better questions") arrow = Arrow(top_expr, better_questions) self.play(Write(top_expr)) self.play( ShowCreationPerSubmobject( arrow, rate_func = lambda t : min(smooth(3*t), 1) ), Write(better_questions), run_time = 3 ) self.wait(2) class AsymmetriesInTheMath(Scene): def construct(self): assyms_of_top = VMobject( OldTexText("Asymmetries of "), TOP("a", "b", "c", radius = 0.75).set_color(BLUE) ).arrange() assyms_of_top.to_edge(UP) assyms_of_math = OldTexText(""" Asymmetries of $\\underbrace{a \\cdot a \\cdots a}_{\\text{$b$ times}} = c$ """) VMobject(*assyms_of_math.split()[13:]).set_color(YELLOW) assyms_of_math.next_to(assyms_of_top, DOWN, buff = 2) rad = OldTex("\\sqrt{\\quad}").to_edge(LEFT).shift(UP) rad.set_color(RED) log = OldTex("\\log").next_to(rad, DOWN) log.set_color(RED) self.play(FadeIn(assyms_of_top)) self.wait() self.play(FadeIn(assyms_of_math)) self.wait() self.play(Write(VMobject(rad, log))) self.wait() class AddedVsOplussed(Scene): def construct(self): top = TOP() left_times = top.put_in_vertex(0, OldTex("\\times")) left_dot = top.put_in_vertex(0, Dot()) right_times = top.put_in_vertex(2, OldTex("\\times")) right_dot = top.put_in_vertex(2, Dot()) plus = top.put_in_vertex(1, OldTex("+")) oplus = top.put_in_vertex(1, OldTex("\\oplus")) left_times.set_color(YELLOW) right_times.set_color(YELLOW) plus.set_color(GREEN) oplus.set_color(BLUE) self.add(top, left_dot, plus, right_times) self.wait() self.play( Transform( VMobject(left_dot, plus, right_times), VMobject(right_dot, oplus, left_times), path_arc = np.pi/2 ) ) self.wait() class ReciprocalTop(Scene): def construct(self): top = TOP() start_two = top.put_on_vertex(2, 2) end_two = top.put_on_vertex(0, 2) x = top.put_on_vertex(1, "x") one_over_x = top.put_on_vertex(1, "\\dfrac{1}{x}") x.set_color(GREEN) one_over_x.set_color(BLUE) start_two.set_color(YELLOW) end_two.set_color(YELLOW) self.add(top, start_two, x) self.wait() self.play( Transform( VMobject(start_two, x), VMobject(end_two, one_over_x) ), ApplyMethod(top.rotate, np.pi, UP, path_arc = np.pi/7) ) self.wait() class NotSymbolicPatterns(Scene): def construct(self): randy = Randolph() symbolic_patterns = OldTexText("Symbolic patterns") symbolic_patterns.to_edge(RIGHT).shift(UP) line = Line(LEFT, RIGHT, color = RED, stroke_width = 7) line.replace(symbolic_patterns) substantive_reasoning = OldTexText("Substantive reasoning") substantive_reasoning.to_edge(RIGHT).shift(DOWN) self.add(randy, symbolic_patterns) self.wait() self.play(ShowCreation(line)) self.play( Write(substantive_reasoning), ApplyMethod(randy.change_mode, "pondering_looking_left"), run_time = 1 ) self.wait(2) self.play( ApplyMethod(line.shift, 10*DOWN), ApplyMethod(substantive_reasoning.shift, 10*DOWN), ApplyMethod(randy.change_mode, "sad"), run_time = 1 ) self.wait(2) class ChangeWeCanBelieveIn(Scene): def construct(self): words = OldTexText("Change we can believe in") change = VMobject(*words.split()[:6]) top = TOP(radius = 0.75) top.shift(change.get_right()-top.get_right()) self.play(Write(words)) self.play( FadeOut(change), GrowFromCenter(top) ) self.wait(3) class TriangleOfPowerIsBetter(Scene): def construct(self): top = TOP("x", "y", "z", radius = 0.75) top.set_color(BLUE) alts = VMobject(*list(map(Tex, [ "x^y", "\\log_x(z)", "\\sqrt[y]{z}" ]))) for mob, color in zip(alts.split(), OPERATION_COLORS): mob.set_color(color) alts.arrange(DOWN) greater_than = OldTex(">") top.next_to(greater_than, LEFT) alts.next_to(greater_than, RIGHT) self.play(Write(VMobject(top, greater_than, alts))) self.wait() class InYourOwnNotes(Scene): def construct(self): anims = [ self.get_log_anim(3*LEFT), self.get_exp_anim(3*RIGHT), ] for anim in anims: self.add(anim.mobject) self.wait(2) self.play(*anims) self.wait(2) def get_log_anim(self, center): O_log_n = OldTex(["O(", "\\log(n)", ")"]) O_log_n.shift(center) log_n = O_log_n.split()[1] #super hacky g = log_n.split()[2] for mob in g.submobjects: mob.is_subpath = False mob.set_fill(BLACK, 1.0) log_n.add(mob) g.submobjects = [] #end hack top = TOP(2, None, "n", radius = 0.75) top.set_width(log_n.get_width()) top.shift(log_n.get_center()) new_O_log_n = O_log_n.copy() new_O_log_n.submobjects[1] = top return Transform(O_log_n, new_O_log_n) def get_exp_anim(self, center): epii = OldTex("e^{\\pi i} = -1") epii.shift(center) top = TOP("e", "\\pi i", "-1", radius = 0.75) top.shift(center) e, pi, i, equals, minus, one = epii.split() ##hacky loop = e.submobjects[0] loop.is_subpath = False loop.set_fill(BLACK, 1.0) e.submobjects = [] ## start = VMobject( equals, VMobject(e, loop), VMobject(pi, i), VMobject(minus, one) ) return Transform(start, top) class Qwerty(Scene): def construct(self): qwerty = VMobject( OldTexText(list("QWERTYUIOP")), OldTexText(list("ASDFGHJKL")), OldTexText(list("ZXCVBNM")), ) qwerty.arrange(DOWN) dvorak = VMobject( OldTexText(list("PYFGCRL")), OldTexText(list("AOEUIDHTNS")), OldTexText(list("QJKXBMWVZ")), ) dvorak.arrange(DOWN) d1, d2, d3 = dvorak.split() d1.shift(0.9*RIGHT) d3.shift(0.95*RIGHT) self.add(qwerty) self.wait(2) self.play(Transform(qwerty, dvorak)) self.wait(2) class ShowLog(Scene): def construct(self): equation = VMobject(*[ TOP(2, None, "x"), OldTex("+"), TOP(2, None, "y"), OldTex("="), TOP(2, None, "xy") ]).arrange() old_eq = OldTex("\\log_2(x) + \\log_2(y) = \\log_2(xy)") old_eq.to_edge(UP) self.play(FadeIn(equation)) self.wait(3) self.play(FadeIn(old_eq)) self.wait(2) class NoOneWillActuallyDoThis(Scene): def construct(self): randy = Randolph().to_corner() bubble = SpeechBubble().pin_to(randy) words = OldTexText("No one will actually do this...") tau_v_pi = OldTex("\\tau > \\pi").scale(2) morty = Mortimer("speaking").to_corner(DOWN+RIGHT) morty_bubble = SpeechBubble( direction = RIGHT, height = 4 ) morty_bubble.pin_to(morty) final_words = OldTexText("If this war is won, it will \\\\ not be won with that attitude") lil_thought_bubble = ThoughtBubble(height = 3, width = 5) lil_thought_bubble.set_fill(BLACK, 1.0) lil_thought_bubble.pin_to(randy) lil_thought_bubble.write("Okay buddy, calm down, it's notation \\\\ we're talking about not war.") lil_thought_bubble.show() self.add(randy) self.play( ApplyMethod(randy.change_mode, "sassy"), ShowCreation(bubble) ) bubble.add_content(words) self.play(Write(words), run_time = 2) self.play(Blink(randy)) bubble.add_content(tau_v_pi) self.play( FadeOut(words), GrowFromCenter(tau_v_pi), ApplyMethod(randy.change_mode, "speaking") ) self.remove(words) self.play(Blink(randy)) self.wait(2) self.play( FadeOut(bubble), FadeIn(morty), ShowCreation(morty_bubble), ApplyMethod(randy.change_mode, "plain") ) morty_bubble.add_content(final_words) self.play(Write(final_words)) self.wait() self.play(Blink(morty)) self.wait(2) self.play(ShowCreation(lil_thought_bubble))
videos_3b1b/_2016/triangle_of_power/intro.py
from manim_imports_ext import * class TrigAnimation(Animation): CONFIG = { "rate_func" : None, "run_time" : 5, "sin_color" : BLUE, "cos_color" : RED, "tan_color" : GREEN } def __init__(self, **kwargs): digest_config(self, kwargs) x_axis = NumberLine( x_min = -3, x_max = 3, color = BLUE_E ) y_axis = x_axis.copy().rotate(np.pi/2) circle = Circle(color = WHITE) self.trig_lines = [ Line(ORIGIN, RIGHT, color = color) for color in (self.sin_color, self.cos_color, self.tan_color) ] mobject = VMobject( x_axis, y_axis, circle, *self.trig_lines ) mobject.to_edge(RIGHT) self.center = mobject.get_center() Animation.__init__(self, mobject, **kwargs) def interpolate_mobject(self, alpha): theta = 2*np.pi*alpha circle_point = np.cos(theta)*RIGHT+np.sin(theta)*UP+self.center points = [ circle_point[0]*RIGHT, circle_point[1]*UP+self.center, ( np.sign(np.cos(theta))*np.sqrt( np.tan(theta)**2 - np.sin(theta)**2 ) + np.cos(theta) )*RIGHT + self.center, ] for line, point in zip(self.trig_lines, points): line.set_points_as_corners([circle_point, point]) class Notation(Scene): def construct(self): self.introduce_notation() self.shift_to_good_and_back() self.shift_to_visuals() self.swipe_left() def introduce_notation(self): notation = OldTexText("Notation") notation.to_edge(UP) self.sum1 = OldTex("\\sum_{n=1}^\\infty \\dfrac{1}{n}") self.prod1 = OldTex("\\prod_{p\\text{ prime}}\\left(1-p^{-s}\\right)") self.trigs1 = OldTex([ ["\\sin", "(x)"], ["\\cos", "(x)"], ["\\tan", "(x)"], ], next_to_direction = DOWN) self.func1 = OldTex("f(x) = y") symbols = [self.sum1, self.prod1, self.trigs1, self.func1] for sym, vect in zip(symbols, compass_directions(4, UP+LEFT)): sym.scale(0.5) vect[0] *= 2 sym.shift(vect) self.symbols = VMobject(*symbols) self.play(Write(notation)) self.play(Write(self.symbols)) self.wait() self.add(notation, self.symbols) def shift_to_good_and_back(self): sum2 = self.sum1.copy() sigma = sum2.submobjects[1] plus = OldTex("+").replace(sigma) sum2.submobjects[1] = plus prod2 = self.prod1.copy() pi = prod2.submobjects[0] times = OldTex("\\times").replace(pi) prod2.submobjects[0] = times new_sin, new_cos, new_tan = [ VMobject().set_points_as_corners( corners ).replace(trig_part.split()[0]) for corners, trig_part in zip( [ [RIGHT, RIGHT+UP, LEFT], [RIGHT+UP, LEFT, RIGHT], [RIGHT+UP, RIGHT, LEFT], ], self.trigs1.split() ) ] x1, x2, x3 = [ trig_part.split()[1] for trig_part in self.trigs1.split() ] trigs2 = VMobject( VMobject(new_sin, x1), VMobject(new_cos, x2), VMobject(new_tan, x3), ) x, arrow, y = OldTex("x \\rightarrow y").split() f = OldTex("f") f.next_to(arrow, UP) func2 = VMobject(f, VMobject(), x, VMobject(), arrow, y) func2.scale(0.5) func2.shift(self.func1.get_center()) good_symbols = VMobject(sum2, prod2, trigs2, func2) bad_symbols = self.symbols.copy() self.play(Transform( self.symbols, good_symbols, path_arc = np.pi )) self.wait(3) self.play(Transform( self.symbols, bad_symbols, path_arc = np.pi )) self.wait() def shift_to_visuals(self): sigma, prod, trig, func = self.symbols.split() new_trig = trig.copy() sin, cos, tan = [ trig_part.split()[0] for trig_part in new_trig.split() ] trig_anim = TrigAnimation() sin.set_color(trig_anim.sin_color) cos.set_color(trig_anim.cos_color) tan.set_color(trig_anim.tan_color) new_trig.to_corner(UP+RIGHT) sum_lines = self.get_harmonic_sum_lines() self.play( Transform(trig, new_trig), *it.starmap(ApplyMethod, [ (sigma.to_corner, UP+LEFT), (prod.shift, 15*LEFT), (func.shift, 5*UP), ]) ) sum_lines.next_to(sigma, DOWN) self.remove(prod, func) self.play( trig_anim, Write(sum_lines) ) self.play(trig_anim) self.wait() def get_harmonic_sum_lines(self): result = VMobject() for n in range(1, 8): big_line = NumberLine( x_min = 0, x_max = 1.01, tick_frequency = 1./n, numbers_with_elongated_ticks = [], color = WHITE ) little_line = Line( big_line.number_to_point(0), big_line.number_to_point(1./n), color = RED ) big_line.add(little_line) big_line.shift(0.5*n*DOWN) result.add(big_line) return result def swipe_left(self): everyone = VMobject(*self.mobjects) self.play(ApplyMethod(everyone.shift, 20*LEFT)) class ButDots(Scene): def construct(self): but = OldTexText("but") dots = OldTex("\\dots") dots.next_to(but, aligned_edge = DOWN) but.shift(20*RIGHT) self.play(ApplyMethod(but.shift, 20*LEFT)) self.play(Write(dots, run_time = 5)) self.wait() class ThreesomeOfNotation(Scene): def construct(self): exp = OldTex("x^y = z") log = OldTex("\\log_x(z) = y") rad = OldTex("\\sqrt[y]{z} = x") exp.to_edge(LEFT).shift(2*UP) rad.to_edge(RIGHT).shift(2*DOWN) x1, y1, eq, z1 = exp.split() l, o, g, x2, p, z2, p, eq, y2 = log.split() y3, r, r, z3, eq, x3 = rad.split() vars1 = VMobject(x1, y1, z1).copy() vars2 = VMobject(x2, y2, z2) vars3 = VMobject(x3, y3, z3) self.play(Write(exp)) self.play(Transform(vars1, vars2, path_arc = -np.pi)) self.play(Write(log)) self.play(Transform(vars1, vars3, path_arc = -np.pi)) self.play(Write(rad)) self.wait() words = OldTexText("Artificially unrelated") words.to_corner(UP+RIGHT) words.set_color(YELLOW) self.play(Write(words)) self.wait() class TwoThreeEightExample(Scene): def construct(self): start = OldTex("2 \\cdot 2 \\cdot 2 = 8") two1, dot1, two2, dot2, two3, eq, eight = start.split() brace = Brace(VMobject(two1, two3), DOWN) three = OldTex("3").next_to(brace, DOWN, buff = 0.2) rogue_two = two1.copy() self.add(two1) self.play( Transform(rogue_two, two2), Write(dot1), run_time = 0.5 ) self.add(two2) self.play( Transform(rogue_two, two3), Write(dot2), run_time = 0.5 ) self.add(two3) self.remove(rogue_two) self.play( Write(eq), Write(eight), GrowFromCenter(brace), Write(three), run_time = 1 ) self.wait() exp = OldTex("2^3") exp.next_to(eq, LEFT) exp.shift(0.2*UP) base_two, exp_three = exp.split() self.play( Transform( VMobject(two1, dot1, two2, dot2, brace, three), exp_three, path_arc = -np.pi/2 ), Transform(two3, base_two) ) self.clear() self.add(base_two, exp_three, eq, eight) self.wait(3) rad_three, rad1, rad2, rad_eight, rad_eq, rad_two = \ OldTex("\\sqrt[3]{8} = 2").split() self.play(*[ Transform(*pair, path_arc = np.pi/2) for pair in [ (exp_three, rad_three), (VMobject(), rad1), (VMobject(), rad2), (eight, rad_eight), (eq, rad_eq), (base_two, rad_two) ] ]) self.wait() self.play(ApplyMethod( VMobject(rad1, rad2).set_color, RED, rate_func = there_and_back, run_time = 2 )) self.remove(rad1, rad2) self.wait() l, o, g, log_two, p1, log_eight, p2, log_eq, log_three = \ OldTex("\\log_2(8) = 3").split() self.clear() self.play(*[ Transform(*pair, path_arc = np.pi/2) for pair in [ (rad1, l), (rad2, o), (rad2.copy(), g), (rad_two, log_two), (VMobject(), p1), (rad_eight, log_eight), (VMobject(), p2), (rad_eq, log_eq), (rad_three, log_three) ] ]) self.wait() self.play(ApplyMethod( VMobject(l, o, g).set_color, RED, rate_func = there_and_back, run_time = 2 )) self.wait() class WhatTheHell(Scene): def construct(self): randy = Randolph() randy.to_corner(DOWN+LEFT) exp, rad, log = list(map(Tex,[ "2^3 = 8", "\\sqrt[3]{8} = 2", "\\log_2(8) = 3", ])) # exp.set_color(BLUE_D) # rad.set_color(RED_D) # log.set_color(GREEN_D) arrow1 = DoubleArrow(DOWN, UP) arrow2 = arrow1.copy() last = exp for mob in arrow1, rad, arrow2, log: mob.next_to(last, DOWN) last = mob q_marks = VMobject(*[ OldTex("?!").next_to(arrow, RIGHT) for arrow in (arrow1, arrow2) ]) q_marks.set_color(RED_D) everyone = VMobject(exp, rad, log, arrow1, arrow2, q_marks) everyone.scale(0.7) everyone.to_corner(UP+RIGHT) phrases = [ OldTexText( ["Communicate with", words] ).next_to(mob, LEFT, buff = 1) for words, mob in [ ("position", exp), ("a new symbol", rad), ("a word", log) ] ] for phrase, color in zip(phrases, [BLUE, RED, GREEN]): phrase.split()[1].set_color(color) self.play(ApplyMethod(randy.change_mode, "angry")) self.play(FadeIn(VMobject(exp, rad, log))) self.play( ShowCreationPerSubmobject(arrow1), ShowCreationPerSubmobject(arrow2) ) self.play(Write(q_marks)) self.wait() self.remove(randy) self.play(Write(VMobject(*phrases))) self.wait() class Countermathematical(Scene): def construct(self): counterintuitive = OldTexText("Counterintuitive") mathematical = OldTexText("mathematical") intuitive = VMobject(*counterintuitive.split()[7:]) mathematical.shift(intuitive.get_left()-mathematical.get_left()) self.add(counterintuitive) self.wait() self.play(Transform(intuitive, mathematical)) self.wait() class PascalsCollision(Scene): def construct(self): pascals_triangle = PascalsTriangle() pascals_triangle.scale(0.5) final_triangle = PascalsTriangle() final_triangle.fill_with_n_choose_k() pascals_triangle.to_corner(UP+LEFT) final_triangle.scale(0.7) final_triangle.to_edge(UP) equation = OldTex([ "{n \\choose k}", " = \\dfrac{n!}{(n-k)!k!}" ]) equation.scale(0.5) equation.to_corner(UP+RIGHT) n_choose_k, formula = equation.split() words = OldTexText("Seemingly unrelated") words.shift(2*DOWN) to_remove = VMobject(*words.split()[:-7]) self.add(pascals_triangle, n_choose_k, formula) self.play(Write(words)) self.wait() self.play( Transform(pascals_triangle, final_triangle), Transform(n_choose_k, final_triangle), FadeOut(formula), ApplyMethod(to_remove.shift, 5*DOWN) ) self.wait() class LogarithmProperties(Scene): def construct(self): randy = Randolph() randy.to_corner() bubble = ThoughtBubble().pin_to(randy) props = [ OldTex("\\log_a(x) = \\dfrac{\\log_b(a)}{\\log_b(x)}"), OldTex("\\log_a(x) = \\dfrac{\\log_b(x)}{\\log_b(a)}"), OldTex("\\log_a(x) = \\log_b(x) - \\log_b(a)"), OldTex("\\log_a(x) = \\log_b(x) + \\log_b(a)"), OldTex("\\log_a(x) = \\dfrac{\\log_b(x)}{\\log_b(a)}"), ] bubble.add_content(props[0]) words = OldTexText("What was it again?") words.set_color(YELLOW) words.scale(0.5) words.next_to(props[0], UP) self.play( ApplyMethod(randy.change_mode, "confused"), ShowCreation(bubble), Write(words) ) self.show_frame() for i, prop in enumerate(props[1:]): self.play(ApplyMethod(bubble.add_content, prop)) if i%2 == 0: self.play(Blink(randy)) else: self.wait() class HaveToShare(Scene): def construct(self): words = list(map(TexText, [ "Lovely", "Symmetrical", "Utterly Reasonable" ])) for w1, w2 in zip(words, words[1:]): w2.next_to(w1, DOWN) VMobject(*words).center() left_dot, top_dot, bottom_dot = [ Dot(point, radius = 0.1) for point in (ORIGIN, RIGHT+0.5*UP, RIGHT+0.5*DOWN) ] line1, line2 = [ Line(left_dot.get_center(), dot.get_center(), buff = 0) for dot in (top_dot, bottom_dot) ] share = VMobject(left_dot, top_dot, bottom_dot, line1, line2) share.next_to(words[1], RIGHT, buff = 1) share.set_color(RED) for word in words: self.play(FadeIn(word)) self.wait() self.play(Write(share, run_time = 1)) self.wait()
videos_3b1b/_2016/hilbert/section2.py
from manim_imports_ext import * import displayer as disp from hilbert.curves import \ TransformOverIncreasingOrders, FlowSnake, HilbertCurve, \ SnakeCurve, PeanoCurve from hilbert.section1 import get_mathy_and_bubble from scipy.spatial.distance import cdist def get_time_line(): length = 2.6*FRAME_WIDTH year_range = 400 time_line = NumberLine( numerical_radius = year_range/2, unit_length_to_spatial_width = length/year_range, tick_frequency = 10, leftmost_tick = 1720, number_at_center = 1870, numbers_with_elongated_ticks = list(range(1700, 2100, 100)) ) time_line.sort_points(lambda p : p[0]) time_line.set_color_by_gradient( PeanoCurve.CONFIG["start_color"], PeanoCurve.CONFIG["end_color"] ) time_line.add_numbers( 2020, *list(range(1800, 2050, 50)) ) return time_line class SectionTwo(Scene): def construct(self): self.add(OldTexText("Section 2: Filling space")) self.wait() class HilbertCurveIsPerfect(Scene): def construct(self): curve = HilbertCurve(order = 6) curve.set_color(WHITE) colored_curve = curve.copy() colored_curve.thin_out(3) lion = ImageMobject("lion", invert = False) lion.replace(curve, stretch = True) sparce_lion = lion.copy() sparce_lion.thin_out(100) distance_matrix = cdist(colored_curve.points, sparce_lion.points) closest_point_indices = np.apply_along_axis( np.argmin, 1, distance_matrix ) colored_curve.rgbas = sparce_lion.rgbas[closest_point_indices] line = Line(5*LEFT, 5*RIGHT) Mobject.align_data_and_family(line, colored_curve) line.rgbas = colored_curve.rgbas self.add(lion) self.play(ShowCreation(curve, run_time = 3)) self.play( FadeOut(lion), Transform(curve, colored_curve), run_time = 3 ) self.wait() self.play(Transform(curve, line, run_time = 5)) self.wait() class AskMathematicianFriend(Scene): def construct(self): mathy, bubble = get_mathy_and_bubble() bubble.sort_points(lambda p : np.dot(p, UP+RIGHT)) self.add(mathy) self.wait() self.play(ApplyMethod( mathy.blink, rate_func = squish_rate_func(there_and_back) )) self.wait() self.play(ShowCreation(bubble)) self.wait() self.play( ApplyMethod(mathy.shift, 3*(DOWN+LEFT)), ApplyPointwiseFunction( lambda p : 15*p/get_norm(p), bubble ), run_time = 3 ) class TimeLineAboutSpaceFilling(Scene): def construct(self): curve = PeanoCurve(order = 5) curve.stretch_to_fit_width(FRAME_WIDTH) curve.stretch_to_fit_height(FRAME_HEIGHT) curve_start = curve.copy() curve_start.apply_over_attr_arrays( lambda arr : arr[:200] ) time_line = get_time_line() time_line.shift(-time_line.number_to_point(2000)) self.add(time_line) self.play(ApplyMethod( time_line.shift, -time_line.number_to_point(1900), run_time = 3 )) brace = Brace( Mobject( Point(time_line.number_to_point(1865)), Point(time_line.number_to_point(1888)), ), UP ) words = OldTexText(""" Cantor drives himself (and the \\\\ mathematical community at large) \\\\ crazy with research on infinity. """) words.next_to(brace, UP) self.play( GrowFromCenter(brace), ShimmerIn(words) ) self.wait() self.play( Transform(time_line, curve_start), FadeOut(brace), FadeOut(words) ) self.play(ShowCreation( curve, run_time = 5, rate_func=linear )) self.wait() class NotPixelatedSpace(Scene): def construct(self): grid = Grid(64, 64) space_region = Region() space_mobject = MobjectFromRegion(space_region, GREY_D) curve = PeanoCurve(order = 5).replace(space_mobject) line = Line(5*LEFT, 5*RIGHT) line.set_color_by_gradient(curve.start_color, curve.end_color) for mob in grid, space_mobject: mob.sort_points(get_norm) infinitely = OldTexText("Infinitely") detailed = OldTexText("detailed") extending = OldTexText("extending") detailed.next_to(infinitely, RIGHT) extending.next_to(infinitely, RIGHT) Mobject(extending, infinitely, detailed).center() arrows = Mobject(*[ Arrow(2*p, 4*p) for theta in np.arange(np.pi/6, 2*np.pi, np.pi/3) for p in [rotate_vector(RIGHT, theta)] ]) self.add(grid) self.wait() self.play(Transform(grid, space_mobject, run_time = 5)) self.remove(grid) self.set_color_region(space_region, GREY_D) self.wait() self.add(infinitely, detailed) self.wait() self.play(DelayByOrder(Transform(detailed, extending))) self.play(ShowCreation(arrows)) self.wait() self.clear() self.set_color_region(space_region, GREY_D) self.play(ShowCreation(line)) self.play(Transform(line, curve, run_time = 5)) class HistoryOfDiscover(Scene): def construct(self): time_line = get_time_line() time_line.shift(-time_line.number_to_point(1900)) hilbert_curve = HilbertCurve(order = 3) peano_curve = PeanoCurve(order = 2) for curve in hilbert_curve, peano_curve: curve.scale(0.5) hilbert_curve.to_corner(DOWN+RIGHT) peano_curve.to_corner(UP+LEFT) squares = Mobject(*[ Square(side_length=3, color=WHITE).replace(curve) for curve in (hilbert_curve, peano_curve) ]) self.add(time_line) self.wait() for year, curve, vect, text in [ (1890, peano_curve, UP, "Peano Curve"), (1891, hilbert_curve, DOWN, "Hilbert Curve"), ]: point = time_line.number_to_point(year) point[1] = 0.2 arrow = Arrow(point+2*vect, point, buff = 0.1) arrow.set_color_by_gradient(curve.start_color, curve.end_color) year_mob = OldTex(str(year)) year_mob.next_to(arrow, vect) words = OldTexText(text) words.next_to(year_mob, vect) self.play( ShowCreation(arrow), ShimmerIn(year_mob), ShimmerIn(words) ) self.play(ShowCreation(curve)) self.wait() self.play(ShowCreation(squares)) self.wait() self.play(ApplyMethod( Mobject(*self.mobjects).shift, 20*(DOWN+RIGHT) )) class DefinitionOfCurve(Scene): def construct(self): start_words = OldTexText([ "``", "Space Filling", "Curve ''", ]).to_edge(TOP, buff = 0.25) quote, space_filling, curve_quote = start_words.copy().split() curve_quote.shift( space_filling.get_left()-\ curve_quote.get_left() ) space_filling = Point(space_filling.get_center()) end_words = Mobject(*[ quote, space_filling, curve_quote ]).center().to_edge(TOP, buff = 0.25) space_filling_fractal = OldTexText(""" ``Space Filling Fractal'' """).to_edge(UP) curve = HilbertCurve(order = 2).shift(DOWN) fine_curve = HilbertCurve(order = 8) fine_curve.replace(curve) dots = Mobject(*[ Dot( curve.get_points()[n*curve.get_num_points()/15], color = YELLOW_C ) for n in range(1, 15) if n not in [4, 11] ]) start_words.shift(2*(UP+LEFT)) self.play( ApplyMethod(start_words.shift, 2*(DOWN+RIGHT)) ) self.wait() self.play(Transform(start_words, end_words)) self.wait() self.play(ShowCreation(curve)) self.wait() self.play(ShowCreation( dots, run_time = 3, )) self.wait() self.clear() self.play(ShowCreation(fine_curve, run_time = 5)) self.wait() self.play(ShimmerIn(space_filling_fractal)) self.wait() class PseudoHilbertCurvesDontFillSpace(Scene): def construct(self): curve = HilbertCurve(order = 1) grid = Grid(2, 2, stroke_width=1) self.add(grid, curve) for order in range(2, 6): self.wait() new_grid = Grid(2**order, 2**order, stroke_width=1) self.play( ShowCreation(new_grid), Animation(curve) ) self.remove(grid) grid = new_grid self.play(Transform( curve, HilbertCurve(order = order) )) square = Square(side_length = 6, color = WHITE) square.corner = Mobject1D() square.corner.add_line(3*DOWN, ORIGIN) square.corner.add_line(ORIGIN, 3*RIGHT) square.digest_mobject_attrs() square.scale(2**(-5)) square.corner.set_color( Color(rgb = curve.rgbas[curve.get_num_points()/3]) ) square.shift( grid.get_corner(UP+LEFT)-\ square.get_corner(UP+LEFT) ) self.wait() self.play( FadeOut(grid), FadeOut(curve), FadeIn(square) ) self.play( ApplyMethod(square.replace, grid) ) self.wait() class HilbertCurveIsLimit(Scene): def construct(self): mathy, bubble = get_mathy_and_bubble() bubble.write( "A Hilbert curve is the \\\\ limit of all these \\dots" ) self.add(mathy, bubble) self.play(ShimmerIn(bubble.content)) self.wait() class DefiningCurves(Scene): def construct(self): words = OldTexText( ["One does not simply define the limit \\\\ \ of a sequence of","curves","\\dots"] ) top_words = OldTexText([ "curves", "are functions" ]).to_edge(UP) curves1 = words.split()[1] curves2 = top_words.split()[0] words.ingest_submobjects() number = OldTex("0.27") pair = OldTex("(0.53, 0.02)") pair.next_to(number, buff = 2) arrow = Arrow(number, pair) Mobject(number, arrow, pair).center().shift(UP) number_line = UnitInterval() number_line.stretch_to_fit_width(5) number_line.to_edge(LEFT).shift(DOWN) grid = Grid(4, 4).scale(0.4) grid.next_to(number_line, buff = 2) low_arrow = Arrow(number_line, grid) self.play(ShimmerIn(words)) self.wait() self.play( FadeOut(words), ApplyMethod(curves1.replace, curves2), ShimmerIn(top_words.split()[1]) ) self.wait() self.play(FadeIn(number)) self.play(ShowCreation(arrow)) self.play(FadeIn(pair)) self.wait() self.play(ShowCreation(number_line)) self.play(ShowCreation(low_arrow)) self.play(ShowCreation(grid)) self.wait() class PseudoHilbertCurveAsFunctionExample(Scene): args_list = [(2,), (3,)] # For subclasses to turn args in the above # list into stings which can be appended to the name @staticmethod def args_to_string(order): return "Order%d"%order @staticmethod def string_to_args(order_str): return int(order_str) def construct(self, order): if order == 2: result_tex = "(0.125, 0.75)" elif order == 3: result_tex = "(0.0758, 0.6875)" phc, arg, result = OldTex([ "\\text{PHC}_%d"%order, "(0.3)", "= %s"%result_tex ]).to_edge(UP).split() function = OldTexText("Function", size = "\\normal") function.shift(phc.get_center()+DOWN+2*LEFT) function_arrow = Arrow(function, phc) line = Line(5*LEFT, 5*RIGHT) curve = HilbertCurve(order = order) line.match_colors(curve) grid = Grid(2**order, 2**order) grid.fade() for mob in curve, grid: mob.scale(0.7) index = int(0.3*line.get_num_points()) dot1 = Dot(line.get_points()[index]) arrow1 = Arrow(arg, dot1, buff = 0.1) dot2 = Dot(curve.get_points()[index]) arrow2 = Arrow(result.get_bottom(), dot2, buff = 0.1) self.add(phc) self.play( ShimmerIn(function), ShowCreation(function_arrow) ) self.wait() self.remove(function_arrow, function) self.play(ShowCreation(line)) self.wait() self.play( ShimmerIn(arg), ShowCreation(arrow1), ShowCreation(dot1) ) self.wait() self.remove(arrow1) self.play( FadeIn(grid), Transform(line, curve), Transform(dot1, dot2), run_time = 2 ) self.wait() self.play( ShimmerIn(result), ShowCreation(arrow2) ) self.wait() class ContinuityRequired(Scene): def construct(self): words = OldTexText([ "A function must be", "\\emph{continuous}", "if it is to represent a curve." ]) words.split()[1].set_color(YELLOW_C) self.add(words) self.wait() class FormalDefinitionOfContinuity(Scene): def construct(self): self.setup() self.label_spaces() self.move_dot() self.label_jump() self.draw_circles() self.vary_circle_sizes() self.discontinuous_point() def setup(self): self.input_color = YELLOW_C self.output_color = RED def spiril(t): theta = 2*np.pi*t return t*np.cos(theta)*RIGHT+t*np.sin(theta)*UP self.spiril1 = ParametricCurve( lambda t : 1.5*RIGHT + DOWN + 2*spiril(t), density = 5*DEFAULT_POINT_DENSITY_1D, ) self.spiril2 = ParametricCurve( lambda t : 5.5*RIGHT + UP - 2*spiril(1-t), density = 5*DEFAULT_POINT_DENSITY_1D, ) Mobject.align_data_and_family(self.spiril1, self.spiril2) self.output = Mobject(self.spiril1, self.spiril2) self.output.ingest_submobjects() self.output.set_color(GREEN_A) self.interval = UnitInterval() self.interval.set_width(FRAME_X_RADIUS-1) self.interval.to_edge(LEFT) self.input_dot = Dot(color = self.input_color) self.output_dot = self.input_dot.copy().set_color(self.output_color) left, right = self.interval.get_left(), self.interval.get_right() self.input_homotopy = lambda x_y_z_t : (x_y_z_t[0], x_y_z_t[1], x_y_z_t[3]) + interpolate(left, right, x_y_z_t[3]) output_size = self.output.get_num_points()-1 output_points = self.output.points self.output_homotopy = lambda x_y_z_t1 : (x_y_z_t1[0], x_y_z_t1[1], x_y_z_t1[2]) + output_points[int(x_y_z_t1[3]*output_size)] def get_circles_and_points(self, min_input, max_input): input_left, input_right = [ self.interval.number_to_point(num) for num in (min_input, max_input) ] input_circle = Circle( radius = get_norm(input_left-input_right)/2, color = WHITE ) input_circle.shift((input_left+input_right)/2) input_points = Line( input_left, input_right, color = self.input_color ) output_points = Mobject(color = self.output_color) n = self.output.get_num_points() output_points.add_points( self.output.get_points()[int(min_input*n):int(max_input*n)] ) output_center = output_points.get_points()[int(0.5*output_points.get_num_points())] max_distance = get_norm(output_center-output_points.get_points()[-1]) output_circle = Circle( radius = max_distance, color = WHITE ) output_circle.shift(output_center) return ( input_circle, input_points, output_circle, output_points ) def label_spaces(self): input_space = OldTexText("Input Space") input_space.to_edge(UP) input_space.shift(LEFT*FRAME_X_RADIUS/2) output_space = OldTexText("Output Space") output_space.to_edge(UP) output_space.shift(RIGHT*FRAME_X_RADIUS/2) line = Line( UP*FRAME_Y_RADIUS, DOWN*FRAME_Y_RADIUS, color = WHITE ) self.play( ShimmerIn(input_space), ShimmerIn(output_space), ShowCreation(line), ShowCreation(self.interval), ) self.wait() def move_dot(self): kwargs = { "rate_func" : None, "run_time" : 3 } self.play( Homotopy(self.input_homotopy, self.input_dot, **kwargs), Homotopy(self.output_homotopy, self.output_dot, **kwargs), ShowCreation(self.output, **kwargs) ) self.wait() def label_jump(self): jump_points = Mobject( Point(self.spiril1.get_points()[-1]), Point(self.spiril2.get_points()[0]) ) self.brace = Brace(jump_points, RIGHT) self.jump = OldTexText("Jump") self.jump.next_to(self.brace, RIGHT) self.play( GrowFromCenter(self.brace), ShimmerIn(self.jump) ) self.wait() self.remove(self.brace, self.jump) def draw_circles(self): input_value = 0.45 input_radius = 0.04 for dot in self.input_dot, self.output_dot: dot.center() kwargs = { "rate_func" : lambda t : interpolate(1, input_value, smooth(t)) } self.play( Homotopy(self.input_homotopy, self.input_dot, **kwargs), Homotopy(self.output_homotopy, self.output_dot, **kwargs) ) A, B = list(map(Mobject.get_center, [self.input_dot, self.output_dot])) A_text = OldTexText("A") A_text.shift(A+2*(LEFT+UP)) A_arrow = Arrow( A_text, self.input_dot, color = self.input_color ) B_text = OldTexText("B") B_text.shift(B+2*RIGHT+DOWN) B_arrow = Arrow( B_text, self.output_dot, color = self.output_color ) tup = self.get_circles_and_points( input_value-input_radius, input_value+input_radius ) input_circle, input_points, output_circle, output_points = tup for text, arrow in [(A_text, A_arrow), (B_text, B_arrow)]: self.play( ShimmerIn(text), ShowCreation(arrow) ) self.wait() self.remove(A_text, A_arrow, B_text, B_arrow) self.play(ShowCreation(input_circle)) self.wait() self.play(ShowCreation(input_points)) self.wait() input_points_copy = input_points.copy() self.play( Transform(input_points_copy, output_points), run_time = 2 ) self.wait() self.play(ShowCreation(output_circle)) self.wait() self.wait() self.remove(*[ input_circle, input_points, output_circle, input_points_copy ]) def vary_circle_sizes(self): input_value = 0.45 radius = 0.04 vary_circles = VaryCircles( self, input_value, radius, run_time = 5, ) self.play(vary_circles) self.wait() text = OldTexText("Function is ``Continuous at A''") text.shift(2*UP).to_edge(LEFT) arrow = Arrow(text, self.input_dot) self.play( ShimmerIn(text), ShowCreation(arrow) ) self.wait() self.remove(vary_circles.mobject, text, arrow) def discontinuous_point(self): point_description = OldTexText( "Point where the function jumps" ) point_description.shift(3*RIGHT) discontinuous_at_A = OldTexText( "``Discontinuous at A''", size = "\\Large" ) discontinuous_at_A.shift(2*UP).to_edge(LEFT) text = OldTexText(""" Circle around ouput \\\\ points can never \\\\ be smaller than \\\\ the jump """) text.scale(0.75) text.shift(3.5*RIGHT) input_value = 0.5 input_radius = 0.04 vary_circles = VaryCircles( self, input_value, input_radius, run_time = 5, ) for dot in self.input_dot, self.output_dot: dot.center() kwargs = { "rate_func" : lambda t : interpolate(0.45, input_value, smooth(t)) } self.play( Homotopy(self.input_homotopy, self.input_dot, **kwargs), Homotopy(self.output_homotopy, self.output_dot, **kwargs) ) discontinuous_arrow = Arrow(discontinuous_at_A, self.input_dot) arrow = Arrow( point_description, self.output_dot, buff = 0.05, color = self.output_color ) self.play( ShimmerIn(point_description), ShowCreation(arrow) ) self.wait() self.remove(point_description, arrow) tup = self.get_circles_and_points( input_value-input_radius, input_value+input_radius ) input_circle, input_points, output_circle, output_points = tup input_points_copy = input_points.copy() self.play(ShowCreation(input_circle)) self.play(ShowCreation(input_points)) self.play( Transform(input_points_copy, output_points), run_time = 2 ) self.play(ShowCreation(output_circle)) self.wait() self.play(ShimmerIn(text)) self.remove(input_circle, input_points, output_circle, input_points_copy) self.play(vary_circles) self.wait() self.play( ShimmerIn(discontinuous_at_A), ShowCreation(discontinuous_arrow) ) self.wait(3) self.remove(vary_circles.mobject, discontinuous_at_A, discontinuous_arrow) def continuous_point(self): pass class VaryCircles(Animation): def __init__(self, scene, input_value, radius, **kwargs): digest_locals(self) Animation.__init__(self, Mobject(), **kwargs) def interpolate_mobject(self, alpha): radius = self.radius + 0.9*self.radius*np.sin(1.5*np.pi*alpha) self.mobject = Mobject(*self.scene.get_circles_and_points( self.input_value-radius, self.input_value+radius )).ingest_submobjects() class FunctionIsContinuousText(Scene): def construct(self): all_points = OldTexText("$f$ is continuous at every input point") continuous = OldTexText("$f$ is continuous") all_points.shift(UP) continuous.shift(DOWN) arrow = Arrow(all_points, continuous) self.play(ShimmerIn(all_points)) self.play(ShowCreation(arrow)) self.play(ShimmerIn(continuous)) self.wait() class DefineActualHilbertCurveText(Scene): def construct(self): self.add(OldTexText(""" Finally define a Hilbert Curve\\dots """)) self.wait() class ReliesOnWonderfulProperty(Scene): def construct(self): self.add(OldTexText(""" \\dots which relies on a certain property of Pseudo-Hilbert-curves. """)) self.wait() class WonderfulPropertyOfPseudoHilbertCurves(Scene): def construct(self): val = 0.3 text = OldTexText([ "PHC", "$_n", "(", "%3.1f"%val, ")$", " has a ", "limit point ", "as $n \\to \\infty$" ]) func_parts = text.copy().split()[:5] Mobject(*func_parts).center().to_edge(UP) num_str, val_str = func_parts[1], func_parts[3] curve = UnitInterval() curve.sort_points(lambda p : p[0]) dot = Dot().shift(curve.number_to_point(val)) arrow = Arrow(val_str, dot, buff = 0.1) curve.add_numbers(0, 1) self.play(ShowCreation(curve)) self.play( ShimmerIn(val_str), ShowCreation(arrow), ShowCreation(dot) ) self.wait() self.play( FadeOut(arrow), *[ FadeIn(func_parts[i]) for i in (0, 1, 2, 4) ] ) for num in range(2,9): new_curve = HilbertCurve(order = num) new_curve.scale(0.8) new_dot = Dot(new_curve.get_points()[int(val*new_curve.get_num_points())]) new_num_str = OldTex(str(num)).replace(num_str) self.play( Transform(curve, new_curve), Transform(dot, new_dot), Transform(num_str, new_num_str) ) self.wait() text.to_edge(UP) text_parts = text.split() for index in 1, -1: text_parts[index].set_color() starters = Mobject(*func_parts + [ Point(mob.get_center(), stroke_width=1) for mob in text_parts[5:] ]) self.play(Transform(starters, text)) arrow = Arrow(text_parts[-2].get_bottom(), dot, buff = 0.1) self.play(ShowCreation(arrow)) self.wait() class FollowManyPoints(Scene): def construct(self): text = OldTexText([ "PHC", "_n", "(", "x", ")$", " has a limit point ", "as $n \\to \\infty$", "\\\\ for all $x$" ]) parts = text.split() parts[-1].next_to(Mobject(*parts[:-1]), DOWN) parts[-1].set_color(BLUE) parts[3].set_color(BLUE) parts[1].set_color() parts[-2].set_color() text.to_edge(UP) curve = UnitInterval() curve.sort_points(lambda p : p[0]) vals = np.arange(0.1, 1, 0.1) dots = Mobject(*[ Dot(curve.number_to_point(val)) for val in vals ]) curve.add_numbers(0, 1) starter_dots = dots.copy().ingest_submobjects() starter_dots.shift(2*UP) self.add(curve, text) self.wait() self.play(DelayByOrder(ApplyMethod(starter_dots.shift, 2*DOWN))) self.wait() self.remove(starter_dots) self.add(dots) for num in range(1, 10): new_curve = HilbertCurve(order = num) new_curve.scale(0.8) new_dots = Mobject(*[ Dot(new_curve.get_points()[int(val*new_curve.get_num_points())]) for val in vals ]) self.play( Transform(curve, new_curve), Transform(dots, new_dots), ) # self.wait() class FormalDefinitionOfHilbertCurve(Scene): def construct(self): val = 0.7 text = OldTex([ "\\text{HC}(", "x", ")", "=\\lim_{n \\to \\infty}\\text{PHC}_n(", "x", ")" ]) text.to_edge(UP) x1 = text.split()[1] x2 = text.split()[-2] x2.set_color(BLUE) explanation = OldTexText("Actual Hilbert curve function") exp_arrow = Arrow(explanation, text.split()[0]) curve = UnitInterval() dot = Dot(curve.number_to_point(val)) x_arrow = Arrow(x1.get_bottom(), dot, buff = 0) curve.sort_points(lambda p : p[0]) curve.add_numbers(0, 1) self.add(*text.split()[:3]) self.play( ShimmerIn(explanation), ShowCreation(exp_arrow) ) self.wait() self.remove(explanation, exp_arrow) self.play(ShowCreation(curve)) self.play( ApplyMethod(x1.set_color, BLUE), ShowCreation(x_arrow), ShowCreation(dot) ) self.wait() self.remove(x_arrow) limit = Mobject(*text.split()[3:]).ingest_submobjects() limit.stroke_width = 1 self.play(ShimmerIn(limit)) for num in range(1, 9): new_curve = HilbertCurve(order = num) new_curve.scale(0.8) new_dot = Dot(new_curve.get_points()[int(val*new_curve.get_num_points())]) self.play( Transform(curve, new_curve), Transform(dot, new_dot), ) class CouldNotDefineForSnakeCurve(Scene): def construct(self): self.add(OldTexText(""" You could not define a limit curve from snake curves. """)) self.wait() class ThreeThingsToProve(Scene): def construct(self): definition = OldTex([ "\\text{HC}(", "x", ")", "=\\lim_{n \\to \\infty}\\text{PHC}_n(", "x", ")" ]) definition.to_edge(UP) definition.split()[1].set_color(BLUE) definition.split()[-2].set_color(BLUE) intro = OldTexText("Three things need to be proven") prove_that = OldTexText("Prove that HC is $\\dots$") prove_that.scale(0.7) prove_that.to_edge(LEFT) items = OldTexText([ "\\begin{enumerate}", "\\item Well-defined: ", "Points on Pseudo-Hilbert-curves really do converge", "\\item A Curve: ", "HC is continuous", "\\item Space-filling: ", "Each point in the unit square is an output of HC", "\\end{enumerate}", ]).split() items[1].set_color(GREEN) items[3].set_color(YELLOW_C) items[5].set_color(MAROON) Mobject(*items).to_edge(RIGHT) self.add(definition) self.play(ShimmerIn(intro)) self.wait() self.play(Transform(intro, prove_that)) for item in items[1:-1]: self.play(ShimmerIn(item)) self.wait() class TilingSpace(Scene): def construct(self): coords_set = [ORIGIN] for n in range(int(FRAME_WIDTH)): for vect in UP, RIGHT: for k in range(n): new_coords = coords_set[-1]+((-1)**n)*vect coords_set.append(new_coords) square = Square(side_length = 1, color = WHITE) squares = Mobject(*[ square.copy().shift(coords) for coords in coords_set ]).ingest_submobjects() self.play( DelayByOrder(FadeIn(squares)), run_time = 3 ) curve = HilbertCurve(order = 6).scale(1./6) all_curves = Mobject(*[ curve.copy().shift(coords) for coords in coords_set ]).ingest_submobjects() all_curves.thin_out(10) self.play(ShowCreation( all_curves, rate_func=linear, run_time = 15 )) class ColorIntervals(Scene): def construct(self): number_line = NumberLine( numerical_radius = 5, number_at_center = 5, leftmost_tick = 0, density = 2*DEFAULT_POINT_DENSITY_1D ) number_line.shift(2*RIGHT) number_line.add_numbers() number_line.scale(2) brace = Brace(Mobject( *number_line.submobjects[:2] )) self.add(number_line) for n in range(0, 10, 2): if n == 0: brace_anim = GrowFromCenter(brace) else: brace_anim = ApplyMethod(brace.shift, 2*RIGHT) self.play( ApplyMethod( number_line.set_color, RED, lambda p : p[0] > n-6.2 and p[0] < n-4 and p[1] > -0.4 ), brace_anim )
videos_3b1b/_2016/hilbert/fractal_porn.py
from manim_imports_ext import * from from_3b1b.old.hilbert.curves import * class Intro(TransformOverIncreasingOrders): @staticmethod def args_to_string(*args): return "" @staticmethod def string_to_args(string): raise Exception("string_to_args Not Implemented!") def construct(self): words1 = OldTexText( "If you watched my video about Hilbert's space-filling curve\\dots" ) words2 = OldTexText( "\\dots you might be curious to see what a few other space-filling curves look like." ) words2.scale(0.8) for words in words1, words2: words.to_edge(UP, buff = 0.2) self.setup(HilbertCurve) self.play(ShimmerIn(words1)) for x in range(4): self.increase_order() self.remove(words1) self.increase_order( ShimmerIn(words2) ) for x in range(4): self.increase_order() class BringInPeano(Intro): def construct(self): words1 = OldTexText(""" For each one, see if you can figure out what the pattern of construction is. """) words2 = OldTexText(""" This one is the Peano curve. """) words3 = OldTexText(""" It is the original space-filling curve. """) self.setup(PeanoCurve) self.play(ShimmerIn(words1)) self.wait(5) self.remove(words1) self.add(words2.to_edge(UP)) for x in range(3): self.increase_order() self.remove(words2) self.increase_order(ShimmerIn(words3.to_edge(UP))) for x in range(2): self.increase_order() class FillOtherShapes(Intro): def construct(self): words1 = OldTexText(""" But of course, there's no reason we should limit ourselves to filling in squares. """) words2 = OldTexText(""" Here's a simple triangle-filling curve I defined in a style reflective of a Hilbert curve. """) words1.to_edge(UP) words2.scale(0.8).to_edge(UP, buff = 0.2) self.setup(TriangleFillingCurve) self.play(ShimmerIn(words1)) for x in range(3): self.increase_order() self.remove(words1) self.add(words2) for x in range(5): self.increase_order() class SmallerFlowSnake(FlowSnake): CONFIG = { "radius" : 4 } class MostDelightfulName(Intro): def construct(self): words1 = OldTexText(""" This one has the most delightful name, thanks to mathematician/programmer Bill Gosper: """) words2 = OldTexText("``Flow Snake''") words3 = OldTexText(""" What makes this one particularly interesting is that the boundary itself is a fractal. """) for words in words1, words2, words3: words.to_edge(UP) self.setup(SmallerFlowSnake) self.play(ShimmerIn(words1)) for x in range(3): self.increase_order() self.remove(words1) self.add(words2) for x in range(3): self.increase_order() self.remove(words2) self.play(ShimmerIn(words3)) class SurpriseFractal(Intro): def construct(self): words = OldTexText(""" It might come as a surprise how some well-known fractals can be described with curves. """) words.to_edge(UP) self.setup(Sierpinski) self.add(OldTexText("Speaking of other fractals\\dots")) self.wait(3) self.clear() self.play(ShimmerIn(words)) for x in range(9): self.increase_order() class IntroduceKoch(Intro): def construct(self): words = list(map(TexText, [ "This is another famous fractal.", "The ``Koch Snowflake''", "Let's finish things off by seeing how to turn \ this into a space-filling curve" ])) for text in words: text.to_edge(UP) self.setup(KochCurve) self.add(words[0]) for x in range(3): self.increase_order() self.remove(words[0]) self.add(words[1]) for x in range(4): self.increase_order() self.remove(words[1]) self.add(words[2]) self.wait(6) class StraightKoch(KochCurve): CONFIG = { "axiom" : "A" } class SharperKoch(StraightKoch): CONFIG = { "angle" : 0.9*np.pi/2, } class DullerKoch(StraightKoch): CONFIG = { "angle" : np.pi/6, } class SpaceFillingKoch(StraightKoch): CONFIG = { "angle" : np.pi/2, } class FromKochToSpaceFilling(Scene): def construct(self): self.max_order = 7 self.revisit_koch() self.show_angles() self.show_change_side_by_side() def revisit_koch(self): words = list(map(TexText, [ "First, look at how one section of this curve is made.", "This pattern of four lines is the ``seed''", "With each iteration, every straight line is \ replaced with an appropriately small copy of the seed", ])) for text in words: text.to_edge(UP) self.add(words[0]) curve = StraightKoch(order = self.max_order) self.play(Transform( curve, StraightKoch(order = 1), run_time = 5 )) self.remove(words[0]) self.add(words[1]) self.wait(4) self.remove(words[1]) self.add(words[2]) self.wait(3) for order in range(2, self.max_order): self.play(Transform( curve, StraightKoch(order = order) )) if order == 2: self.wait(2) elif order == 3: self.wait() self.clear() def show_angles(self): words = OldTexText(""" Let's see what happens as we change the angle in this seed """) words.to_edge(UP) koch, sharper_koch, duller_koch = curves = [ CurveClass(order = 1) for CurveClass in (StraightKoch, SharperKoch, DullerKoch) ] arcs = [ Arc( 2*(np.pi/2 - curve.angle), radius = r, start_angle = np.pi+curve.angle ).shift(curve.get_points()[curve.get_num_points()/2]) for curve, r in zip(curves, [0.6, 0.7, 0.4]) ] theta = OldTex("\\theta") theta.shift(arcs[0].get_center()+2.5*DOWN) arrow = Arrow(theta, arcs[0]) self.add(words, koch) self.play(ShowCreation(arcs[0])) self.play( ShowCreation(arrow), ShimmerIn(theta) ) self.wait(2) self.remove(theta, arrow) self.play( Transform(koch, duller_koch), Transform(arcs[0], arcs[2]), ) self.play( Transform(koch, sharper_koch), Transform(arcs[0], arcs[1]), ) self.clear() def show_change_side_by_side(self): seed = OldTexText("Seed") seed.shift(3*LEFT+2*DOWN) fractal = OldTexText("Fractal") fractal.shift(3*RIGHT+2*DOWN) words = list(map(TexText, [ "A sharper angle results in a richer curve", "A more obtuse angle gives a sparser curve", "And as the angle approaches 0\\dots", "We have a new space-filling curve." ])) for text in words: text.to_edge(UP) sharper, duller, space_filling = [ CurveClass(order = 1).shift(3*LEFT) for CurveClass in (SharperKoch, DullerKoch, SpaceFillingKoch) ] shaper_f, duller_f, space_filling_f = [ CurveClass(order = self.max_order).shift(3*RIGHT) for CurveClass in (SharperKoch, DullerKoch, SpaceFillingKoch) ] self.add(words[0]) left_curve = SharperKoch(order = 1) right_curve = SharperKoch(order = 1) self.play( Transform(left_curve, sharper), ApplyMethod(right_curve.shift, 3*RIGHT), ) self.play( Transform( right_curve, SharperKoch(order = 2).shift(3*RIGHT) ), ShimmerIn(seed), ShimmerIn(fractal) ) for order in range(3, self.max_order): self.play(Transform( right_curve, SharperKoch(order = order).shift(3*RIGHT) )) self.remove(words[0]) self.add(words[1]) kwargs = { "run_time" : 4, } self.play( Transform(left_curve, duller, **kwargs), Transform(right_curve, duller_f, **kwargs) ) self.wait() kwargs["run_time"] = 7 kwargs["rate_func"] = None self.remove(words[1]) self.add(words[2]) self.play( Transform(left_curve, space_filling, **kwargs), Transform(right_curve, space_filling_f, **kwargs) ) self.remove(words[2]) self.add(words[3]) self.wait()
videos_3b1b/_2016/hilbert/section3.py
from manim_imports_ext import * import displayer as disp from hilbert.curves import \ TransformOverIncreasingOrders, FlowSnake, HilbertCurve, \ SnakeCurve, Sierpinski from hilbert.section1 import get_mathy_and_bubble class SectionThree(Scene): def construct(self): self.add(OldTexText("A few words on the usefulness of infinite math")) self.wait() class InfiniteResultsFiniteWorld(Scene): def construct(self): left_words = OldTexText("Infinite result") right_words = OldTexText("Finite world") for words in left_words, right_words: words.scale(0.8) left_formula = OldTex( "\\sum_{n = 0}^{\\infty} 2^n = -1" ) right_formula = OldTex("111\\cdots111") for formula in left_formula, right_formula: formula.add( Brace(formula, UP), ) formula.ingest_submobjects() right_overwords = OldTexText( "\\substack{\ \\text{How computers} \\\\ \ \\text{represent $-1$}\ }" ).scale(1.5) left_mobs = [left_words, left_formula] right_mobs = [right_words, right_formula] for mob in left_mobs: mob.to_edge(RIGHT, buff = 1) mob.shift(FRAME_X_RADIUS*LEFT) for mob in right_mobs: mob.to_edge(LEFT, buff = 1) mob.shift(FRAME_X_RADIUS*RIGHT) arrow = Arrow(left_words, right_words) right_overwords.next_to(right_formula, UP) self.play(ShimmerIn(left_words)) self.play(ShowCreation(arrow)) self.play(ShimmerIn(right_words)) self.wait() self.play( ShimmerIn(left_formula), ApplyMethod(left_words.next_to, left_formula, UP) ) self.wait() self.play( ShimmerIn(right_formula), Transform(right_words, right_overwords) ) self.wait() self.finite_analog( Mobject(left_formula, left_words), arrow, Mobject(right_formula, right_words) ) def finite_analog(self, left_mob, arrow, right_mob): self.clear() self.add(left_mob, arrow, right_mob) ex = OldTexText("\\times") ex.set_color(RED) # ex.shift(arrow.get_center()) middle = OldTex( "\\sum_{n=0}^N 2^n \\equiv -1 \\mod 2^{N+1}" ) finite_analog = OldTexText("Finite analog") finite_analog.scale(0.8) brace = Brace(middle, UP) finite_analog.next_to(brace, UP) new_left = left_mob.copy().to_edge(LEFT) new_right = right_mob.copy().to_edge(RIGHT) left_arrow, right_arrow = [ Arrow( mob1.get_right()[0]*RIGHT, mob2.get_left()[0]*RIGHT, buff = 0 ) for mob1, mob2 in [ (new_left, middle), (middle, new_right) ] ] for mob in ex, middle: mob.sort_points(get_norm) self.play(GrowFromCenter(ex)) self.wait() self.play( Transform(left_mob, new_left), Transform(arrow.copy(), left_arrow), DelayByOrder(Transform(ex, middle)), Transform(arrow, right_arrow), Transform(right_mob, new_right) ) self.play( GrowFromCenter(brace), ShimmerIn(finite_analog) ) self.wait() self.equivalence( left_mob, left_arrow, Mobject(middle, brace, finite_analog) ) def equivalence(self, left_mob, arrow, right_mob): self.clear() self.add(left_mob, arrow, right_mob) words = OldTexText("is equivalent to") words.shift(0.25*LEFT) words.set_color(BLUE) new_left = left_mob.copy().shift(RIGHT) new_right = right_mob.copy() new_right.shift( (words.get_right()[0]-\ right_mob.get_left()[0]+\ 0.5 )*RIGHT ) for mob in arrow, words: mob.sort_points(get_norm) self.play( ApplyMethod(left_mob.shift, RIGHT), Transform(arrow, words), ApplyMethod(right_mob.to_edge, RIGHT) ) self.wait() class HilbertCurvesStayStable(Scene): def construct(self): scale_factor = 0.9 grid = Grid(4, 4, stroke_width = 1) curve = HilbertCurve(order = 2) for mob in grid, curve: mob.scale(scale_factor) words = OldTexText(""" Sequence of curves is stable $\\leftrightarrow$ existence of limit curve """, size = "\\normal") words.scale(1.25) words.to_edge(UP) self.add(curve, grid) self.wait() for n in range(3, 7): if n == 5: self.play(ShimmerIn(words)) new_grid = Grid(2**n, 2**n, stroke_width = 1) new_curve = HilbertCurve(order = n) for mob in new_grid, new_curve: mob.scale(scale_factor) self.play( ShowCreation(new_grid), Animation(curve) ) self.remove(grid) grid = new_grid self.play(Transform(curve, new_curve)) self.wait() class InfiniteObjectsEncapsulateFiniteObjects(Scene): def get_triangles(self): triangle = Polygon( LEFT/np.sqrt(3), UP, RIGHT/np.sqrt(3), color = GREEN ) triangles = Mobject( triangle.copy().scale(0.5).shift(LEFT), triangle, triangle.copy().scale(0.3).shift(0.5*UP+RIGHT) ) triangles.center() return triangles def construct(self): words =[ OldTexText(text, size = "\\large") for text in [ "Truths about infinite objects", " encapsulate ", "facts about finite objects" ] ] words[0].set_color(RED) words[1].next_to(words[0]) words[2].set_color(GREEN).next_to(words[1]) Mobject(*words).center().to_edge(UP) infinite_objects = [ OldTex( "\\sum_{n=0}^\\infty", size = "\\normal" ).set_color(RED_E), Sierpinski(order = 8).scale(0.3), OldTexText( "$\\exists$ something infinite $\\dots$" ).set_color(RED_B) ] finite_objects = [ OldTex( "\\sum_{n=0}^N", size = "\\normal" ).set_color(GREEN_E), self.get_triangles(), OldTexText( "$\\forall$ finite somethings $\\dots$" ).set_color(GREEN_B) ] for infinite, finite, n in zip(infinite_objects, finite_objects, it.count(1, 2)): infinite.next_to(words[0], DOWN, buff = n) finite.next_to(words[2], DOWN, buff = n) self.play(ShimmerIn(words[0])) self.wait() self.play(ShimmerIn(infinite_objects[0])) self.play(ShowCreation(infinite_objects[1])) self.play(ShimmerIn(infinite_objects[2])) self.wait() self.play(ShimmerIn(words[1]), ShimmerIn(words[2])) self.play(ShimmerIn(finite_objects[0])) self.play(ShowCreation(finite_objects[1])) self.play(ShimmerIn(finite_objects[2])) self.wait() class StatementRemovedFromReality(Scene): def construct(self): mathy, bubble = get_mathy_and_bubble() bubble.stretch_to_fit_width(4) mathy.to_corner(DOWN+LEFT) bubble.pin_to(mathy) bubble.shift(LEFT) morty = Mortimer() morty.to_corner(DOWN+RIGHT) morty_bubble = SpeechBubble() morty_bubble.stretch_to_fit_width(4) morty_bubble.pin_to(morty) bubble.write(""" Did you know a curve \\\\ can fill all space? """) morty_bubble.write("Who cares?") self.add(mathy, morty) for bub, buddy in [(bubble, mathy), (morty_bubble, morty)]: self.play(Transform( Point(bub.get_tip()), bub )) self.play(ShimmerIn(bub.content)) self.play(ApplyMethod( buddy.blink, rate_func = squish_rate_func(there_and_back) ))
videos_3b1b/_2016/hilbert/section1.py
from manim_imports_ext import * import displayer as disp from hilbert.curves import \ TransformOverIncreasingOrders, FlowSnake, HilbertCurve, \ SnakeCurve from constants import * def get_grid(): return Grid(64, 64) def get_freq_line(): return UnitInterval().shift(2*DOWN) ##Change? def get_mathy_and_bubble(): mathy = Mathematician() mathy.to_edge(DOWN).shift(4*LEFT) bubble = SpeechBubble(initial_width = 8) bubble.pin_to(mathy) return mathy, bubble class AboutSpaceFillingCurves(TransformOverIncreasingOrders): @staticmethod def args_to_string(): return "" @staticmethod def string_to_args(arg_str): return () def construct(self): self.bubble = ThoughtBubble().ingest_submobjects() self.bubble.scale(1.5) TransformOverIncreasingOrders.construct(self, FlowSnake, 7) self.play(Transform(self.curve, self.bubble)) self.show_infinite_objects() self.pose_question() self.wait() def show_infinite_objects(self): sigma, summand, equals, result = OldTex([ "\\sum_{n = 1}^{\\infty}", "\\dfrac{1}{n^2}", "=", "\\dfrac{\pi^2}{6}" ]).split() alt_summand = OldTex("n").replace(summand) alt_result = OldTex("-\\dfrac{1}{12}").replace(result) rationals, other_equals, naturals = OldTex([ "|\\mathds{Q}|", "=", "|\\mathds{N}|" ]).scale(2).split() infinity = OldTex("\\infty").scale(2) local_mobjects = list(filter( lambda m : isinstance(m, Mobject), list(locals().values()), )) for mob in local_mobjects: mob.sort_points(get_norm) self.play(ShimmerIn(infinity)) self.wait() self.play( ShimmerIn(summand), ShimmerIn(equals), ShimmerIn(result), DelayByOrder(Transform(infinity, sigma)) ) self.wait() self.play( Transform(summand, alt_summand), Transform(result, alt_result), ) self.wait() self.remove(infinity) self.play(*[ CounterclockwiseTransform( Mobject(summand, equals, result, sigma), Mobject(rationals, other_equals, naturals) ) ]) self.wait() self.clear() self.add(self.bubble) def pose_question(self): infinity, rightarrow, N = OldTex([ "\\infty", "\\rightarrow", "N" ]).scale(2).split() question_mark = OldTexText("?").scale(2) self.add(question_mark) self.wait() self.play(*[ ShimmerIn(mob) for mob in (infinity, rightarrow, N) ] + [ ApplyMethod(question_mark.next_to, rightarrow, UP), ]) self.wait() class PostponePhilosophizing(Scene): def construct(self): abstract, arrow, concrete = OldTexText([ "Abstract", " $\\rightarrow$ ", "Concrete" ]).scale(2).split() self.add(abstract, arrow, concrete) self.wait() self.play(*[ ApplyMethod( word1.replace, word2, path_func = path_along_arc(np.pi/2) ) for word1, word2 in it.permutations([abstract, concrete]) ]) self.wait() class GrowHilbertWithName(Scene): def construct(self): curve = HilbertCurve(order = 1) words = OldTexText("``Hilbert Curve''") words.to_edge(UP, buff = 0.2) self.play( ShimmerIn(words), Transform(curve, HilbertCurve(order = 2)), run_time = 2 ) for n in range(3, 8): self.play( Transform(curve, HilbertCurve(order = n)), run_time = 5. /n ) class SectionOne(Scene): def construct(self): self.add(OldTexText("Section 1: Seeing with your ears")) self.wait() class WriteSomeSoftware(Scene): pass #Done viea screen capture, written here for organization class ImageToSound(Scene): def construct(self): string = Vibrate(color = BLUE_D, run_time = 5) picture = ImageMobject("lion", invert = False) picture.scale(0.8) picture_copy = picture.copy() picture.sort_points(get_norm) string.mobject.sort_points(lambda p : -get_norm(p)) self.add(picture) self.wait() self.play(Transform( picture, string.mobject, run_time = 3, rate_func = rush_into )) self.remove(picture) self.play(string) for mob in picture_copy, string.mobject: mob.sort_points(lambda p : get_norm(p)%1) self.play(Transform( string.mobject, picture_copy, run_time = 5, rate_func = rush_from )) class LinksInDescription(Scene): def construct(self): text = OldTexText(""" See links in the description for more on sight via sound. """) self.play(ShimmerIn(text)) self.play(ShowCreation(Arrow(text, 3*DOWN))) self.wait(2) class ImageDataIsTwoDimensional(Scene): def construct(self): image = ImageMobject("lion", invert = False) image.scale(0.5) image.shift(2*LEFT) self.add(image) for vect, num in zip([DOWN, RIGHT], [1, 2]): brace = Brace(image, vect) words_mob = OldTexText("Dimension %d"%num) words_mob.next_to(image, vect, buff = 1) self.play( Transform(Point(brace.get_center()), brace), ShimmerIn(words_mob), run_time = 2 ) self.wait() class SoundDataIsOneDimensional(Scene): def construct(self): overtones = 5 floor = 2*DOWN main_string = Vibrate(color = BLUE_D) component_strings = [ Vibrate( num_periods = k+1, overtones = 1, color = color, center = 2*DOWN + UP*k ) for k, color in zip( list(range(overtones)), Color(BLUE_E).range_to(WHITE, overtones) ) ] dots = [ Dot( string.mobject.get_center(), color = string.mobject.get_color() ) for string in component_strings ] freq_line = get_freq_line() freq_line.shift(floor) freq_line.sort_points(get_norm) brace = Brace(freq_line, UP) words = OldTexText("Range of frequency values") words.next_to(brace, UP) self.play(*[ TransformAnimations( main_string.copy(), string, run_time = 5 ) for string in component_strings ]) self.clear() self.play(*[ TransformAnimations( string, Animation(dot) ) for string, dot in zip(component_strings, dots) ]) self.clear() self.play( ShowCreation(freq_line), GrowFromCenter(brace), ShimmerIn(words), *[ Transform( dot, dot.copy().scale(2).rotate(-np.pi/2).shift(floor), path_func = path_along_arc(np.pi/3) ) for dot in dots ] ) self.wait(0.5) class GridOfPixels(Scene): def construct(self): low_res = ImageMobject("low_resolution_lion", invert = False) high_res = ImageMobject("Lion", invert = False) grid = get_grid().scale(0.8) for mob in low_res, high_res: mob.replace(grid, stretch = True) side_brace = Brace(low_res, LEFT) top_brace = Brace(low_res, UP) top_words = OldTexText("256 Px", size = "\\normal") side_words = top_words.copy().rotate(np.pi/2) top_words.next_to(top_brace, UP) side_words.next_to(side_brace, LEFT) self.add(high_res) self.wait() self.play(DelayByOrder(Transform(high_res, low_res))) self.wait() self.play( GrowFromCenter(top_brace), GrowFromCenter(side_brace), ShimmerIn(top_words), ShimmerIn(side_words) ) self.wait() for mob in grid, high_res: mob.sort_points(get_norm) self.play(DelayByOrder(Transform(high_res, grid))) self.wait() class ShowFrequencySpace(Scene): def construct(self): freq_line = get_freq_line() self.add(freq_line) self.wait() for tex, vect in zip(["20 Hz", "20{,}000 Hz"], [LEFT, RIGHT]): tex_mob = OldTexText(tex) tex_mob.to_edge(vect) tex_mob.shift(UP) arrow = Arrow(tex_mob, freq_line.get_edge_center(vect)) self.play( ShimmerIn(tex_mob), ShowCreation(arrow) ) self.wait() class AssociatePixelWithFrequency(Scene): def construct(self): big_grid_dim = 20. small_grid_dim = 6. big_grid = Grid(64, 64, height = big_grid_dim, width = big_grid_dim) big_grid.to_corner(UP+RIGHT, buff = 2) small_grid = big_grid.copy() small_grid.scale(small_grid_dim/big_grid_dim) small_grid.center() pixel = MobjectFromRegion( region_from_polygon_vertices(*0.2*np.array([ RIGHT+DOWN, RIGHT+UP, LEFT+UP, LEFT+DOWN ])) ) pixel.set_color(WHITE) pixel_width = big_grid.width/big_grid.columns pixel.set_width(pixel_width) pixel.to_corner(UP+RIGHT, buff = 2) pixel.shift(5*pixel_width*(2*LEFT+DOWN)) freq_line = get_freq_line() dot = Dot() dot.shift(freq_line.get_center() + 2*RIGHT) string = Line(LEFT, RIGHT, color = GREEN) arrow = Arrow(dot, string.get_center()) vibration_config = { "overtones" : 1, "spatial_period" : 2, } vibration, loud_vibration, quiet_vibration = [ Vibrate(string.copy(), amplitude = a, **vibration_config) for a in [0.5, 1., 0.25] ] self.add(small_grid) self.wait() self.play( Transform(small_grid, big_grid) ) self.play(FadeIn(pixel)) self.wait() self.play( FadeOut(small_grid), ShowCreation(freq_line) ) self.remove(small_grid) self.play( Transform(pixel, dot), ) self.wait() self.play(ShowCreation(arrow)) self.play(loud_vibration) self.play( TransformAnimations(loud_vibration, quiet_vibration), ApplyMethod(dot.fade, 0.9) ) self.clear() self.add(freq_line, dot, arrow) self.play(quiet_vibration) class ListenToAllPixels(Scene): def construct(self): grid = get_grid() grid.sort_points(get_norm) freq_line = get_freq_line() freq_line.sort_points(lambda p : p[0]) red, blue = Color(RED), Color(BLUE) freq_line.set_color_by_gradient(red, blue) colors = [ Color(rgb = interpolate( np.array(red.rgb), np.array(blue.rgb), alpha )) for alpha in np.arange(4)/3. ] string = Line(3*LEFT, 3*RIGHT, color = colors[1]) vibration = Vibrate(string) vibration_copy = vibration.copy() vibration_copy.mobject.stroke_width = 1 sub_vibrations = [ Vibrate( string.copy().shift((n-1)*UP).set_color(colors[n]), overtones = 1, spatial_period = 6./(n+1), temporal_period = 1./(n+1), amplitude = 0.5/(n+1) ) for n in range(4) ] words = OldTex("&\\vdots \\\\ \\text{thousands }& \\text{of frequencies} \\\\ &\\vdots") words.to_edge(UP, buff = 0.1) self.add(grid) self.wait() self.play(DelayByOrder(ApplyMethod( grid.set_color_by_gradient, red, blue ))) self.play(Transform(grid, freq_line)) self.wait() self.play( ShimmerIn( words, rate_func = squish_rate_func(smooth, 0, 0.2) ), *sub_vibrations, run_time = 5 ) self.play( *[ TransformAnimations( sub_vib, vibration ) for sub_vib in sub_vibrations ]+[FadeOut(words)] ) self.clear() self.add(freq_line) self.play(vibration) class LayAsideSpeculation(Scene): def construct(self): words = OldTexText("Would this actually work?") grid = get_grid() grid.set_width(6) grid.to_edge(LEFT) freq_line = get_freq_line() freq_line.set_width(6) freq_line.center().to_edge(RIGHT) mapping = Mobject( grid, freq_line, Arrow(grid, freq_line) ) mapping.ingest_submobjects() lower_left = Point().to_corner(DOWN+LEFT, buff = 0) lower_right = Point().to_corner(DOWN+RIGHT, buff = 0) self.add(words) self.wait() self.play( Transform(words, lower_right), Transform(lower_left, mapping) ) self.wait() class RandomMapping(Scene): def construct(self): grid = get_grid() grid.set_width(6) grid.to_edge(LEFT) freq_line = get_freq_line() freq_line.set_width(6) freq_line.center().to_edge(RIGHT) # for mob in grid, freq_line: # indices = np.arange(mob.get_num_points()) # random.shuffle(indices) # mob.points = mob.get_points()[indices] stars = Stars(stroke_width = grid.stroke_width) self.add(grid) targets = [stars, freq_line] alphas = [not_quite_there(rush_into), rush_from] for target, rate_func in zip(targets, alphas): self.play(Transform( grid, target, run_time = 3, rate_func = rate_func, path_func = path_along_arc(-np.pi/2) )) self.wait() class DataScrambledAnyway(Scene): def construct(self): self.add(OldTexText("Data is scrambled anyway, right?")) self.wait() class LeverageExistingIntuitions(Scene): def construct(self): self.add(OldTexText("Leverage existing intuitions")) self.wait() class ThinkInTermsOfReverseMapping(Scene): def construct(self): grid = get_grid() grid.set_width(6) grid.to_edge(LEFT) freq_line = get_freq_line() freq_line.set_width(6) freq_line.center().to_edge(RIGHT) arrow = Arrow(grid, freq_line) color1, color2 = YELLOW_C, RED square_length = 0.01 dot1 = Dot(color = color1) dot1.shift(3*RIGHT) dot2 = Dot(color = color2) dot2.shift(3.1*RIGHT) arrow1 = Arrow(2*RIGHT+UP, dot1, color = color1, buff = 0.1) arrow2 = Arrow(4*RIGHT+UP, dot2, color = color2, buff = 0.1) dot3, arrow3 = [ mob.copy().shift(5*LEFT+UP) for mob in (dot1, arrow1) ] dot4, arrow4 = [ mob.copy().shift(5*LEFT+0.9*UP) for mob in (dot2, arrow2) ] self.add(grid, freq_line, arrow) self.wait() self.play(ApplyMethod( arrow.rotate, np.pi, path_func = clockwise_path() )) self.wait() self.play(ShowCreation(arrow1)) self.add(dot1) self.play(ShowCreation(arrow2)) self.add(dot2) self.wait() self.remove(arrow1, arrow2) self.play( Transform(dot1, dot3), Transform(dot2, dot4) ) self.play( ApplyMethod(grid.fade, 0.8), Animation(Mobject(dot3, dot4)) ) self.play(ShowCreation(arrow3)) self.play(ShowCreation(arrow4)) self.wait() class WeaveLineThroughPixels(Scene): @staticmethod def args_to_string(order): return str(order) @staticmethod def string_to_args(order_str): return int(order_str) def construct(self, order): start_color, end_color = RED, GREEN curve = HilbertCurve(order = order) line = Line(5*LEFT, 5*RIGHT) for mob in curve, line: mob.set_color_by_gradient(start_color, end_color) freq_line = get_freq_line() freq_line.replace(line, stretch = True) unit = 6./(2**order) #sidelength of pixel up = unit*UP right = unit*RIGHT lower_left = 3*(LEFT+DOWN) squares = Mobject(*[ Square( side_length = unit, color = WHITE ).shift(x*right+y*up) for x, y in it.product(list(range(2**order)), list(range(2**order))) ]) squares.center() targets = Mobject() for square in squares.submobjects: center = square.get_center() distances = np.apply_along_axis( lambda p : get_norm(p-center), 1, curve.points ) index_along_curve = np.argmin(distances) fraction_along_curve = index_along_curve/float(curve.get_num_points()) target = square.copy().center().scale(0.8/(2**order)) line_index = int(fraction_along_curve*line.get_num_points()) target.shift(line.get_points()[line_index]) targets.add(target) self.add(squares) self.play(ShowCreation( curve, run_time = 5, rate_func=linear )) self.wait() self.play( Transform(curve, line), Transform(squares, targets), run_time = 3 ) self.wait() self.play(ShowCreation(freq_line)) self.wait() class WellPlayedGameOfSnake(Scene): def construct(self): grid = Grid(16, 16).fade() snake_curve = SnakeCurve(order = 4) words = OldTexText("``Snake Curve''") words.next_to(grid, UP) self.add(grid) self.play(ShowCreation( snake_curve, run_time = 7, rate_func=linear )) self.wait() self.play(ShimmerIn(words)) self.wait() class TellMathematicianFriend(Scene): def construct(self): mathy, bubble = get_mathy_and_bubble() squiggle_mouth = mathy.mouth.copy() squiggle_mouth.apply_function( lambda x_y_z : (x_y_z[0], x_y_z[1]+0.02*np.sin(50*x_y_z[0]), x_y_z[2]) ) bubble.ingest_submobjects() bubble.write("Why not use a Hilbert curve \\textinterrobang ") words1 = bubble.content bubble.write("So, it's not one curve but an infinite family of curves \\dots") words2 = bubble.content bubble.write("Well, no, it \\emph{is} just one thing, but I need \\\\ \ to tell you about a certain infinite family first.") words3 = bubble.content description = OldTexText("Mathematician friend", size = "\\small") description.next_to(mathy, buff = 2) arrow = Arrow(description, mathy) self.add(mathy) self.play( ShowCreation(arrow), ShimmerIn(description) ) self.wait() point = Point(bubble.get_tip()) self.play( Transform(point, bubble), ) self.remove(point) self.add(bubble) self.play(ShimmerIn(words1)) self.wait() self.remove(description, arrow) self.play( Transform(mathy.mouth, squiggle_mouth), ApplyMethod(mathy.arm.wag, 0.2*RIGHT, LEFT), ) self.remove(words1) self.add(words2) self.wait(2) self.remove(words2) self.add(words3) self.wait(2) self.play( ApplyPointwiseFunction( lambda p : 15*p/get_norm(p), bubble ), ApplyMethod(mathy.shift, 5*(DOWN+LEFT)), FadeOut(words3), run_time = 3 ) class Order1PseudoHilbertCurve(Scene): def construct(self): words, s = OldTexText(["Pseudo-Hilbert Curve", "s"]).split() pre_words = OldTexText("Order 1") pre_words.next_to(words, LEFT, buff = 0.5) s.next_to(words, RIGHT, buff = 0.05, aligned_edge = DOWN) cluster = Mobject(pre_words, words, s) cluster.center() cluster.scale(0.7) cluster.to_edge(UP, buff = 0.3) cluster.set_color(GREEN) grid1 = Grid(1, 1) grid2 = Grid(2, 2) curve = HilbertCurve(order = 1) self.add(words, s) self.wait() self.play(Transform( s, pre_words, path_func = path_along_arc(-np.pi/3) )) self.wait() self.play(ShowCreation(grid1)) self.wait() self.play(ShowCreation(grid2)) self.wait() kwargs = { "run_time" : 5, "rate_func" : None } self.play(ShowCreation(curve, **kwargs)) self.wait() class Order2PseudoHilbertCurve(Scene): def construct(self): words = OldTexText("Order 2 Pseudo-Hilbert Curve") words.to_edge(UP, buff = 0.3) words.set_color(GREEN) grid2 = Grid(2, 2) grid4 = Grid(4, 4, stroke_width = 2) # order_1_curve = HilbertCurve(order = 1) # squaggle_curve = order_1_curve.copy().apply_function( # lambda (x, y, z) : (x + np.cos(3*y), y + np.sin(3*x), z) # ) # squaggle_curve.show() mini_curves = [ HilbertCurve(order = 1).scale(0.5).shift(1.5*vect) for vect in [ LEFT+DOWN, LEFT+UP, RIGHT+UP, RIGHT+DOWN ] ] last_curve = mini_curves[0] naive_curve = Mobject(last_curve) for mini_curve in mini_curves[1:]: line = Line(last_curve.get_points()[-1], mini_curve.get_points()[0]) naive_curve.add(line, mini_curve) last_curve = mini_curve naive_curve.ingest_submobjects() naive_curve.set_color_by_gradient(RED, GREEN) order_2_curve = HilbertCurve(order = 2) self.add(words, grid2) self.wait() self.play(ShowCreation(grid4)) self.play(*[ ShowCreation(mini_curve) for mini_curve in mini_curves ]) self.wait() self.play(ShowCreation(naive_curve, run_time = 5)) self.remove(*mini_curves) self.wait() self.play(Transform(naive_curve, order_2_curve)) self.wait() class Order3PseudoHilbertCurve(Scene): def construct(self): words = OldTexText("Order 3 Pseudo-Hilbert Curve") words.set_color(GREEN) words.to_edge(UP) grid4 = Mobject( Grid(2, 2), Grid(4, 4, stroke_width = 2) ) grid8 = Grid(8, 8, stroke_width = 1) order_3_curve = HilbertCurve(order = 3) mini_curves = [ HilbertCurve(order = 2).scale(0.5).shift(1.5*vect) for vect in [ LEFT+DOWN, LEFT+UP, RIGHT+UP, RIGHT+DOWN ] ] self.add(words, grid4) self.wait() self.play(ShowCreation(grid8)) self.wait() self.play(*list(map(GrowFromCenter, mini_curves))) self.wait() self.clear() self.add(words, grid8, *mini_curves) self.play(*[ ApplyMethod(curve.rotate, np.pi, axis) for curve, axis in [ (mini_curves[0], UP+RIGHT), (mini_curves[3], UP+LEFT) ] ]) self.play(ShowCreation(order_3_curve, run_time = 5)) self.wait() class GrowToOrder8PseudoHilbertCurve(Scene): def construct(self): self.curve = HilbertCurve(order = 1) self.add(self.curve) self.wait() while self.curve.order < 8: self.increase_order() def increase_order(self): mini_curves = [ self.curve.copy().scale(0.5).shift(1.5*vect) for vect in [ LEFT+DOWN, LEFT+UP, RIGHT+UP, RIGHT+DOWN ] ] self.remove(self.curve) self.play( Transform(self.curve.copy(), mini_curves[0]) ) self.play(*[ GrowFromCenter(mini_curve) for mini_curve in mini_curves[1:] ]) self.wait() self.clear() self.add(*mini_curves) self.play(*[ ApplyMethod(curve.rotate, np.pi, axis) for curve, axis in [ (mini_curves[0], UP+RIGHT), (mini_curves[3], UP+LEFT) ] ]) self.curve = HilbertCurve(order = self.curve.order+1) self.play(ShowCreation(self.curve, run_time = 2)) self.remove(*mini_curves) self.wait() class UseOrder8(Scene): def construct(self): mathy, bubble = get_mathy_and_bubble() bubble.write("For a 256x256 pixel array...") words = OldTexText("Order 8 Pseudo-Hilbert Curve") words.set_color(GREEN) words.to_edge(UP, buff = 0.3) curve = HilbertCurve(order = 8) self.add(mathy, bubble) self.play(ShimmerIn(bubble.content)) self.wait() self.clear() self.add(words) self.play(ShowCreation( curve, run_time = 7, rate_func=linear )) self.wait() class HilbertBetterThanSnakeQ(Scene): def construct(self): hilbert_curves, snake_curves = [ [ CurveClass(order = n) for n in range(2, 7) ] for CurveClass in (HilbertCurve, SnakeCurve) ] for curve in hilbert_curves+snake_curves: curve.scale(0.8) for curve in hilbert_curves: curve.to_edge(LEFT) for curve in snake_curves: curve.to_edge(RIGHT) greater_than = OldTex(">") question_mark = OldTexText("?") question_mark.next_to(greater_than, UP) self.add(greater_than, question_mark) hilbert_curve = hilbert_curves[0] snake_curve = snake_curves[0] for new_hc, new_sc in zip(hilbert_curves[1:], snake_curves[1:]): self.play(*[ Transform(hilbert_curve, new_hc), Transform(snake_curve, new_sc) ]) self.wait() class ImagineItWorks(Scene): def construct(self): self.add(OldTexText("Imagine your project succeeds...")) self.wait() class RandyWithHeadphones(Scene): def construct(self): headphones = ImageMobject("Headphones.png") headphones.scale(0.1) headphones.stretch(2, 0) headphones.shift(1.2*UP+0.05*LEFT) headphones.set_color(GREY) randy = Randolph() self.add(randy, headphones) self.wait(2) self.play(ApplyMethod(randy.blink)) self.wait(4) class IncreaseResolution(Scene): def construct(self): grids = [ Grid( 2**order, 2**order, stroke_width = 1 ).shift(0.3*DOWN) for order in (6, 7) ] grid = grids[0] side_brace = Brace(grid, LEFT) top_brace = Brace(grid, UP) top_words = OldTexText("256") new_top_words = OldTexText("512") side_words = top_words.copy() new_side_words = new_top_words.copy() for words in top_words, new_top_words: words.next_to(top_brace, UP, buff = 0.1) for words in side_words, new_side_words: words.next_to(side_brace, LEFT) self.add(grid) self.play( GrowFromCenter(side_brace), GrowFromCenter(top_brace), ShimmerIn(top_words), ShimmerIn(side_words) ) self.wait() self.play( DelayByOrder(Transform(*grids)), Transform(top_words, new_top_words), Transform(side_words, new_side_words) ) self.wait() class IncreasingResolutionWithSnakeCurve(Scene): def construct(self): start_curve = SnakeCurve(order = 6) end_curve = SnakeCurve(order = 7) start_dots, end_dots = [ Mobject(*[ Dot( curve.get_points()[int(x*curve.get_num_points())], color = color ) for x, color in [ (0.202, GREEN), (0.48, BLUE), (0.7, RED) ] ]) for curve in (start_curve, end_curve) ] self.add(start_curve) self.wait() self.play( ShowCreation(start_dots, run_time = 2), ApplyMethod(start_curve.fade) ) end_curve.fade() self.play( Transform(start_curve, end_curve), Transform(start_dots, end_dots) ) self.wait() class TrackSpecificCurvePoint(Scene): CURVE_CLASS = None #Fillin def construct(self): line = get_freq_line().center() line.sort_points(lambda p : p[0]) curves = [ self.CURVE_CLASS(order = order) for order in range(3, 10) ] alpha = 0.48 dot = Dot(UP) start_dot = Dot(0.1*LEFT) dots = [ Dot(curve.get_points()[alpha*curve.get_num_points()]) for curve in curves ] self.play(ShowCreation(line)) self.play(Transform(dot, start_dot)) self.wait() for new_dot, curve in zip(dots, curves): self.play( Transform(line, curve), Transform(dot, new_dot) ) self.wait() class TrackSpecificSnakeCurvePoint(TrackSpecificCurvePoint): CURVE_CLASS = SnakeCurve class NeedToRelearn(Scene): def construct(self): top_words = OldTexText("Different pixel-frequency association") bottom_words = OldTexText("Need to relearn sight-via-sound") top_words.shift(UP) bottom_words.shift(DOWN) arrow = Arrow(top_words, bottom_words) self.play(ShimmerIn(top_words)) self.wait() self.play(ShowCreation(arrow)) self.play(ShimmerIn(bottom_words)) self.wait() class TrackSpecificHilbertCurvePoint(TrackSpecificCurvePoint): CURVE_CLASS = HilbertCurve
videos_3b1b/_2016/brachistochrone/multilayered.py
import numpy as np import itertools as it from manim_imports_ext import * from from_3b1b.old.brachistochrone.light import PhotonScene from from_3b1b.old.brachistochrone.curves import * class MultilayeredScene(Scene): CONFIG = { "n_layers" : 5, "top_color" : BLUE_E, "bottom_color" : BLUE_A, "total_glass_height" : 5, "top" : 3*UP, "RectClass" : Rectangle #FilledRectangle } def get_layers(self, n_layers = None): if n_layers is None: n_layers = self.n_layers width = FRAME_WIDTH height = float(self.total_glass_height)/n_layers rgb_pair = [ np.array(Color(color).get_rgb()) for color in (self.top_color, self.bottom_color) ] rgb_range = [ interpolate(*rgb_pair+[x]) for x in np.arange(0, 1, 1./n_layers) ] tops = [ self.top + x*height*DOWN for x in range(n_layers) ] color = Color() result = [] for top, rgb in zip(tops, rgb_range): color.set_rgb(rgb) rect = self.RectClass( height = height, width = width, color = color ) rect.shift(top-rect.get_top()) result.append(rect) return result def add_layers(self): self.layers = self.get_layers() self.add(*self.layers) self.freeze_background() def get_bottom(self): return self.top + self.total_glass_height*DOWN def get_continuous_glass(self): result = self.RectClass( width = FRAME_WIDTH, height = self.total_glass_height, ) result.sort_points(lambda p : -p[1]) result.set_color_by_gradient(self.top_color, self.bottom_color) result.shift(self.top-result.get_top()) return result class TwoToMany(MultilayeredScene): CONFIG = { "RectClass" : FilledRectangle } def construct(self): glass = self.get_glass() layers = self.get_layers() self.add(glass) self.wait() self.play(*[ FadeIn( layer, rate_func = squish_rate_func(smooth, x, 1) ) for layer, x in zip(layers[1:], it.count(0, 0.2)) ]+[ Transform(glass, layers[0]) ]) self.wait() def get_glass(self): return self.RectClass( height = FRAME_Y_RADIUS, width = FRAME_WIDTH, color = BLUE_E ).shift(FRAME_Y_RADIUS*DOWN/2) class RaceLightInLayers(MultilayeredScene, PhotonScene): CONFIG = { "RectClass" : FilledRectangle } def construct(self): self.add_layers() line = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) lines = [ line.copy().shift(layer.get_center()) for layer in self.layers ] def rate_maker(x): return lambda t : min(x*x*t, 1) min_rate, max_rate = 1., 2. rates = np.arange(min_rate, max_rate, (max_rate-min_rate)/self.n_layers) self.play(*[ self.photon_run_along_path( line, rate_func = rate_maker(rate), run_time = 2 ) for line, rate in zip(lines, rates) ]) class ShowDiscretePath(MultilayeredScene, PhotonScene): CONFIG = { "RectClass" : FilledRectangle } def construct(self): self.add_layers() self.cycloid = Cycloid(end_theta = np.pi) self.generate_discrete_path() self.play(ShowCreation(self.discrete_path)) self.wait() self.play(self.photon_run_along_path( self.discrete_path, rate_func = rush_into, run_time = 3 )) self.wait() def generate_discrete_path(self): points = self.cycloid.points tops = [mob.get_top()[1] for mob in self.layers] tops.append(tops[-1]-self.layers[0].get_height()) indices = [ np.argmin(np.abs(points[:, 1]-top)) for top in tops ] self.bend_points = points[indices[1:-1]] self.path_angles = [] self.discrete_path = Mobject1D( color = WHITE, density = 3*DEFAULT_POINT_DENSITY_1D ) for start, end in zip(indices, indices[1:]): start_point, end_point = points[start], points[end] self.discrete_path.add_line( start_point, end_point ) self.path_angles.append( angle_of_vector(start_point-end_point)-np.pi/2 ) self.discrete_path.add_line( points[end], FRAME_X_RADIUS*RIGHT+(tops[-1]-0.5)*UP ) class NLayers(MultilayeredScene): CONFIG = { "RectClass" : FilledRectangle } def construct(self): self.add_layers() brace = Brace( Mobject( Point(self.top), Point(self.get_bottom()) ), RIGHT ) n_layers = OldTexText("$n$ layers") n_layers.next_to(brace) self.wait() self.add(brace) self.show_frame() self.play( GrowFromCenter(brace), GrowFromCenter(n_layers) ) self.wait() class ShowLayerVariables(MultilayeredScene, PhotonScene): CONFIG = { "RectClass" : FilledRectangle } def construct(self): self.add_layers() v_equations = [] start_ys = [] end_ys = [] center_paths = [] braces = [] for layer, x in zip(self.layers[:3], it.count(1)): eq_mob = OldTex( ["v_%d"%x, "=", "\sqrt{\phantom{y_1}}"], size = "\\Large" ) eq_mob.shift(layer.get_center()+2*LEFT) v_eq = eq_mob.split() v_eq[0].set_color(layer.get_color()) path = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) path.shift(layer.get_center()) brace_endpoints = Mobject( Point(self.top), Point(layer.get_bottom()) ) brace = Brace(brace_endpoints, RIGHT) brace.shift(x*RIGHT) start_y = OldTex("y_%d"%x, size = "\\Large") end_y = start_y.copy() start_y.next_to(brace, RIGHT) end_y.shift(v_eq[-1].get_center()) nudge = 0.2*RIGHT end_y.shift(nudge) v_equations.append(v_eq) start_ys.append(start_y) end_ys.append(end_y) center_paths.append(path) braces.append(brace) for v_eq, path, time in zip(v_equations, center_paths, [2, 1, 0.5]): photon_run = self.photon_run_along_path( path, rate_func=linear ) self.play( FadeToColor(v_eq[0], WHITE), photon_run, run_time = time ) self.wait() starts = [0, 0.3, 0.6] self.play(*it.chain(*[ [ GrowFromCenter( mob, rate_func=squish_rate_func(smooth, start, 1) ) for mob, start in zip(mobs, starts) ] for mobs in (start_ys, braces) ])) self.wait() triplets = list(zip(v_equations, start_ys, end_ys)) anims = [] for v_eq, start_y, end_y in triplets: anims += [ ShowCreation(v_eq[1]), ShowCreation(v_eq[2]), Transform(start_y.copy(), end_y) ] self.play(*anims) self.wait() class LimitingProcess(MultilayeredScene): CONFIG = { "RectClass" : FilledRectangle } def construct(self): num_iterations = 3 layer_sets = [ self.get_layers((2**x)*self.n_layers) for x in range(num_iterations) ] glass_sets = [ Mobject(*[ Mobject( *layer_sets[x][(2**x)*index:(2**x)*(index+1)] ) for index in range(self.n_layers) ]).ingest_submobjects() for x in range(num_iterations) ] glass_sets.append(self.get_continuous_glass()) for glass_set in glass_sets: glass_set.sort_points(lambda p : p[1]) curr_set = glass_sets[0] self.add(curr_set) for layer_set in glass_sets[1:]: self.wait() self.play(Transform(curr_set, layer_set)) self.wait() class ShowLightAndSlidingObject(MultilayeredScene, TryManyPaths, PhotonScene): CONFIG = { "show_time" : False, "wait_and_add" : False, "RectClass" : FilledRectangle } def construct(self): glass = self.get_continuous_glass() self.play(ApplyMethod(glass.fade, 0.8)) self.freeze_background() paths = self.get_paths() for path in paths: if path.get_height() > self.total_glass_height: path.stretch(0.7, 1) path.shift(self.top - path.get_top()) path.rgbas[:,2] = 0 loop = paths.pop(1) ##Bad! randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) photon_run = self.photon_run_along_path( loop, rate_func = lambda t : smooth(1.2*t, 2), run_time = 4.1 ) text = self.get_text().to_edge(UP, buff = 0.2) self.play(ShowCreation(loop)) self.wait() self.play(photon_run) self.remove(photon_run.mobject) randy = self.slide(randy, loop) self.add(randy) self.wait() self.remove(randy) self.play(ShimmerIn(text)) for path in paths: self.play(Transform( loop, path, path_func = path_along_arc(np.pi/2), run_time = 2 )) class ContinuouslyObeyingSnellsLaw(MultilayeredScene): CONFIG = { "arc_radius" : 0.5, "RectClass" : FilledRectangle } def construct(self): glass = self.get_continuous_glass() self.add(glass) self.freeze_background() cycloid = Cycloid(end_theta = np.pi) cycloid.set_color(YELLOW) chopped_cycloid = cycloid.copy() n = cycloid.get_num_points() chopped_cycloid.filter_out(lambda p : p[1] > 1 and p[0] < 0) chopped_cycloid.reverse_points() self.play(ShowCreation(cycloid)) ref_mob = self.snells_law_at_every_point(cycloid, chopped_cycloid) self.show_equation(chopped_cycloid, ref_mob) def snells_law_at_every_point(self, cycloid, chopped_cycloid): square = Square(side_length = 0.2, color = WHITE) words = OldTexText(["Snell's law ", "everywhere"]) snells, rest = words.split() colon = OldTexText(":") words.next_to(square) words.shift(0.3*UP) combo = Mobject(square, words) combo.get_center = lambda : square.get_center() new_snells = snells.copy().center().to_edge(UP, buff = 1.5) colon.next_to(new_snells) colon.shift(0.05*DOWN) self.play(MoveAlongPath( combo, cycloid, run_time = 5 )) self.play(MoveAlongPath( combo, chopped_cycloid, run_time = 4 )) dot = Dot(combo.get_center()) self.play(Transform(square, dot)) self.play( Transform(snells, new_snells), Transform(rest, colon) ) self.wait() return colon def get_marks(self, point1, point2): vert_line = Line(2*DOWN, 2*UP) tangent_line = vert_line.copy() theta = OldTex("\\theta") theta.scale(0.5) angle = angle_of_vector(point1 - point2) tangent_line.rotate( angle - tangent_line.get_angle() ) angle_from_vert = angle - np.pi/2 for mob in vert_line, tangent_line: mob.shift(point1 - mob.get_center()) arc = Arc(angle_from_vert, start_angle = np.pi/2) arc.scale(self.arc_radius) arc.shift(point1) vect_angle = angle_from_vert/2 + np.pi/2 vect = rotate_vector(RIGHT, vect_angle) theta.center() theta.shift(point1) theta.shift(1.5*self.arc_radius*vect) return arc, theta, vert_line, tangent_line def show_equation(self, chopped_cycloid, ref_mob): point2, point1 = chopped_cycloid.get_points()[-2:] arc, theta, vert_line, tangent_line = self.get_marks( point1, point2 ) equation = OldTex([ "\\sin(\\theta)", "\\over \\sqrt{y}", ]) sin, sqrt_y = equation.split() equation.next_to(ref_mob) const = OldTex(" = \\text{constant}") const.next_to(equation) ceil_point = np.array(point1) ceil_point[1] = self.top[1] brace = Brace( Mobject(Point(point1), Point(ceil_point)), RIGHT ) y_mob = OldTex("y").next_to(brace) self.play( GrowFromCenter(sin), ShowCreation(arc), GrowFromCenter(theta) ) self.play(ShowCreation(vert_line)) self.play(ShowCreation(tangent_line)) self.wait() self.play( GrowFromCenter(sqrt_y), GrowFromCenter(brace), GrowFromCenter(y_mob) ) self.wait() self.play(Transform( Point(const.get_left()), const )) self.wait()
videos_3b1b/_2016/brachistochrone/cycloid.py
from manim_imports_ext import * from from_3b1b.old.brachistochrone.curves import * class RollAlongVector(Animation): CONFIG = { "rotation_vector" : OUT, } def __init__(self, mobject, vector, **kwargs): radius = mobject.get_width()/2 radians = get_norm(vector)/radius last_alpha = 0 digest_config(self, kwargs, locals()) Animation.__init__(self, mobject, **kwargs) def interpolate_mobject(self, alpha): d_alpha = alpha - self.last_alpha self.last_alpha = alpha self.mobject.rotate( d_alpha*self.radians, self.rotation_vector ) self.mobject.shift(d_alpha*self.vector) class CycloidScene(Scene): CONFIG = { "point_a" : 6*LEFT+3*UP, "radius" : 2, "end_theta" : 2*np.pi } def construct(self): self.generate_cycloid() self.generate_circle() self.generate_ceiling() def grow_parts(self): self.play(*[ ShowCreation(mob) for mob in (self.circle, self.ceiling) ]) def generate_cycloid(self): self.cycloid = Cycloid( point_a = self.point_a, radius = self.radius, end_theta = self.end_theta ) def generate_circle(self, **kwargs): self.circle = Circle(radius = self.radius, **kwargs) self.circle.shift(self.point_a - self.circle.get_top()) radial_line = Line( self.circle.get_center(), self.point_a ) self.circle.add(radial_line) def generate_ceiling(self): self.ceiling = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) self.ceiling.shift(self.cycloid.get_top()[1]*UP) def draw_cycloid(self, run_time = 3, *anims, **kwargs): kwargs["run_time"] = run_time self.play( RollAlongVector( self.circle, self.cycloid.get_points()[-1]-self.cycloid.get_points()[0], **kwargs ), ShowCreation(self.cycloid, **kwargs), *anims ) def roll_back(self, run_time = 3, *anims, **kwargs): kwargs["run_time"] = run_time self.play( RollAlongVector( self.circle, self.cycloid.get_points()[0]-self.cycloid.get_points()[- 1], rotation_vector = IN, **kwargs ), ShowCreation( self.cycloid, rate_func = lambda t : smooth(1-t), **kwargs ), *anims ) self.generate_cycloid() class IntroduceCycloid(CycloidScene): def construct(self): CycloidScene.construct(self) equation = OldTex([ "\\dfrac{\\sin(\\theta)}{\\sqrt{y}}", "= \\text{constant}" ]) sin_sqrt, const = equation.split() new_eq = equation.copy() new_eq.to_edge(UP, buff = 1.3) cycloid_word = OldTexText("Cycloid") arrow = Arrow(2*UP, cycloid_word) arrow.reverse_points() q_mark = OldTexText("?") self.play(*list(map(ShimmerIn, equation.split()))) self.wait() self.play( ApplyMethod(equation.shift, 2.2*UP), ShowCreation(arrow) ) q_mark.next_to(sin_sqrt) self.play(ShimmerIn(cycloid_word)) self.wait() self.grow_parts() self.draw_cycloid() self.wait() extra_terms = [const, arrow, cycloid_word] self.play(*[ Transform(mob, q_mark) for mob in extra_terms ]) self.remove(*extra_terms) self.roll_back() q_marks, arrows = self.get_q_marks_and_arrows(sin_sqrt) self.draw_cycloid(3, ShowCreation(q_marks), ShowCreation(arrows) ) self.wait() def get_q_marks_and_arrows(self, mob, n_marks = 10): circle = Circle().replace(mob) q_marks, arrows = result = [Mobject(), Mobject()] for x in range(n_marks): index = (x+0.5)*self.cycloid.get_num_points()/n_marks q_point = self.cycloid.get_points()[index] vect = q_point-mob.get_center() start_point = circle.get_boundary_point(vect) arrow = Arrow( start_point, q_point, color = BLUE_E ) q_marks.add(OldTexText("?").shift(q_point)) arrows.add(arrow) for mob in result: mob.ingest_submobjects() return result class LeviSolution(CycloidScene): CONFIG = { "cycloid_fraction" : 0.25, } def construct(self): CycloidScene.construct(self) self.add(self.ceiling) self.init_points() methods = [ self.draw_cycloid, self.roll_into_position, self.draw_p_and_c, self.show_pendulum, self.show_diameter, self.show_theta, self.show_similar_triangles, self.show_sin_thetas, self.show_y, self.rearrange, ] for method in methods: method() self.wait() def init_points(self): index = int(self.cycloid_fraction*self.cycloid.get_num_points()) p_point = self.cycloid.get_points()[index] p_dot = Dot(p_point) p_label = OldTex("P") p_label.next_to(p_dot, DOWN+LEFT) c_point = self.point_a + self.cycloid_fraction*self.radius*2*np.pi*RIGHT c_dot = Dot(c_point) c_label = OldTex("C") c_label.next_to(c_dot, UP) digest_locals(self) def roll_into_position(self): self.play(RollAlongVector( self.circle, (1-self.cycloid_fraction)*self.radius*2*np.pi*LEFT, rotation_vector = IN, run_time = 2 )) def draw_p_and_c(self): radial_line = self.circle.submobjects[0] ##Hacky self.play(Transform(radial_line, self.p_dot)) self.remove(radial_line) self.add(self.p_dot) self.play(ShimmerIn(self.p_label)) self.wait() self.play(Transform(self.ceiling.copy(), self.c_dot)) self.play(ShimmerIn(self.c_label)) def show_pendulum(self, arc_angle = np.pi, arc_color = GREEN): words = OldTexText(": Instantaneous center of rotation") words.next_to(self.c_label) line = Line(self.p_point, self.c_point) line_angle = line.get_angle()+np.pi line_length = line.get_length() line.add(self.p_dot.copy()) line.get_center = lambda : self.c_point tangent_line = Line(3*LEFT, 3*RIGHT) tangent_line.rotate(line_angle-np.pi/2) tangent_line.shift(self.p_point) tangent_line.set_color(arc_color) right_angle_symbol = Mobject( Line(UP, UP+RIGHT), Line(UP+RIGHT, RIGHT) ) right_angle_symbol.scale(0.3) right_angle_symbol.rotate(tangent_line.get_angle()+np.pi) right_angle_symbol.shift(self.p_point) self.play(ShowCreation(line)) self.play(ShimmerIn(words)) self.wait() pairs = [ (line_angle, arc_angle/2), (line_angle+arc_angle/2, -arc_angle), (line_angle-arc_angle/2, arc_angle/2), ] arcs = [] for start, angle in pairs: arc = Arc( angle = angle, radius = line_length, start_angle = start, color = GREEN ) arc.shift(self.c_point) self.play( ShowCreation(arc), ApplyMethod( line.rotate, angle, path_func = path_along_arc(angle) ), run_time = 2 ) arcs.append(arc) self.wait() self.play(Transform(arcs[1], tangent_line)) self.add(tangent_line) self.play(ShowCreation(right_angle_symbol)) self.wait() self.tangent_line = tangent_line self.right_angle_symbol = right_angle_symbol self.pc_line = line self.remove(words, *arcs) def show_diameter(self): exceptions = [ self.circle, self.tangent_line, self.pc_line, self.right_angle_symbol ] everything = set(self.mobjects).difference(exceptions) everything_copy = Mobject(*everything).copy() light_everything = everything_copy.copy() dark_everything = everything_copy.copy() dark_everything.fade(0.8) bottom_point = np.array(self.c_point) bottom_point += 2*self.radius*DOWN diameter = Line(bottom_point, self.c_point) brace = Brace(diameter, RIGHT) diameter_word = OldTexText("Diameter") d_mob = OldTex("D") diameter_word.next_to(brace) d_mob.next_to(diameter) self.remove(*everything) self.play(Transform(everything_copy, dark_everything)) self.wait() self.play(ShowCreation(diameter)) self.play(GrowFromCenter(brace)) self.play(ShimmerIn(diameter_word)) self.wait() self.play(*[ Transform(mob, d_mob) for mob in (brace, diameter_word) ]) self.remove(brace, diameter_word) self.add(d_mob) self.play(Transform(everything_copy, light_everything)) self.remove(everything_copy) self.add(*everything) self.d_mob = d_mob self.bottom_point = bottom_point def show_theta(self, radius = 1): arc = Arc( angle = self.tangent_line.get_angle()-np.pi/2, radius = radius, start_angle = np.pi/2 ) theta = OldTex("\\theta") theta.shift(1.5*arc.get_center()) Mobject(arc, theta).shift(self.bottom_point) self.play( ShowCreation(arc), ShimmerIn(theta) ) self.arc = arc self.theta = theta def show_similar_triangles(self): y_point = np.array(self.p_point) y_point[1] = self.point_a[1] new_arc = Arc( angle = self.tangent_line.get_angle()-np.pi/2, radius = 0.5, start_angle = np.pi ) new_arc.shift(self.c_point) new_theta = self.theta.copy() new_theta.next_to(new_arc, LEFT) new_theta.shift(0.1*DOWN) kwargs = { "stroke_width" : 2*DEFAULT_STROKE_WIDTH, } triangle1 = Polygon( self.p_point, self.c_point, self.bottom_point, color = MAROON, **kwargs ) triangle2 = Polygon( y_point, self.p_point, self.c_point, color = WHITE, **kwargs ) y_line = Line(self.p_point, y_point) self.play( Transform(self.arc.copy(), new_arc), Transform(self.theta.copy(), new_theta), run_time = 3 ) self.wait() self.play(FadeIn(triangle1)) self.wait() self.play(Transform(triangle1, triangle2)) self.play(ApplyMethod(triangle1.set_color, MAROON)) self.wait() self.remove(triangle1) self.add(y_line) self.y_line = y_line def show_sin_thetas(self): pc = Line(self.p_point, self.c_point) mob = Mobject(self.theta, self.d_mob).copy() mob.ingest_submobjects() triplets = [ (pc, "D\\sin(\\theta)", 0.5), (self.y_line, "D\\sin^2(\\theta)", 0.7), ] for line, tex, scale in triplets: trig_mob = OldTex(tex) trig_mob.set_width( scale*line.get_length() ) trig_mob.shift(-1.2*trig_mob.get_top()) trig_mob.rotate(line.get_angle()) trig_mob.shift(line.get_center()) if line is self.y_line: trig_mob.shift(0.1*UP) self.play(Transform(mob, trig_mob)) self.add(trig_mob) self.wait() self.remove(mob) self.d_sin_squared_theta = trig_mob def show_y(self): y_equals = OldTex(["y", "="]) y_equals.shift(2*UP) y_expression = OldTex([ "D ", "\\sin", "^2", "(\\theta)" ]) y_expression.next_to(y_equals) y_expression.shift(0.05*UP+0.1*RIGHT) temp_expr = self.d_sin_squared_theta.copy() temp_expr.rotate(-np.pi/2) temp_expr.replace(y_expression) y_mob = OldTex("y") y_mob.next_to(self.y_line, RIGHT) y_mob.shift(0.2*UP) self.play( Transform(self.d_sin_squared_theta, temp_expr), ShimmerIn(y_mob), ShowCreation(y_equals) ) self.remove(self.d_sin_squared_theta) self.add(y_expression) self.y_equals = y_equals self.y_expression = y_expression def rearrange(self): sqrt_nudge = 0.2*LEFT y, equals = self.y_equals.split() d, sin, squared, theta = self.y_expression.split() y_sqrt = OldTex("\\sqrt{\\phantom{y}}") d_sqrt = y_sqrt.copy() y_sqrt.shift(y.get_center()+sqrt_nudge) d_sqrt.shift(d.get_center()+sqrt_nudge) self.play( ShimmerIn(y_sqrt), ShimmerIn(d_sqrt), ApplyMethod(squared.shift, 4*UP), ApplyMethod(theta.shift, 1.5* squared.get_width()*LEFT) ) self.wait() y_sqrt.add(y) d_sqrt.add(d) sin.add(theta) sin_over = OldTex("\\dfrac{\\phantom{\\sin(\\theta)}}{\\quad}") sin_over.next_to(sin, DOWN, 0.15) new_eq = equals.copy() new_eq.next_to(sin_over, LEFT) one_over = OldTex("\\dfrac{1}{\\quad}") one_over.next_to(new_eq, LEFT) one_over.shift( (sin_over.get_bottom()[1]-one_over.get_bottom()[1])*UP ) self.play( Transform(equals, new_eq), ShimmerIn(sin_over), ShimmerIn(one_over), ApplyMethod( d_sqrt.next_to, one_over, DOWN, path_func = path_along_arc(-np.pi) ), ApplyMethod( y_sqrt.next_to, sin_over, DOWN, path_func = path_along_arc(-np.pi) ), run_time = 2 ) self.wait() brace = Brace(d_sqrt, DOWN) constant = OldTexText("Constant") constant.next_to(brace, DOWN) self.play( GrowFromCenter(brace), ShimmerIn(constant) ) class EquationsForCycloid(CycloidScene): def construct(self): CycloidScene.construct(self) equations = OldTex([ "x(t) = Rt - R\\sin(t)", "y(t) = -R + R\\cos(t)" ]) top, bottom = equations.split() bottom.next_to(top, DOWN) equations.center() equations.to_edge(UP, buff = 1.3) self.play(ShimmerIn(equations)) self.grow_parts() self.draw_cycloid(rate_func=linear, run_time = 5) self.wait() class SlidingObject(CycloidScene, PathSlidingScene): CONFIG = { "show_time" : False, "wait_and_add" : False } args_list = [(True,), (False,)] @staticmethod def args_to_string(with_words): return "WithWords" if with_words else "WithoutWords" @staticmethod def string_to_args(string): return string == "WithWords" def construct(self, with_words): CycloidScene.construct(self) randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) central_randy = randy.copy() start_randy = self.adjust_mobject_to_index( randy.copy(), 1, self.cycloid.points ) if with_words: words1 = OldTexText("Trajectory due to gravity") arrow = OldTex("\\leftrightarrow") words2 = OldTexText("Trajectory due \\emph{constantly} rotating wheel") words1.next_to(arrow, LEFT) words2.next_to(arrow, RIGHT) words = Mobject(words1, arrow, words2) words.set_width(FRAME_WIDTH-1) words.to_edge(UP, buff = 0.2) words.to_edge(LEFT) self.play(ShowCreation(self.cycloid.copy())) self.slide(randy, self.cycloid) self.add(self.slider) self.wait() self.grow_parts() self.draw_cycloid() self.wait() self.play(Transform(self.slider, start_randy)) self.wait() self.roll_back() self.wait() if with_words: self.play(*list(map(ShimmerIn, [words1, arrow, words2]))) self.wait() self.remove(self.circle) start_time = len(self.frames)*self.frame_duration self.remove(self.slider) self.slide(central_randy, self.cycloid) end_time = len(self.frames)*self.frame_duration self.play_over_time_range( start_time, end_time, RollAlongVector( self.circle, self.cycloid.get_points()[-1]-self.cycloid.get_points()[0], run_time = end_time-start_time, rate_func=linear ) ) self.add(self.circle, self.slider) self.wait() class RotateWheel(CycloidScene): def construct(self): CycloidScene.construct(self) self.circle.center() self.play(Rotating( self.circle, axis = OUT, run_time = 5, rate_func = smooth ))
videos_3b1b/_2016/brachistochrone/curves.py
from manim_imports_ext import * RANDY_SCALE_FACTOR = 0.3 class Cycloid(ParametricCurve): CONFIG = { "point_a" : 6*LEFT+3*UP, "radius" : 2, "end_theta" : 3*np.pi/2, "density" : 5*DEFAULT_POINT_DENSITY_1D, "color" : YELLOW } def __init__(self, **kwargs): digest_config(self, kwargs) ParametricCurve.__init__(self, self.pos_func, **kwargs) def pos_func(self, t): T = t*self.end_theta return self.point_a + self.radius * np.array([ T - np.sin(T), np.cos(T) - 1, 0 ]) class LoopTheLoop(ParametricCurve): CONFIG = { "color" : YELLOW_D, "density" : 10*DEFAULT_POINT_DENSITY_1D } def __init__(self, **kwargs): digest_config(self, kwargs) def func(t): t = (6*np.pi/2)*(t-0.5) return (t/2-np.sin(t))*RIGHT + \ (np.cos(t)+(t**2)/10)*UP ParametricCurve.__init__(self, func, **kwargs) class SlideWordDownCycloid(Animation): CONFIG = { "rate_func" : None, "run_time" : 8 } def __init__(self, word, **kwargs): self.path = Cycloid(end_theta = np.pi) word_mob = OldTexText(list(word)) end_word = word_mob.copy() end_word.shift(-end_word.get_bottom()) end_word.shift(self.path.get_corner(DOWN+RIGHT)) end_word.shift(3*RIGHT) self.end_letters = end_word.split() for letter in word_mob.split(): letter.center() letter.angle = 0 unit_interval = np.arange(0, 1, 1./len(word)) self.start_times = 0.5*(1-(unit_interval)) Animation.__init__(self, word_mob, **kwargs) def interpolate_mobject(self, alpha): virtual_times = 2*(alpha - self.start_times) cut_offs = [ 0.1, 0.3, 0.7, ] for letter, time, end_letter in zip( self.mobject.split(), virtual_times, self.end_letters ): time = max(time, 0) time = min(time, 1) if time < cut_offs[0]: brightness = time/cut_offs[0] letter.rgbas = brightness*np.ones(letter.rgbas.shape) position = self.path.get_points()[0] angle = 0 elif time < cut_offs[1]: alpha = (time-cut_offs[0])/(cut_offs[1]-cut_offs[0]) angle = -rush_into(alpha)*np.pi/2 position = self.path.get_points()[0] elif time < cut_offs[2]: alpha = (time-cut_offs[1])/(cut_offs[2]-cut_offs[1]) index = int(alpha*self.path.get_num_points()) position = self.path.get_points()[index] try: angle = angle_of_vector( self.path.get_points()[index+1] - \ self.path.get_points()[index] ) except: angle = letter.angle else: alpha = (time-cut_offs[2])/(1-cut_offs[2]) start = self.path.get_points()[-1] end = end_letter.get_bottom() position = interpolate(start, end, rush_from(alpha)) angle = 0 letter.shift(position-letter.get_bottom()) letter.rotate(angle-letter.angle) letter.angle = angle class BrachistochroneWordSliding(Scene): def construct(self): anim = SlideWordDownCycloid("Brachistochrone") anim.path.set_color_by_gradient(WHITE, BLUE_E) self.play(ShowCreation(anim.path)) self.play(anim) self.wait() self.play( FadeOut(anim.path), ApplyMethod(anim.mobject.center) ) class PathSlidingScene(Scene): CONFIG = { "gravity" : 3, "delta_t" : 0.05, "wait_and_add" : True, "show_time" : True, } def slide(self, mobject, path, roll = False, ceiling = None): points = path.points time_slices = self.get_time_slices(points, ceiling = ceiling) curr_t = 0 last_index = 0 curr_index = 1 if self.show_time: self.t_equals = OldTex("t = ") self.t_equals.shift(3.5*UP+4*RIGHT) self.add(self.t_equals) while curr_index < len(points): self.slider = mobject.copy() self.adjust_mobject_to_index( self.slider, curr_index, points ) if roll: distance = get_norm( points[curr_index] - points[last_index] ) self.roll(mobject, distance) self.add(self.slider) if self.show_time: self.write_time(curr_t) self.wait(self.frame_duration) self.remove(self.slider) curr_t += self.delta_t last_index = curr_index while time_slices[curr_index] < curr_t: curr_index += 1 if curr_index == len(points): break if self.wait_and_add: self.add(self.slider) self.wait() else: return self.slider def get_time_slices(self, points, ceiling = None): dt_list = np.zeros(len(points)) ds_list = np.apply_along_axis( get_norm, 1, points[1:]-points[:-1] ) if ceiling is None: ceiling = points[0, 1] delta_y_list = np.abs(ceiling - points[1:,1]) delta_y_list += 0.001*(delta_y_list == 0) v_list = self.gravity*np.sqrt(delta_y_list) dt_list[1:] = ds_list / v_list return np.cumsum(dt_list) def adjust_mobject_to_index(self, mobject, index, points): point_a, point_b = points[index-1], points[index] while np.all(point_a == point_b): index += 1 point_b = points[index] theta = angle_of_vector(point_b - point_a) mobject.rotate(theta) mobject.shift(points[index]) self.midslide_action(point_a, theta) return mobject def midslide_action(self, point, angle): pass def write_time(self, time): if hasattr(self, "time_mob"): self.remove(self.time_mob) digits = list(map(Tex, "%.2f"%time)) digits[0].next_to(self.t_equals, buff = 0.1) for left, right in zip(digits, digits[1:]): right.next_to(left, buff = 0.1, aligned_edge = DOWN) self.time_mob = Mobject(*digits) self.add(self.time_mob) def roll(self, mobject, arc_length): radius = mobject.get_width()/2 theta = arc_length / radius mobject.rotate(-theta) def add_cycloid_end_points(self): cycloid = Cycloid() point_a = Dot(cycloid.get_points()[0]) point_b = Dot(cycloid.get_points()[-1]) A = OldTex("A").next_to(point_a, LEFT) B = OldTex("B").next_to(point_b, RIGHT) self.add(point_a, point_b, A, B) digest_locals(self) class TryManyPaths(PathSlidingScene): def construct(self): randy = Randolph() randy.shift(-randy.get_bottom()) self.slider = randy.copy() randy.scale(RANDY_SCALE_FACTOR) paths = self.get_paths() point_a = Dot(paths[0].get_points()[0]) point_b = Dot(paths[0].get_points()[-1]) A = OldTex("A").next_to(point_a, LEFT) B = OldTex("B").next_to(point_b, RIGHT) for point, tex in [(point_a, A), (point_b, B)]: self.play(ShowCreation(point)) self.play(ShimmerIn(tex)) self.wait() curr_path = None for path in paths: new_slider = self.adjust_mobject_to_index( randy.copy(), 1, path.points ) if curr_path is None: curr_path = path self.play(ShowCreation(curr_path)) else: self.play(Transform(curr_path, path)) self.play(Transform(self.slider, new_slider)) self.wait() self.remove(self.slider) self.slide(randy, curr_path) self.clear() self.add(point_a, point_b, A, B, curr_path) text = self.get_text() text.to_edge(UP) self.play(ShimmerIn(text)) for path in paths: self.play(Transform( curr_path, path, path_func = path_along_arc(np.pi/2), run_time = 3 )) def get_text(self): return OldTexText("Which path is fastest?") def get_paths(self): sharp_corner = Mobject( Line(3*UP+LEFT, LEFT), Arc(angle = np.pi/2, start_angle = np.pi), Line(DOWN, DOWN+3*RIGHT) ).ingest_submobjects().set_color(GREEN) paths = [ Arc( angle = np.pi/2, radius = 3, start_angle = 4 ), LoopTheLoop(), Line(7*LEFT, 7*RIGHT, color = RED_D), sharp_corner, FunctionGraph( lambda x : 0.05*(x**2)+0.1*np.sin(2*x) ), FunctionGraph( lambda x : x**2, x_min = -3, x_max = 2, density = 3*DEFAULT_POINT_DENSITY_1D ) ] cycloid = Cycloid() self.align_paths(paths, cycloid) return paths + [cycloid] def align_paths(self, paths, target_path): start = target_path.get_points()[0] end = target_path.get_points()[-1] for path in paths: path.put_start_and_end_on(start, end) class RollingRandolph(PathSlidingScene): def construct(self): randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) self.add_cycloid_end_points() self.slide(randy, self.cycloid, roll = True) class NotTheCircle(PathSlidingScene): def construct(self): self.add_cycloid_end_points() start = self.point_a.get_center() end = self.point_b.get_center() angle = 2*np.pi/3 path = Arc(angle, radius = 3) path.set_color_by_gradient(RED_D, WHITE) radius = Line(ORIGIN, path.get_points()[0]) randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) randy_copy = randy.copy() words = OldTexText("Circular paths are good, \\\\ but still not the best") words.shift(UP) self.play( ShowCreation(path), ApplyMethod( radius.rotate, angle, path_func = path_along_arc(angle) ) ) self.play(FadeOut(radius)) self.play( ApplyMethod( path.put_start_and_end_on, start, end, path_func = path_along_arc(-angle) ), run_time = 3 ) self.adjust_mobject_to_index(randy_copy, 1, path.points) self.play(FadeIn(randy_copy)) self.remove(randy_copy) self.slide(randy, path) self.play(ShimmerIn(words)) self.wait() class TransitionAwayFromSlide(PathSlidingScene): def construct(self): randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) self.add_cycloid_end_points() arrow = Arrow(ORIGIN, 2*RIGHT) arrows = Mobject(*[ arrow.copy().shift(vect) for vect in (3*LEFT, ORIGIN, 3*RIGHT) ]) arrows.shift(FRAME_WIDTH*RIGHT) self.add(arrows) self.add(self.cycloid) self.slide(randy, self.cycloid) everything = Mobject(*self.mobjects) self.play(ApplyMethod( everything.shift, 4*FRAME_X_RADIUS*LEFT, run_time = 2, rate_func = rush_into )) class MinimalPotentialEnergy(Scene): def construct(self): horiz_radius = 5 vert_radius = 3 vert_axis = NumberLine(numerical_radius = vert_radius) vert_axis.rotate(np.pi/2) vert_axis.shift(horiz_radius*LEFT) horiz_axis = NumberLine( numerical_radius = 5, numbers_with_elongated_ticks = [] ) axes = Mobject(horiz_axis, vert_axis) graph = FunctionGraph( lambda x : 0.4*(x-2)*(x+2)+3, x_min = -2, x_max = 2, density = 3*DEFAULT_POINT_DENSITY_1D ) graph.stretch_to_fit_width(2*horiz_radius) graph.set_color(YELLOW) min_point = Dot(graph.get_bottom()) nature_finds = OldTexText("Nature finds this point") nature_finds.scale(0.5) nature_finds.set_color(GREEN) nature_finds.shift(2*RIGHT+3*UP) arrow = Arrow( nature_finds.get_bottom(), min_point, color = GREEN ) side_words_start = OldTexText("Parameter describing") top_words, last_side_words = [ list(map(TexText, pair)) for pair in [ ("Light's travel time", "Potential energy"), ("path", "mechanical state") ] ] for word in top_words + last_side_words + [side_words_start]: word.scale(0.7) side_words_start.next_to(horiz_axis, DOWN) side_words_start.to_edge(RIGHT) for words in top_words: words.next_to(vert_axis, UP) words.to_edge(LEFT) for words in last_side_words: words.next_to(side_words_start, DOWN) for words in top_words[1], last_side_words[1]: words.set_color(RED) self.add( axes, top_words[0], side_words_start, last_side_words[0] ) self.play(ShowCreation(graph)) self.play( ShimmerIn(nature_finds), ShowCreation(arrow), ShowCreation(min_point) ) self.wait() self.play( FadeOut(top_words[0]), FadeOut(last_side_words[0]), GrowFromCenter(top_words[1]), GrowFromCenter(last_side_words[1]) ) self.wait(3) class WhatGovernsSpeed(PathSlidingScene): CONFIG = { "num_pieces" : 6, "wait_and_add" : False, "show_time" : False, } def construct(self): randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) self.add_cycloid_end_points() points = self.cycloid.points ceiling = points[0, 1] n = len(points) broken_points = [ points[k*n/self.num_pieces:(k+1)*n/self.num_pieces] for k in range(self.num_pieces) ] words = OldTexText(""" What determines the speed\\\\ at each point? """) words.to_edge(UP) self.add(self.cycloid) sliders, vectors = [], [] for points in broken_points: path = Mobject().add_points(points) vect = points[-1] - points[-2] magnitude = np.sqrt(ceiling - points[-1, 1]) vect = magnitude*vect/get_norm(vect) slider = self.slide(randy, path, ceiling = ceiling) vector = Vector(slider.get_center(), vect) self.add(slider, vector) sliders.append(slider) vectors.append(vector) self.wait() self.play(ShimmerIn(words)) self.wait(3) slider = sliders.pop(1) vector = vectors.pop(1) faders = sliders+vectors+[words] self.play(*list(map(FadeOut, faders))) self.remove(*faders) self.show_geometry(slider, vector) def show_geometry(self, slider, vector): point_a = self.point_a.get_center() horiz_line = Line(point_a, point_a + 6*RIGHT) ceil_point = point_a ceil_point[0] = slider.get_center()[0] vert_brace = Brace( Mobject(Point(ceil_point), Point(slider.get_center())), RIGHT, buff = 0.5 ) vect_brace = Brace(slider) vect_brace.stretch_to_fit_width(vector.get_length()) vect_brace.rotate(np.arctan(vector.get_slope())) vect_brace.center().shift(vector.get_center()) nudge = 0.2*(DOWN+LEFT) vect_brace.shift(nudge) y_mob = OldTex("y") y_mob.next_to(vert_brace) sqrt_y = OldTex("k\\sqrt{y}") sqrt_y.scale(0.5) sqrt_y.shift(vect_brace.get_center()) sqrt_y.shift(3*nudge) self.play(ShowCreation(horiz_line)) self.play( GrowFromCenter(vert_brace), ShimmerIn(y_mob) ) self.play( GrowFromCenter(vect_brace), ShimmerIn(sqrt_y) ) self.wait(3) self.solve_energy() def solve_energy(self): loss_in_potential = OldTexText("Loss in potential: ") loss_in_potential.shift(2*UP) potential = OldTex("m g y".split()) potential.next_to(loss_in_potential) kinetic = OldTex([ "\\dfrac{1}{2}","m","v","^2","=" ]) kinetic.next_to(potential, LEFT) nudge = 0.1*UP kinetic.shift(nudge) loss_in_potential.shift(nudge) ms = Mobject(kinetic.split()[1], potential.split()[0]) two = OldTex("2") two.shift(ms.split()[1].get_center()) half = kinetic.split()[0] sqrt = OldTex("\\sqrt{\\phantom{2mg}}") sqrt.shift(potential.get_center()) nudge = 0.2*LEFT sqrt.shift(nudge) squared = kinetic.split()[3] equals = kinetic.split()[-1] new_eq = equals.copy().next_to(kinetic.split()[2]) self.play( Transform( Point(loss_in_potential.get_left()), loss_in_potential ), *list(map(GrowFromCenter, potential.split())) ) self.wait(2) self.play( FadeOut(loss_in_potential), GrowFromCenter(kinetic) ) self.wait(2) self.play(ApplyMethod(ms.shift, 5*UP)) self.wait() self.play(Transform( half, two, path_func = counterclockwise_path() )) self.wait() self.play( Transform( squared, sqrt, path_func = clockwise_path() ), Transform(equals, new_eq) ) self.wait(2) class ThetaTInsteadOfXY(Scene): def construct(self): cycloid = Cycloid() index = cycloid.get_num_points()/3 point = cycloid.get_points()[index] vect = cycloid.get_points()[index+1]-point vect /= get_norm(vect) vect *= 3 vect_mob = Vector(point, vect) dot = Dot(point) xy = OldTex("\\big( x(t), y(t) \\big)") xy.next_to(dot, UP+RIGHT, buff = 0.1) vert_line = Line(2*DOWN, 2*UP) vert_line.shift(point) angle = vect_mob.get_angle() + np.pi/2 arc = Arc(angle, radius = 1, start_angle = -np.pi/2) arc.shift(point) theta = OldTex("\\theta(t)") theta.next_to(arc, DOWN, buff = 0.1, aligned_edge = LEFT) theta.shift(0.2*RIGHT) self.play(ShowCreation(cycloid)) self.play(ShowCreation(dot)) self.play(ShimmerIn(xy)) self.wait() self.play( FadeOut(xy), ShowCreation(vect_mob) ) self.play( ShowCreation(arc), ShowCreation(vert_line), ShimmerIn(theta) ) self.wait() class DefineCurveWithKnob(PathSlidingScene): def construct(self): self.knob = Circle(color = BLUE_D) self.knob.add_line(UP, DOWN) self.knob.to_corner(UP+RIGHT) self.knob.shift(0.5*DOWN) self.last_angle = np.pi/2 arrow = Vector(ORIGIN, RIGHT) arrow.next_to(self.knob, LEFT) words = OldTexText("Turn this knob over time to define the curve") words.next_to(arrow, LEFT) self.path = self.get_path() self.path.shift(1.5*DOWN) self.path.show() self.path.set_color(BLACK) randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) self.play(ShimmerIn(words)) self.play(ShowCreation(arrow)) self.play(ShowCreation(self.knob)) self.wait() self.add(self.path) self.slide(randy, self.path) self.wait() def get_path(self): return Cycloid(end_theta = 2*np.pi) def midslide_action(self, point, angle): d_angle = angle-self.last_angle self.knob.rotate(d_angle) self.last_angle = angle self.path.set_color(BLUE_D, lambda p : p[0] < point[0]) class WonkyDefineCurveWithKnob(DefineCurveWithKnob): def get_path(self): return ParametricCurve( lambda t : t*RIGHT + (-0.2*t-np.sin(2*np.pi*t/6))*UP, start = -7, end = 10 ) class SlowDefineCurveWithKnob(DefineCurveWithKnob): def get_path(self): return ParametricCurve( lambda t : t*RIGHT + (np.exp(-(t+2)**2)-0.2*np.exp(t-2)), start = -4, end = 4 ) class BumpyDefineCurveWithKnob(DefineCurveWithKnob): def get_path(self): result = FunctionGraph( lambda x : 0.05*(x**2)+0.1*np.sin(2*x) ) result.rotate(-np.pi/20) result.scale(0.7) result.shift(DOWN) return result
videos_3b1b/_2016/brachistochrone/light.py
import numpy as np import itertools as it from manim_imports_ext import * from from_3b1b.old.brachistochrone.curves import \ Cycloid, PathSlidingScene, RANDY_SCALE_FACTOR, TryManyPaths class Lens(Arc): CONFIG = { "radius" : 2, "angle" : np.pi/2, "color" : BLUE_B, } def __init__(self, **kwargs): digest_config(self, kwargs) Arc.__init__(self, self.angle, **kwargs) def init_points(self): Arc.init_points(self) self.rotate(-np.pi/4) self.shift(-self.get_left()) self.add_points(self.copy().rotate(np.pi).points) class PhotonScene(Scene): def wavify(self, mobject): result = mobject.copy() result.ingest_submobjects() tangent_vectors = result.get_points()[1:]-result.get_points()[:-1] lengths = np.apply_along_axis( get_norm, 1, tangent_vectors ) thick_lengths = lengths.repeat(3).reshape((len(lengths), 3)) unit_tangent_vectors = tangent_vectors/thick_lengths rot_matrix = np.transpose(rotation_matrix(np.pi/2, OUT)) normal_vectors = np.dot(unit_tangent_vectors, rot_matrix) # total_length = np.sum(lengths) times = np.cumsum(lengths) nudge_sizes = 0.1*np.sin(2*np.pi*times) thick_nudge_sizes = nudge_sizes.repeat(3).reshape((len(nudge_sizes), 3)) nudges = thick_nudge_sizes*normal_vectors result.get_points()[1:] += nudges return result def photon_run_along_path(self, path, color = YELLOW, **kwargs): if "rate_func" not in kwargs: kwargs["rate_func"] = None photon = self.wavify(path) photon.set_color(color) return ShowPassingFlash(photon, **kwargs) class SimplePhoton(PhotonScene): def construct(self): text = OldTexText("Light") text.to_edge(UP) self.play(ShimmerIn(text)) self.play(self.photon_run_along_path( Cycloid(), rate_func=linear )) self.wait() class MultipathPhotonScene(PhotonScene): CONFIG = { "num_paths" : 5 } def run_along_paths(self, **kwargs): paths = self.get_paths() colors = Color(YELLOW).range_to(WHITE, len(paths)) for path, color in zip(paths, colors): path.set_color(color) photon_runs = [ self.photon_run_along_path(path) for path in paths ] for photon_run, path in zip(photon_runs, paths): self.play( photon_run, ShowCreation( path, rate_func = lambda t : 0.9*smooth(t) ), **kwargs ) self.wait() def generate_paths(self): raise Exception("Not Implemented") class PhotonThroughLens(MultipathPhotonScene): def construct(self): self.lens = Lens() self.add(self.lens) self.run_along_paths() def get_paths(self): interval_values = np.arange(self.num_paths).astype('float') interval_values /= (self.num_paths-1.) first_contact = [ self.lens.point_from_proportion(0.4*v+0.55) for v in reversed(interval_values) ] second_contact = [ self.lens.point_from_proportion(0.3*v + 0.1) for v in interval_values ] focal_point = 2*RIGHT return [ Mobject( Line(FRAME_X_RADIUS*LEFT + fc[1]*UP, fc), Line(fc, sc), Line(sc, focal_point), Line(focal_point, 6*focal_point-5*sc) ).ingest_submobjects() for fc, sc in zip(first_contact, second_contact) ] class TransitionToOptics(PhotonThroughLens): def construct(self): optics = OldTexText("Optics") optics.to_edge(UP) self.add(optics) self.has_started = False PhotonThroughLens.construct(self) def play(self, *args, **kwargs): if not self.has_started: self.has_started = True everything = Mobject(*self.mobjects) vect = FRAME_WIDTH*RIGHT everything.shift(vect) self.play(ApplyMethod( everything.shift, -vect, rate_func = rush_from )) Scene.play(self, *args, **kwargs) class PhotonOffMirror(MultipathPhotonScene): def construct(self): self.mirror = Line(*FRAME_Y_RADIUS*np.array([DOWN, UP])) self.mirror.set_color(GREY) self.add(self.mirror) self.run_along_paths() def get_paths(self): interval_values = np.arange(self.num_paths).astype('float') interval_values /= (self.num_paths-1) anchor_points = [ self.mirror.point_from_proportion(0.6*v+0.3) for v in interval_values ] start_point = 5*LEFT+3*UP end_points = [] for point in anchor_points: vect = start_point-point vect[1] *= -1 end_points.append(point+2*vect) return [ Mobject( Line(start_point, anchor_point), Line(anchor_point, end_point) ).ingest_submobjects() for anchor_point, end_point in zip(anchor_points, end_points) ] class PhotonsInWater(MultipathPhotonScene): def construct(self): water = Region(lambda x, y : y < 0, color = BLUE_E) self.add(water) self.run_along_paths() def get_paths(self): x, y = -3, 3 start_point = x*RIGHT + y*UP angles = np.arange(np.pi/18, np.pi/3, np.pi/18) midpoints = y*np.arctan(angles) end_points = midpoints + FRAME_Y_RADIUS*np.arctan(2*angles) return [ Mobject( Line(start_point, [midpoint, 0, 0]), Line([midpoint, 0, 0], [end_point, -FRAME_Y_RADIUS, 0]) ).ingest_submobjects() for midpoint, end_point in zip(midpoints, end_points) ] class ShowMultiplePathsScene(PhotonScene): def construct(self): text = OldTexText("Which path minimizes travel time?") text.to_edge(UP) self.generate_start_and_end_points() point_a = Dot(self.start_point) point_b = Dot(self.end_point) A = OldTexText("A").next_to(point_a, UP) B = OldTexText("B").next_to(point_b, DOWN) paths = self.get_paths() for point, letter in [(point_a, A), (point_b, B)]: self.play( ShowCreation(point), ShimmerIn(letter) ) self.play(ShimmerIn(text)) curr_path = paths[0].copy() curr_path_copy = curr_path.copy().ingest_submobjects() self.play( self.photon_run_along_path(curr_path), ShowCreation(curr_path_copy, rate_func = rush_into) ) self.remove(curr_path_copy) for path in paths[1:] + [paths[0]]: self.play(Transform(curr_path, path, run_time = 4)) self.wait() self.path = curr_path.ingest_submobjects() def generate_start_and_end_points(self): raise Exception("Not Implemented") def get_paths(self): raise Exception("Not implemented") class ShowMultiplePathsThroughLens(ShowMultiplePathsScene): def construct(self): self.lens = Lens() self.add(self.lens) ShowMultiplePathsScene.construct(self) def generate_start_and_end_points(self): self.start_point = 3*LEFT + UP self.end_point = 2*RIGHT def get_paths(self): alphas = [0.25, 0.4, 0.58, 0.75] lower_right, upper_right, upper_left, lower_left = list(map( self.lens.point_from_proportion, alphas )) return [ Mobject( Line(self.start_point, a), Line(a, b), Line(b, self.end_point) ).set_color(color) for (a, b), color in zip( [ (upper_left, upper_right), (upper_left, lower_right), (lower_left, lower_right), (lower_left, upper_right), ], Color(YELLOW).range_to(WHITE, 4) ) ] class ShowMultiplePathsOffMirror(ShowMultiplePathsScene): def construct(self): mirror = Line(*FRAME_Y_RADIUS*np.array([DOWN, UP])) mirror.set_color(GREY) self.add(mirror) ShowMultiplePathsScene.construct(self) def generate_start_and_end_points(self): self.start_point = 4*LEFT + 2*UP self.end_point = 4*LEFT + 2*DOWN def get_paths(self): return [ Mobject( Line(self.start_point, midpoint), Line(midpoint, self.end_point) ).set_color(color) for midpoint, color in zip( [2*UP, 2*DOWN], Color(YELLOW).range_to(WHITE, 2) ) ] class ShowMultiplePathsInWater(ShowMultiplePathsScene): def construct(self): glass = Region(lambda x, y : y < 0, color = BLUE_E) self.generate_start_and_end_points() straight = Line(self.start_point, self.end_point) slow = OldTexText("Slow") slow.rotate(np.arctan(straight.get_slope())) slow.shift(straight.get_points()[int(0.7*straight.get_num_points())]) slow.shift(0.5*DOWN) too_long = OldTexText("Too long") too_long.shift(UP) air = OldTexText("Air").shift(2*UP) water = OldTexText("Water").shift(2*DOWN) self.add(glass) self.play(GrowFromCenter(air)) self.play(GrowFromCenter(water)) self.wait() self.remove(air, water) ShowMultiplePathsScene.construct(self) self.play( Transform(self.path, straight) ) self.wait() self.play(GrowFromCenter(slow)) self.wait() self.remove(slow) self.leftmost.ingest_submobjects() self.play(Transform(self.path, self.leftmost, run_time = 3)) self.wait() self.play(ShimmerIn(too_long)) self.wait() def generate_start_and_end_points(self): self.start_point = 3*LEFT + 2*UP self.end_point = 3*RIGHT + 2*DOWN def get_paths(self): self.leftmost, self.rightmost = result = [ Mobject( Line(self.start_point, midpoint), Line(midpoint, self.end_point) ).set_color(color) for midpoint, color in zip( [3*LEFT, 3*RIGHT], Color(YELLOW).range_to(WHITE, 2) ) ] return result class StraightLinesFastestInConstantMedium(PhotonScene): def construct(self): kwargs = {"size" : "\\Large"} left = OldTexText("Speed of light is constant", **kwargs) arrow = OldTex("\\Rightarrow", **kwargs) right = OldTexText("Staight path is fastest", **kwargs) left.next_to(arrow, LEFT) right.next_to(arrow, RIGHT) squaggle, line = self.get_paths() self.play(*list(map(ShimmerIn, [left, arrow, right]))) self.play(ShowCreation(squaggle)) self.play(self.photon_run_along_path( squaggle, run_time = 2, rate_func=linear )) self.play(Transform( squaggle, line, path_func = path_along_arc(np.pi) )) self.play(self.photon_run_along_path(line, rate_func=linear)) self.wait() def get_paths(self): squaggle = ParametricCurve( lambda t : (0.5*t+np.cos(t))*RIGHT+np.sin(t)*UP, start = -np.pi, end = 2*np.pi ) squaggle.shift(2*UP) start, end = squaggle.get_points()[0], squaggle.get_points()[-1] line = Line(start, end) result = [squaggle, line] for mob in result: mob.set_color(BLUE_D) return result class PhtonBendsInWater(PhotonScene, ZoomedScene): def construct(self): glass = Region(lambda x, y : y < 0, color = BLUE_E) kwargs = { "density" : self.zoom_factor*DEFAULT_POINT_DENSITY_1D } top_line = Line(FRAME_Y_RADIUS*UP+2*LEFT, ORIGIN, **kwargs) extension = Line(ORIGIN, FRAME_Y_RADIUS*DOWN+2*RIGHT, **kwargs) bottom_line = Line(ORIGIN, FRAME_Y_RADIUS*DOWN+RIGHT, **kwargs) path1 = Mobject(top_line, extension) path2 = Mobject(top_line, bottom_line) for mob in path1, path2: mob.ingest_submobjects() extension.set_color(RED) theta1 = np.arctan(bottom_line.get_slope()) theta2 = np.arctan(extension.get_slope()) arc = Arc(theta2-theta1, start_angle = theta1, radius = 2) question_mark = OldTexText("$\\theta$?") question_mark.shift(arc.get_center()+0.5*DOWN+0.25*RIGHT) wave = self.wavify(path2) wave.set_color(YELLOW) wave.scale(0.5) self.add(glass) self.play(ShowCreation(path1)) self.play(Transform(path1, path2)) self.wait() # self.activate_zooming() self.wait() self.play(ShowPassingFlash( wave, run_time = 3, rate_func=linear )) self.wait() self.play(ShowCreation(extension)) self.play( ShowCreation(arc), ShimmerIn(question_mark) ) class LightIsFasterInAirThanWater(ShowMultiplePathsInWater): def construct(self): glass = Region(lambda x, y : y < 0, color = BLUE_E) equation = OldTex("v_{\\text{air}} > v_{\\text{water}}") equation.to_edge(UP) path = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) path1 = path.copy().shift(2*UP) path2 = path.copy().shift(2*DOWN) self.add(glass) self.play(ShimmerIn(equation)) self.wait() photon_runs = [] photon_runs.append(self.photon_run_along_path( path1, rate_func = lambda t : min(1, 1.2*t) )) photon_runs.append(self.photon_run_along_path(path2)) self.play(*photon_runs, **{"run_time" : 2}) self.wait() class GeometryOfGlassSituation(ShowMultiplePathsInWater): def construct(self): glass = Region(lambda x, y : y < 0, color = BLUE_E) self.generate_start_and_end_points() left = self.start_point[0]*RIGHT right = self.end_point[0]*RIGHT start_x = interpolate(left, right, 0.2) end_x = interpolate(left, right, 1.0) left_line = Line(self.start_point, left, color = RED_D) right_line = Line(self.end_point, right, color = RED_D) h_1, h_2 = list(map(Tex, ["h_1", "h_2"])) h_1.next_to(left_line, LEFT) h_2.next_to(right_line, RIGHT) point_a = Dot(self.start_point) point_b = Dot(self.end_point) A = OldTexText("A").next_to(point_a, UP) B = OldTexText("B").next_to(point_b, DOWN) x = start_x left_brace = Brace(Mobject(Point(left), Point(x))) right_brace = Brace(Mobject(Point(x), Point(right)), UP) x_mob = OldTex("x") x_mob.next_to(left_brace, DOWN) w_minus_x = OldTex("w-x") w_minus_x.next_to(right_brace, UP) top_line = Line(self.start_point, x) bottom_line = Line(x, self.end_point) top_dist = OldTex("\\sqrt{h_1^2+x^2}") top_dist.scale(0.5) a = 0.3 n = top_line.get_num_points() point = top_line.get_points()[int(a*n)] top_dist.next_to(Point(point), RIGHT, buff = 0.3) bottom_dist = OldTex("\\sqrt{h_2^2+(w-x)^2}") bottom_dist.scale(0.5) n = bottom_line.get_num_points() point = bottom_line.get_points()[int((1-a)*n)] bottom_dist.next_to(Point(point), LEFT, buff = 1) end_top_line = Line(self.start_point, end_x) end_bottom_line = Line(end_x, self.end_point) end_brace = Brace(Mobject(Point(left), Point(end_x))) end_x_mob = OldTex("x").next_to(end_brace, DOWN) axes = Mobject( NumberLine(), NumberLine().rotate(np.pi/2).shift(7*LEFT) ) graph = FunctionGraph( lambda x : 0.4*(x+1)*(x-3)+4, x_min = -2, x_max = 4 ) graph.set_color(YELLOW) Mobject(axes, graph).scale(0.2).to_corner(UP+RIGHT, buff = 1) axes.add(OldTex("x", size = "\\small").next_to(axes, RIGHT)) axes.add(OldTexText("Travel time", size = "\\small").next_to( axes, UP )) new_graph = graph.copy() midpoint = new_graph.get_points()[new_graph.get_num_points()/2] new_graph.filter_out(lambda p : p[0] < midpoint[0]) new_graph.reverse_points() pairs_for_end_transform = [ (mob, mob.copy()) for mob in (top_line, bottom_line, left_brace, x_mob) ] self.add(glass, point_a, point_b, A, B) line = Mobject(top_line, bottom_line).ingest_submobjects() self.play(ShowCreation(line)) self.wait() self.play( GrowFromCenter(left_brace), GrowFromCenter(x_mob) ) self.play( GrowFromCenter(right_brace), GrowFromCenter(w_minus_x) ) self.play(ShowCreation(left_line), ShimmerIn(h_1)) self.play(ShowCreation(right_line), GrowFromCenter(h_2)) self.play(ShimmerIn(top_dist)) self.play(GrowFromCenter(bottom_dist)) self.wait(3) self.clear() self.add(glass, point_a, point_b, A, B, top_line, bottom_line, left_brace, x_mob) self.play(ShowCreation(axes)) kwargs = { "run_time" : 4, } self.play(*[ Transform(*pair, **kwargs) for pair in [ (top_line, end_top_line), (bottom_line, end_bottom_line), (left_brace, end_brace), (x_mob, end_x_mob) ] ]+[ShowCreation(graph, **kwargs)]) self.wait() self.show_derivatives(graph) line = self.show_derivatives(new_graph) self.add(line) self.play(*[ Transform(*pair, rate_func = lambda x : 0.3*smooth(x)) for pair in pairs_for_end_transform ]) self.wait() def show_derivatives(self, graph, run_time = 2): step = self.frame_duration/run_time for a in smooth(np.arange(0, 1-step, step)): index = int(a*graph.get_num_points()) p1, p2 = graph.get_points()[index], graph.get_points()[index+1] line = Line(LEFT, RIGHT) line.rotate(angle_of_vector(p2-p1)) line.shift(p1) self.add(line) self.wait(self.frame_duration) self.remove(line) return line class Spring(Line): CONFIG = { "num_loops" : 5, "loop_radius" : 0.3, "color" : GREY } def init_points(self): ## self.start, self.end length = get_norm(self.end-self.start) angle = angle_of_vector(self.end-self.start) micro_radius = self.loop_radius/length m = 2*np.pi*(self.num_loops+0.5) def loop(t): return micro_radius*( RIGHT + np.cos(m*t)*LEFT + np.sin(m*t)*UP ) new_epsilon = self.epsilon/(m*micro_radius)/length self.add_points([ t*RIGHT + loop(t) for t in np.arange(0, 1, new_epsilon) ]) self.scale(length/(1+2*micro_radius)) self.rotate(angle) self.shift(self.start) class SpringSetup(ShowMultiplePathsInWater): def construct(self): self.ring_shift_val = 6*RIGHT self.slide_kwargs = { "rate_func" : there_and_back, "run_time" : 5 } self.setup_background() rod = Region( lambda x, y : (abs(x) < 5) & (abs(y) < 0.05), color = GOLD_E ) ring = Arc( angle = 11*np.pi/6, start_angle = -11*np.pi/12, radius = 0.2, color = YELLOW ) ring.shift(-self.ring_shift_val/2) self.generate_springs(ring) self.add_rod_and_ring(rod, ring) self.slide_ring(ring) self.wait() self.add_springs() self.add_force_definitions() self.slide_system(ring) self.show_horizontal_component(ring) self.show_angles(ring) self.show_equation() def setup_background(self): glass = Region(lambda x, y : y < 0, color = BLUE_E) self.generate_start_and_end_points() point_a = Dot(self.start_point) point_b = Dot(self.end_point) A = OldTexText("A").next_to(point_a, UP) B = OldTexText("B").next_to(point_b, DOWN) self.add(glass, point_a, point_b, A, B) def generate_springs(self, ring): self.start_springs, self.end_springs = [ Mobject( Spring(self.start_point, r.get_top()), Spring(self.end_point, r.get_bottom()) ) for r in (ring, ring.copy().shift(self.ring_shift_val)) ] def add_rod_and_ring(self, rod, ring): rod_word = OldTexText("Rod") rod_word.next_to(Point(), UP) ring_word = OldTexText("Ring") ring_word.next_to(ring, UP) self.wait() self.add(rod) self.play(ShimmerIn(rod_word)) self.wait() self.remove(rod_word) self.play(ShowCreation(ring)) self.play(ShimmerIn(ring_word)) self.wait() self.remove(ring_word) def slide_ring(self, ring): self.play(ApplyMethod( ring.shift, self.ring_shift_val, **self.slide_kwargs )) def add_springs(self): colors = iter([BLACK, BLUE_E]) for spring in self.start_springs.split(): circle = Circle(color = next(colors)) circle.reverse_points() circle.scale(spring.loop_radius) circle.shift(spring.get_points()[0]) self.play(Transform(circle, spring)) self.remove(circle) self.add(spring) self.wait() def add_force_definitions(self): top_force = OldTex("F_1 = \\dfrac{1}{v_{\\text{air}}}") bottom_force = OldTex("F_2 = \\dfrac{1}{v_{\\text{water}}}") top_spring, bottom_spring = self.start_springs.split() top_force.next_to(top_spring) bottom_force.next_to(bottom_spring, DOWN, buff = -0.5) words = OldTexText(""" The force in a real spring is proportional to that spring's length """) words.to_corner(UP+RIGHT) for force in top_force, bottom_force: self.play(GrowFromCenter(force)) self.wait() self.play(ShimmerIn(words)) self.wait(3) self.remove(top_force, bottom_force, words) def slide_system(self, ring): equilibrium_slide_kwargs = dict(self.slide_kwargs) def jiggle_to_equilibrium(t): return 0.7*(1+((1-t)**2)*(-np.cos(10*np.pi*t))) equilibrium_slide_kwargs = { "rate_func" : jiggle_to_equilibrium, "run_time" : 3 } start = Mobject(ring, self.start_springs) end = Mobject( ring.copy().shift(self.ring_shift_val), self.end_springs ) for kwargs in self.slide_kwargs, equilibrium_slide_kwargs: self.play(Transform(start, end, **kwargs)) self.wait() def show_horizontal_component(self, ring): v_right = Vector(ring.get_top(), RIGHT) v_left = Vector(ring.get_bottom(), LEFT) self.play(*list(map(ShowCreation, [v_right, v_left]))) self.wait() self.remove(v_right, v_left) def show_angles(self, ring): ring_center = ring.get_center() lines, arcs, thetas = [], [], [] counter = it.count(1) for point in self.start_point, self.end_point: line = Line(point, ring_center, color = GREY) angle = np.pi/2-np.abs(np.arctan(line.get_slope())) arc = Arc(angle, radius = 0.5).rotate(np.pi/2) if point is self.end_point: arc.rotate(np.pi) theta = OldTex("\\theta_%d"%next(counter)) theta.scale(0.5) theta.shift(2*arc.get_center()) arc.shift(ring_center) theta.shift(ring_center) lines.append(line) arcs.append(arc) thetas.append(theta) vert_line = Line(2*UP, 2*DOWN) vert_line.shift(ring_center) top_spring, bottom_spring = self.start_springs.split() self.play( Transform(ring, Point(ring_center)), Transform(top_spring, lines[0]), Transform(bottom_spring, lines[1]) ) self.play(ShowCreation(vert_line)) anims = [] for arc, theta in zip(arcs, thetas): anims += [ ShowCreation(arc), GrowFromCenter(theta) ] self.play(*anims) self.wait() def show_equation(self): equation = OldTex([ "\\left(\\dfrac{1}{\\phantom{v_air}}\\right)", "\\sin(\\theta_1)", "=", "\\left(\\dfrac{1}{\\phantom{v_water}}\\right)", "\\sin(\\theta_2)" ]) equation.to_corner(UP+RIGHT) frac1, sin1, equals, frac2, sin2 = equation.split() v_air, v_water = [ OldTex("v_{\\text{%s}}"%s, size = "\\Large") for s in ("air", "water") ] v_air.next_to(Point(frac1.get_center()), DOWN) v_water.next_to(Point(frac2.get_center()), DOWN) frac1.add(v_air) frac2.add(v_water) f1, f2 = [ OldTex("F_%d"%d, size = "\\Large") for d in (1, 2) ] f1.next_to(sin1, LEFT) f2.next_to(equals, RIGHT) sin2_start = sin2.copy().next_to(f2, RIGHT) bar1 = OldTex("\\dfrac{\\qquad}{\\qquad}") bar2 = bar1.copy() bar1.next_to(sin1, DOWN) bar2.next_to(sin2, DOWN) v_air_copy = v_air.copy().next_to(bar1, DOWN) v_water_copy = v_water.copy().next_to(bar2, DOWN) bars = Mobject(bar1, bar2) new_eq = equals.copy().center().shift(bars.get_center()) snells = OldTexText("Snell's Law") snells.set_color(YELLOW) snells.shift(new_eq.get_center()[0]*RIGHT) snells.shift(UP) anims = [] for mob in f1, sin1, equals, f2, sin2_start: anims.append(ShimmerIn(mob)) self.play(*anims) self.wait() for f, frac in (f1, frac1), (f2, frac2): target = frac.copy().ingest_submobjects() also = [] if f is f2: also.append(Transform(sin2_start, sin2)) sin2 = sin2_start self.play(Transform(f, target), *also) self.remove(f) self.add(frac) self.wait() self.play( FadeOut(frac1), FadeOut(frac2), Transform(v_air, v_air_copy), Transform(v_water, v_water_copy), ShowCreation(bars), Transform(equals, new_eq) ) self.wait() frac1 = Mobject(sin1, bar1, v_air) frac2 = Mobject(sin2, bar2, v_water) for frac, vect in (frac1, LEFT), (frac2, RIGHT): self.play(ApplyMethod( frac.next_to, equals, vect )) self.wait() self.play(ShimmerIn(snells)) self.wait() class WhatGovernsTheSpeedOfLight(PhotonScene, PathSlidingScene): def construct(self): randy = Randolph() randy.scale(RANDY_SCALE_FACTOR) randy.shift(-randy.get_bottom()) self.add_cycloid_end_points() self.add(self.cycloid) self.slide(randy, self.cycloid) self.play(self.photon_run_along_path(self.cycloid)) self.wait() class WhichPathWouldLightTake(PhotonScene, TryManyPaths): def construct(self): words = OldTexText( ["Which path ", "would \\emph{light} take", "?"] ) words.split()[1].set_color(YELLOW) words.to_corner(UP+RIGHT) self.add_cycloid_end_points() anims = [ self.photon_run_along_path( path, rate_func = smooth ) for path in self.get_paths() ] self.play(anims[0], ShimmerIn(words)) for anim in anims[1:]: self.play(anim) class StateSnellsLaw(PhotonScene): def construct(self): point_a = 3*LEFT+3*UP point_b = 1.5*RIGHT+3*DOWN midpoint = ORIGIN lines, arcs, thetas = [], [], [] counter = it.count(1) for point in point_a, point_b: line = Line(point, midpoint, color = RED_D) angle = np.pi/2-np.abs(np.arctan(line.get_slope())) arc = Arc(angle, radius = 0.5).rotate(np.pi/2) if point is point_b: arc.rotate(np.pi) line.reverse_points() theta = OldTex("\\theta_%d"%next(counter)) theta.scale(0.5) theta.shift(2*arc.get_center()) arc.shift(midpoint) theta.shift(midpoint) lines.append(line) arcs.append(arc) thetas.append(theta) vert_line = Line(2*UP, 2*DOWN) vert_line.shift(midpoint) path = Mobject(*lines).ingest_submobjects() glass = Region(lambda x, y : y < 0, color = BLUE_E) self.add(glass) equation = OldTex([ "\\dfrac{\\sin(\\theta_1)}{v_{\\text{air}}}", "=", "\\dfrac{\\sin(\\theta_2)}{v_{\\text{water}}}", ]) equation.to_corner(UP+RIGHT) exp1, equals, exp2 = equation.split() snells_law = OldTexText("Snell's Law:") snells_law.set_color(YELLOW) snells_law.to_edge(UP) self.play(ShimmerIn(snells_law)) self.wait() self.play(ShowCreation(path)) self.play(self.photon_run_along_path(path)) self.wait() self.play(ShowCreation(vert_line)) self.play(*list(map(ShowCreation, arcs))) self.play(*list(map(GrowFromCenter, thetas))) self.wait() self.play(ShimmerIn(exp1)) self.wait() self.play(*list(map(ShimmerIn, [equals, exp2]))) self.wait()
videos_3b1b/_2016/brachistochrone/wordplay.py
import numpy as np import itertools as it import os from manim_imports_ext import * from from_3b1b.old.brachistochrone.drawing_images import sort_by_color class Intro(Scene): def construct(self): logo = ImageMobject("LogoGeneration", invert = False) name_mob = OldTexText("3Blue1Brown").center() name_mob.set_color("grey") name_mob.shift(2*DOWN) self.add(name_mob, logo) new_text = OldTexText(["with ", "Steven Strogatz"]) new_text.next_to(name_mob, DOWN) self.play(*[ ShimmerIn(part) for part in new_text.split() ]) self.wait() with_word, steve = new_text.split() steve_copy = steve.copy().center().to_edge(UP) # logo.sort_points(lambda p : -get_norm(p)) sort_by_color(logo) self.play( Transform(steve, steve_copy), DelayByOrder(Transform(logo, Point())), FadeOut(with_word), FadeOut(name_mob), run_time = 3 ) class IntroduceSteve(Scene): def construct(self): name = OldTexText("Steven Strogatz") name.to_edge(UP) contributions = OldTexText("Frequent Contributions") contributions.scale(0.5).to_edge(RIGHT).shift(2*UP) books_word = OldTexText("Books") books_word.scale(0.5).to_edge(LEFT).shift(2*UP) radio_lab, sci_fri, cornell, book2, book3, book4 = [ ImageMobject(filename, invert = False, filter_color = WHITE) for filename in [ "radio_lab", "science_friday", "cornell", "strogatz_book2", "strogatz_book3", "strogatz_book4", ] ] book1 = ImageMobject("strogatz_book1", invert = False) nyt = ImageMobject("new_york_times") logos = [radio_lab, nyt, sci_fri] books = [book1, book2, book3, book4] sample_size = Square(side_length = 2) last = contributions for image in logos: image.replace(sample_size) image.next_to(last, DOWN) last = image sci_fri.scale(0.9) shift_val = 0 sample_size.scale(0.75) for book in books: book.replace(sample_size) book.next_to(books_word, DOWN) book.shift(shift_val*(RIGHT+DOWN)) shift_val += 0.5 sample_size.scale(2) cornell.replace(sample_size) cornell.next_to(name, DOWN) self.add(name) self.play(FadeIn(cornell)) self.play(ShimmerIn(books_word)) for book in books: book.shift(5*LEFT) self.play(ApplyMethod(book.shift, 5*RIGHT)) self.play(ShimmerIn(contributions)) for logo in logos: self.play(FadeIn(logo)) self.wait() class ShowTweets(Scene): def construct(self): tweets = [ ImageMobject("tweet%d"%x, invert = False) for x in range(1, 4) ] for tweet in tweets: tweet.scale(0.4) tweets[0].to_corner(UP+LEFT) tweets[1].next_to(tweets[0], RIGHT, aligned_edge = UP) tweets[2].next_to(tweets[1], DOWN) self.play(GrowFromCenter(tweets[0])) for x in 1, 2: self.play( Transform(Point(tweets[x-1].get_center()), tweets[x]), Animation(tweets[x-1]) ) self.wait() class LetsBeHonest(Scene): def construct(self): self.play(ShimmerIn(OldTexText(""" Let's be honest about who benefits from this collaboration... """))) self.wait() class WhatIsTheBrachistochrone(Scene): def construct(self): self.play(ShimmerIn(OldTexText(""" So \\dots what is the Brachistochrone? """))) self.wait() class DisectBrachistochroneWord(Scene): def construct(self): word = OldTexText(["Bra", "chis", "to", "chrone"]) original_word = word.copy() dots = [] for part in word.split(): if dots: part.next_to(dots[-1], buff = 0.06) dot = OldTex("\\cdot") dot.next_to(part, buff = 0.06) dots.append(dot) dots = Mobject(*dots[:-1]) dots.shift(0.1*DOWN) Mobject(word, dots).center() overbrace1 = Brace(Mobject(*word.split()[:-1]), UP) overbrace2 = Brace(word.split()[-1], UP) shortest = OldTexText("Shortest") shortest.next_to(overbrace1, UP) shortest.set_color(YELLOW) time = OldTexText("Time") time.next_to(overbrace2, UP) time.set_color(YELLOW) chrono_example = OldTexText(""" As in ``Chronological'' \\\\ or ``Synchronize'' """) chrono_example.scale(0.5) chrono_example.to_edge(RIGHT) chrono_example.shift(2*UP) chrono_example.set_color(BLUE_D) chrono_arrow = Arrow( word.get_right(), chrono_example.get_bottom(), color = BLUE_D ) brachy_example = OldTexText("As in . . . brachydactyly?") brachy_example.scale(0.5) brachy_example.to_edge(LEFT) brachy_example.shift(2*DOWN) brachy_example.set_color(GREEN) brachy_arrow = Arrow( word.get_left(), brachy_example.get_top(), color = GREEN ) pronunciation = OldTexText(["/br", "e", "kist","e","kr$\\bar{o}$n/"]) pronunciation.split()[1].rotate(np.pi) pronunciation.split()[3].rotate(np.pi) pronunciation.scale(0.7) pronunciation.shift(DOWN) latin = OldTexText(list("Latin")) greek = OldTexText(list("Greek")) for mob in latin, greek: mob.to_edge(LEFT) question_mark = OldTexText("?").next_to(greek, buff = 0.1) stars = Stars().set_color(BLACK) stars.scale(0.5).shift(question_mark.get_center()) self.play(Transform(original_word, word), ShowCreation(dots)) self.play(ShimmerIn(pronunciation)) self.wait() self.play( GrowFromCenter(overbrace1), GrowFromCenter(overbrace2) ) self.wait() self.play(ShimmerIn(latin)) self.play(FadeIn(question_mark)) self.play(Transform( latin, greek, path_func = counterclockwise_path() )) self.wait() self.play(Transform(question_mark, stars)) self.remove(stars) self.wait() self.play(ShimmerIn(shortest)) self.play(ShimmerIn(time)) for ex, ar in [(chrono_example, chrono_arrow), (brachy_example, brachy_arrow)]: self.play( ShowCreation(ar), ShimmerIn(ex) ) self.wait() class OneSolutionTwoInsights(Scene): def construct(self): one_solution = OldTexText(["One ", "solution"]) two_insights = OldTexText(["Two ", " insights"]) two, insights = two_insights.split() johann = ImageMobject("Johann_Bernoulli2", invert = False) mark = ImageMobject("Mark_Levi", invert = False) for mob in johann, mark: mob.scale(0.4) johann.next_to(insights, LEFT) mark.next_to(johann, RIGHT) name = OldTexText("Mark Levi").to_edge(UP) self.play(*list(map(ShimmerIn, one_solution.split()))) self.wait() for pair in zip(one_solution.split(), two_insights.split()): self.play(Transform(*pair, path_func = path_along_arc(np.pi))) self.wait() self.clear() self.add(two, insights) for word, man in [(two, johann), (insights, mark)]: self.play( Transform(word, Point(word.get_left())), GrowFromCenter(man) ) self.wait() self.clear() self.play(ApplyMethod(mark.center)) self.play(ShimmerIn(name)) self.wait() class CircleOfIdeas(Scene): def construct(self): words = list(map(TexText, [ "optics", "calculus", "mechanics", "geometry", "history" ])) words[0].set_color(YELLOW) words[1].set_color(BLUE_D) words[2].set_color(GREY) words[3].set_color(GREEN) words[4].set_color(MAROON) brachistochrone = OldTexText("Brachistochrone") displayed_words = [] for word in words: anims = self.get_spinning_anims(displayed_words) word.shift(3*RIGHT) point = Point() anims.append(Transform(point, word)) self.play(*anims) self.remove(point) self.add(word) displayed_words.append(word) self.play(*self.get_spinning_anims(displayed_words)) self.play(*[ Transform( word, word.copy().set_color(BLACK).center().scale(0.1), path_func = path_along_arc(np.pi), rate_func=linear, run_time = 2 ) for word in displayed_words ]+[ GrowFromCenter(brachistochrone) ]) self.wait() def get_spinning_anims(self, words, angle = np.pi/6): anims = [] for word in words: old_center = word.get_center() new_center = rotate_vector(old_center, angle) vect = new_center-old_center anims.append(ApplyMethod( word.shift, vect, path_func = path_along_arc(angle), rate_func=linear )) return anims class FermatsPrincipleStatement(Scene): def construct(self): words = OldTexText([ "Fermat's principle:", """ If a beam of light travels from point $A$ to $B$, it does so along the fastest path possible. """ ]) words.split()[0].set_color(BLUE) everything = MobjectFromRegion(Region()) everything.scale(0.9) angles = np.apply_along_axis( angle_of_vector, 1, everything.points ) norms = np.apply_along_axis( get_norm, 1, everything.points ) norms -= np.min(norms) norms /= np.max(norms) alphas = 0.25 + 0.75 * norms * (1 + np.sin(12*angles))/2 everything.rgbas = alphas.repeat(3).reshape((len(alphas), 3)) Mobject(everything, words).show() everything.sort_points(get_norm) self.add(words) self.play( DelayByOrder(FadeIn(everything, run_time = 3)), Animation(words) ) self.play( ApplyMethod(everything.set_color, WHITE), ) self.wait() class VideoProgression(Scene): def construct(self): spacing = 2*UP brachy, optics, light_in_two, snells, multi = words = [ OldTexText(text) for text in [ "Brachistochrone", "Optics", "Light in two media", "Snell's Law", "Multilayered glass", ] ] for mob in light_in_two, snells: mob.shift(-spacing) arrow1 = Arrow(brachy, optics) arrow2 = Arrow(optics, snells) point = Point(DOWN) self.play(ShimmerIn(brachy)) self.wait() self.play( ApplyMethod(brachy.shift, spacing), Transform(point, optics) ) optics = point arrow1 = Arrow(optics, brachy) self.play(ShowCreation(arrow1)) self.wait() arrow2 = Arrow(light_in_two, optics) self.play( ShowCreation(arrow2), ShimmerIn(light_in_two) ) self.wait() self.play( FadeOut(light_in_two), GrowFromCenter(snells), DelayByOrder( ApplyMethod(arrow2.set_color, BLUE_D) ) ) self.wait() self.play( FadeOut(optics), GrowFromCenter(multi), DelayByOrder( ApplyMethod(arrow1.set_color, BLUE_D) ) ) self.wait() class BalanceCompetingFactors(Scene): args_list = [ ("Short", "Steep"), ("Minimal time \\\\ in water", "Short path") ] @staticmethod def args_to_string(*words): return "".join([word.split(" ")[0] for word in words]) def construct(self, *words): factor1, factor2 = [ OldTexText("Factor %d"%x).set_color(c) for x, c in [ (1, RED_D), (2, BLUE_D) ] ] real_factor1, real_factor2 = list(map(TexText, words)) for word in factor1, factor2, real_factor1, real_factor2: word.shift(0.2*UP-word.get_bottom()) for f1 in factor1, real_factor1: f1.set_color(RED_D) f1.shift(2*LEFT) for f2 in factor2, real_factor2: f2.set_color(BLUE_D) f2.shift(2*RIGHT) line = Line( factor1.get_left(), factor2.get_right() ) line.center() self.balancers = Mobject(factor1, factor2, line) self.hidden_balancers = Mobject(real_factor1, real_factor2) triangle = Polygon(RIGHT, np.sqrt(3)*UP, LEFT) triangle.next_to(line, DOWN, buff = 0) self.add(triangle, self.balancers) self.rotate(1) self.rotate(-2) self.wait() self.play(Transform( factor1, real_factor1, path_func = path_along_arc(np.pi/4) )) self.rotate(2) self.wait() self.play(Transform( factor2, real_factor2, path_func = path_along_arc(np.pi/4) )) self.rotate(-2) self.wait() self.rotate(1) def rotate(self, factor): angle = np.pi/11 self.play(Rotate( self.balancers, factor*angle, run_time = abs(factor) )) self.hidden_balancers.rotate(factor*angle) class Challenge(Scene): def construct(self): self.add(OldTexText(""" Can you find a new solution to the Brachistochrone problem by finding an intuitive reason that time-minimizing curves look like straight lines in $t$-$\\theta$ space? """)) self.wait() class Section1(Scene): def construct(self): self.add(OldTexText("Section 1: Johann Bernoulli's insight")) self.wait() class Section2(Scene): def construct(self): self.add(OldTexText( "Section 2: Mark Levi's insight, and a challenge", size = "\\large" )) self.wait() class NarratorInterjection(Scene): def construct(self): words1 = OldTex("<\\text{Narrator interjection}>") words2 = OldTex("<\\!/\\text{Narrator interjection}>") self.add(words1) self.wait() self.clear() self.add(words2) self.wait() class ThisCouldBeTheEnd(Scene): def construct(self): words = OldTexText([ "This could be the end\\dots", "but\\dots" ]) for part in words.split(): self.play(ShimmerIn(part)) self.wait() class MyOwnChallenge(Scene): def construct(self): self.add(OldTexText("My own challenge:")) self.wait() class WarmupChallenge(Scene): def construct(self): self.add(OldTexText("\\large Warm-up challenge: Confirm this for yourself")) self.wait() class FindAnotherSolution(Scene): def construct(self): self.add(OldTexText("Find another brachistochrone solution\\dots")) self.wait() class ProofOfSnellsLaw(Scene): def construct(self): self.add(OldTexText("Proof of Snell's law:")) self.wait() class CondensedVersion(Scene): def construct(self): snells = OldTexText("Snell's") snells.shift(-snells.get_left()) snells.to_edge(UP) for vect in [RIGHT, RIGHT, LEFT, DOWN, DOWN, DOWN]: snells.add(snells.copy().next_to(snells, vect)) snells.ingest_submobjects() snells.show() condensed = OldTexText("condensed") self.add(snells) self.wait() self.play(DelayByOrder( Transform(snells, condensed, run_time = 2) )) self.wait()
videos_3b1b/_2016/brachistochrone/drawing_images.py
import numpy as np import itertools as it import operator as op import sys import inspect from PIL import Image import cv2 import random from scipy.spatial.distance import cdist from scipy import ndimage from manim_imports_ext import * DEFAULT_GAUSS_BLUR_CONFIG = { "ksize" : (5, 5), "sigmaX" : 6, "sigmaY" : 6, } DEFAULT_CANNY_CONFIG = { "threshold1" : 50, "threshold2" : 100, } DEFAULT_BLUR_RADIUS = 0.5 DEFAULT_CONNECTED_COMPONENT_THRESHOLD = 25 def reverse_colors(nparray): return nparray[:,:,[2, 1, 0]] def show(nparray): Image.fromarray(reverse_colors(nparray)).show() def thicken(nparray): height, width = nparray.shape nparray = nparray.reshape((height, width, 1)) return np.repeat(nparray, 3, 2) def sort_by_color(mob): indices = np.argsort(np.apply_along_axis( lambda p : -get_norm(p), 1, mob.rgbas )) mob.rgbas = mob.rgbas[indices] mob.points = mob.get_points()[indices] def get_image_array(name): image_files = os.listdir(IMAGE_DIR) possibilities = [s for s in image_files if s.startswith(name)] for possibility in possibilities: try: path = os.path.join(IMAGE_DIR, possibility) image = Image.open(path) image = image.convert('RGB') return np.array(image) except: pass raise Exception("Image for %s not found"%name) def get_edges(image_array): blurred = cv2.GaussianBlur( image_array, **DEFAULT_GAUSS_BLUR_CONFIG ) edges = cv2.Canny( blurred, **DEFAULT_CANNY_CONFIG ) return edges def nearest_neighbor_align(mobject1, mobject2): distance_matrix = cdist(mobject1.points, mobject2.points) closest_point_indices = np.apply_along_axis( np.argmin, 0, distance_matrix ) new_mob1 = Mobject() new_mob2 = Mobject() for n in range(mobject1.get_num_points()): indices = (closest_point_indices == n) new_mob1.add_points( [mobject1.get_points()[n]]*sum(indices) ) new_mob2.add_points( mobject2.get_points()[indices], rgbas = mobject2.rgbas[indices] ) return new_mob1, new_mob2 def get_connected_components(image_array, blur_radius = DEFAULT_BLUR_RADIUS, threshold = DEFAULT_CONNECTED_COMPONENT_THRESHOLD): blurred_image = ndimage.gaussian_filter(image_array, blur_radius) labels, component_count = ndimage.label(blurred_image > threshold) return [ image_array * (labels == count) for count in range(1, component_count+1) ] def color_region(bw_region, colored_image): return thicken(bw_region > 0) * colored_image class TracePicture(Scene): args_list = [ ("Newton",), ("Mark_Levi",), ("Steven_Strogatz",), ("Pierre_de_Fermat",), ("Galileo_Galilei",), ("Jacob_Bernoulli",), ("Johann_Bernoulli2",), ("Old_Newton",) ] @staticmethod def args_to_string(name): return name @staticmethod def string_to_args(name): return name def construct(self, name): run_time = 20 scale_factor = 0.8 image_array = get_image_array(name) edge_mobject = self.get_edge_mobject(image_array) full_picture = MobjectFromPixelArray(image_array) for mob in edge_mobject, full_picture: # mob.stroke_width = 4 mob.scale(scale_factor) mob.show() self.play( DelayByOrder(FadeIn( full_picture, run_time = run_time, rate_func = squish_rate_func(smooth, 0.7, 1) )), ShowCreation( edge_mobject, run_time = run_time, rate_func=linear ) ) self.remove(edge_mobject) self.wait() def get_edge_mobject(self, image_array): edged_image = get_edges(image_array) individual_edges = get_connected_components(edged_image) colored_edges = [ color_region(edge, image_array) for edge in individual_edges ] colored_edge_mobject_list = [ MobjectFromPixelArray(colored_edge) for colored_edge in colored_edges ] random.shuffle(colored_edge_mobject_list) edge_mobject = Mobject(*colored_edge_mobject_list) edge_mobject.ingest_submobjects() return edge_mobject class JohannThinksHeIsBetter(Scene): def construct(self): names = [ "Johann_Bernoulli2", "Jacob_Bernoulli", "Gottfried_Wilhelm_von_Leibniz", "Newton" ] guys = [ ImageMobject(name, invert = False) for name in names ] johann = guys[0] johann.scale(0.8) pensive_johann = johann.copy() pensive_johann.scale(0.25) pensive_johann.to_corner(DOWN+LEFT) comparitive_johann = johann.copy() template = Square(side_length = 2) comparitive_johann.replace(template) comparitive_johann.shift(UP+LEFT) greater_than = OldTex(">") greater_than.next_to(comparitive_johann) for guy, name in zip(guys, names)[1:]: guy.replace(template) guy.next_to(greater_than) name_mob = OldTexText(name.replace("_", " ")) name_mob.scale(0.5) name_mob.next_to(guy, DOWN) guy.name_mob = name_mob guy.sort_points(lambda p : np.dot(p, DOWN+RIGHT)) bubble = ThoughtBubble(initial_width = 12) bubble.stretch_to_fit_height(6) bubble.ingest_submobjects() bubble.pin_to(pensive_johann) bubble.shift(DOWN) point = Point(johann.get_corner(UP+RIGHT)) upper_point = Point(comparitive_johann.get_corner(UP+RIGHT)) lightbulb = ImageMobject("Lightbulb", invert = False) lightbulb.scale(0.1) lightbulb.sort_points(get_norm) lightbulb.next_to(upper_point, RIGHT) self.add(johann) self.wait() self.play( Transform(johann, pensive_johann), Transform(point, bubble), run_time = 2 ) self.remove(point) self.add(bubble) weakling = guys[1] self.play( FadeIn(comparitive_johann), ShowCreation(greater_than), FadeIn(weakling) ) self.wait(2) for guy in guys[2:]: self.play(DelayByOrder(Transform( weakling, upper_point ))) self.play( FadeIn(guy), ShimmerIn(guy.name_mob) ) self.wait(3) self.remove(guy.name_mob) weakling = guy self.play(FadeOut(weakling), FadeOut(greater_than)) self.play(ShowCreation(lightbulb)) self.wait() self.play(FadeOut(comparitive_johann), FadeOut(lightbulb)) self.play(ApplyMethod( Mobject(johann, bubble).scale, 10, run_time = 3 )) class NewtonVsJohann(Scene): def construct(self): newton, johann = [ ImageMobject(name, invert = False).scale(0.5) for name in ("Newton", "Johann_Bernoulli2") ] greater_than = OldTex(">") newton.next_to(greater_than, RIGHT) johann.next_to(greater_than, LEFT) self.add(johann, greater_than, newton) for i in range(2): kwargs = { "path_func" : counterclockwise_path(), "run_time" : 2 } self.play( ApplyMethod(newton.replace, johann, **kwargs), ApplyMethod(johann.replace, newton, **kwargs), ) self.wait() class JohannThinksOfFermat(Scene): def construct(self): johann, fermat = [ ImageMobject(name, invert = False) for name in ("Johann_Bernoulli2", "Pierre_de_Fermat") ] johann.scale(0.2) johann.to_corner(DOWN+LEFT) bubble = ThoughtBubble(initial_width = 12) bubble.stretch_to_fit_height(6) bubble.pin_to(johann) bubble.shift(DOWN) bubble.add_content(fermat) fermat.scale(0.4) self.add(johann, bubble) self.wait() self.play(FadeIn(fermat)) self.wait() class MathematiciansOfEurope(Scene): def construct(self): europe = ImageMobject("Europe", use_cache = False) self.add(europe) self.freeze_background() mathematicians = [ ("Newton", [-1.75, -0.75, 0]), ("Jacob_Bernoulli",[-0.75, -1.75, 0]), ("Ehrenfried_von_Tschirnhaus",[0.5, -0.5, 0]), ("Gottfried_Wilhelm_von_Leibniz",[0.2, -1.75, 0]), ("Guillaume_de_L'Hopital", [-1.75, -1.25, 0]), ] for name, point in mathematicians: man = ImageMobject(name, invert = False) if name == "Newton": name = "Isaac_Newton" name_mob = OldTexText(name.replace("_", " ")) name_mob.to_corner(UP+LEFT, buff=0.75) self.add(name_mob) man.set_height(4) mobject = Point(man.get_corner(UP+LEFT)) self.play(Transform(mobject, man)) man.scale(0.2) man.shift(point) self.play(Transform(mobject, man)) self.remove(name_mob) class OldNewtonIsDispleased(Scene): def construct(self): old_newton = ImageMobject("Old_Newton", invert = False) old_newton.scale(0.8) self.add(old_newton) self.freeze_background() words = OldTexText("Note the displeasure") words.to_corner(UP+RIGHT) face_point = 1.8*UP+0.5*LEFT arrow = Arrow(words.get_bottom(), face_point) self.play(ShimmerIn(words)) self.play(ShowCreation(arrow)) self.wait() class NewtonConsideredEveryoneBeneathHim(Scene): def construct(self): mathematicians = [ ImageMobject(name, invert = False) for name in [ "Old_Newton", "Johann_Bernoulli2", "Jacob_Bernoulli", "Ehrenfried_von_Tschirnhaus", "Gottfried_Wilhelm_von_Leibniz", "Guillaume_de_L'Hopital", ] ] newton = mathematicians.pop(0) newton.scale(0.8) new_newton = newton.copy() new_newton.set_height(3) new_newton.to_edge(UP) for man in mathematicians: man.set_width(1.7) johann = mathematicians.pop(0) johann.next_to(new_newton, DOWN) last_left, last_right = johann, johann for man, count in zip(mathematicians, it.count()): if count%2 == 0: man.next_to(last_left, LEFT) last_left = man else: man.next_to(last_right, RIGHT) last_right = man self.play( Transform(newton, new_newton), GrowFromCenter(johann) ) self.wait() self.play(FadeIn(Mobject(*mathematicians))) self.wait()
videos_3b1b/_2016/brachistochrone/graveyard.py
import numpy as np import itertools as it from manim_imports_ext import * from from_3b1b.old.brachistochrone.curves import Cycloid class MultilayeredGlass(PhotonScene, ZoomedScene): CONFIG = { "num_discrete_layers" : 5, "num_variables" : 3, "top_color" : BLUE_E, "bottom_color" : BLUE_A, "zoomed_canvas_frame_shape" : (5, 5), "square_color" : GREEN_B, } def construct(self): self.cycloid = Cycloid(end_theta = np.pi) self.cycloid.set_color(YELLOW) self.top = self.cycloid.get_top()[1] self.bottom = self.cycloid.get_bottom()[1]-1 self.generate_layers() self.generate_discrete_path() photon_run = self.photon_run_along_path( self.discrete_path, run_time = 1, rate_func = rush_into ) self.continuous_to_smooth() self.add(*self.layers) self.show_layer_variables() self.play(photon_run) self.play(ShowCreation(self.discrete_path)) self.isolate_bend_points() self.clear() self.add(*self.layers) self.show_main_equation() self.ask_continuous_question() def continuous_to_smooth(self): self.add(*self.layers) continuous = self.get_continuous_background() self.add(continuous) self.wait() self.play(ShowCreation( continuous, rate_func = lambda t : smooth(1-t) )) self.remove(continuous) self.wait() def get_continuous_background(self): glass = FilledRectangle( height = self.top-self.bottom, width = FRAME_WIDTH, ) glass.sort_points(lambda p : -p[1]) glass.shift((self.top-glass.get_top()[1])*UP) glass.set_color_by_gradient(self.top_color, self.bottom_color) return glass def generate_layer_info(self): self.layer_thickness = float(self.top-self.bottom)/self.num_discrete_layers self.layer_tops = np.arange( self.top, self.bottom, -self.layer_thickness ) top_rgb, bottom_rgb = [ np.array(Color(color).get_rgb()) for color in (self.top_color, self.bottom_color) ] epsilon = 1./(self.num_discrete_layers-1) self.layer_colors = [ Color(rgb = interpolate(top_rgb, bottom_rgb, alpha)) for alpha in np.arange(0, 1+epsilon, epsilon) ] def generate_layers(self): self.generate_layer_info() def create_region(top, color): return Region( lambda x, y : (y < top) & (y > top-self.layer_thickness), color = color ) self.layers = [ create_region(top, color) for top, color in zip(self.layer_tops, self.layer_colors) ] def generate_discrete_path(self): points = self.cycloid.points tops = list(self.layer_tops) tops.append(tops[-1]-self.layer_thickness) indices = [ np.argmin(np.abs(points[:, 1]-top)) for top in tops ] self.bend_points = points[indices[1:-1]] self.path_angles = [] self.discrete_path = Mobject1D( color = YELLOW, density = 3*DEFAULT_POINT_DENSITY_1D ) for start, end in zip(indices, indices[1:]): start_point, end_point = points[start], points[end] self.discrete_path.add_line( start_point, end_point ) self.path_angles.append( angle_of_vector(start_point-end_point)-np.pi/2 ) self.discrete_path.add_line( points[end], FRAME_X_RADIUS*RIGHT+(self.layer_tops[-1]-1)*UP ) def show_layer_variables(self): layer_top_pairs = list(zip( self.layer_tops[:self.num_variables], self.layer_tops[1:] )) v_equations = [] start_ys = [] end_ys = [] center_paths = [] braces = [] for (top1, top2), x in zip(layer_top_pairs, it.count(1)): eq_mob = OldTex( ["v_%d"%x, "=", "\sqrt{\phantom{y_1}}"], size = "\\Large" ) midpoint = UP*(top1+top2)/2 eq_mob.shift(midpoint) v_eq = eq_mob.split() center_paths.append(Line( midpoint+FRAME_X_RADIUS*LEFT, midpoint+FRAME_X_RADIUS*RIGHT )) brace_endpoints = Mobject( Point(self.top*UP+x*RIGHT), Point(top2*UP+x*RIGHT) ) brace = Brace(brace_endpoints, RIGHT) start_y = OldTex("y_%d"%x, size = "\\Large") end_y = start_y.copy() start_y.next_to(brace, RIGHT) end_y.shift(v_eq[-1].get_center()) end_y.shift(0.2*RIGHT) v_equations.append(v_eq) start_ys.append(start_y) end_ys.append(end_y) braces.append(brace) for v_eq, path, time in zip(v_equations, center_paths, [2, 1, 0.5]): photon_run = self.photon_run_along_path( path, rate_func=linear ) self.play( ShimmerIn(v_eq[0]), photon_run, run_time = time ) self.wait() for start_y, brace in zip(start_ys, braces): self.add(start_y) self.play(GrowFromCenter(brace)) self.wait() quads = list(zip(v_equations, start_ys, end_ys, braces)) self.equations = [] for v_eq, start_y, end_y, brace in quads: self.remove(brace) self.play( ShowCreation(v_eq[1]), ShowCreation(v_eq[2]), Transform(start_y, end_y) ) v_eq.append(start_y) self.equations.append(Mobject(*v_eq)) def isolate_bend_points(self): arc_radius = 0.1 self.activate_zooming() little_square = self.get_zoomed_camera_mobject() for index in range(3): bend_point = self.bend_points[index] line = Line( bend_point+DOWN, bend_point+UP, color = WHITE, density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D ) angle_arcs = [] for i, rotation in [(index, np.pi/2), (index+1, -np.pi/2)]: arc = Arc(angle = self.path_angles[i]) arc.scale(arc_radius) arc.rotate(rotation) arc.shift(bend_point) angle_arcs.append(arc) thetas = [] for i in [index+1, index+2]: theta = OldTex("\\theta_%d"%i) theta.scale(0.5/self.zoom_factor) vert = UP if i == index+1 else DOWN horiz = rotate_vector(vert, np.pi/2) theta.next_to( Point(bend_point), horiz, buff = 0.01 ) theta.shift(1.5*arc_radius*vert) thetas.append(theta) figure_marks = [line] + angle_arcs + thetas self.play(ApplyMethod( little_square.shift, bend_point - little_square.get_center(), run_time = 2 )) self.play(*list(map(ShowCreation, figure_marks))) self.wait() equation_frame = little_square.copy() equation_frame.scale(0.5) equation_frame.shift( little_square.get_corner(UP+RIGHT) - \ equation_frame.get_corner(UP+RIGHT) ) equation_frame.scale(0.9) self.show_snells(index+1, equation_frame) self.remove(*figure_marks) self.disactivate_zooming() def show_snells(self, index, frame): left_text, right_text = [ "\\dfrac{\\sin(\\theta_%d)}{\\phantom{\\sqrt{y_1}}}"%x for x in (index, index+1) ] left, equals, right = OldTex( [left_text, "=", right_text] ).split() vs = [] sqrt_ys = [] for x, numerator in [(index, left), (index+1, right)]: v, sqrt_y = [ OldTex( text, size = "\\Large" ).next_to(numerator, DOWN) for text in ("v_%d"%x, "\\sqrt{y_%d}"%x) ] vs.append(v) sqrt_ys.append(sqrt_y) start, end = [ Mobject( left.copy(), mobs[0], equals.copy(), right.copy(), mobs[1] ).replace(frame) for mobs in (vs, sqrt_ys) ] self.add(start) self.wait(2) self.play(Transform( start, end, path_func = counterclockwise_path() )) self.wait(2) self.remove(start, end) def show_main_equation(self): self.equation = OldTex(""" \\dfrac{\\sin(\\theta)}{\\sqrt{y}} = \\text{constant} """) self.equation.shift(LEFT) self.equation.shift( (self.layer_tops[0]-self.equation.get_top())*UP ) self.add(self.equation) self.wait() def ask_continuous_question(self): continuous = self.get_continuous_background() line = Line( UP, DOWN, density = self.zoom_factor*DEFAULT_POINT_DENSITY_1D ) theta = OldTex("\\theta") theta.scale(0.5/self.zoom_factor) self.play( ShowCreation(continuous), Animation(self.equation) ) self.remove(*self.layers) self.play(ShowCreation(self.cycloid)) self.activate_zooming() little_square = self.get_zoomed_camera_mobject() self.add(line) indices = np.arange( 0, self.cycloid.get_num_points()-1, 10 ) for index in indices: point = self.cycloid.get_points()[index] next_point = self.cycloid.get_points()[index+1] angle = angle_of_vector(point - next_point) for mob in little_square, line: mob.shift(point - mob.get_center()) arc = Arc(angle-np.pi/2, start_angle = np.pi/2) arc.scale(0.1) arc.shift(point) self.add(arc) if angle > np.pi/2 + np.pi/6: vect_angle = interpolate(np.pi/2, angle, 0.5) vect = rotate_vector(RIGHT, vect_angle) theta.center() theta.shift(point) theta.shift(0.15*vect) self.add(theta) self.wait(self.frame_duration) self.remove(arc)
videos_3b1b/_2016/brachistochrone/misc.py
import numpy as np import itertools as it from manim_imports_ext import * from from_3b1b.old.brachistochrone.curves import Cycloid class PhysicalIntuition(Scene): def construct(self): n_terms = 4 def func(xxx_todo_changeme): (x, y, ignore) = xxx_todo_changeme z = complex(x, y) if (np.abs(x%1 - 0.5)<0.01 and y < 0.01) or np.abs(z)<0.01: return ORIGIN out_z = 1./(2*np.tan(np.pi*z)*(z**2)) return out_z.real*RIGHT - out_z.imag*UP arrows = Mobject(*[ Arrow(ORIGIN, np.sqrt(2)*point) for point in compass_directions(4, RIGHT+UP) ]) arrows.set_color(YELLOW) arrows.ingest_submobjects() all_arrows = Mobject(*[ arrows.copy().scale(0.3/(x)).shift(x*RIGHT) for x in range(1, n_terms+2) ]) terms = OldTex([ "\\dfrac{1}{%d^2} + "%(x+1) for x in range(n_terms) ]+["\\cdots"]) terms.shift(2*UP) plane = NumberPlane(color = BLUE_E) axes = Mobject(NumberLine(), NumberLine().rotate(np.pi/2)) axes.set_color(WHITE) for term in terms.split(): self.play(ShimmerIn(term, run_time = 0.5)) self.wait() self.play(ShowCreation(plane), ShowCreation(axes)) self.play(*[ Transform(*pair) for pair in zip(terms.split(), all_arrows.split()) ]) self.play(PhaseFlow( func, plane, run_time = 5, virtual_time = 8 )) class TimeLine(Scene): def construct(self): dated_events = [ { "date" : 1696, "text": "Johann Bernoulli poses Brachistochrone problem", "picture" : "Johann_Bernoulli2" }, { "date" : 1662, "text" : "Fermat states his principle of least time", "picture" : "Pierre_de_Fermat" } ] speical_dates = [2016] + [ obj["date"] for obj in dated_events ] centuries = list(range(1600, 2100, 100)) timeline = NumberLine( numerical_radius = 300, number_at_center = 1800, unit_length_to_spatial_width = FRAME_X_RADIUS/100, tick_frequency = 10, numbers_with_elongated_ticks = centuries ) timeline.add_numbers(*centuries) centers = [ Point(timeline.number_to_point(year)) for year in speical_dates ] timeline.add(*centers) timeline.shift(-centers[0].get_center()) self.add(timeline) self.wait() run_times = iter([3, 1]) for point, event in zip(centers[1:], dated_events): self.play(ApplyMethod( timeline.shift, -point.get_center(), run_time = next(run_times) )) picture = ImageMobject(event["picture"], invert = False) picture.set_width(2) picture.to_corner(UP+RIGHT) event_mob = OldTexText(event["text"]) event_mob.shift(2*LEFT+2*UP) date_mob = OldTex(str(event["date"])) date_mob.scale(0.5) date_mob.shift(0.6*UP) line = Line(event_mob.get_bottom(), 0.2*UP) self.play( ShimmerIn(event_mob), ShowCreation(line), ShimmerIn(date_mob) ) self.play(FadeIn(picture)) self.wait(3) self.play(*list(map(FadeOut, [event_mob, date_mob, line, picture]))) class StayedUpAllNight(Scene): def construct(self): clock = Circle(radius = 2, color = WHITE) clock.add(Dot(ORIGIN)) ticks = Mobject(*[ Line(1.8*vect, 2*vect, color = GREY) for vect in compass_directions(12) ]) clock.add(ticks) hour_hand = Line(ORIGIN, UP) minute_hand = Line(ORIGIN, 1.5*UP) clock.add(hour_hand, minute_hand) clock.to_corner(UP+RIGHT) hour_hand.get_center = lambda : clock.get_center() minute_hand.get_center = lambda : clock.get_center() solution = ImageMobject( "Newton_brachistochrone_solution2", use_cache = False ) solution.stroke_width = 3 solution.set_color(GREY) solution.set_width(5) solution.to_corner(UP+RIGHT) newton = ImageMobject("Old_Newton", invert = False) newton.scale(0.8) phil_trans = OldTexText("Philosophical Transactions") rect = Rectangle(height = 6, width = 4.5, color = WHITE) rect.to_corner(UP+RIGHT) rect.shift(DOWN) phil_trans.set_width(0.8*rect.get_width()) phil_trans.next_to(Point(rect.get_top()), DOWN) new_solution = solution.copy() new_solution.set_width(phil_trans.get_width()) new_solution.next_to(phil_trans, DOWN, buff = 1) not_newton = OldTexText("-Totally not by Newton") not_newton.set_width(2.5) not_newton.next_to(new_solution, DOWN, aligned_edge = RIGHT) phil_trans.add(rect) newton_complaint = OldTexText([ "``I do not love to be", " \\emph{dunned} ", "and teased by foreigners''" ], size = "\\small") newton_complaint.to_edge(UP, buff = 0.2) dunned = newton_complaint.split()[1] dunned.set_color() dunned_def = OldTexText("(old timey term for making \\\\ demands on someone)") dunned_def.scale(0.7) dunned_def.next_to(phil_trans, LEFT) dunned_def.shift(2*UP) dunned_arrow = Arrow(dunned_def, dunned) johann = ImageMobject("Johann_Bernoulli2", invert = False) johann.scale(0.4) johann.to_edge(LEFT) johann.shift(DOWN) johann_quote = OldTexText("``I recognize the lion by his claw''") johann_quote.next_to(johann, UP, aligned_edge = LEFT) self.play(ApplyMethod(newton.to_edge, LEFT)) self.play(ShowCreation(clock)) kwargs = { "axis" : OUT, "rate_func" : smooth } self.play( Rotating(hour_hand, radians = -2*np.pi, **kwargs), Rotating(minute_hand, radians = -12*2*np.pi, **kwargs), run_time = 5 ) self.wait() self.clear() self.add(newton) clock.ingest_submobjects() self.play(Transform(clock, solution)) self.remove(clock) self.add(solution) self.wait() self.play( FadeIn(phil_trans), Transform(solution, new_solution) ) self.wait() self.play(ShimmerIn(not_newton)) phil_trans.add(solution, not_newton) self.wait() self.play(*list(map(ShimmerIn, newton_complaint.split()))) self.wait() self.play( ShimmerIn(dunned_def), ShowCreation(dunned_arrow) ) self.wait() self.remove(dunned_def, dunned_arrow) self.play(FadeOut(newton_complaint)) self.remove(newton_complaint) self.play( FadeOut(newton), GrowFromCenter(johann) ) self.remove(newton) self.wait() self.play(ShimmerIn(johann_quote)) self.wait() class ThetaTGraph(Scene): def construct(self): t_axis = NumberLine() theta_axis = NumberLine().rotate(np.pi/2) theta_mob = OldTex("\\theta(t)") t_mob = OldTex("t") theta_mob.next_to(theta_axis, RIGHT) theta_mob.to_edge(UP) t_mob.next_to(t_axis, UP) t_mob.to_edge(RIGHT) graph = ParametricCurve( lambda t : 4*t*RIGHT + 2*smooth(t)*UP ) line = Line(graph.get_points()[0], graph.get_points()[-1], color = WHITE) q_mark = OldTexText("?") q_mark.next_to(Point(graph.get_center()), LEFT) stars = Stars(color = BLACK) stars.scale(0.1).shift(q_mark.get_center()) squiggle = ParametricCurve( lambda t : t*RIGHT + 0.2*t*(5-t)*(np.sin(t)**2)*UP, start = 0, end = 5 ) self.play( ShowCreation(t_axis), ShowCreation(theta_axis), ShimmerIn(theta_mob), ShimmerIn(t_mob) ) self.play( ShimmerIn(q_mark), ShowCreation(graph) ) self.wait() self.play( Transform(q_mark, stars), Transform(graph, line) ) self.wait() self.play(Transform(graph, squiggle)) self.wait() class SolutionsToTheBrachistochrone(Scene): def construct(self): r_range = np.arange(0.5, 2, 0.25) cycloids = Mobject(*[ Cycloid(radius = r, end_theta=2*np.pi) for r in r_range ]) lower_left = 2*DOWN+6*LEFT lines = Mobject(*[ Line( lower_left, lower_left+5*r*np.cos(np.arctan(r))*RIGHT+2*r*np.sin(np.arctan(r))*UP ) for r in r_range ]) nl = NumberLine(numbers_with_elongated_ticks = []) x_axis = nl.copy().shift(3*UP) y_axis = nl.copy().rotate(np.pi/2).shift(6*LEFT) t_axis = nl.copy().shift(2*DOWN) x_label = OldTex("x") x_label.next_to(x_axis, DOWN) x_label.to_edge(RIGHT) y_label = OldTex("y") y_label.next_to(y_axis, RIGHT) y_label.shift(2*DOWN) t_label = OldTex("t") t_label.next_to(t_axis, UP) t_label.to_edge(RIGHT) theta_label = OldTex("\\theta") theta_label.next_to(y_axis, RIGHT) theta_label.to_edge(UP) words = OldTexText("Boundary conditions?") words.next_to(lines, RIGHT) words.shift(2*UP) self.play(ShowCreation(x_axis), ShimmerIn(x_label)) self.play(ShowCreation(y_axis), ShimmerIn(y_label)) self.play(ShowCreation(cycloids)) self.wait() self.play( Transform(cycloids, lines), Transform(x_axis, t_axis), Transform(x_label, t_label), Transform(y_label, theta_label), run_time = 2 ) self.wait() self.play(ShimmerIn(words)) self.wait() class VideoLayout(Scene): def construct(self): left, right = 5*LEFT, 5*RIGHT top_words = OldTexText("The next 15 minutes of your life:") top_words.to_edge(UP) line = Line(left, right, color = BLUE_D) for a in np.arange(0, 4./3, 1./3): vect = interpolate(left, right, a) line.add_line(vect+0.2*DOWN, vect+0.2*UP) left_brace = Brace( Mobject( Point(left), Point(interpolate(left, right, 2./3)) ), DOWN ) right_brace = Brace( Mobject( Point(interpolate(left, right, 2./3)), Point(right) ), UP ) left_brace.words = list(map(TexText, [ "Problem statement", "History", "Johann Bernoulli's cleverness" ])) curr = left_brace right_brace.words = list(map(TexText, [ "Challenge", "Mark Levi's cleverness", ])) for brace in left_brace, right_brace: curr = brace direction = DOWN if brace is left_brace else UP for word in brace.words: word.next_to(curr, direction) curr = word right_brace.words.reverse() self.play(ShimmerIn(top_words)) self.play(ShowCreation(line)) for brace in left_brace, right_brace: self.play(GrowFromCenter(brace)) self.wait() for word in brace.words: self.play(ShimmerIn(word)) self.wait() class ShortestPathProblem(Scene): def construct(self): point_a, point_b = 3*LEFT, 3*RIGHT dots = [] for point, char in [(point_a, "A"), (point_b, "B")]: dot = Dot(point) letter = OldTex(char) letter.next_to(dot, UP+LEFT) dot.add(letter) dots.append(dot) path = ParametricCurve( lambda t : (t/2 + np.cos(t))*RIGHT + np.sin(t)*UP, start = -2*np.pi, end = 2*np.pi ) path.scale(6/(2*np.pi)) path.shift(point_a - path.get_points()[0]) path.set_color(RED) line = Line(point_a, point_b) words = OldTexText("Shortest path from $A$ to $B$") words.to_edge(UP) self.play( ShimmerIn(words), *list(map(GrowFromCenter, dots)) ) self.play(ShowCreation(path)) self.play(Transform( path, line, path_func = path_along_arc(np.pi) )) self.wait() class MathBetterThanTalking(Scene): def construct(self): mathy = Mathematician() mathy.to_corner(DOWN+LEFT) bubble = ThoughtBubble() bubble.pin_to(mathy) bubble.write("Math $>$ Talking about math") self.add(mathy) self.play(ShowCreation(bubble)) self.play(ShimmerIn(bubble.content)) self.wait() self.play(ApplyMethod( mathy.blink, rate_func = squish_rate_func(there_and_back, 0.4, 0.6) )) class DetailsOfProofBox(Scene): def construct(self): rect = Rectangle(height = 4, width = 6, color = WHITE) words = OldTexText("Details of proof") words.to_edge(UP) self.play( ShowCreation(rect), ShimmerIn(words) ) self.wait() class TalkedAboutSnellsLaw(Scene): def construct(self): randy = Randolph() randy.to_corner(DOWN+LEFT) morty = Mortimer() morty.to_edge(DOWN+RIGHT) randy.bubble = SpeechBubble().pin_to(randy) morty.bubble = SpeechBubble().pin_to(morty) phrases = [ "Let's talk about Snell's law", "I love Snell's law", "It's like running from \\\\ a beach into the ocean", "It's like two constant \\\\ tension springs", ] self.add(randy, morty) talkers = it.cycle([randy, morty]) for talker, phrase in zip(talkers, phrases): talker.bubble.write(phrase) self.play( FadeIn(talker.bubble), ShimmerIn(talker.bubble.content) ) self.play(ApplyMethod( talker.blink, rate_func = squish_rate_func(there_and_back) )) self.wait() self.remove(talker.bubble, talker.bubble.content) class YetAnotherMarkLevi(Scene): def construct(self): words = OldTexText("Yet another bit of Mark Levi cleverness") words.to_edge(UP) levi = ImageMobject("Mark_Levi", invert = False) levi.set_width(6) levi.show() self.add(levi) self.play(ShimmerIn(words)) self.wait(2)
videos_3b1b/_2016/eola/chapter6.py
from manim_imports_ext import * from ka_playgrounds.circuits import Resistor, Source, LongResistor class OpeningQuote(Scene): def construct(self): words = OldTexText( "To ask the", "right question\\\\", "is harder than to answer it." ) words.to_edge(UP) words[1].set_color(BLUE) author = OldTexText("-Georg Cantor") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(2) self.play(Write(author, run_time = 3)) self.wait() class ListTerms(Scene): def construct(self): title = OldTexText("Under the light of linear transformations") title.set_color(YELLOW) title.to_edge(UP) randy = Randolph().to_corner() words = VMobject(*list(map(TexText, [ "Inverse matrices", "Column space", "Rank", "Null space", ]))) words.arrange(DOWN, aligned_edge = LEFT) words.next_to(title, DOWN, aligned_edge = LEFT) words.shift(RIGHT) self.add(title, randy) for i, word in enumerate(words.split()): self.play(Write(word), run_time = 1) if i%2 == 0: self.play(Blink(randy)) else: self.wait() self.wait() class NoComputations(TeacherStudentsScene): def construct(self): self.setup() self.student_says( "Will you cover \\\\ computations?", target_mode = "raise_left_hand" ) self.random_blink() self.teacher_says( "Well...uh...no", target_mode = "guilty", ) self.play(*[ ApplyMethod(student.change_mode, mode) for student, mode in zip( self.get_students(), ["dejected", "confused", "angry"] ) ]) self.random_blink() self.wait() new_words = self.teacher.bubble.position_mobject_inside( OldTexText([ "Search", "``Gaussian elimination'' \\\\", "and", "``Row echelon form''", ]) ) new_words.split()[1].set_color(YELLOW) new_words.split()[3].set_color(GREEN) self.play( Transform(self.teacher.bubble.content, new_words), self.teacher.change_mode, "speaking" ) self.play(*[ ApplyMethod(student.change_mode, "pondering") for student in self.get_students() ]) self.random_blink() class PuntToSoftware(Scene): def construct(self): self.play(Write("Let the computers do the computing")) class UsefulnessOfMatrices(Scene): def construct(self): title = OldTexText("Usefulness of matrices") title.set_color(YELLOW) title.to_edge(UP) self.add(title) self.wait(3) #Play some 3d linear transform over this equations = OldTex(""" 6x - 3y + 2z &= 7 \\\\ x + 2y + 5z &= 0 \\\\ 2x - 8y - z &= -2 \\\\ """) equations.to_edge(RIGHT, buff = 2) syms = VMobject(*np.array(equations.split())[[1, 4, 7]]) new_syms = VMobject(*[ m.copy().set_color(c) for m, c in zip(syms.split(), [X_COLOR, Y_COLOR, Z_COLOR]) ]) new_syms.arrange(RIGHT, buff = 0.5) new_syms.next_to(equations, LEFT, buff = 3) sym_brace = Brace(new_syms, DOWN) unknowns = sym_brace.get_text("Unknown variables") eq_brace = Brace(equations, DOWN) eq_words = eq_brace.get_text("Equations") self.play(Write(equations)) self.wait() self.play(Transform(syms.copy(), new_syms, path_arc = np.pi/2)) for brace, words in (sym_brace, unknowns), (eq_brace, eq_words): self.play( GrowFromCenter(brace), Write(words) ) self.wait() class CircuitDiagram(Scene): def construct(self): self.add(OldTexText("Voltages").to_edge(UP)) source = Source() p1, p2 = source.get_top(), source.get_bottom() r1 = Resistor(p1, p1+2*RIGHT) r2 = LongResistor(p1+2*RIGHT, p2+2*RIGHT) r3 = Resistor(p1+2*RIGHT, p1+2*2*RIGHT) l1 = Line(p1+2*2*RIGHT, p2+2*2*RIGHT) l2 = Line(p2+2*2*RIGHT, p2) circuit = VMobject(source, r1, r2, r3, l1, l2) circuit.center() v1 = OldTex("v_1").next_to(r1, UP) v2 = OldTex("v_2").next_to(r2, RIGHT) v3 = OldTex("v_3").next_to(r3, UP) unknowns = VMobject(v1, v2, v3) unknowns.set_color(BLUE) self.play(ShowCreation(circuit)) self.wait() self.play(Write(unknowns)) self.wait() class StockLine(VMobject): CONFIG = { "num_points" : 15, "step_range" : 2 } def init_points(self): points = [ORIGIN] for x in range(self.num_points): step_size = self.step_range*(random.random() - 0.5) points.append(points[-1] + 0.5*RIGHT + step_size*UP) self.set_points_as_corners(points) class StockPrices(Scene): def construct(self): self.add(OldTexText("Stock prices").to_edge(UP)) x_axis = Line(ORIGIN, FRAME_X_RADIUS*RIGHT) y_axis = Line(ORIGIN, FRAME_Y_RADIUS*UP) everyone = VMobject(x_axis, y_axis) stock_lines = [] for color in TEAL, PINK, YELLOW, RED, BLUE: sl = StockLine(color = color) sl.move_to(y_axis.get_center(), aligned_edge = LEFT) everyone.add(sl) stock_lines.append(sl) everyone.center() self.add(x_axis, y_axis) self.play(ShowCreation( VMobject(*stock_lines), run_time = 3, lag_ratio = 0.5 )) self.wait() class MachineLearningNetwork(Scene): def construct(self): self.add(OldTexText("Machine learning parameters").to_edge(UP)) layers = [] for i, num_nodes in enumerate([3, 4, 4, 1]): layer = VMobject(*[ Circle(radius = 0.5, color = YELLOW) for x in range(num_nodes) ]) for j, mob in enumerate(layer.split()): sym = OldTex("x_{%d, %d}"%(i, j)) sym.move_to(mob) mob.add(sym) layer.arrange(DOWN, buff = 0.5) layer.center() layers.append(layer) VMobject(*layers).arrange(RIGHT, buff = 1.5) lines = VMobject() for l_layer, r_layer in zip(layers, layers[1:]): for l_node, r_node in it.product(l_layer.split(), r_layer.split()): lines.add(Line(l_node, r_node)) lines.set_submobject_colors_by_gradient(BLUE_E, BLUE_A) for mob in VMobject(*layers), lines: self.play(Write(mob), run_time = 2) self.wait() class ComplicatedSystem(Scene): def construct(self): system = OldTex(""" \\begin{align*} \\dfrac{1}{1-e^{2x-3y+4z}} &= 1 \\\\ \\\\ \\sin(xy) + z^2 &= \\sqrt{y} \\\\ \\\\ x^2 + y^2 &= e^{-z} \\end{align*} """) system.to_edge(UP) randy = Randolph().to_corner(DOWN+LEFT) self.add(randy) self.play(Write(system, run_time = 1)) self.play(randy.change_mode, "sassy") self.play(Blink(randy)) self.wait() class SystemOfEquations(Scene): def construct(self): equations = self.get_equations() self.show_linearity_rules(equations) self.describe_organization(equations) self.factor_into_matrix(equations) def get_equations(self): matrix = Matrix([ [2, 5, 3], [4, 0, 8], [1, 3, 0] ]) mob_matrix = matrix.get_mob_matrix() rhs = list(map(Tex, list(map(str, [-3, 0, 2])))) variables = list(map(Tex, list("xyz"))) for v, color in zip(variables, [X_COLOR, Y_COLOR, Z_COLOR]): v.set_color(color) equations = VMobject() for row in mob_matrix: equation = VMobject(*it.chain(*list(zip( row, [v.copy() for v in variables], list(map(Tex, list("++="))) )))) equation.arrange( RIGHT, buff = 0.1, aligned_edge = DOWN ) equation.split()[4].shift(0.1*DOWN) equation.split()[-1].next_to(equation.split()[-2], RIGHT) equations.add(equation) equations.arrange(DOWN, aligned_edge = RIGHT) for eq, rhs_elem in zip(equations.split(), rhs): rhs_elem.next_to(eq, RIGHT) eq.add(rhs_elem) equations.center() self.play(Write(equations)) self.add(equations) return equations def show_linearity_rules(self, equations): top_equation = equations.split()[0] other_equations = VMobject(*equations.split()[1:]) other_equations.save_state() scaled_vars = VMobject(*[ VMobject(*top_equation.split()[3*i:3*i+2]) for i in range(3) ]) scaled_vars.save_state() isolated_scaled_vars = scaled_vars.copy() isolated_scaled_vars.scale(1.5) isolated_scaled_vars.next_to(top_equation, UP) scalars = VMobject(*[m.split()[0] for m in scaled_vars.split()]) plusses = np.array(top_equation.split())[[2, 5]] self.play(other_equations.fade, 0.7) self.play(Transform(scaled_vars, isolated_scaled_vars)) self.play(scalars.set_color, YELLOW, lag_ratio = 0.5) self.play(*[ ApplyMethod(m.scale, 1.2, rate_func = there_and_back) for m in scalars.split() ]) self.wait() self.remove(scalars) self.play(scaled_vars.restore) self.play(*[ ApplyMethod(p.scale, 1.5, rate_func = there_and_back) for p in plusses ]) self.wait() self.show_nonlinearity_examples() self.play(other_equations.restore) def show_nonlinearity_examples(self): squared = OldTex("x^2") squared.split()[0].set_color(X_COLOR) sine = OldTex("\\sin(x)") sine.split()[-2].set_color(X_COLOR) product = OldTex("xy") product.split()[0].set_color(X_COLOR) product.split()[1].set_color(Y_COLOR) words = OldTexText("Not allowed!") words.set_color(RED) words.to_corner(UP+LEFT, buff = 1) arrow = Vector(RIGHT, color = RED) arrow.next_to(words, RIGHT) for mob in squared, sine, product: mob.scale(1.7) mob.next_to(arrow.get_end(), RIGHT, buff = 0.5) circle_slash = Circle(color = RED) line = Line(LEFT, RIGHT, color = RED) line.rotate(np.pi/4) circle_slash.add(line) circle_slash.next_to(arrow, RIGHT) def draw_circle_slash(mob): circle_slash.replace(mob) circle_slash.scale(1.4) self.play(ShowCreation(circle_slash), run_time = 0.5) self.wait(0.5) self.play(FadeOut(circle_slash), run_time = 0.5) self.play( Write(squared), Write(words, run_time = 1), ShowCreation(arrow), ) draw_circle_slash(squared) for mob in sine, product: self.play(Transform(squared, mob)) draw_circle_slash(mob) self.play(*list(map(FadeOut, [words, arrow, squared]))) self.wait() def describe_organization(self, equations): variables = VMobject(*it.chain(*[ eq.split()[:-2] for eq in equations.split() ])) variables.words = "Throw variables on the left" constants = VMobject(*[ eq.split()[-1] for eq in equations.split() ]) constants.words = "Lingering constants on the right" xs, ys, zs = [ VMobject(*[ eq.split()[i] for eq in equations.split() ]) for i in (1, 4, 7) ] ys.words = "Vertically align variables" colors = [PINK, YELLOW, BLUE_B, BLUE_C, BLUE_D] for mob, color in zip([variables, constants, xs, ys, zs], colors): mob.square = Square(color = color) mob.square.replace(mob, stretch = True) mob.square.scale(1.1) if hasattr(mob, "words"): mob.words = OldTexText(mob.words) mob.words.set_color(color) mob.words.next_to(mob.square, UP) ys.square.add(xs.square, zs.square) zero_circles = VMobject(*[ Circle().replace(mob).scale(1.3) for mob in [ VMobject(*equations.split()[i].split()[j:j+2]) for i, j in [(1, 3), (2, 6)] ] ]) zero_circles.set_color(PINK) zero_circles.words = OldTexText("Add zeros as needed") zero_circles.words.set_color(zero_circles.get_color()) zero_circles.words.next_to(equations, UP) for mob in variables, constants, ys: self.play( FadeIn(mob.square), FadeIn(mob.words) ) self.wait() self.play(*list(map(FadeOut, [mob.square, mob.words]))) self.play( ShowCreation(zero_circles), Write(zero_circles.words, run_time = 1) ) self.wait() self.play(*list(map(FadeOut, [zero_circles, zero_circles.words]))) self.wait() title = OldTexText("``Linear system of equations''") title.scale(1.5) title.to_edge(UP) self.play(Write(title)) self.wait() self.play(FadeOut(title)) def factor_into_matrix(self, equations): coefficients = np.array([ np.array(eq.split())[[0, 3, 6]] for eq in equations.split() ]) variable_arrays = np.array([ np.array(eq.split())[[1, 4, 7]] for eq in equations.split() ]) rhs_entries = np.array([ eq.split()[-1] for eq in equations.split() ]) matrix = Matrix(copy.deepcopy(coefficients)) x_array = Matrix(copy.deepcopy(variable_arrays[0])) v_array = Matrix(copy.deepcopy(rhs_entries)) equals = OldTex("=") ax_equals_v = VMobject(matrix, x_array, equals, v_array) ax_equals_v.arrange(RIGHT) ax_equals_v.to_edge(RIGHT) all_brackets = [ mob.get_brackets() for mob in (matrix, x_array, v_array) ] self.play(equations.to_edge, LEFT) arrow = Vector(RIGHT, color = YELLOW) arrow.next_to(ax_equals_v, LEFT) self.play(ShowCreation(arrow)) self.play(*it.chain(*[ [ Transform( m1.copy(), m2, run_time = 2, path_arc = -np.pi/2 ) for m1, m2 in zip( start_array.flatten(), matrix_mobject.get_entries().split() ) ] for start_array, matrix_mobject in [ (coefficients, matrix), (variable_arrays[0], x_array), (variable_arrays[1], x_array), (variable_arrays[2], x_array), (rhs_entries, v_array) ] ])) self.play(*[ Write(mob) for mob in all_brackets + [equals] ]) self.wait() self.label_matrix_product(matrix, x_array, v_array) def label_matrix_product(self, matrix, x_array, v_array): matrix.words = "Coefficients" matrix.symbol = "A" x_array.words = "Variables" x_array.symbol = "\\vec{\\textbf{x}}" v_array.words = "Constants" v_array.symbol = "\\vec{\\textbf{v}}" parts = matrix, x_array, v_array for mob in parts: mob.brace = Brace(mob, UP) mob.words = mob.brace.get_text(mob.words) mob.words.shift_onto_screen() mob.symbol = OldTex(mob.symbol) mob.brace.put_at_tip(mob.symbol) x_array.words.set_submobject_colors_by_gradient( X_COLOR, Y_COLOR, Z_COLOR ) x_array.symbol.set_color(PINK) v_array.symbol.set_color(YELLOW) for mob in parts: self.play( GrowFromCenter(mob.brace), FadeIn(mob.words) ) self.wait() self.play(*list(map(FadeOut, [mob.brace, mob.words]))) self.wait() for mob in parts: self.play( FadeIn(mob.brace), Write(mob.symbol) ) compact_equation = VMobject(*[ mob.symbol for mob in parts ]) compact_equation.submobjects.insert( 2, OldTex("=").next_to(x_array, RIGHT) ) compact_equation.target = compact_equation.copy() compact_equation.target.arrange(buff = 0.1) compact_equation.target.to_edge(UP) self.play(Transform( compact_equation.copy(), compact_equation.target )) self.wait() class LinearSystemTransformationScene(LinearTransformationScene): def setup(self): LinearTransformationScene.setup(self) equation = OldTex([ "A", "\\vec{\\textbf{x}}", "=", "\\vec{\\textbf{v}}", ]) equation.scale(1.5) equation.next_to(ORIGIN, LEFT).to_edge(UP) equation.add_background_rectangle() self.add_foreground_mobject(equation) self.equation = equation self.A, self.x, eq, self.v = equation.split()[1].split() self.x.set_color(PINK) self.v.set_color(YELLOW) class MentionThatItsATransformation(LinearSystemTransformationScene): CONFIG = { "t_matrix" : np.array([[2, 1], [2, 3]]) } def construct(self): self.setup() brace = Brace(self.A) words = brace.get_text("Transformation") words.add_background_rectangle() self.play(GrowFromCenter(brace), Write(words, run_time = 1)) self.add_foreground_mobject(words, brace) self.apply_transposed_matrix(self.t_matrix) self.wait() class LookForX(MentionThatItsATransformation): CONFIG = { "show_basis_vectors" : False } def construct(self): self.setup() v = [-4, - 1] x = np.linalg.solve(self.t_matrix.T, v) v = Vector(v, color = YELLOW) x = Vector(x, color = PINK) v_label = self.get_vector_label(v, "v", color = YELLOW) x_label = self.get_vector_label(x, "x", color = PINK) for label in x_label, v_label: label.add_background_rectangle() self.play( ShowCreation(v), Write(v_label) ) self.add_foreground_mobject(v_label) x = self.add_vector(x, animate = False) self.play( ShowCreation(x), Write(x_label) ) self.wait() self.add(VMobject(x, x_label).copy().fade()) self.apply_transposed_matrix(self.t_matrix) self.wait() class ThinkAboutWhatsHappening(Scene): def construct(self): randy = Randolph() randy.to_corner() bubble = randy.get_bubble(height = 5) bubble.add_content(OldTex(""" 3x + 1y + 4z &= 1 \\\\ 5x + 9y + 2z &= 6 \\\\ 5x + 3y + 5z &= 8 """)) self.play(randy.change_mode, "pondering") self.play(ShowCreation(bubble)) self.play(Write(bubble.content, run_time = 2)) self.play(Blink(randy)) self.wait() everything = VMobject(*self.get_mobjects()) self.play( ApplyFunction( lambda m : m.shift(2*DOWN).scale(5), everything ), bubble.content.set_color, BLACK, run_time = 2 ) class SystemOfTwoEquationsTwoUnknowns(Scene): def construct(self): system = OldTex(""" 2x + 2y &= -4 \\\\ 1x + 3y &= -1 """) system.to_edge(UP) for indices, color in ((1, 9), X_COLOR), ((4, 12), Y_COLOR): for i in indices: system.split()[i].set_color(color) matrix = Matrix([[2, 2], [1, 3]]) v = Matrix([-4, -1]) x = Matrix(["x", "y"]) x.get_entries().set_submobject_colors_by_gradient(X_COLOR, Y_COLOR) matrix_system = VMobject( matrix, x, OldTex("="), v ) matrix_system.arrange(RIGHT) matrix_system.next_to(system, DOWN, buff = 1) matrix.label = "A" matrix.label_color = WHITE x.label = "\\vec{\\textbf{x}}" x.label_color = PINK v.label = "\\vec{\\textbf{v}}" v.label_color = YELLOW for mob in matrix, x, v: brace = Brace(mob) label = brace.get_text("$%s$"%mob.label) label.set_color(mob.label_color) brace.add(label) mob.brace = brace self.add(system) self.play(Write(matrix_system)) self.wait() for mob in matrix, v, x: self.play(Write(mob.brace)) self.wait() class ShowBijectivity(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "t_matrix" : np.array([[0, -1], [2, 1]]) } def construct(self): self.setup() vectors = VMobject(*[ Vector([x, y]) for x, y in it.product(*[ np.arange(-int(val)+0.5, int(val)+0.5) for val in (FRAME_X_RADIUS, FRAME_Y_RADIUS) ]) ]) vectors.set_submobject_colors_by_gradient(BLUE_E, PINK) dots = VMobject(*[ Dot(v.get_end(), color = v.get_color()) for v in vectors.split() ]) titles = [ OldTexText([ "Each vector lands on\\\\", "exactly one vector" ]), OldTexText([ "Every vector has \\\\", "been landed on" ]) ] for title in titles: title.to_edge(UP) background = BackgroundRectangle(VMobject(*titles)) self.add_foreground_mobject(background, titles[0]) kwargs = { "lag_ratio" : 0.5, "run_time" : 2 } anims = list(map(Animation, self.foreground_mobjects)) self.play(ShowCreation(vectors, **kwargs), *anims) self.play(Transform(vectors, dots, **kwargs), *anims) self.wait() self.add_transformable_mobject(vectors) self.apply_transposed_matrix(self.t_matrix) self.wait() self.play(Transform(*titles)) self.wait() self.apply_transposed_matrix( np.linalg.inv(self.t_matrix.T).T ) self.wait() class LabeledExample(LinearSystemTransformationScene): CONFIG = { "title" : "", "t_matrix" : [[0, 0], [0, 0]], "show_square" : False, } def setup(self): LinearSystemTransformationScene.setup(self) title = OldTexText(self.title) title.next_to(self.equation, DOWN, buff = 1) title.add_background_rectangle() title.shift_onto_screen() self.add_foreground_mobject(title) self.title = title if self.show_square: self.add_unit_square() def construct(self): self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() class SquishExmapleWithWords(LabeledExample): CONFIG = { "title" : "$A$ squishes things to a lower dimension", "t_matrix" : [[-2, -1], [2, 1]] } class FullRankExmapleWithWords(LabeledExample): CONFIG = { "title" : "$A$ keeps things 2D", "t_matrix" : [[3, 0], [2, 1]] } class SquishExmapleDet(SquishExmapleWithWords): CONFIG = { "title" : "$\\det(A) = 0$", "show_square" : True, } class FullRankExmapleDet(FullRankExmapleWithWords): CONFIG = { "title" : "$\\det(A) \\ne 0$", "show_square" : True, } class StartWithNonzeroDetCase(TeacherStudentsScene): def construct(self): words = OldTexText( "Let's start with \\\\", "the", "$\\det(A) \\ne 0$", "case" ) words[2].set_color(TEAL) self.teacher_says(words) self.random_blink() self.play( random.choice(self.get_students()).change_mode, "happy" ) self.wait() class DeclareNewTransformation(TeacherStudentsScene): def construct(self): words = OldTexText( "Playing a transformation in\\\\", "reverse gives a", "new transformation" ) words[-1].set_color(GREEN) self.teacher_says(words) self.play_student_changes("pondering", "sassy") self.random_blink() class PlayInReverse(FullRankExmapleDet): CONFIG = { "show_basis_vectors" : False } def construct(self): FullRankExmapleDet.construct(self) v = self.add_vector([-4, -1], color = YELLOW) v_label = self.label_vector(v, "v", color = YELLOW) self.add(v.copy()) self.apply_inverse_transpose(self.t_matrix) self.play(v.set_color, PINK) self.label_vector(v, "x", color = PINK) self.wait() class DescribeInverse(LinearTransformationScene): CONFIG = { "show_actual_inverse" : False, "matrix_label" : "$A$", "inv_label" : "$A^{-1}$", } def construct(self): title = OldTexText("Transformation:") new_title = OldTexText("Inverse transformation:") matrix = Matrix(self.t_matrix.T) if not self.show_actual_inverse: inv_matrix = matrix.copy() neg_1 = OldTex("-1") neg_1.move_to( inv_matrix.get_corner(UP+RIGHT), aligned_edge = LEFT ) neg_1.shift(0.1*RIGHT) inv_matrix.add(neg_1) matrix.add(VectorizedPoint(matrix.get_corner(UP+RIGHT))) else: inv_matrix = Matrix(np.linalg.inv(self.t_matrix.T).astype('int')) matrix.label = self.matrix_label inv_matrix.label = self.inv_label for m, text in (matrix, title), (inv_matrix, new_title): m.add_to_back(BackgroundRectangle(m)) text.add_background_rectangle() m.next_to(text, RIGHT) brace = Brace(m) label_mob = brace.get_text(m.label) label_mob.add_background_rectangle() m.add(brace, label_mob) text.add(m) if text.get_width() > FRAME_WIDTH-1: text.set_width(FRAME_WIDTH-1) text.center().to_corner(UP+RIGHT) matrix.set_color(PINK) inv_matrix.set_color(YELLOW) self.add_foreground_mobject(title) self.apply_transposed_matrix(self.t_matrix) self.wait() self.play(Transform(title, new_title)) self.apply_inverse_transpose(self.t_matrix) self.wait() class ClockwiseCounterclockwise(DescribeInverse): CONFIG = { "t_matrix" : [[0, 1], [-1, 0]], "show_actual_inverse" : True, "matrix_label" : "$90^\\circ$ Couterclockwise", "inv_label" : "$90^\\circ$ Clockwise", } class ShearInverseShear(DescribeInverse): CONFIG = { "t_matrix" : [[1, 0], [1, 1]], "show_actual_inverse" : True, "matrix_label" : "Rightward shear", "inv_label" : "Leftward shear", } class MultiplyToIdentity(LinearTransformationScene): def construct(self): self.setup() lhs = OldTex("A^{-1}", "A", "=") lhs.scale(1.5) A_inv, A, eq = lhs.split() identity = Matrix([[1, 0], [0, 1]]) identity.set_column_colors(X_COLOR, Y_COLOR) identity.next_to(eq, RIGHT) VMobject(lhs, identity).center().to_corner(UP+RIGHT) for mob in A, A_inv, eq: mob.add_to_back(BackgroundRectangle(mob)) identity.background = BackgroundRectangle(identity) col1 = VMobject(*identity.get_mob_matrix()[:,0]) col2 = VMobject(*identity.get_mob_matrix()[:,1]) A.text = "Transformation" A_inv.text = "Inverse transformation" product = VMobject(A, A_inv) product.text = "Matrix multiplication" identity.text = "The transformation \\\\ that does nothing" for mob in A, A_inv, product, identity: mob.brace = Brace(mob) mob.text = mob.brace.get_text(mob.text) mob.text.shift_onto_screen() mob.text.add_background_rectangle() self.add_foreground_mobject(A, A_inv) brace, text = A.brace, A.text self.play(GrowFromCenter(brace), Write(text), run_time = 1) self.add_foreground_mobject(brace, text) self.apply_transposed_matrix(self.t_matrix) self.play( Transform(brace, A_inv.brace), Transform(text, A_inv.text), ) self.apply_inverse_transpose(self.t_matrix) self.wait() self.play( Transform(brace, product.brace), Transform(text, product.text) ) self.wait() self.play( Write(identity.background), Write(identity.get_brackets()), Write(eq), Transform(brace, identity.brace), Transform(text, identity.text) ) self.wait() self.play(Write(col1)) self.wait() self.play(Write(col2)) self.wait() class ThereAreComputationMethods(TeacherStudentsScene): def construct(self): self.teacher_says(""" There are methods to compute $A^{-1}$ """) self.random_blink() self.wait() class TwoDInverseFormula(Scene): def construct(self): title = OldTexText("If you're curious...") title.set_color(YELLOW) title.to_edge(UP) morty = Mortimer().to_corner(DOWN+RIGHT) self.add(title, morty) matrix = [["a", "b"], ["c", "d"]] scaled_inv = [["d", "-b"], ["-c", "a"]] formula = OldTex(""" %s^{-1} = \\dfrac{1}{ad-bc} %s """%( matrix_to_tex_string(matrix), matrix_to_tex_string(scaled_inv) )) self.play(Write(formula)) self.play(morty.change_mode, "confused") self.play(Blink(morty)) class SymbolicInversion(Scene): def construct(self): vec = lambda s : "\\vec{\\textbf{%s}}"%s words = OldTexText("Once you have this:") words.to_edge(UP, buff = 2) inv = OldTex("A^{-1}") inv.set_color(GREEN) inv.next_to(words.split()[-1], RIGHT, aligned_edge = DOWN) inv2 = inv.copy() start = OldTex("A", vec("x"), "=", vec("v")) interim = OldTex("A^{-1}", "A", vec("x"), "=", "A^{-1}", vec("v")) end = OldTex(vec("x"), "=", "A^{-1}", vec("v")) A, x, eq, v = start.split() x.set_color(PINK) v.set_color(YELLOW) interim_mobs = [inv, A, x, eq, inv2, v] for i, mob in enumerate(interim_mobs): mob.interim = mob.copy().move_to(interim.split()[i]) self.add(start) self.play(Write(words), FadeIn(inv), run_time = 1) self.wait() self.play( FadeOut(words), *[Transform(m, m.interim) for m in interim_mobs] ) self.wait() product = VMobject(A, inv) product.brace = Brace(product) product.words = product.brace.get_text( "The ``do nothing'' matrix" ) product.words.set_color(BLUE) self.play( GrowFromCenter(product.brace), Write(product.words, run_time = 1), product.set_color, BLUE ) self.wait() self.play(*[ ApplyMethod(m.set_color, BLACK) for m in (product, product.brace, product.words) ]) self.wait() self.play(ApplyFunction( lambda m : m.center().to_edge(UP), VMobject(x, eq, inv2, v) )) self.wait() class PlayInReverseWithSolution(PlayInReverse): CONFIG = { "t_matrix" : [[2, 1], [2, 3]] } def setup(self): LinearTransformationScene.setup(self) equation = OldTex([ "\\vec{\\textbf{x}}", "=", "A^{-1}", "\\vec{\\textbf{v}}", ]) equation.to_edge(UP) equation.add_background_rectangle() self.add_foreground_mobject(equation) self.equation = equation self.x, eq, self.inv, self.v = equation.split()[1].split() self.x.set_color(PINK) self.v.set_color(YELLOW) self.inv.set_color(GREEN) class OneUniqueSolution(Scene): def construct(self): system = OldTex(""" \\begin{align*} ax + cy &= e \\\\ bx + dy &= f \\end{align*} """) VMobject(*np.array(system.split())[[1, 8]]).set_color(X_COLOR) VMobject(*np.array(system.split())[[4, 11]]).set_color(Y_COLOR) brace = Brace(system, UP) brace.set_color(YELLOW) words = brace.get_text("One unique solution \\dots", "probably") words.set_color(YELLOW) words.split()[1].set_color(GREEN) self.add(system) self.wait() self.play( GrowFromCenter(brace), Write(words.split()[0]) ) self.wait() self.play(Write(words.split()[1], run_time = 1)) self.wait() class ThreeDTransformXToV(Scene): pass class ThreeDTransformAndReverse(Scene): pass class DetNEZeroRule(Scene): def construct(self): text = OldTex("\\det(A) \\ne 0") text.shift(2*UP) A_inv = OldTexText("$A^{-1}$ exists") A_inv.shift(DOWN) arrow = Arrow(text, A_inv) self.play(Write(text)) self.wait() self.play(ShowCreation(arrow)) self.play(Write(A_inv, run_time = 1)) self.wait() class ThreeDInverseRule(Scene): def construct(self): form = OldTex("A^{-1} A = ") form.scale(2) matrix = Matrix(np.identity(3, 'int')) matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR) matrix.next_to(form, RIGHT) self.add(form) self.play(Write(matrix)) self.wait() class ThreeDApplyReverseToV(Scene): pass class InversesDontAlwaysExist(TeacherStudentsScene): def construct(self): self.teacher_says("$A^{-1}$ doesn't always exist") self.random_blink() self.wait() self.random_blink() class InvertNonInvertable(LinearTransformationScene): CONFIG = { "t_matrix" : [[2, 1], [-2, -1]] } def setup(self): LinearTransformationScene.setup(self) det_text = OldTex("\\det(A) = 0") det_text.scale(1.5) det_text.to_corner(UP+LEFT) det_text.add_background_rectangle() self.add_foreground_mobject(det_text) def construct(self): no_func = OldTexText("No function does this") no_func.shift(2*UP) no_func.set_color(RED) no_func.add_background_rectangle() grid = VMobject(self.plane, self.i_hat, self.j_hat) grid.save_state() self.apply_transposed_matrix(self.t_matrix, path_arc = 0) self.wait() self.play(Write(no_func, run_time = 1)) self.add_foreground_mobject(no_func) self.play( grid.restore, *list(map(Animation, self.foreground_mobjects)), run_time = 3 ) self.wait() class OneInputMultipleOutputs(InvertNonInvertable): def construct(self): input_vectors = VMobject(*[ Vector([x+2, x]) for x in np.arange(-4, 4.5, 0.5) ]) input_vectors.set_submobject_colors_by_gradient(PINK, YELLOW) output_vector = Vector([4, 2], color = YELLOW) grid = VMobject(self.plane, self.i_hat, self.j_hat) grid.save_state() self.apply_transposed_matrix(self.t_matrix, path_arc = 0) self.play(ShowCreation(output_vector)) single_input = OldTexText("Single vector") single_input.add_background_rectangle() single_input.next_to(output_vector.get_end(), UP) single_input.set_color(YELLOW) self.play(Write(single_input)) self.wait() self.remove(single_input, output_vector) self.play( grid.restore, *[ Transform(output_vector.copy(), input_vector) for input_vector in input_vectors.split() ] + list(map(Animation, self.foreground_mobjects)), run_time = 3 ) multiple_outputs = OldTexText( "Must map to \\\\", "multiple vectors" ) multiple_outputs.split()[1].set_submobject_colors_by_gradient(YELLOW, PINK) multiple_outputs.next_to(ORIGIN, DOWN).to_edge(RIGHT) multiple_outputs.add_background_rectangle() self.play(Write(multiple_outputs, run_time = 2)) self.wait() class SolutionsCanStillExist(TeacherStudentsScene): def construct(self): words = OldTexText(""" Solutions can still exist when""", "$\\det(A) = 0$" ) words[1].set_color(TEAL) self.teacher_says(words) self.random_blink(2) class ShowVInAndOutOfColumnSpace(LinearSystemTransformationScene): CONFIG = { "t_matrix" : [[2, 1], [-2, -1]] } def construct(self): v_out = Vector([1, -1]) v_in = Vector([-4, -2]) v_out.words = "No solution exists" v_in.words = "Solutions exist" v_in.words_color = YELLOW v_out.words_color = RED self.apply_transposed_matrix(self.t_matrix, path_arc = 0) self.wait() for v in v_in, v_out: self.add_vector(v, animate = True) words = OldTexText(v.words) words.set_color(v.words_color) words.next_to(v.get_end(), DOWN+RIGHT) words.add_background_rectangle() self.play(Write(words), run_time = 2) self.wait() class NotAllSquishesAreCreatedEqual(TeacherStudentsScene): def construct(self): self.student_says(""" Some squishes feel ...squishier """) self.random_blink(2) class PrepareForRank(Scene): def construct(self): new_term, rank = words = OldTexText( "New terminology: ", "rank" ) rank.set_color(TEAL) self.play(Write(words)) self.wait() class DefineRank(Scene): def construct(self): rank = OldTexText("``Rank''") rank.set_color(TEAL) arrow = DoubleArrow(LEFT, RIGHT) dims = OldTexText( "Number of\\\\", "dimensions \\\\", "in the output" ) dims[1].set_color(rank.get_color()) rank.next_to(arrow, LEFT) dims.next_to(arrow, RIGHT) self.play(Write(rank)) self.play( ShowCreation(arrow), *list(map(Write, dims)) ) self.wait() class DefineColumnSpace(Scene): def construct(self): left_words = OldTexText( "Set of all possible\\\\", "outputs", "$A\\vec{\\textbf{v}}$", ) left_words[1].set_color(TEAL) VMobject(*left_words[-1][1:]).set_color(YELLOW) arrow = DoubleArrow(LEFT, RIGHT).to_edge(UP) right_words = OldTexText("``Column space''", "of $A$") right_words[0].set_color(left_words[1].get_color()) everyone = VMobject(left_words, arrow, right_words) everyone.arrange(RIGHT) everyone.to_edge(UP) self.play(Write(left_words)) self.wait() self.play( ShowCreation(arrow), Write(right_words) ) self.wait() class ColumnsRepresentBasisVectors(Scene): def construct(self): matrix = Matrix([[3, 1], [4, 1]]) matrix.shift(UP) i_hat_words, j_hat_words = [ OldTexText("Where $\\hat{\\%smath}$ lands"%char) for char in ("i", "j") ] i_hat_words.set_color(X_COLOR) i_hat_words.next_to(ORIGIN, LEFT).to_edge(UP) j_hat_words.set_color(Y_COLOR) j_hat_words.next_to(ORIGIN, RIGHT).to_edge(UP) self.add(matrix) self.wait() for i, words in enumerate([i_hat_words, j_hat_words]): arrow = Arrow( words.get_bottom(), matrix.get_mob_matrix()[0,i].get_top(), color = words.get_color() ) self.play( Write(words, run_time = 1), ShowCreation(arrow), *[ ApplyMethod(m.set_color, words.get_color()) for m in matrix.get_mob_matrix()[:,i] ] ) self.wait() class ThreeDOntoPlane(Scene): pass class ThreeDOntoLine(Scene): pass class ThreeDOntoPoint(Scene): pass class TowDColumnsDontSpan(LinearTransformationScene): CONFIG = { "t_matrix" : [[2, 1], [-2, -1]] } def construct(self): matrix = Matrix(self.t_matrix.T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.add_to_back(BackgroundRectangle(matrix)) self.add_foreground_mobject(matrix) brace = Brace(matrix) words = VMobject( OldTexText("Span", "of columns"), OldTex("\\Updownarrow"), OldTexText("``Column space''") ) words.arrange(DOWN, buff = 0.1) words.next_to(brace, DOWN) words[0][0].set_color(PINK) words[2].set_color(TEAL) words[0].add_background_rectangle() words[2].add_background_rectangle() VMobject(matrix, brace, words).to_corner(UP+LEFT) self.apply_transposed_matrix(self.t_matrix, path_arc = 0) self.play( GrowFromCenter(brace), Write(words, run_time = 2) ) self.wait() self.play(ApplyFunction( lambda m : m.scale(-1).shift(self.i_hat.get_end()), self.j_hat )) bases = [self.i_hat, self.j_hat] for mob in bases: mob.original = mob.copy() for x in range(8): for mob in bases: mob.target = mob.original.copy() mob.target.set_stroke(width = 6) target_len = random.uniform(0.5, 1.5) target_len *= random.choice([-1, 1]) mob.target.scale(target_len) self.j_hat.target.shift( -self.j_hat.target.get_start()+ \ self.i_hat.target.get_end() ) self.play(Transform( VMobject(*bases), VMobject(*[m.target for m in bases]), run_time = 2 )) class FullRankWords(Scene): def construct(self): self.play(Write(OldTexText("Full rank").scale(2))) class ThreeDColumnsDontSpan(Scene): def construct(self): matrix = Matrix(np.array([ [1, 1, 0], [0, 1, 1], [-1, -2, -1], ]).T) matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR) brace = Brace(matrix) words = brace.get_text( "Columns don't", "span \\\\", "full output space" ) words[1].set_color(PINK) self.add(matrix) self.play( GrowFromCenter(brace), Write(words, run_time = 2) ) self.wait() class NameColumnSpace(Scene): def construct(self): matrix = Matrix(np.array([ [1, 1, 0], [0, 1, 1], [-1, -2, -1], ]).T) matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR) matrix.to_corner(UP+LEFT) cols = list(matrix.copy().get_mob_matrix().T) col_arrays = list(map(Matrix, cols)) span_text = OldTex( "\\text{Span}", "\\Big(", matrix_to_tex_string([1, 2, 3]), ",", matrix_to_tex_string([1, 2, 3]), ",", matrix_to_tex_string([1, 2, 3]), "\\big)" ) for i in 1, -1: span_text[i].stretch(1.5, 1) span_text[i].do_in_place( span_text[i].set_height, span_text.get_height() ) for col_array, index in zip(col_arrays, [2, 4, 6]): col_array.replace(span_text[index], dim_to_match = 1) span_text.submobjects[index] = col_array span_text.arrange(RIGHT, buff = 0.2) arrow = DoubleArrow(LEFT, RIGHT) column_space = OldTexText("``Column space''") for mob in column_space, arrow: mob.set_color(TEAL) text = VMobject(span_text, arrow, column_space) text.arrange(RIGHT) text.next_to(matrix, DOWN, buff = 1, aligned_edge = LEFT) self.add(matrix) self.wait() self.play(*[ Transform( VMobject(*matrix.copy().get_mob_matrix()[:,i]), col_arrays[i].get_entries() ) for i in range(3) ]) self.play( Write(span_text), *list(map(Animation, self.get_mobjects_from_last_animation())) ) self.play( ShowCreation(arrow), Write(column_space) ) self.wait() self.play(FadeOut(matrix)) self.clear() self.add(text) words = OldTexText( "To solve", "$A\\vec{\\textbf{x}} = \\vec{\\textbf{v}}$,\\\\", "$\\vec{\\textbf{v}}$", "must be in \\\\ the", "column space." ) VMobject(*words[1][1:3]).set_color(PINK) VMobject(*words[1][4:6]).set_color(YELLOW) words[2].set_color(YELLOW) words[4].set_color(TEAL) words.to_corner(UP+LEFT) self.play(Write(words)) self.wait(2) self.play(FadeOut(words)) brace = Brace(column_space, UP) rank_words = brace.get_text( "Number of dimensions \\\\ is called", "``rank''" ) rank_words[1].set_color(MAROON) self.play( GrowFromCenter(brace), Write(rank_words) ) self.wait() self.cycle_through_span_possibilities(span_text) def cycle_through_span_possibilities(self, span_text): span_text.save_state() two_d_span = span_text.copy() for index, arr, c in (2, [1, 1], X_COLOR), (4, [0, 1], Y_COLOR): col = Matrix(arr) col.replace(two_d_span[index]) two_d_span.submobjects[index] = col col.get_entries().set_color(c) for index in 5, 6: two_d_span[index].scale(0) two_d_span.arrange(RIGHT, buff = 0.2) two_d_span[-1].next_to(two_d_span[4], RIGHT, buff = 0.2) two_d_span.move_to(span_text, aligned_edge = RIGHT) mob_matrix = np.array([ two_d_span[i].get_entries().split() for i in (2, 4) ]) self.play(Transform(span_text, two_d_span)) #horrible hack span_text.shift(10*DOWN) span_text = span_text.copy().restore() ### self.add(two_d_span) self.wait() self.replace_number_matrix(mob_matrix, [[1, 1], [1, 1]]) self.wait() self.replace_number_matrix(mob_matrix, [[0, 0], [0, 0]]) self.wait() self.play(Transform(two_d_span, span_text)) self.wait() self.remove(two_d_span) self.add(span_text) mob_matrix = np.array([ span_text[i].get_entries().split() for i in (2, 4, 6) ]) self.replace_number_matrix(mob_matrix, [[1, 1, 0], [0, 1, 1], [1, 0, 1]]) self.wait() self.replace_number_matrix(mob_matrix, [[1, 1, 0], [0, 1, 1], [-1, -2, -1]]) self.wait() self.replace_number_matrix(mob_matrix, [[1, 1, 0], [2, 2, 0], [3, 3, 0]]) self.wait() self.replace_number_matrix(mob_matrix, np.zeros((3, 3)).astype('int')) self.wait() def replace_number_matrix(self, matrix, new_numbers): starters = matrix.flatten() targets = list(map(Tex, list(map(str, np.array(new_numbers).flatten())))) for start, target in zip(starters, targets): target.move_to(start) target.set_color(start.get_color()) self.play(*[ Transform(*pair, path_arc = np.pi) for pair in zip(starters, targets) ]) class IHatShear(LinearTransformationScene): CONFIG = { "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 0 }, } def construct(self): self.apply_transposed_matrix([[1, 1], [0, 1]]) self.wait() class DiagonalDegenerate(LinearTransformationScene): def construct(self): self.apply_transposed_matrix([[1, 1], [1, 1]]) class ZeroMatirx(LinearTransformationScene): def construct(self): origin = Dot(ORIGIN) self.play(Transform( VMobject(self.plane, self.i_hat, self.j_hat), origin, run_time = 3 )) self.wait() class RankNumber(Scene): CONFIG = { "number" : 3, "color" : BLUE } def construct(self): words = OldTexText("Rank", "%d"%self.number) words[1].set_color(self.color) self.add(words) class RankNumber2(RankNumber): CONFIG = { "number" : 2, "color" : RED, } class RankNumber1(RankNumber): CONFIG = { "number" : 1, "color" : GREEN } class RankNumber0(RankNumber): CONFIG = { "number" : 0, "color" : GREY } class NameFullRank(Scene): def construct(self): matrix = Matrix([[2, 5, 1], [3, 1, 4], [-4, 0, 0]]) matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR) matrix.to_edge(UP) brace = Brace(matrix) top_words = brace.get_text( "When", "rank", "$=$", "number of columns", ) top_words[1].set_color(MAROON) low_words = OldTexText( "matrix is", "``full rank''" ) low_words[1].set_color(MAROON) low_words.next_to(top_words, DOWN) VMobject(matrix, brace, top_words, low_words).to_corner(UP+LEFT) self.add(matrix) self.play( GrowFromCenter(brace), Write(top_words) ) self.wait() self.play(Write(low_words)) self.wait() class OriginIsAlwaysInColumnSpace(LinearTransformationScene): def construct(self): vector = Matrix([0, 0]).set_color(YELLOW) words = OldTexText("is always in the", "column space") words[1].set_color(TEAL) words.next_to(vector, RIGHT) vector.add_to_back(BackgroundRectangle(vector)) words.add_background_rectangle() VMobject(vector, words).center().to_edge(UP) arrow = Arrow(vector.get_bottom(), ORIGIN) dot = Dot(ORIGIN, color = YELLOW) self.play(Write(vector), Write(words)) self.play(ShowCreation(arrow)) self.play(ShowCreation(dot, run_time = 0.5)) self.add_foreground_mobject(vector, words, arrow, dot) self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() self.apply_transposed_matrix([[1./3, -1./2], [-1./3, 1./2]]) self.wait() class FullRankCase(LinearTransformationScene): CONFIG = { "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 0 }, } def construct(self): t_matrices = [ [[2, 1], [-3, 2]], [[1./2, 1], [1./3, -1./2]] ] vector = Matrix([0, 0]).set_color(YELLOW) title = VMobject( OldTexText("Only"), vector, OldTexText("lands on"), vector.copy() ) title.arrange(buff = 0.2) title.to_edge(UP) for mob in title: mob.add_to_back(BackgroundRectangle(mob)) arrow = Arrow(vector.get_bottom(), ORIGIN) dot = Dot(ORIGIN, color = YELLOW) words_on = False for t_matrix in t_matrices: self.apply_transposed_matrix(t_matrix) if not words_on: self.play(Write(title)) self.play(ShowCreation(arrow)) self.play(ShowCreation(dot, run_time = 0.5)) self.add_foreground_mobject(title, arrow, dot) words_on = True self.apply_inverse_transpose(t_matrix) self.wait() class NameNullSpace(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "t_matrix" : [[1, -1], [-1, 1]] } def construct(self): vectors = self.get_vectors() dot = Dot(ORIGIN, color = YELLOW) line = Line(vectors[0].get_end(), vectors[-1].get_end()) line.set_color(YELLOW) null_space_label = OldTexText("``Null space''") kernel_label = OldTexText("``Kernel''") null_space_label.move_to(vectors[13].get_end(), aligned_edge = UP+LEFT) kernel_label.next_to(null_space_label, DOWN) for mob in null_space_label, kernel_label: mob.set_color(YELLOW) mob.add_background_rectangle() self.play(ShowCreation(vectors, run_time = 3)) self.wait() vectors.save_state() self.plane.save_state() self.apply_transposed_matrix( self.t_matrix, added_anims = [Transform(vectors, dot)], path_arc = 0 ) self.wait() self.play( vectors.restore, self.plane.restore, *list(map(Animation, self.foreground_mobjects)), run_time = 2 ) self.play(Transform( vectors, line, run_time = 2, lag_ratio = 0.5 )) self.wait() for label in null_space_label, kernel_label: self.play(Write(label)) self.wait() self.apply_transposed_matrix( self.t_matrix, added_anims = [ Transform(vectors, dot), ApplyMethod(null_space_label.scale, 0), ApplyMethod(kernel_label.scale, 0), ], path_arc = 0 ) self.wait() def get_vectors(self, offset = 0): vect = np.array(UP+RIGHT) vectors = VMobject(*[ Vector(a*vect + offset) for a in np.linspace(-5, 5, 18) ]) vectors.set_submobject_colors_by_gradient(PINK, YELLOW) return vectors class ThreeDNullSpaceIsLine(Scene): pass class ThreeDNullSpaceIsPlane(Scene): pass class NullSpaceSolveForVEqualsZero(NameNullSpace): def construct(self): vec = lambda s : "\\vec{\\textbf{%s}}"%s equation = OldTex("A", vec("x"), "=", vec("v")) A, x, eq, v = equation x.set_color(PINK) v.set_color(YELLOW) zero_vector = Matrix([0, 0]) zero_vector.set_color(YELLOW) zero_vector.scale(0.7) zero_vector.move_to(v, aligned_edge = LEFT) VMobject(equation, zero_vector).next_to(ORIGIN, LEFT).to_edge(UP) zero_vector_rect = BackgroundRectangle(zero_vector) equation.add_background_rectangle() self.play(Write(equation)) self.wait() self.play( ShowCreation(zero_vector_rect), Transform(v, zero_vector) ) self.wait() self.add_foreground_mobject(zero_vector_rect, equation) NameNullSpace.construct(self) class OffsetNullSpace(NameNullSpace): def construct(self): x = Vector([-2, 1], color = RED) vectors = self.get_vectors() offset_vectors = self.get_vectors(offset = x.get_end()) dots = VMobject(*[ Dot(v.get_end(), color = v.get_color()) for v in offset_vectors ]) dot = Dot( self.get_matrix_transformation(self.t_matrix)(x.get_end()), color = RED ) circle = Circle(color = YELLOW).replace(dot) circle.scale(5) words = OldTexText(""" All vectors still land on the same spot """) words.set_color(YELLOW) words.add_background_rectangle() words.next_to(circle) x_copies = VMobject(*[ x.copy().shift(v.get_end()) for v in vectors ]) self.play(FadeIn(vectors)) self.wait() self.add_vector(x, animate = True) self.wait() x_copy = VMobject(x.copy()) self.play(Transform(x_copy, x_copies)) self.play( Transform(vectors, offset_vectors), *[ Transform(v, VectorizedPoint(v.get_end())) for v in x_copy ] ) self.remove(x_copy) self.wait() self.play(Transform(vectors, dots)) self.wait() self.apply_transposed_matrix( self.t_matrix, added_anims = [Transform(vectors, dot)] ) self.wait() self.play( ShowCreation(circle), Write(words) ) self.wait() class ShowAdditivityProperty(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "t_matrix" : [[1, 0.5], [-1, 1]], "include_background_plane" : False, } def construct(self): v = Vector([2, -1]) w = Vector([1, 2]) v.set_color(YELLOW) w.set_color(MAROON_B) sum_vect = Vector(v.get_end()+w.get_end(), color = PINK) form = OldTex( "A(", "\\vec{\\textbf{v}}", "+", "\\vec{\\textbf{w}}", ")", "=A", "\\vec{\\textbf{v}}", "+A", "\\vec{\\textbf{w}}", ) form.to_corner(UP+RIGHT) VMobject(form[1], form[6]).set_color(YELLOW) VMobject(form[3], form[8]).set_color(MAROON_B) initial_sum = VMobject(*form[1:4]) transformer = VMobject(form[0], form[4]) final_sum = VMobject(*form[5:]) form_rect = BackgroundRectangle(form) self.add(form_rect) self.add_vector(v, animate = True) self.add_vector(w, animate = True) w_copy = w.copy() self.play(w_copy.shift, v.get_end()) self.add_vector(sum_vect, animate = True) self.play( Write(initial_sum), FadeOut(w_copy) ) self.add_foreground_mobject(form_rect, initial_sum) self.apply_transposed_matrix( self.t_matrix, added_anims = [Write(transformer)] ) self.wait() self.play(w.copy().shift, v.get_end()) self.play(Write(final_sum)) self.wait() class AddJustOneNullSpaceVector(NameNullSpace): def construct(self): vectors = self.get_vectors() self.add(vectors) null_vector = vectors[int(0.7*len(vectors.split()))] vectors.remove(null_vector) null_vector.label = "$\\vec{\\textbf{n}}$" x = Vector([-1, 1], color = RED) x.label = "$\\vec{\\textbf{x}}$" sum_vect = Vector( x.get_end() + null_vector.get_end(), color = PINK ) for v in x, null_vector: v.label = OldTexText(v.label) v.label.set_color(v.get_color()) v.label.next_to(v.get_end(), UP) v.label.add_background_rectangle() dot = Dot(ORIGIN, color = null_vector.get_color()) form = OldTex( "A(", "\\vec{\\textbf{x}}", "+", "\\vec{\\textbf{n}}", ")", "=A", "\\vec{\\textbf{x}}", "+A", "\\vec{\\textbf{n}}", ) form.to_corner(UP+RIGHT) VMobject(form[1], form[6]).set_color(x.get_color()) VMobject(form[3], form[8]).set_color(null_vector.get_color()) initial_sum = VMobject(*form[1:4]) transformer = VMobject(form[0], form[4]) final_sum = VMobject(*form[5:]) brace = Brace(VMobject(*form[-2:])) brace.add(brace.get_text("+0").add_background_rectangle()) form_rect = BackgroundRectangle(form) sum_vect.label = initial_sum.copy() sum_vect.label.next_to(sum_vect.get_end(), UP) self.add_vector(x, animate = True) self.play(Write(x.label)) self.wait() self.play( FadeOut(vectors), Animation(null_vector) ) self.play(Write(null_vector.label)) self.wait() x_copy = x.copy() self.play(x_copy.shift, null_vector.get_end()) self.add_vector(sum_vect, animate = True) self.play( FadeOut(x_copy), Write(sum_vect.label) ) self.wait() self.play( ShowCreation(form_rect), sum_vect.label.replace, initial_sum ) self.add_foreground_mobject(form_rect, sum_vect.label) self.remove(x.label, null_vector.label) self.apply_transposed_matrix( self.t_matrix, added_anims = [ Transform(null_vector, dot), Write(transformer) ] ) self.play(Write(final_sum)) self.wait() self.play(Write(brace)) self.wait() words = OldTexText( "$\\vec{\\textbf{x}}$", "and the", "$\\vec{\\textbf{x}} + \\vec{\\textbf{n}}$\\\\", "land on the same spot" ) words[0].set_color(x.get_color()) VMobject(*words[2][:2]).set_color(x.get_color()) VMobject(*words[2][3:]).set_color(null_vector.get_color()) words.next_to(brace, DOWN) words.to_edge(RIGHT) self.play(Write(words)) self.wait() class NullSpaceOffsetRule(Scene): def construct(self): vec = lambda s : "\\vec{\\textbf{%s}}"%s equation = OldTex("A", vec("x"), "=", vec("v")) A, x, equals, v = equation x.set_color(PINK) v.set_color(YELLOW) A_text = OldTexText( "When $A$ is not", "full rank" ) A_text[1].set_color(MAROON_C) A_text.next_to(A, UP+LEFT, buff = 1) A_text.shift_onto_screen() A_arrow = Arrow(A_text.get_bottom(), A, color = WHITE) v_text = OldTexText( "If", "$%s$"%vec("v"), "is in the", "column space", "of $A$" ) v_text[1].set_color(YELLOW) v_text[3].set_color(TEAL) v_text.next_to(v, DOWN+RIGHT, buff = 1) v_text.shift_onto_screen() v_arrow = Arrow(v_text.get_top(), v, color = YELLOW) self.add(equation) self.play(Write(A_text, run_time = 2)) self.play(ShowCreation(A_arrow)) self.wait() self.play(Write(v_text, run_time = 2)) self.play(ShowCreation(v_arrow)) self.wait() class MuchLeftToLearn(TeacherStudentsScene): def construct(self): self.teacher_says( "That's the high \\\\", "level overview" ) self.random_blink() self.wait() self.teacher_says( "There is still \\\\", "much to learn" ) for pi in self.get_students(): target_mode = random.choice([ "raise_right_hand", "raise_left_hand" ]) self.play(pi.change_mode, target_mode) self.random_blink() self.wait() class NotToLearnItAllNow(TeacherStudentsScene): def construct(self): self.teacher_says(""" The goal is not to learn it all now """) self.random_blink() self.wait() self.random_blink() class NextVideo(Scene): def construct(self): title = OldTexText(""" Next video: Nonsquare matrices """) title.set_width(FRAME_WIDTH - 2) title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class WhatAboutNonsquareMatrices(TeacherStudentsScene): def construct(self): self.student_says( "What about \\\\ nonsquare matrices?", target_mode = "raise_right_hand" ) self.play(self.get_students()[0].change_mode, "confused") self.random_blink(6)
videos_3b1b/_2016/eola/chapter3.py
from manim_imports_ext import * def curvy_squish(point): x, y, z = point return (x+np.cos(y))*RIGHT + (y+np.sin(x))*UP class OpeningQuote(Scene): def construct(self): words = OldTexText([ "Unfortunately, no one can be told what the", "Matrix", "is. You have to", "see it for yourself.", ]) words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) words.split()[1].set_color(GREEN) words.split()[3].set_color(BLUE) author = OldTexText("-Morpheus") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) comment = OldTexText(""" (Surprisingly apt words on the importance of understanding matrix operations visually.) """) comment.next_to(author, DOWN, buff = 1) self.play(FadeIn(words)) self.wait(3) self.play(Write(author, run_time = 3)) self.wait() self.play(Write(comment)) self.wait() class Introduction(TeacherStudentsScene): def construct(self): title = OldTexText(["Matrices as", "Linear transformations"]) title.to_edge(UP) title.set_color(YELLOW) linear_transformations = title.split()[1] self.add(*title.split()) self.setup() self.teacher_says(""" Listen up folks, this one is particularly important """, height = 3) self.random_blink(2) self.teacher_thinks("", height = 3) self.remove(linear_transformations) everything = VMobject(*self.get_mobjects()) def spread_out(p): p = p + 2*DOWN return (FRAME_X_RADIUS+FRAME_Y_RADIUS)*p/get_norm(p) self.play( ApplyPointwiseFunction(spread_out, everything), ApplyFunction( lambda m : m.center().to_edge(UP), linear_transformations ) ) class MatrixVectorMechanicalMultiplication(NumericalMatrixMultiplication): CONFIG = { "left_matrix" : [[1, -3], [2, 4]], "right_matrix" : [[5], [7]] } class PostponeHigherDimensions(TeacherStudentsScene): def construct(self): self.setup() self.student_says("What about 3 dimensions?") self.random_blink() self.teacher_says("All in due time,\\\\ young padawan") self.random_blink() class DescribeTransformation(Scene): def construct(self): self.add_title() self.show_function() def add_title(self): title = OldTexText(["Linear", "transformation"]) title.to_edge(UP) linear, transformation = title.split() brace = Brace(transformation, DOWN) function = OldTexText("function").next_to(brace, DOWN) function.set_color(YELLOW) self.play(Write(title)) self.wait() self.play( GrowFromCenter(brace), Write(function), ApplyMethod(linear.fade) ) def show_function(self): f_of_x = OldTex("f(x)") L_of_v = OldTex("L(\\vec{\\textbf{v}})") nums = [5, 2, -3] num_inputs = VMobject(*list(map(Tex, list(map(str, nums))))) num_outputs = VMobject(*[ OldTex(str(num**2)) for num in nums ]) for mob in num_inputs, num_outputs: mob.arrange(DOWN, buff = 1) num_inputs.next_to(f_of_x, LEFT, buff = 1) num_outputs.next_to(f_of_x, RIGHT, buff = 1) f_point = VectorizedPoint(f_of_x.get_center()) input_vect = Matrix([5, 7]) input_vect.next_to(L_of_v, LEFT, buff = 1) output_vect = Matrix([2, -3]) output_vect.next_to(L_of_v, RIGHT, buff = 1) vector_input_words = OldTexText("Vector input") vector_input_words.set_color(MAROON_C) vector_input_words.next_to(input_vect, DOWN) vector_output_words = OldTexText("Vector output") vector_output_words.set_color(BLUE) vector_output_words.next_to(output_vect, DOWN) self.play(Write(f_of_x, run_time = 1)) self.play(Write(num_inputs, run_time = 2)) self.wait() for mob in f_point, num_outputs: self.play(Transform( num_inputs, mob, lag_ratio = 0.5 )) self.wait() self.play( FadeOut(num_inputs), Transform(f_of_x, L_of_v) ) self.play( Write(input_vect), Write(vector_input_words) ) self.wait() for mob in f_point, output_vect: self.play(Transform( input_vect, mob, lag_ratio = 0.5 )) self.play(Write(vector_output_words)) self.wait() class WhyConfuseWithTerminology(TeacherStudentsScene): def construct(self): self.setup() self.student_says("Why confuse us with \\\\ redundant terminology?") other_students = [self.get_students()[i] for i in (0, 2)] self.play(*[ ApplyMethod(student.change_mode, "confused") for student in other_students ]) self.random_blink() self.wait() statement = OldTexText([ "The word", "``transformation''", "suggests \\\\ that you think using", "movement", ]) statement.split()[1].set_color(BLUE) statement.split()[-1].set_color(YELLOW) self.teacher_says(statement, width = 10) self.play(*[ ApplyMethod(student.change_mode, "happy") for student in other_students ]) self.random_blink() self.wait() class ThinkinfOfFunctionsAsGraphs(VectorScene): def construct(self): axes = self.add_axes() graph = FunctionGraph(lambda x : x**2, x_min = -2, x_max = 2) name = OldTex("f(x) = x^2") name.next_to(graph, RIGHT).to_edge(UP) point = Dot(graph.point_from_proportion(0.8)) point_label = OldTex("(2, f(2))") point_label.next_to(point.get_center(), DOWN+RIGHT, buff = 0.1) self.play(ShowCreation(graph)) self.play(Write(name, run_time = 1)) self.play( ShowCreation(point), Write(point_label), run_time = 1 ) self.wait() def collapse_func(p): return np.dot(p, [RIGHT, RIGHT, OUT]) + (FRAME_Y_RADIUS+1)*DOWN self.play( ApplyPointwiseFunction(collapse_func, axes), ApplyPointwiseFunction(collapse_func, graph), ApplyMethod(point.shift, 10*DOWN), ApplyMethod(point_label.shift, 10*DOWN), ApplyPointwiseFunction(collapse_func, name), run_time = 2 ) self.clear() words = OldTexText(["Instead think about", "\\emph{movement}"]) words.split()[-1].set_color(YELLOW) self.play(Write(words)) self.wait() class TransformJustOneVector(VectorScene): def construct(self): self.lock_in_faded_grid() v1_coords = [-3, 1] t_matrix = [[0, -1], [2, -1]] v1 = Vector(v1_coords) v2 = Vector( np.dot(np.array(t_matrix).transpose(), v1_coords), color = PINK ) for v, word in (v1, "Input"), (v2, "Output"): v.label = OldTexText("%s vector"%word) v.label.next_to(v.get_end(), UP) v.label.set_color(v.get_color()) self.play(ShowCreation(v)) self.play(Write(v.label)) self.wait() self.remove(v2) self.play( Transform( v1.copy(), v2, path_arc = -np.pi/2, run_time = 3 ), ApplyMethod(v1.fade) ) self.wait() class TransformManyVectors(LinearTransformationScene): CONFIG = { "transposed_matrix" : [[2, 1], [1, 2]], "use_dots" : False, } def construct(self): self.lock_in_faded_grid() vectors = VMobject(*[ Vector([x, y]) for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5) for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5) ]) vectors.set_submobject_colors_by_gradient(PINK, YELLOW) t_matrix = self.transposed_matrix transformed_vectors = VMobject(*[ Vector( np.dot(np.array(t_matrix).transpose(), v.get_end()[:2]), color = v.get_color() ) for v in vectors.split() ]) self.play(ShowCreation(vectors, lag_ratio = 0.5)) self.wait() if self.use_dots: self.play(Transform( vectors, self.vectors_to_dots(vectors), run_time = 3, lag_ratio = 0.5 )) transformed_vectors = self.vectors_to_dots(transformed_vectors) self.wait() self.play(Transform( vectors, transformed_vectors, run_time = 3, path_arc = -np.pi/2 )) self.wait() if self.use_dots: self.play(Transform( vectors, self.dots_to_vectors(vectors), run_time = 2, lag_ratio = 0.5 )) self.wait() def vectors_to_dots(self, vectors): return VMobject(*[ Dot(v.get_end(), color = v.get_color()) for v in vectors.split() ]) def dots_to_vectors(self, dots): return VMobject(*[ Vector(dot.get_center(), color = dot.get_color()) for dot in dots.split() ]) class TransformManyVectorsAsPoints(TransformManyVectors): CONFIG = { "use_dots" : True } class TransformInfiniteGrid(LinearTransformationScene): CONFIG = { "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, }, "show_basis_vectors" : False } def construct(self): self.setup() self.play(ShowCreation( self.plane, run_time = 3, lag_ratio = 0.5 )) self.wait() self.apply_transposed_matrix([[2, 1], [1, 2]]) self.wait() class TransformInfiniteGridWithBackground(TransformInfiniteGrid): CONFIG = { "include_background_plane" : True, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, "secondary_line_ratio" : 0 }, } class ApplyComplexFunction(LinearTransformationScene): CONFIG = { "function" : lambda z : 0.5*z**2, "show_basis_vectors" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_X_RADIUS, "y_radius" : FRAME_Y_RADIUS, "secondary_line_ratio" : 0 }, } def construct(self): self.setup() self.plane.prepare_for_nonlinear_transform(100) self.wait() self.play(ApplyMethod( self.plane.apply_complex_function, self.function, run_time = 5, path_arc = np.pi/2 )) self.wait() class ExponentialTransformation(ApplyComplexFunction): CONFIG = { "function" : np.exp, } class CrazyTransformation(ApplyComplexFunction): CONFIG = { "function" : lambda z : np.sin(z)**2 + np.sinh(z) } class LookToWordLinear(Scene): def construct(self): title = OldTexText(["Linear ", "transformations"]) title.to_edge(UP) faded_title = title.copy().fade() linear, transformation = title.split() faded_linear, faded_transformation = faded_title.split() linear_brace = Brace(linear, DOWN) transformation_brace = Brace(transformation, DOWN) function = OldTexText("function") function.set_color(YELLOW) function.next_to(transformation_brace, DOWN) new_sub_word = OldTexText("What does this mean?") new_sub_word.set_color(BLUE) new_sub_word.next_to(linear_brace, DOWN) self.add( faded_linear, transformation, transformation_brace, function ) self.wait() self.play( Transform(faded_linear, linear), Transform(transformation, faded_transformation), Transform(transformation_brace, linear_brace), Transform(function, new_sub_word), lag_ratio = 0.5 ) self.wait() class IntroduceLinearTransformations(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, } def construct(self): self.setup() self.wait() self.apply_transposed_matrix([[2, 1], [1, 2]]) self.wait() lines_rule = OldTexText("Lines remain lines") lines_rule.shift(2*UP).to_edge(LEFT) origin_rule = OldTexText("Origin remains fixed") origin_rule.shift(2*UP).to_edge(RIGHT) arrow = Arrow(origin_rule, ORIGIN) dot = Dot(ORIGIN, radius = 0.1, color = RED) for rule in lines_rule, origin_rule: rule.add_background_rectangle() self.play( Write(lines_rule, run_time = 2), ) self.wait() self.play( Write(origin_rule, run_time = 2), ShowCreation(arrow), GrowFromCenter(dot) ) self.wait() class ToThePedants(Scene): def construct(self): words = OldTexText([ "To the pedants:\\\\", """ Yeah yeah, I know that's not the formal definition for linear transformations, as seen in textbooks, but I'm building visual intuition here, and what I've said is equivalent to the formal definition (which I'll get to later in the series). """]) words.split()[0].set_color(RED) words.to_edge(UP) self.add(words) self.wait() class SimpleLinearTransformationScene(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "transposed_matrix" : [[2, 1], [1, 2]] } def construct(self): self.setup() self.wait() self.apply_transposed_matrix(self.transposed_matrix) self.wait() class SimpleNonlinearTransformationScene(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "words" : "Not linear: some lines get curved" } def construct(self): self.setup() self.wait() self.apply_nonlinear_transformation(self.func) words = OldTexText(self.words) words.to_corner(UP+RIGHT) words.set_color(RED) words.add_background_rectangle() self.play(Write(words)) self.wait() def func(self, point): return curvy_squish(point) class MovingOrigin(SimpleNonlinearTransformationScene): CONFIG = { "words" : "Not linear: Origin moves" } def setup(self): LinearTransformationScene.setup(self) dot = Dot(ORIGIN, color = RED) self.add_transformable_mobject(dot) def func(self, point): matrix_transform = self.get_matrix_transformation([[2, 0], [1, 1]]) return matrix_transform(point) + 2*UP+3*LEFT class SneakyNonlinearTransformation(SimpleNonlinearTransformationScene): CONFIG = { "words" : "\\dots" } def func(self, point): x, y, z = point new_x = np.sign(x)*FRAME_X_RADIUS*smooth(abs(x) / FRAME_X_RADIUS) new_y = np.sign(y)*FRAME_Y_RADIUS*smooth(abs(y) / FRAME_Y_RADIUS) return [new_x, new_y, 0] class SneakyNonlinearTransformationExplained(SneakyNonlinearTransformation): CONFIG = { "words" : "Not linear: diagonal lines get curved" } def setup(self): LinearTransformationScene.setup(self) diag = Line( FRAME_Y_RADIUS*LEFT+FRAME_Y_RADIUS*DOWN, FRAME_Y_RADIUS*RIGHT + FRAME_Y_RADIUS*UP ) diag.insert_n_curves(20) diag.make_smooth() diag.set_color(YELLOW) self.play(ShowCreation(diag)) self.add_transformable_mobject(diag) class GridLinesRemainParallel(SimpleLinearTransformationScene): CONFIG = { "transposed_matrix" : [ [3, 0], [1, 2] ] } def construct(self): SimpleLinearTransformationScene.construct(self) text = OldTexText([ "Grid lines remain", "parallel", "and", "evenly spaced", ]) glr, p, a, es = text.split() p.set_color(YELLOW) es.set_color(GREEN) text.add_background_rectangle() text.shift(-text.get_bottom()) self.play(Write(text)) self.wait() class Rotation(SimpleLinearTransformationScene): CONFIG = { "angle" : np.pi/3, } def construct(self): self.transposed_matrix = [ [np.cos(self.angle), np.sin(self.angle)], [-np.sin(self.angle), np.cos(self.angle)] ] SimpleLinearTransformationScene.construct(self) class YetAnotherLinearTransformation(SimpleLinearTransformationScene): CONFIG = { "transposed_matrix" : [ [-1, 1], [3, 2], ] } def construct(self): SimpleLinearTransformationScene.construct(self) words = OldTexText(""" How would you describe one of these numerically? """ ) words.add_background_rectangle() words.to_edge(UP) words.set_color(GREEN) formula = OldTex([ matrix_to_tex_string(["x_\\text{in}", "y_\\text{in}"]), "\\rightarrow ???? \\rightarrow", matrix_to_tex_string(["x_\\text{out}", "y_{\\text{out}}"]) ]) formula.add_background_rectangle() self.play(Write(words)) self.wait() self.play( ApplyMethod(self.plane.fade, 0.7), ApplyMethod(self.background_plane.fade, 0.7), Write(formula, run_time = 2), Animation(words) ) self.wait() class FollowIHatJHat(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False } def construct(self): self.setup() i_hat = self.add_vector([1, 0], color = X_COLOR) i_label = self.label_vector( i_hat, "\\hat{\\imath}", color = X_COLOR, label_scale_factor = 1 ) j_hat = self.add_vector([0, 1], color = Y_COLOR) j_label = self.label_vector( j_hat, "\\hat{\\jmath}", color = Y_COLOR, label_scale_factor = 1 ) self.wait() self.play(*list(map(FadeOut, [i_label, j_label]))) self.apply_transposed_matrix([[-1, 1], [-2, -1]]) self.wait() class TrackBasisVectorsExample(LinearTransformationScene): CONFIG = { "transposed_matrix" : [[1, -2], [3, 0]], "v_coords" : [-1, 2], "v_coord_strings" : ["-1", "2"], "result_coords_string" : """ = \\left[ \\begin{array}{c} -1(1) + 2(3) \\\\ -1(-2) + 2(0) \\end{arary}\\right] = \\left[ \\begin{array}{c} 5 \\\\ 2 \\end{arary}\\right] """ } def construct(self): self.setup() self.label_bases() self.introduce_vector() self.wait() self.apply_transposed_matrix(self.transposed_matrix) self.wait() self.show_linear_combination(clean_up = False) self.write_linear_map_rule() self.show_basis_vector_coords() def label_bases(self): triplets = [ (self.i_hat, "\\hat{\\imath}", X_COLOR), (self.j_hat, "\\hat{\\jmath}", Y_COLOR), ] label_mobs = [] for vect, label, color in triplets: label_mobs.append(self.add_transformable_label( vect, label, "\\text{Transformed } " + label, color = color, direction = "right", )) self.i_label, self.j_label = label_mobs def introduce_vector(self): v = self.add_vector(self.v_coords) coords = Matrix(self.v_coords) coords.scale(VECTOR_LABEL_SCALE_FACTOR) coords.next_to(v.get_end(), np.sign(self.v_coords[0])*RIGHT) self.play(Write(coords, run_time = 1)) v_def = self.get_v_definition() pre_def = VMobject( VectorizedPoint(coords.get_center()), VMobject(*[ mob.copy() for mob in coords.get_mob_matrix().flatten() ]) ) self.play(Transform( pre_def, v_def, run_time = 2, lag_ratio = 0 )) self.remove(pre_def) self.add_foreground_mobject(v_def) self.wait() self.show_linear_combination() self.remove(coords) def show_linear_combination(self, clean_up = True): i_hat_copy, j_hat_copy = [m.copy() for m in (self.i_hat, self.j_hat)] self.play(ApplyFunction( lambda m : m.scale(self.v_coords[0]).fade(0.3), i_hat_copy )) self.play(ApplyFunction( lambda m : m.scale(self.v_coords[1]).fade(0.3), j_hat_copy )) self.play(ApplyMethod(j_hat_copy.shift, i_hat_copy.get_end())) self.wait(2) if clean_up: self.play(FadeOut(i_hat_copy), FadeOut(j_hat_copy)) def get_v_definition(self): v_def = OldTex([ "\\vec{\\textbf{v}}", " = %s"%self.v_coord_strings[0], "\\hat{\\imath}", "+%s"%self.v_coord_strings[1], "\\hat{\\jmath}", ]) v, equals_neg_1, i_hat, plus_2, j_hat = v_def.split() v.set_color(YELLOW) i_hat.set_color(X_COLOR) j_hat.set_color(Y_COLOR) v_def.add_background_rectangle() v_def.to_corner(UP + LEFT) self.v_def = v_def return v_def def write_linear_map_rule(self): rule = OldTex([ "\\text{Transformed } \\vec{\\textbf{v}}", " = %s"%self.v_coord_strings[0], "(\\text{Transformed }\\hat{\\imath})", "+%s"%self.v_coord_strings[1], "(\\text{Transformed } \\hat{\\jmath})", ]) v, equals_neg_1, i_hat, plus_2, j_hat = rule.split() v.set_color(YELLOW) i_hat.set_color(X_COLOR) j_hat.set_color(Y_COLOR) rule.scale(0.85) rule.next_to(self.v_def, DOWN, buff = 0.2) rule.to_edge(LEFT) rule.add_background_rectangle() self.play(Write(rule, run_time = 2)) self.wait() self.linear_map_rule = rule def show_basis_vector_coords(self): i_coords = matrix_to_mobject(self.transposed_matrix[0]) j_coords = matrix_to_mobject(self.transposed_matrix[1]) i_coords.set_color(X_COLOR) j_coords.set_color(Y_COLOR) for coords in i_coords, j_coords: coords.add_background_rectangle() coords.scale(0.7) i_coords.next_to(self.i_hat.get_end(), RIGHT) j_coords.next_to(self.j_hat.get_end(), RIGHT) calculation = OldTex([ " = %s"%self.v_coord_strings[0], matrix_to_tex_string(self.transposed_matrix[0]), "+%s"%self.v_coord_strings[1], matrix_to_tex_string(self.transposed_matrix[1]), ]) equals_neg_1, i_hat, plus_2, j_hat = calculation.split() i_hat.set_color(X_COLOR) j_hat.set_color(Y_COLOR) calculation.scale(0.8) calculation.next_to(self.linear_map_rule, DOWN) calculation.to_edge(LEFT) calculation.add_background_rectangle() result = OldTex(self.result_coords_string) result.scale(0.8) result.add_background_rectangle() result.next_to(calculation, DOWN) result.to_edge(LEFT) self.play(Write(i_coords, run_time = 1)) self.wait() self.play(Write(j_coords, run_time = 1)) self.wait() self.play(Write(calculation)) self.wait() self.play(Write(result)) self.wait() class WatchManyVectorsMove(TransformManyVectors): def construct(self): self.setup() vectors = VMobject(*[ Vector([x, y]) for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5) for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5) ]) vectors.set_submobject_colors_by_gradient(PINK, YELLOW) dots = self.vectors_to_dots(vectors) self.play(ShowCreation(dots, lag_ratio = 0.5)) self.play(Transform( dots, vectors, lag_ratio = 0.5, run_time = 2 )) self.remove(dots) for v in vectors.split(): self.add_vector(v, animate = False) self.apply_transposed_matrix([[1, -2], [3, 0]]) self.wait() self.play( ApplyMethod(self.plane.fade), FadeOut(vectors), Animation(self.i_hat), Animation(self.j_hat), ) self.wait() class NowWithoutWatching(Scene): def construct(self): text = OldTexText("Now without watching...") text.to_edge(UP) randy = Randolph(mode = "pondering") self.add(randy) self.play(Write(text, run_time = 1)) self.play(ApplyMethod(randy.blink)) self.wait(2) class DeduceResultWithGeneralCoordinates(Scene): def construct(self): i_hat_to = OldTex("\\hat{\\imath} \\rightarrow") j_hat_to = OldTex("\\hat{\\jmath} \\rightarrow") i_coords = Matrix([1, -2]) j_coords = Matrix([3, 0]) i_coords.next_to(i_hat_to, RIGHT, buff = 0.1) j_coords.next_to(j_hat_to, RIGHT, buff = 0.1) i_group = VMobject(i_hat_to, i_coords) j_group = VMobject(j_hat_to, j_coords) i_group.set_color(X_COLOR) j_group.set_color(Y_COLOR) i_group.next_to(ORIGIN, LEFT, buff = 1).to_edge(UP) j_group.next_to(ORIGIN, RIGHT, buff = 1).to_edge(UP) vect = Matrix(["x", "y"]) x, y = vect.get_mob_matrix().flatten() VMobject(x, y).set_color(YELLOW) rto = OldTex("\\rightarrow") equals = OldTex("=") plus = OldTex("+") row1 = OldTex("1x + 3y") row2 = OldTex("-2x + 0y") VMobject( row1.split()[0], row2.split()[0], row2.split()[1] ).set_color(X_COLOR) VMobject( row1.split()[1], row1.split()[4], row2.split()[2], row2.split()[5] ).set_color(YELLOW) VMobject( row1.split()[3], row2.split()[4] ).set_color(Y_COLOR) result = Matrix([row1, row2]) result.show() vect_group = VMobject( vect, rto, x.copy(), i_coords.copy(), plus, y.copy(), j_coords.copy(), equals, result ) vect_group.arrange(RIGHT, buff = 0.1) self.add(i_group, j_group) for mob in vect_group.split(): self.play(Write(mob)) self.wait() class MatrixVectorMultiplication(LinearTransformationScene): CONFIG = { "abstract" : False } def construct(self): self.setup() matrix = self.build_to_matrix() self.label_matrix(matrix) vector, formula = self.multiply_by_vector(matrix) self.reposition_matrix_and_vector(matrix, vector, formula) def build_to_matrix(self): self.wait() self.apply_transposed_matrix([[3, -2], [2, 1]]) self.wait() i_coords = vector_coordinate_label(self.i_hat) j_coords = vector_coordinate_label(self.j_hat) if self.abstract: new_i_coords = Matrix(["a", "c"]) new_j_coords = Matrix(["b", "d"]) new_i_coords.move_to(i_coords) new_j_coords.move_to(j_coords) i_coords = new_i_coords j_coords = new_j_coords i_coords.set_color(X_COLOR) j_coords.set_color(Y_COLOR) i_brackets = i_coords.get_brackets() j_brackets = j_coords.get_brackets() for coords in i_coords, j_coords: rect = BackgroundRectangle(coords) coords.rect = rect abstract_matrix = np.append( i_coords.get_mob_matrix(), j_coords.get_mob_matrix(), axis = 1 ) concrete_matrix = Matrix( copy.deepcopy(abstract_matrix), add_background_rectangles_to_entries = True ) concrete_matrix.to_edge(UP) if self.abstract: m = concrete_matrix.get_mob_matrix()[1, 0] m.shift(m.get_height()*DOWN/2) matrix_brackets = concrete_matrix.get_brackets() self.play(ShowCreation(i_coords.rect), Write(i_coords)) self.play(ShowCreation(j_coords.rect), Write(j_coords)) self.wait() self.remove(i_coords.rect, j_coords.rect) self.play( Transform( VMobject(*abstract_matrix.flatten()), VMobject(*concrete_matrix.get_mob_matrix().flatten()), ), Transform(i_brackets, matrix_brackets), Transform(j_brackets, matrix_brackets), run_time = 2, lag_ratio = 0 ) everything = VMobject(*self.get_mobjects()) self.play( FadeOut(everything), Animation(concrete_matrix) ) return concrete_matrix def label_matrix(self, matrix): title = OldTexText("``2x2 Matrix''") title.to_edge(UP+LEFT) col_circles = [] for i, color in enumerate([X_COLOR, Y_COLOR]): col = VMobject(*matrix.get_mob_matrix()[:,i]) col_circle = Circle(color = color) col_circle.stretch_to_fit_width(matrix.get_width()/3) col_circle.stretch_to_fit_height(matrix.get_height()) col_circle.move_to(col) col_circles.append(col_circle) i_circle, j_circle = col_circles i_message = OldTexText("Where $\\hat{\\imath}$ lands") j_message = OldTexText("Where $\\hat{\\jmath}$ lands") i_message.set_color(X_COLOR) j_message.set_color(Y_COLOR) i_message.next_to(i_circle, DOWN, buff = 2, aligned_edge = RIGHT) j_message.next_to(j_circle, DOWN, buff = 2, aligned_edge = LEFT) i_arrow = Arrow(i_message, i_circle) j_arrow = Arrow(j_message, j_circle) self.play(Write(title)) self.wait() self.play(ShowCreation(i_circle)) self.play( Write(i_message, run_time = 1.5), ShowCreation(i_arrow), ) self.wait() self.play(ShowCreation(j_circle)) self.play( Write(j_message, run_time = 1.5), ShowCreation(j_arrow) ) self.wait() self.play(*list(map(FadeOut, [ i_message, i_circle, i_arrow, j_message, j_circle, j_arrow ]))) def multiply_by_vector(self, matrix): vector = Matrix(["x", "y"]) if self.abstract else Matrix([5, 7]) vector.set_height(matrix.get_height()) vector.next_to(matrix, buff = 2) brace = Brace(vector, DOWN) words = OldTexText("Any ol' vector") words.next_to(brace, DOWN) self.play( Write(vector), GrowFromCenter(brace), Write(words), run_time = 1 ) self.wait() v1, v2 = vector.get_mob_matrix().flatten() mob_matrix = matrix.copy().get_mob_matrix() col1 = Matrix(mob_matrix[:,0]) col2 = Matrix(mob_matrix[:,1]) formula = VMobject( v1.copy(), col1, OldTex("+"), v2.copy(), col2 ) formula.arrange(RIGHT, buff = 0.1) formula.center() formula_start = VMobject( v1.copy(), VMobject(*matrix.copy().get_mob_matrix()[:,0]), VectorizedPoint(), v2.copy(), VMobject(*matrix.copy().get_mob_matrix()[:,1]), ) self.play( FadeOut(brace), FadeOut(words), Transform( formula_start, formula, run_time = 2, lag_ratio = 0 ) ) self.wait() self.show_result(formula) return vector, formula def show_result(self, formula): if self.abstract: row1 = ["a", "x", "+", "b", "y"] row2 = ["c", "x", "+", "d", "y"] else: row1 = ["3", "(5)", "+", "2", "(7)"] row2 = ["-2", "(5)", "+", "1", "(7)"] row1 = VMobject(*list(map(Tex, row1))) row2 = VMobject(*list(map(Tex, row2))) for row in row1, row2: row.arrange(RIGHT, buff = 0.1) final_sum = Matrix([row1, row2]) row1, row2 = final_sum.get_mob_matrix().flatten() row1.split()[0].set_color(X_COLOR) row2.split()[0].set_color(X_COLOR) row1.split()[3].set_color(Y_COLOR) row2.split()[3].set_color(Y_COLOR) equals = OldTex("=") equals.next_to(formula, RIGHT) final_sum.next_to(equals, RIGHT) self.play( Write(equals, run_time = 1), Write(final_sum) ) self.wait() def reposition_matrix_and_vector(self, matrix, vector, formula): start_state = VMobject(matrix, vector) end_state = start_state.copy() end_state.arrange(RIGHT, buff = 0.1) equals = OldTex("=") equals.next_to(formula, LEFT) end_state.next_to(equals, LEFT) brace = Brace(formula, DOWN) brace_words = OldTexText("Where all the intuition is") brace_words.next_to(brace, DOWN) brace_words.set_color(YELLOW) self.play( Transform( start_state, end_state, lag_ratio = 0 ), Write(equals, run_time = 1) ) self.wait() self.play( FadeIn(brace), FadeIn(brace_words), lag_ratio = 0.5 ) self.wait() class MatrixVectorMultiplicationAbstract(MatrixVectorMultiplication): CONFIG = { "abstract" : True, } class ColumnsToBasisVectors(LinearTransformationScene): CONFIG = { "t_matrix" : [[3, 1], [1, 2]] } def construct(self): self.setup() vector_coords = [-1, 2] vector = self.move_matrix_columns(self.t_matrix, vector_coords) self.scale_and_add(vector, vector_coords) self.wait(3) def move_matrix_columns(self, transposed_matrix, vector_coords = None): matrix = np.array(transposed_matrix).transpose() matrix_mob = Matrix(matrix) matrix_mob.to_corner(UP+LEFT) matrix_mob.add_background_to_entries() col1 = VMobject(*matrix_mob.get_mob_matrix()[:,0]) col1.set_color(X_COLOR) col2 = VMobject(*matrix_mob.get_mob_matrix()[:,1]) col2.set_color(Y_COLOR) matrix_brackets = matrix_mob.get_brackets() matrix_background = BackgroundRectangle(matrix_mob) self.add_foreground_mobject(matrix_background, matrix_mob) if vector_coords is not None: vector = Matrix(vector_coords) VMobject(*vector.get_mob_matrix().flatten()).set_color(YELLOW) vector.set_height(matrix_mob.get_height()) vector.next_to(matrix_mob, RIGHT) vector_background = BackgroundRectangle(vector) self.add_foreground_mobject(vector_background, vector) new_i = Vector(matrix[:,0]) new_j = Vector(matrix[:,1]) i_label = vector_coordinate_label(new_i).set_color(X_COLOR) j_label = vector_coordinate_label(new_j).set_color(Y_COLOR) i_coords = VMobject(*i_label.get_mob_matrix().flatten()) j_coords = VMobject(*j_label.get_mob_matrix().flatten()) i_brackets = i_label.get_brackets() j_brackets = j_label.get_brackets() i_label_background = BackgroundRectangle(i_label) j_label_background = BackgroundRectangle(j_label) i_coords_start = VMobject( matrix_background.copy(), col1.copy(), matrix_brackets.copy() ) i_coords_end = VMobject( i_label_background, i_coords, i_brackets, ) j_coords_start = VMobject( matrix_background.copy(), col2.copy(), matrix_brackets.copy() ) j_coords_end = VMobject( j_label_background, j_coords, j_brackets, ) transform_matrix1 = np.array(matrix) transform_matrix1[:,1] = [0, 1] transform_matrix2 = np.dot( matrix, np.linalg.inv(transform_matrix1) ) self.wait() self.apply_transposed_matrix( transform_matrix1.transpose(), added_anims = [Transform(i_coords_start, i_coords_end)], path_arc = np.pi/2, ) self.add_foreground_mobject(i_coords_start) self.apply_transposed_matrix( transform_matrix2.transpose(), added_anims = [Transform(j_coords_start, j_coords_end) ], path_arc = np.pi/2, ) self.add_foreground_mobject(j_coords_start) self.wait() self.matrix = VGroup(matrix_background, matrix_mob) self.i_coords = i_coords_start self.j_coords = j_coords_start return vector if vector_coords is not None else None def scale_and_add(self, vector, vector_coords): i_copy = self.i_hat.copy() j_copy = self.j_hat.copy() i_target = i_copy.copy().scale(vector_coords[0]).fade(0.3) j_target = j_copy.copy().scale(vector_coords[1]).fade(0.3) coord1, coord2 = vector.copy().get_mob_matrix().flatten() coord1.add_background_rectangle() coord2.add_background_rectangle() self.play( Transform(i_copy, i_target), ApplyMethod(coord1.next_to, i_target.get_center(), DOWN) ) self.play( Transform(j_copy, j_target), ApplyMethod(coord2.next_to, j_target.get_center(), LEFT) ) j_copy.add(coord2) self.play(ApplyMethod(j_copy.shift, i_copy.get_end())) self.add_vector(j_copy.get_end()) self.wait() class Describe90DegreeRotation(LinearTransformationScene): CONFIG = { "transposed_matrix" : [[0, 1], [-1, 0]], "title" : "$90^\\circ$ rotation counterclockwise", } def construct(self): self.setup() title = OldTexText(self.title) title.shift(DOWN) title.add_background_rectangle() matrix = Matrix(np.array(self.transposed_matrix).transpose()) matrix.to_corner(UP+LEFT) matrix_background = BackgroundRectangle(matrix) col1 = VMobject(*matrix.get_mob_matrix()[:,0]) col2 = VMobject(*matrix.get_mob_matrix()[:,1]) col1.set_color(X_COLOR) col2.set_color(Y_COLOR) self.add_foreground_mobject(matrix_background, matrix.get_brackets()) self.wait() self.apply_transposed_matrix(self.transposed_matrix) self.wait() self.play(Write(title)) self.add_foreground_mobject(title) for vect, color, col in [(self.i_hat, X_COLOR, col1), (self.j_hat, Y_COLOR, col2)]: label = vector_coordinate_label(vect) label.set_color(color) background = BackgroundRectangle(label) coords = VMobject(*label.get_mob_matrix().flatten()) brackets = label.get_brackets() self.play(ShowCreation(background), Write(label)) self.wait() self.play( ShowCreation(background, rate_func = lambda t : smooth(1-t)), ApplyMethod(coords.replace, col), FadeOut(brackets), ) self.remove(label) self.add_foreground_mobject(coords) self.wait() self.show_vector(matrix) def show_vector(self, matrix): vector = Matrix(["x", "y"]) VMobject(*vector.get_mob_matrix().flatten()).set_color(YELLOW) vector.set_height(matrix.get_height()) vector.next_to(matrix, RIGHT) v_background = BackgroundRectangle(vector) matrix = np.array(self.transposed_matrix).transpose() inv = np.linalg.inv(matrix) self.apply_transposed_matrix(inv.transpose(), run_time = 0.5) self.add_vector([1, 2]) self.wait() self.apply_transposed_matrix(self.transposed_matrix) self.play(ShowCreation(v_background), Write(vector)) self.wait() class DescribeShear(Describe90DegreeRotation): CONFIG = { "transposed_matrix" : [[1, 0], [1, 1]], "title" : "``Shear''", } class OtherWayAround(Scene): def construct(self): self.play(Write("What about the other way around?")) self.wait(2) class DeduceTransformationFromMatrix(ColumnsToBasisVectors): def construct(self): self.setup() self.move_matrix_columns([[1, 2], [3, 1]]) class LinearlyDependentColumns(ColumnsToBasisVectors): def construct(self): self.setup() title = OldTexText("Linearly dependent") subtitle = OldTexText("columns") title.add_background_rectangle() subtitle.add_background_rectangle() subtitle.next_to(title, DOWN) title.add(subtitle) title.shift(UP).to_edge(LEFT) title.set_color(YELLOW) self.add_foreground_mobject(title) self.move_matrix_columns([[2, 1], [-2, -1]]) class NextVideo(Scene): def construct(self): title = OldTexText("Next video: Matrix multiplication as composition") title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class FinalSlide(Scene): def construct(self): text = OldTexText(""" \\footnotesize Technically, the definition of ``linear'' is as follows: A transformation L is linear if it satisfies these two properties: \\begin{align*} L(\\vec{\\textbf{v}} + \\vec{\\textbf{w}}) &= L(\\vec{\\textbf{v}}) + L(\\vec{\\textbf{w}}) & & \\text{``Additivity''} \\\\ L(c\\vec{\\textbf{v}}) &= c L(\\vec{\\textbf{v}}) & & \\text{``Scaling''} \\end{align*} I'll talk about these properties later on, but I'm a big believer in first understanding things visually. Once you do, it becomes much more intuitive why these two properties make sense. So for now, you can feel fine thinking of linear transformations as those which keep grid lines parallel and evenly spaced (and which fix the origin in place), since this visual definition is actually equivalent to the two properties above. """, enforce_new_line_structure = False) text.set_height(FRAME_HEIGHT - 2) text.to_edge(UP) self.add(text) self.wait() ### Old scenes class RotateIHat(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False } def construct(self): self.setup() i_hat, j_hat = self.get_basis_vectors() i_label, j_label = self.get_basis_vector_labels() self.add_vector(i_hat) self.play(Write(i_label, run_time = 1)) self.wait() self.play(FadeOut(i_label)) self.apply_transposed_matrix([[0, 1], [-1, 0]]) self.wait() self.play(Write(j_label, run_time = 1)) self.wait() class TransformationsAreFunctions(Scene): def construct(self): title = OldTexText([ """Linear transformations are a special kind of""", "function" ]) title_start, function = title.split() function.set_color(YELLOW) title.to_edge(UP) equation = OldTex([ "L", "(", "\\vec{\\textbf{v}}", ") = ", "\\vec{\\textbf{w}}", ]) L, lp, _input, equals, _output = equation.split() L.set_color(YELLOW) _input.set_color(MAROON_C) _output.set_color(BLUE) equation.scale(2) equation.next_to(title, DOWN, buff = 1) starting_vector = OldTexText("Starting vector") starting_vector.shift(DOWN+3*LEFT) starting_vector.set_color(MAROON_C) ending_vector = OldTexText("The vector where it lands") ending_vector.shift(DOWN).to_edge(RIGHT) ending_vector.set_color(BLUE) func_arrow = Arrow(function.get_bottom(), L.get_top(), color = YELLOW) start_arrow = Arrow(starting_vector.get_top(), _input.get_bottom(), color = MAROON_C) ending_arrow = Arrow(ending_vector, _output, color = BLUE) self.add(title) self.play( Write(equation), ShowCreation(func_arrow) ) for v, a in [(starting_vector, start_arrow), (ending_vector, ending_arrow)]: self.play(Write(v), ShowCreation(a), run_time = 1) self.wait() class UsedToThinkinfOfFunctionsAsGraphs(VectorScene): def construct(self): self.show_graph() self.show_inputs_and_output() def show_graph(self): axes = self.add_axes() graph = FunctionGraph(lambda x : x**2, x_min = -2, x_max = 2) name = OldTex("f(x) = x^2") name.next_to(graph, RIGHT).to_edge(UP) point = Dot(graph.point_from_proportion(0.8)) point_label = OldTex("(x, x^2)") point_label.next_to(point, DOWN+RIGHT, buff = 0.1) self.play(ShowCreation(graph)) self.play(Write(name, run_time = 1)) self.play( ShowCreation(point), Write(point_label), run_time = 1 ) self.wait() def collapse_func(p): return np.dot(p, [RIGHT, RIGHT, OUT]) + (FRAME_Y_RADIUS+1)*DOWN self.play( ApplyPointwiseFunction( collapse_func, axes, lag_ratio = 0, ), ApplyPointwiseFunction(collapse_func, graph), ApplyMethod(point.shift, 10*DOWN), ApplyMethod(point_label.shift, 10*DOWN), ApplyFunction(lambda m : m.center().to_edge(UP), name), run_time = 1 ) self.clear() self.add(name) self.wait() def show_inputs_and_output(self): numbers = list(range(-3, 4)) inputs = VMobject(*list(map(Tex, list(map(str, numbers))))) inputs.arrange(DOWN, buff = 0.5, aligned_edge = RIGHT) arrows = VMobject(*[ Arrow(LEFT, RIGHT).next_to(mob) for mob in inputs.split() ]) outputs = VMobject(*[ OldTex(str(num**2)).next_to(arrow) for num, arrow in zip(numbers, arrows.split()) ]) everyone = VMobject(inputs, arrows, outputs) everyone.center().to_edge(UP, buff = 1.5) self.play(Write(inputs, run_time = 1)) self.wait() self.play( Transform(inputs.copy(), outputs), ShowCreation(arrows) ) self.wait() class TryingToVisualizeFourDimensions(Scene): def construct(self): randy = Randolph().to_corner() bubble = randy.get_bubble() formula = OldTex(""" L\\left(\\left[ \\begin{array}{c} x \\\\ y \\end{array} \\right]\\right) = \\left[ \\begin{array}{c} 2x + y \\\\ x + 2y \\end{array} \\right] """) formula.next_to(randy, RIGHT) formula.split()[3].set_color(X_COLOR) formula.split()[4].set_color(Y_COLOR) VMobject(*formula.split()[9:9+4]).set_color(MAROON_C) VMobject(*formula.split()[13:13+4]).set_color(BLUE) thought = OldTexText(""" Do I imagine plotting $(x, y, 2x+y, x+2y)$??? """) thought.split()[-17].set_color(X_COLOR) thought.split()[-15].set_color(Y_COLOR) VMobject(*thought.split()[-13:-13+4]).set_color(MAROON_C) VMobject(*thought.split()[-8:-8+4]).set_color(BLUE) bubble.position_mobject_inside(thought) thought.shift(0.2*UP) self.add(randy) self.play( ApplyMethod(randy.look, DOWN+RIGHT), Write(formula) ) self.play( ApplyMethod(randy.change_mode, "pondering"), ShowCreation(bubble), Write(thought) ) self.play(Blink(randy)) self.wait() self.remove(thought) bubble.make_green_screen() self.wait() self.play(Blink(randy)) self.play(ApplyMethod(randy.change_mode, "confused")) self.wait() self.play(Blink(randy)) self.wait() class ForgetAboutGraphs(Scene): def construct(self): self.play(Write("You must unlearn graphs")) self.wait() class ThinkAboutFunctionAsMovingVector(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "leave_ghost_vectors" : True, } def construct(self): self.setup() vector = self.add_vector([2, 1]) label = self.add_transformable_label(vector, "v") self.wait() self.apply_transposed_matrix([[1, 1], [-3, 1]]) self.wait() class PrepareForFormalDefinition(TeacherStudentsScene): def construct(self): self.setup() self.teacher_says("Get ready for a formal definition!") self.wait(3) bubble = self.student_thinks("") bubble.make_green_screen() self.wait(3) class AdditivityProperty(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "give_title" : True, "transposed_matrix" : [[2, 0], [1, 1]], "nonlinear_transformation" : None, "vector_v" : [2, 1], "vector_w" : [1, -2], "proclaim_sum" : True, } def construct(self): self.setup() added_anims = [] if self.give_title: title = OldTexText(""" First fundamental property of linear transformations """) title.to_edge(UP) title.set_color(YELLOW) title.add_background_rectangle() self.play(Write(title)) added_anims.append(Animation(title)) self.wait() self.play(ApplyMethod(self.plane.fade), *added_anims) v, w = self.draw_all_vectors() self.apply_transformation(added_anims) self.show_final_sum(v, w) def draw_all_vectors(self): v = self.add_vector(self.vector_v, color = MAROON_C) v_label = self.add_transformable_label(v, "v") w = self.add_vector(self.vector_w, color = GREEN) w_label = self.add_transformable_label(w, "w") new_w = w.copy().fade(0.4) self.play(ApplyMethod(new_w.shift, v.get_end())) sum_vect = self.add_vector(new_w.get_end(), color = PINK) sum_label = self.add_transformable_label( sum_vect, "%s + %s"%(v_label.expression, w_label.expression), rotate = True ) self.play(FadeOut(new_w)) return v, w def apply_transformation(self, added_anims): if self.nonlinear_transformation: self.apply_nonlinear_transformation(self.nonlinear_transformation) else: self.apply_transposed_matrix( self.transposed_matrix, added_anims = added_anims ) self.wait() def show_final_sum(self, v, w): new_w = w.copy() self.play(ApplyMethod(new_w.shift, v.get_end())) self.wait() if self.proclaim_sum: text = OldTexText("It's still their sum!") text.add_background_rectangle() text.move_to(new_w.get_end(), aligned_edge = -new_w.get_end()) text.shift_onto_screen() self.play(Write(text)) self.wait() class NonlinearLacksAdditivity(AdditivityProperty): CONFIG = { "give_title" : False, "nonlinear_transformation" : curvy_squish, "vector_v" : [3, 2], "vector_w" : [2, -3], "proclaim_sum" : False, } class SecondAdditivityExample(AdditivityProperty): CONFIG = { "give_title" : False, "transposed_matrix" : [[1, -1], [2, 1]], "vector_v" : [-2, 2], "vector_w" : [3, 0], "proclaim_sum" : False, } class ShowGridCreation(Scene): def construct(self): plane = NumberPlane() coords = VMobject(*plane.get_coordinate_labels()) self.play(ShowCreation(plane, run_time = 3)) self.play(Write(coords, run_time = 3)) self.wait() class MoveAroundAllVectors(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "focus_on_one_vector" : False, "include_background_plane" : False, } def construct(self): self.setup() vectors = VMobject(*[ Vector([x, y]) for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5) for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5) ]) vectors.set_submobject_colors_by_gradient(PINK, YELLOW) dots = self.get_dots(vectors) self.wait() self.play(ShowCreation(dots)) self.wait() self.play(Transform(dots, vectors)) self.wait() self.remove(dots) if self.focus_on_one_vector: vector = vectors.split()[43]#yeah, great coding Grant self.remove(vectors) self.add_vector(vector) self.play(*[ FadeOut(v) for v in vectors.split() if v is not vector ]) self.wait() self.add(vector.copy().set_color(GREY_D)) else: for vector in vectors.split(): self.add_vector(vector, animate = False) self.apply_transposed_matrix([[3, 0], [1, 2]]) self.wait() dots = self.get_dots(vectors) self.play(Transform(vectors, dots)) self.wait() def get_dots(self, vectors): return VMobject(*[ Dot(v.get_end(), color = v.get_color()) for v in vectors.split() ]) class ReasonForThinkingAboutArrows(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False } def construct(self): self.setup() self.plane.fade() v_color = MAROON_C w_color = BLUE v = self.add_vector([3, 1], color = v_color) w = self.add_vector([1, -2], color = w_color) vectors = VMobject(v, w) self.to_and_from_dots(vectors) self.scale_and_add(vectors) self.apply_transposed_matrix([[1, 1], [-1, 0]]) self.scale_and_add(vectors) def to_and_from_dots(self, vectors): vectors_copy = vectors.copy() dots = VMobject(*[ Dot(v.get_end(), color = v.get_color()) for v in vectors.split() ]) self.wait() self.play(Transform(vectors, dots)) self.wait() self.play(Transform(vectors, vectors_copy)) self.wait() def scale_and_add(self, vectors): vectors_copy = vectors.copy() v, w, = vectors.split() scaled_v = Vector(0.5*v.get_end(), color = v.get_color()) scaled_w = Vector(1.5*w.get_end(), color = w.get_color()) shifted_w = scaled_w.copy().shift(scaled_v.get_end()) sum_vect = Vector(shifted_w.get_end(), color = PINK) self.play( ApplyMethod(v.scale, 0.5), ApplyMethod(w.scale, 1.5), ) self.play(ApplyMethod(w.shift, v.get_end())) self.add_vector(sum_vect) self.wait() self.play(Transform( vectors, vectors_copy, lag_ratio = 0 )) self.wait() class LinearTransformationWithOneVector(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, } def construct(self): self.setup() v = self.add_vector([3, 1]) self.vector_to_coords(v) self.apply_transposed_matrix([[-1, 1], [-2, -1]]) self.vector_to_coords(v)
videos_3b1b/_2016/eola/chapter9.py
from manim_imports_ext import * from _2016.eola.chapter1 import plane_wave_homotopy V_COLOR = YELLOW class Jennifer(PiCreature): CONFIG = { "color" : PINK, "start_corner" : DOWN+LEFT, } class You(PiCreature): CONFIG = { "color" : BLUE_E, "start_corner" : DOWN+RIGHT, "flip_at_start" : True, } def get_small_bubble(pi_creature, height = 4, width = 3): pi_center_x = pi_creature.get_center()[0] kwargs = { "height" : 4, "bubble_center_adjustment_factor" : 1./6, } bubble = ThoughtBubble(**kwargs) bubble.stretch_to_fit_width(3)##Canonical width bubble.rotate(np.pi/4) bubble.stretch_to_fit_width(width) bubble.stretch_to_fit_height(height) if pi_center_x < 0: bubble.flip() bubble.next_to(pi_creature, UP, buff = MED_SMALL_BUFF) bubble.shift_onto_screen() bubble.set_fill(BLACK, opacity = 0.8) return bubble class OpeningQuote(Scene): def construct(self): words = OldTexText( "\\centering ``Mathematics is the art of giving the \\\\", "same name ", "to ", "different things", ".''", arg_separator = " " ) words.set_color_by_tex("same name ", BLUE) words.set_color_by_tex("different things", MAROON_B) # words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) author = OldTexText("-Henri Poincar\\'e.") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(2) self.play(Write(author, run_time = 3)) self.wait(2) class LinearCombinationScene(LinearTransformationScene): CONFIG = { "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_X_RADIUS, "y_radius" : FRAME_Y_RADIUS, "secondary_line_ratio" : 1 }, } def setup(self): LinearTransformationScene.setup(self) self.i_hat.label = self.get_vector_label( self.i_hat, "\\hat{\\imath}", "right" ) self.j_hat.label = self.get_vector_label( self.j_hat, "\\hat{\\jmath}", "left" ) def show_linear_combination(self, numerical_coords, basis_vectors, coord_mobs, revert_to_original = True, show_sum_vect = False, sum_vect_color = V_COLOR, ): for basis in basis_vectors: if not hasattr(basis, "label"): basis.label = VectorizedPoint() direction = np.round(rotate_vector( basis.get_end(), np.pi/2 )) basis.label.next_to(basis.get_center(), direction) basis.save_state() basis.label.save_state() if coord_mobs is None: coord_mobs = list(map(Tex, list(map(str, numerical_coords)))) VGroup(*coord_mobs).set_fill(opacity = 0) for coord, basis in zip(coord_mobs, basis_vectors): coord.next_to(basis.label, LEFT) for coord, basis, scalar in zip(coord_mobs, basis_vectors, numerical_coords): basis.target = basis.copy().scale(scalar) basis.label.target = basis.label.copy() coord.target = coord.copy() new_label = VGroup(coord.target, basis.label.target) new_label.arrange(aligned_edge = DOWN) new_label.move_to( basis.label, aligned_edge = basis.get_center()-basis.label.get_center() ) new_label.shift( basis.target.get_center() - basis.get_center() ) coord.target.next_to(basis.label.target, LEFT) coord.target.set_fill(basis.get_color(), opacity = 1) self.play(*list(map(MoveToTarget, [ coord, basis, basis.label ]))) self.wait() self.play(*[ ApplyMethod(m.shift, basis_vectors[0].get_end()) for m in self.get_mobjects_from_last_animation() ]) if show_sum_vect: sum_vect = Vector( basis_vectors[1].get_end(), color = sum_vect_color ) self.play(ShowCreation(sum_vect)) self.wait(2) if revert_to_original: self.play(*it.chain( [basis.restore for basis in basis_vectors], [basis.label.restore for basis in basis_vectors], [FadeOut(coord) for coord in coord_mobs], [FadeOut(sum_vect) for x in [1] if show_sum_vect], )) if show_sum_vect: return sum_vect class RemindOfCoordinates(LinearCombinationScene): CONFIG = { "vector_coords" : [3, 2] } def construct(self): self.remove(self.i_hat, self.j_hat) v = self.add_vector(self.vector_coords, color = V_COLOR) coords = self.write_vector_coordinates(v) self.show_standard_coord_meaning(*coords.get_entries().copy()) self.show_abstract_scalar_idea(*coords.get_entries().copy()) self.scale_basis_vectors(*coords.get_entries().copy()) self.list_implicit_assumptions(*coords.get_entries()) def show_standard_coord_meaning(self, x_coord, y_coord): x, y = self.vector_coords x_line = Line(ORIGIN, x*RIGHT, color = GREEN) y_line = Line(ORIGIN, y*UP, color = RED) y_line.shift(x_line.get_end()) for line, coord, direction in (x_line, x_coord, DOWN), (y_line, y_coord, LEFT): self.play( coord.set_color, line.get_color(), coord.next_to, line.get_center(), direction, ShowCreation(line), ) self.wait() self.wait() self.play(*list(map(FadeOut, [x_coord, y_coord, x_line, y_line]))) def show_abstract_scalar_idea(self, x_coord, y_coord): x_shift, y_shift = 4*LEFT, 4*RIGHT to_save = x_coord, y_coord, self.i_hat, self.j_hat for mob in to_save: mob.save_state() everything = VGroup(*self.get_mobjects()) words = OldTexText("Think of coordinates \\\\ as", "scalars") words.set_color_by_tex("scalars", YELLOW) words.to_edge(UP) x, y = self.vector_coords scaled_i = self.i_hat.copy().scale(x) scaled_j = self.j_hat.copy().scale(y) VGroup(self.i_hat, scaled_i).shift(x_shift) VGroup(self.j_hat, scaled_j).shift(y_shift) self.play( FadeOut(everything), x_coord.scale, 1.5, x_coord.move_to, x_shift + 3*UP, y_coord.scale, 1.5, y_coord.move_to, y_shift + 3*UP, Write(words) ) self.play(*list(map(FadeIn, [self.i_hat, self.j_hat]))) self.wait() self.play(Transform(self.i_hat, scaled_i)) self.play(Transform(self.j_hat, scaled_j)) self.wait() self.play( FadeOut(words), FadeIn(everything), *[mob.restore for mob in to_save] ) self.wait() def scale_basis_vectors(self, x_coord, y_coord): self.play(*list(map(Write, [self.i_hat.label, self.j_hat.label]))) self.show_linear_combination( self.vector_coords, basis_vectors = [self.i_hat, self.j_hat], coord_mobs = [x_coord, y_coord] ) def list_implicit_assumptions(self, x_coord, y_coord): everything = VGroup(*self.get_mobjects()) title = OldTexText("Implicit assumptions") h_line = Line(title.get_left(), title.get_right()) h_line.set_color(YELLOW) h_line.next_to(title, DOWN) title.add(h_line) ass1 = OldTexText("-First coordinate") ass1 = VGroup(ass1, self.i_hat.copy()) ass1.arrange(buff = MED_SMALL_BUFF) ass2 = OldTexText("-Second coordinate") ass2 = VGroup(ass2, self.j_hat.copy()) ass2.arrange(buff = MED_SMALL_BUFF) ass3 = OldTexText("-Unit of distance") group = VGroup(title, ass1, ass2, ass3) group.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) group.to_corner(UP+LEFT) # VGroup(*group[1:]).shift(0.5*DOWN) for words in group: words.add_to_back(BackgroundRectangle(words)) self.play(Write(title)) self.wait() self.play( Write(ass1), ApplyFunction( lambda m : m.rotate(np.pi/6).set_color(X_COLOR), x_coord, rate_func = wiggle ) ) self.wait() self.play( Write(ass2), ApplyFunction( lambda m : m.rotate(np.pi/6).set_color(Y_COLOR), y_coord, rate_func = wiggle ) ) self.wait() self.play(Write(ass3)) self.wait(2) keepers = VGroup(*[ self.i_hat, self.j_hat, self.i_hat.label, self.j_hat.label ]) self.play( FadeOut(everything), Animation(keepers.copy()), Animation(group) ) self.wait() class NameCoordinateSystem(Scene): def construct(self): vector = Vector([3, 2]) coords = Matrix([3, 2]) arrow = OldTex("\\Rightarrow") vector.next_to(arrow, RIGHT, buff = 0) coords.next_to(arrow, LEFT, buff = MED_LARGE_BUFF) group = VGroup(coords, arrow, vector) group.shift(2*UP) coordinate_system = OldTexText("``Coordinate system''") coordinate_system.next_to(arrow, UP, buff = LARGE_BUFF) i_hat, j_hat = Vector([1, 0]), Vector([0, 1]) i_hat.set_color(X_COLOR) j_hat.set_color(Y_COLOR) i_label = OldTex("\\hat{\\imath}") i_label.set_color(X_COLOR) i_label.next_to(i_hat, DOWN) j_label = OldTex("\\hat{\\jmath}") j_label.set_color(Y_COLOR) j_label.next_to(j_hat, LEFT) basis_group = VGroup(i_hat, j_hat, i_label, j_label) basis_group.shift(DOWN) basis_words = OldTexText("``Basis vectors''") basis_words.shift(basis_group.get_bottom()[1]*UP+MED_SMALL_BUFF*DOWN) self.play(Write(coords)) self.play(Write(arrow), ShowCreation(vector)) self.wait() self.play(Write(coordinate_system)) self.wait(2) self.play(Write(basis_group)) self.play(Write(basis_words)) self.wait() class WhatAboutOtherBasis(TeacherStudentsScene): def construct(self): self.teacher_says(""" \\centering What if we used different basis vectors """) self.random_blink() self.play_student_changes("pondering") self.random_blink(2) class JenniferScene(LinearCombinationScene): CONFIG = { "b1_coords" : [2, 1], "b2_coords" : [-1, 1], "foreground_plane_kwargs" : { "x_radius" : FRAME_X_RADIUS, "y_radius" : FRAME_X_RADIUS, }, } def setup(self): LinearCombinationScene.setup(self) self.remove(self.plane, self.i_hat, self.j_hat) self.jenny = Jennifer() self.you = You() self.b1 = Vector(self.b1_coords, color = X_COLOR) self.b2 = Vector(self.b2_coords, color = Y_COLOR) for i, vect in enumerate([self.b1, self.b2]): vect.label = OldTex("\\vec{\\textbf{b}}_%d"%(i+1)) vect.label.scale(0.7) vect.label.add_background_rectangle() vect.label.set_color(vect.get_color()) self.b1.label.next_to( self.b1.get_end()*0.4, UP+LEFT, SMALL_BUFF/2 ) self.b2.label.next_to( self.b2.get_end(), DOWN+LEFT, buff = SMALL_BUFF ) self.basis_vectors = VGroup( self.b1, self.b2, self.b1.label, self.b2.label ) transform = self.get_matrix_transformation(self.cob_matrix().T) self.jenny_plane = self.plane.copy() self.jenny_plane.apply_function(transform) def cob_matrix(self): return np.array([self.b1_coords, self.b2_coords]).T def inv_cob_matrix(self): return np.linalg.inv(self.cob_matrix()) class IntroduceJennifer(JenniferScene): CONFIG = { "v_coords" : [3, 2] } def construct(self): for plane in self.plane, self.jenny_plane: plane.fade() self.introduce_jenny() self.add_basis_vectors() self.show_v_from_both_perspectives() self.how_we_label_her_basis() def introduce_jenny(self): jenny = self.jenny name = OldTexText("Jennifer") name.next_to(jenny, UP) name.shift_onto_screen() self.add(jenny) self.play( jenny.change_mode, "wave_1", jenny.look, OUT, Write(name) ) self.play( jenny.change_mode, "happy", jenny.look, UP+RIGHT, FadeOut(name) ) self.wait() def add_basis_vectors(self): words = OldTexText("Alternate basis vectors") words.shift(2.5*UP) self.play(Write(words, run_time = 2)) for vect in self.b1, self.b2: self.play( ShowCreation(vect), Write(vect.label) ) self.wait() self.play(FadeOut(words)) def show_v_from_both_perspectives(self): v = Vector(self.v_coords) jenny = self.jenny you = self.you you.coords = Matrix([3, 2]) jenny.coords = Matrix(["(5/3)", "(1/3)"]) for pi in you, jenny: pi.bubble = get_small_bubble(pi) pi.bubble.set_fill(BLACK, opacity = 0.7) pi.bubble.add_content(pi.coords) jenny.coords.scale(0.7) new_coords = [-1, 2] new_coords_mob = Matrix(new_coords) new_coords_mob.set_height(jenny.coords.get_height()) new_coords_mob.move_to(jenny.coords) for coords in you.coords, jenny.coords, new_coords_mob: for entry in coords.get_entries(): entry.add_background_rectangle() self.play(ShowCreation(v)) self.wait() self.play(*it.chain( list(map(FadeIn, [ self.plane, self.i_hat, self.j_hat, self.i_hat.label, self.j_hat.label, you ])), list(map(Animation, [jenny, v])), list(map(FadeOut, self.basis_vectors)), )) self.play( ShowCreation(you.bubble), Write(you.coords) ) self.play(you.change_mode, "speaking") self.show_linear_combination( self.v_coords, basis_vectors = [self.i_hat, self.j_hat], coord_mobs = you.coords.get_entries().copy(), ) self.play(*it.chain( list(map(FadeOut, [ self.plane, self.i_hat, self.j_hat, self.i_hat.label, self.j_hat.label, you.bubble, you.coords ])), list(map(FadeIn, [self.jenny_plane, self.basis_vectors])), list(map(Animation, [v, you, jenny])), )) self.play( ShowCreation(jenny.bubble), Write(jenny.coords), jenny.change_mode, "speaking", ) self.play(you.change_mode, "erm") self.show_linear_combination( np.dot(self.inv_cob_matrix(), self.v_coords), basis_vectors = [self.b1, self.b2], coord_mobs = jenny.coords.get_entries().copy(), ) self.play( FadeOut(v), jenny.change_mode, "plain" ) self.play( Transform(jenny.coords, new_coords_mob), Blink(jenny), ) self.hacked_show_linear_combination( new_coords, basis_vectors = [self.b1, self.b2], coord_mobs = jenny.coords.get_entries().copy(), show_sum_vect = True, ) def hacked_show_linear_combination( self, numerical_coords, basis_vectors, coord_mobs = None, show_sum_vect = False, sum_vect_color = V_COLOR, ): for coord, basis, scalar in zip(coord_mobs, basis_vectors, numerical_coords): basis.save_state() basis.label.save_state() basis.target = basis.copy().scale(scalar) basis.label.target = basis.label.copy() coord.target = coord.copy() new_label = VGroup(coord.target, basis.label.target) new_label.arrange(aligned_edge = DOWN) new_label.move_to( basis.label, aligned_edge = basis.get_center()-basis.label.get_center() ) new_label.shift( basis.target.get_center() - basis.get_center() ) coord.target.next_to(basis.label.target, LEFT) coord.target.set_fill(basis.get_color(), opacity = 1) self.play(*list(map(MoveToTarget, [ coord, basis, basis.label ]))) self.wait() self.play(*[ ApplyMethod(m.shift, basis_vectors[0].get_end()) for m in self.get_mobjects_from_last_animation() ]) if show_sum_vect: sum_vect = Vector( basis_vectors[1].get_end(), color = sum_vect_color ) self.play(ShowCreation(sum_vect)) self.wait(2) b1, b2 = basis_vectors self.jenny_plane.save_state() self.jenny.bubble.save_state() self.jenny.coords.target = self.jenny.coords.copy() self.you.bubble.add_content(self.jenny.coords.target) x, y = numerical_coords b1.target = self.i_hat.copy().scale(x) b2.target = self.j_hat.copy().scale(y) b2.target.shift(b1.target.get_end()) new_label1 = VGroup(coord_mobs[0], b1.label) new_label2 = VGroup(coord_mobs[1], b2.label) new_label1.target = new_label1.copy().next_to(b1.target, DOWN) new_label2.target = new_label2.copy().next_to(b2.target, LEFT) i_sym = OldTex("\\hat{\\imath}").add_background_rectangle() j_sym = OldTex("\\hat{\\jmath}").add_background_rectangle() i_sym.set_color(X_COLOR).move_to(new_label1.target[1], aligned_edge = LEFT) j_sym.set_color(Y_COLOR).move_to(new_label2.target[1], aligned_edge = LEFT) Transform(new_label1.target[1], i_sym).update(1) Transform(new_label2.target[1], j_sym).update(1) sum_vect.target = Vector(numerical_coords) self.play( Transform(self.jenny_plane, self.plane), Transform(self.jenny.bubble, self.you.bubble), self.you.change_mode, "speaking", self.jenny.change_mode, "erm", *list(map(MoveToTarget, [ self.jenny.coords, b1, b2, new_label1, new_label2, sum_vect ])) ) self.play(Blink(self.you)) self.wait() self.play(*it.chain( list(map(FadeOut, [ self.jenny.bubble, self.jenny.coords, coord_mobs, sum_vect ])), [ ApplyMethod(pi.change_mode, "plain") for pi in (self.jenny, self.you) ], [mob.restore for mob in (b1, b2, b1.label, b2.label)] )) self.jenny.bubble.restore() def how_we_label_her_basis(self): you, jenny = self.you, self.jenny b1_coords = Matrix(self.b1_coords) b2_coords = Matrix(self.b2_coords) for coords in b1_coords, b2_coords: coords.add_to_back(BackgroundRectangle(coords)) coords.scale(0.7) coords.add_to_back(BackgroundRectangle(coords)) you.bubble.add_content(coords) coords.mover = coords.copy() self.play(jenny.change_mode, "erm") self.play( ShowCreation(you.bubble), Write(b1_coords), you.change_mode, "speaking" ) self.play( b1_coords.mover.next_to, self.b1.get_end(), RIGHT, b1_coords.mover.set_color, X_COLOR ) self.play(Blink(you)) self.wait() self.play(Transform(b1_coords, b2_coords)) self.play( b2_coords.mover.next_to, self.b2.get_end(), LEFT, b2_coords.mover.set_color, Y_COLOR ) self.play(Blink(jenny)) for coords, array in (b1_coords, [1, 0]), (b2_coords, [0, 1]): mover = coords.mover array_mob = Matrix(array) array_mob.set_color(mover.get_color()) array_mob.set_height(mover.get_height()) array_mob.move_to(mover) array_mob.add_to_back(BackgroundRectangle(array_mob)) mover.target = array_mob self.play( self.jenny_plane.restore, FadeOut(self.you.bubble), FadeOut(b1_coords), self.jenny.change_mode, "speaking", self.you.change_mode, "confused", *list(map(Animation, [ self.basis_vectors, b1_coords.mover, b2_coords.mover, ])) ) self.play(MoveToTarget(b1_coords.mover)) self.play(MoveToTarget(b2_coords.mover)) self.play(Blink(self.jenny)) class SpeakingDifferentLanguages(JenniferScene): def construct(self): jenny, you = self.jenny, self.you title = OldTexText("Different languages") title.to_edge(UP) vector = Vector([3, 2]) vector.center().shift(DOWN) you.coords = Matrix([3, 2]) you.text = OldTexText("Looks to be") jenny.coords = Matrix(["5/3", "1/3"]) jenny.text = OldTexText("Non, c'est") for pi in jenny, you: pi.bubble = pi.get_bubble(SpeechBubble, width = 4.5, height = 3.5) if pi is you: pi.bubble.shift(MED_SMALL_BUFF*RIGHT) else: pi.coords.scale(0.8) pi.bubble.shift(MED_SMALL_BUFF*LEFT) pi.coords.next_to(pi.text, buff = MED_SMALL_BUFF) pi.coords.add(pi.text) pi.bubble.add_content(pi.coords) self.add(you, jenny) self.play(Write(title)) self.play( ShowCreation(vector), you.look_at, vector, jenny.look_at, vector, ) for pi in you, jenny: self.play( pi.change_mode, "speaking" if pi is you else "sassy", ShowCreation(pi.bubble), Write(pi.coords) ) self.play(Blink(pi)) self.wait() class ShowGrid(LinearTransformationScene): CONFIG = { "include_background_plane" : False, } def construct(self): self.remove(self.i_hat, self.j_hat) self.wait() self.plane.prepare_for_nonlinear_transform() self.plane.save_state() self.play(Homotopy(plane_wave_homotopy, self.plane)) self.play(self.plane.restore) for vect in self.i_hat, self.j_hat: self.play(ShowCreation(vect)) self.wait() class GridIsAConstruct(TeacherStudentsScene): def construct(self): self.teacher_says(""" \\centering The grid is just a construct """) self.play_student_changes(*["pondering"]*3) self.random_blink(2) class SpaceHasNoGrid(LinearTransformationScene): CONFIG = { "include_background_plane" : False } def construct(self): words = OldTexText("Space has no grid") words.to_edge(UP) self.play( Write(words), FadeOut(self.plane), *list(map(Animation, [self.i_hat, self.j_hat])) ) self.wait() class JennysGrid(JenniferScene): def construct(self): self.add(self.jenny) self.jenny.shift(3*RIGHT) bubble = self.jenny.get_bubble(SpeechBubble, width = 4) bubble.flip() bubble.set_fill(BLACK, opacity = 0.8) bubble.to_edge(LEFT) bubble.write(""" This grid is also just a construct """) coords = [1.5, -3] coords_mob = Matrix(coords) coords_mob.add_background_to_entries() bubble.position_mobject_inside(coords_mob) for vect in self.b1, self.b2: self.play( ShowCreation(vect), Write(vect.label) ) self.wait() self.play( ShowCreation( self.jenny_plane, run_time = 3, lag_ratio = 0.5 ), self.jenny.change_mode, "speaking", self.jenny.look_at, ORIGIN, ShowCreation(bubble), Write(bubble.content), Animation(self.basis_vectors) ) self.play(Blink(self.jenny)) self.play( FadeOut(bubble.content), FadeIn(coords_mob) ) self.show_linear_combination( numerical_coords = coords, basis_vectors = [self.b1, self.b2], coord_mobs = coords_mob.get_entries().copy(), show_sum_vect = True ) class ShowOriginOfGrid(JenniferScene): def construct(self): for plane in self.plane, self.jenny_plane: plane.fade(0.3) self.add(self.jenny_plane) self.jenny_plane.save_state() origin_word = OldTexText("Origin") origin_word.shift(2*RIGHT+2.5*UP) origin_word.add_background_rectangle() arrow = Arrow(origin_word, ORIGIN, color = RED) origin_dot = Dot(ORIGIN, radius = 0.1, color = RED) coords = Matrix([0, 0]) coords.add_to_back(BackgroundRectangle(coords)) coords.next_to(ORIGIN, DOWN+LEFT) vector = Vector([3, -2], color = PINK) self.play( Write(origin_word), ShowCreation(arrow) ) self.play(ShowCreation(origin_dot)) self.wait() self.play( Transform(self.jenny_plane, self.plane), *list(map(Animation, [origin_word, origin_dot, arrow])) ) self.wait() self.play(Write(coords)) self.wait() self.play(FadeIn(vector)) self.wait() self.play(Transform(vector, Mobject.scale(vector.copy(), 0))) self.wait() self.play( self.jenny_plane.restore, *list(map(Animation, [origin_word, origin_dot, arrow, coords])) ) for vect in self.b1, self.b2: self.play( ShowCreation(vect), Write(vect.label) ) self.wait() class AskAboutTranslation(TeacherStudentsScene): def construct(self): self.student_says( "\\centering How do you translate \\\\ between coordinate systems?", target_mode = "raise_right_hand" ) self.random_blink(3) class TranslateFromJenny(JenniferScene): CONFIG = { "coords" : [-1, 2] } def construct(self): self.add_players() self.ask_question() self.establish_coordinates() self.perform_arithmetic() def add_players(self): for plane in self.jenny_plane, self.plane: plane.fade() self.add( self.jenny_plane, self.jenny, self.you, self.basis_vectors ) self.jenny.coords = Matrix(self.coords) self.you.coords = Matrix(["?", "?"]) self.you.coords.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR) for pi in self.jenny, self.you: pi.bubble = get_small_bubble(pi) pi.bubble.set_fill(BLACK, opacity = 0.8) pi.coords.scale(0.8) pi.coords.add_background_to_entries() pi.bubble.add_content(pi.coords) def ask_question(self): self.play( self.jenny.change_mode, "pondering", ShowCreation(self.jenny.bubble), Write(self.jenny.coords) ) coord_mobs = self.jenny.coords.get_entries().copy() self.basis_vectors_copy = self.basis_vectors.copy() self.basis_vectors_copy.fade(0.3) self.add(self.basis_vectors_copy, self.basis_vectors) sum_vect = self.show_linear_combination( numerical_coords = self.coords, basis_vectors = [self.b1, self.b2], coord_mobs = coord_mobs, revert_to_original = False, show_sum_vect = True, ) self.wait() everything = self.get_mobjects() for submob in self.jenny_plane.get_family(): everything.remove(submob) self.play( Transform(self.jenny_plane, self.plane), *list(map(Animation, everything)) ) self.play( self.you.change_mode, "confused", ShowCreation(self.you.bubble), Write(self.you.coords) ) self.wait() def establish_coordinates(self): b1, b2 = self.basis_vectors_copy[:2] b1_coords = Matrix(self.b1_coords).set_color(X_COLOR) b2_coords = Matrix(self.b2_coords).set_color(Y_COLOR) for coords in b1_coords, b2_coords: coords.scale(0.7) coords.add_to_back(BackgroundRectangle(coords)) b1_coords.next_to(b1.get_end(), RIGHT) b2_coords.next_to(b2.get_end(), UP) for coords in b1_coords, b2_coords: self.play(Write(coords)) self.b1_coords_mob, self.b2_coords_mob = b1_coords, b2_coords def perform_arithmetic(self): jenny_x, jenny_y = self.jenny.coords.get_entries().copy() equals, plus, equals2 = syms = list(map(Tex, list("=+="))) result = Matrix([-4, 1]) result.set_height(self.you.coords.get_height()) for mob in syms + [self.you.coords, self.jenny.coords, result]: mob.add_to_back(BackgroundRectangle(mob)) movers = [ self.you.coords, equals, jenny_x, self.b1_coords_mob, plus, jenny_y, self.b2_coords_mob, equals2, result ] for mover in movers: mover.target = mover.copy() mover_targets = VGroup(*[mover.target for mover in movers]) mover_targets.arrange() mover_targets.to_edge(UP) for mob in syms + [result]: mob.move_to(mob.target) mob.set_fill(BLACK, opacity = 0) mover_sets = [ [jenny_x, self.b1_coords_mob], [plus, jenny_y, self.b2_coords_mob], [self.you.coords, equals], ] for mover_set in mover_sets: self.play(*list(map(MoveToTarget, mover_set))) self.wait() self.play( MoveToTarget(equals2), Transform(self.b1_coords_mob.copy(), result.target), Transform(self.b2_coords_mob.copy(), result.target), ) self.remove(*self.get_mobjects_from_last_animation()) result = result.target self.add(equals2, result) self.wait() result_copy = result.copy() self.you.bubble.add_content(result_copy) self.play( self.you.change_mode, "hooray", Transform(result.copy(), result_copy) ) self.play(Blink(self.you)) self.wait() matrix = Matrix(np.array([self.b1_coords, self.b2_coords]).T) matrix.set_column_colors(X_COLOR, Y_COLOR) self.jenny.coords.target = self.jenny.coords.copy() self.jenny.coords.target.next_to(equals, LEFT) matrix.set_height(self.jenny.coords.get_height()) matrix.next_to(self.jenny.coords.target, LEFT) matrix.add_to_back(BackgroundRectangle(matrix)) self.play( FadeOut(self.jenny.bubble), FadeOut(self.you.coords), self.jenny.change_mode, "plain", MoveToTarget(self.jenny.coords), FadeIn(matrix) ) self.wait() class WatchChapter3(TeacherStudentsScene): def construct(self): self.teacher_says(""" You've all watched chapter 3, right? """) self.random_blink() self.play( self.get_students()[0].look, LEFT, self.get_students()[1].change_mode, "happy", self.get_students()[2].change_mode, "happy", ) self.random_blink(2) class TalkThroughChangeOfBasisMatrix(JenniferScene): def construct(self): self.add(self.plane, self.jenny, self.you) self.plane.fade() self.jenny_plane.fade() for pi in self.jenny, self.you: pi.bubble = get_small_bubble(pi) matrix = Matrix(np.array([self.b1_coords, self.b2_coords]).T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(ORIGIN, RIGHT, buff = MED_SMALL_BUFF).to_edge(UP) b1_coords = Matrix(self.b1_coords) b1_coords.set_color(X_COLOR) b1_coords.next_to(self.b1.get_end(), RIGHT) b2_coords = Matrix(self.b2_coords) b2_coords.set_color(Y_COLOR) b2_coords.next_to(self.b2.get_end(), UP) for coords in b1_coords, b2_coords: coords.scale(0.7) basis_coords_pair = VGroup( Matrix([1, 0]).set_color(X_COLOR).scale(0.7), OldTex(","), Matrix([0, 1]).set_color(Y_COLOR).scale(0.7), ) basis_coords_pair.arrange(aligned_edge = DOWN) self.you.bubble.add_content(basis_coords_pair) t_matrix1 = np.array([self.b1_coords, [0, 1]]) t_matrix2 = np.dot( self.cob_matrix(), np.linalg.inv(t_matrix1.T) ).T for mob in matrix, b1_coords, b2_coords: mob.rect = BackgroundRectangle(mob) mob.add_to_back(mob.rect) self.play(Write(matrix)) for vect in self.i_hat, self.j_hat: self.play( ShowCreation(vect), Write(vect.label) ) self.play( self.you.change_mode, "pondering", ShowCreation(self.you.bubble), Write(basis_coords_pair) ) self.play(Blink(self.you)) self.wait() self.add_foreground_mobject( self.jenny, self.you, self.you.bubble, basis_coords_pair, matrix ) matrix_copy = matrix.copy() matrix_copy.rect.set_fill(opacity = 0) self.apply_transposed_matrix( t_matrix1, added_anims = [ Transform(self.i_hat, self.b1), Transform(self.i_hat.label, self.b1.label), Transform(matrix_copy.rect, b1_coords.rect), Transform( matrix_copy.get_brackets(), b1_coords.get_brackets(), ), Transform( VGroup(*matrix_copy.get_mob_matrix()[:,0]), b1_coords.get_entries() ), ] ) self.remove(matrix_copy) self.add_foreground_mobject(b1_coords) matrix_copy = matrix.copy() matrix_copy.rect.set_fill(opacity = 0) self.apply_transposed_matrix( t_matrix2, added_anims = [ Transform(self.j_hat, self.b2), Transform(self.j_hat.label, self.b2.label), Transform(matrix_copy.rect, b2_coords.rect), Transform( matrix_copy.get_brackets(), b2_coords.get_brackets(), ), Transform( VGroup(*matrix_copy.get_mob_matrix()[:,1]), b2_coords.get_entries() ), ] ) self.remove(matrix_copy) self.add_foreground_mobject(b2_coords) basis_coords_pair.target = basis_coords_pair.copy() self.jenny.bubble.add_content(basis_coords_pair.target) self.wait() self.play( FadeOut(b1_coords), FadeOut(b2_coords), self.jenny.change_mode, "speaking", Transform(self.you.bubble, self.jenny.bubble), MoveToTarget(basis_coords_pair), ) class ChangeOfBasisExample(JenniferScene): CONFIG = { "v_coords" : [-1, 2] } def construct(self): self.add( self.plane, self.i_hat, self.j_hat, self.i_hat.label, self.j_hat.label, ) self.j_hat.label.next_to(self.j_hat, RIGHT) v = self.add_vector(self.v_coords) v_coords = Matrix(self.v_coords) v_coords.scale(0.8) v_coords.add_to_back(BackgroundRectangle(v_coords)) v_coords.to_corner(UP+LEFT) v_coords.add_background_to_entries() for pi in self.you, self.jenny: pi.change_mode("pondering") pi.bubble = get_small_bubble(pi) pi.bubble.add_content(v_coords.copy()) pi.add(pi.bubble, pi.bubble.content) start_words = OldTexText("How", "we", "think of") start_words.add_background_rectangle() start_group = VGroup(start_words, v_coords) start_group.arrange(buff = MED_SMALL_BUFF) start_group.next_to(self.you, LEFT, buff = 0) start_group.to_edge(UP) end_words = OldTexText("How", "Jennifer", "thinks of") end_words.add_background_rectangle() end_words.move_to(start_words, aligned_edge = RIGHT) self.play( Write(start_group), FadeIn(self.you), ) self.add_foreground_mobject(start_group, self.you) self.show_linear_combination( numerical_coords = self.v_coords, basis_vectors = [self.i_hat, self.j_hat], coord_mobs = v_coords.get_entries().copy(), ) self.play(*list(map(FadeOut, [self.i_hat.label, self.j_hat.label]))) self.apply_transposed_matrix(self.cob_matrix().T) VGroup(self.i_hat, self.j_hat).fade() self.add(self.b1, self.b2) self.play( Transform(start_words, end_words), Transform(self.you, self.jenny), *list(map(Write, [self.b1.label, self.b2.label])) ) self.play(Blink(self.you)) self.show_linear_combination( numerical_coords = self.v_coords, basis_vectors = [self.b1, self.b2], coord_mobs = v_coords.get_entries().copy(), ) class FeelsBackwards(Scene): def construct(self): matrix = Matrix(np.array([ JenniferScene.CONFIG["b1_coords"], JenniferScene.CONFIG["b2_coords"], ]).T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.shift(UP) top_arrow = Arrow(matrix.get_left(), matrix.get_right()) bottom_arrow = top_arrow.copy().rotate(np.pi) top_arrow.next_to(matrix, UP, buff = LARGE_BUFF) bottom_arrow.next_to(matrix, DOWN, buff = LARGE_BUFF) top_arrow.set_color(BLUE) jenny_grid = OldTexText("Jennifer's grid").set_color(BLUE) our_grid = OldTexText("Our grid").set_color(BLUE) jenny_language = OldTexText("Jennifer's language") our_language = OldTexText("Our language") our_grid.next_to(top_arrow, LEFT) jenny_grid.next_to(top_arrow, RIGHT) jenny_language.next_to(bottom_arrow, RIGHT) our_language.next_to(bottom_arrow, LEFT) self.add(matrix) self.play(Write(our_grid)) self.play( ShowCreation(top_arrow), Write(jenny_grid) ) self.wait() self.play(Write(jenny_language)) self.play( ShowCreation(bottom_arrow), Write(our_language) ) self.wait() ##Swap things inverse_word = OldTexText("Inverse") inverse_word.next_to(matrix, LEFT, buff = MED_SMALL_BUFF) inverse_exponent = OldTex("-1") inverse_exponent.next_to(matrix.get_corner(UP+RIGHT), RIGHT) self.play(*list(map(Write, [inverse_word, inverse_exponent]))) self.play( Swap(jenny_grid, our_grid), top_arrow.scale, 0.8, top_arrow.shift, 0.8*RIGHT, top_arrow.set_color, BLUE, ) self.play( Swap(jenny_language, our_language), bottom_arrow.scale, 0.8, bottom_arrow.shift, 0.8*RIGHT ) self.wait() class AskAboutOtherWayAround(TeacherStudentsScene): def construct(self): self.student_says(""" What about the other way around? """) self.random_blink(3) class RecallInverse(JenniferScene): def construct(self): numerical_t_matrix = np.array([self.b1_coords, self.b2_coords]) matrix = Matrix(numerical_t_matrix.T) matrix.add_to_back(BackgroundRectangle(matrix)) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.to_corner(UP+LEFT, buff = MED_LARGE_BUFF) # matrix.shift(MED_SMALL_BUFF*DOWN) inverse_exponent = OldTex("-1") inverse_exponent.next_to(matrix.get_corner(UP+RIGHT), RIGHT) inverse_exponent.add_background_rectangle() brace = Brace(VGroup(matrix, inverse_exponent)) inverse_word = brace.get_text("Inverse") inverse_word.add_background_rectangle() equals = OldTex("=") equals.add_background_rectangle() inv_matrix = Matrix([ ["1/3", "1/3"], ["-1/3", "2/3"] ]) inv_matrix.set_height(matrix.get_height()) inv_matrix.add_to_back(BackgroundRectangle(inv_matrix)) equals.next_to(matrix, RIGHT, buff = 0.7) inv_matrix.next_to(equals, RIGHT, buff = MED_SMALL_BUFF) self.add_foreground_mobject(matrix) self.apply_transposed_matrix(numerical_t_matrix) self.play( GrowFromCenter(brace), Write(inverse_word), Write(inverse_exponent) ) self.add_foreground_mobject(*self.get_mobjects_from_last_animation()) self.wait() self.apply_inverse_transpose(numerical_t_matrix) self.wait() self.play( Write(equals), Transform(matrix.copy(), inv_matrix) ) self.remove(*self.get_mobjects_from_last_animation()) self.add_foreground_mobject(equals, inv_matrix) self.wait() for mob in self.plane, self.i_hat, self.j_hat: self.add(mob.copy().fade(0.7)) self.apply_transposed_matrix(numerical_t_matrix) self.play(FadeIn(self.jenny)) self.play(self.jenny.change_mode, "speaking") #Little hacky now inv_matrix.set_column_colors(X_COLOR) self.play(*[ ApplyMethod( mob.scale, 1.2, rate_func = there_and_back ) for mob in inv_matrix.get_mob_matrix()[:,0] ]) self.wait() inv_matrix.set_column_colors(X_COLOR, Y_COLOR) self.play(*[ ApplyMethod( mob.scale, 1.2, rate_func = there_and_back ) for mob in inv_matrix.get_mob_matrix()[:,1] ]) self.wait() class WorkOutInverseComputation(Scene): def construct(self): our_vector = Matrix([3, 2]) her_vector = Matrix(["5/3", "1/3"]) matrix = Matrix([["1/3", "1/3"], ["-1/3", "2/3"]]) our_vector.set_color(BLUE_D) her_vector.set_color(MAROON_B) equals = OldTex("=") equation = VGroup( matrix, our_vector, equals, her_vector ) for mob in equation: if isinstance(mob, Matrix): mob.set_height(2) equation.arrange() matrix_brace = Brace(matrix, UP) our_vector_brace = Brace(our_vector) her_vector_brace = Brace(her_vector, UP) matrix_text = matrix_brace.get_text(""" \\centering Inverse change of basis matrix """) our_text = our_vector_brace.get_text(""" \\centering Written in our language """) our_text.set_color(our_vector.get_color()) her_text = her_vector_brace.get_text(""" \\centering Same vector in her language """) her_text.set_color(her_vector.get_color()) for text in our_text, her_text: text.scale(0.7) self.add(our_vector) self.play( GrowFromCenter(our_vector_brace), Write(our_text) ) self.wait() self.play( FadeIn(matrix), GrowFromCenter(matrix_brace), Write(matrix_text) ) self.wait() self.play( Write(equals), Write(her_vector) ) self.play( GrowFromCenter(her_vector_brace), Write(her_text) ) self.wait() class SoThatsTranslation(TeacherStudentsScene): def construct(self): self.teacher_says("So that's translation") self.random_blink(3) class SummarizeTranslationProcess(Scene): def construct(self): self.define_matrix() self.show_translation() def define_matrix(self): matrix = Matrix([[2, -1], [1, 1]]) matrix.set_column_colors(X_COLOR, Y_COLOR) A, equals = list(map(Tex, list("A="))) equation = VGroup(A, equals, matrix) equation.arrange() equation.to_corner(UP+LEFT) equation.shift(RIGHT) words = OldTexText(""" Jennifer's basis vectors, written in our coordinates """) words.to_edge(LEFT) mob_matrix = matrix.get_mob_matrix() arrow1 = Arrow(words, mob_matrix[1, 0], color = X_COLOR) arrow2 = Arrow(words, mob_matrix[1, 1], color = Y_COLOR) self.add(A, equals, matrix) self.play( Write(words), *list(map(ShowCreation, [arrow1, arrow2])) ) self.A_copy = A.copy() def show_translation(self): our_vector = Matrix(["x_o", "y_o"]) her_vector = Matrix(["x_j", "y_j"]) for vector, color in (our_vector, BLUE_D), (her_vector, MAROON_B): # vector.set_height(1.5) vector.set_color(color) A = OldTex("A") A_inv = OldTex("A^{-1}") equals = OldTex("=") equation = VGroup(A, her_vector, equals, our_vector) equation.arrange() equation.to_edge(RIGHT) equation.shift(0.5*UP) A_inv.next_to(our_vector, LEFT) her_words = OldTexText("Vector in her coordinates") her_words.set_color(her_vector.get_color()) her_words.scale(0.8).to_corner(UP+RIGHT) her_arrow = Arrow( her_words, her_vector, color = her_vector.get_color() ) our_words = OldTexText("Same vector in\\\\ our coordinates") our_words.set_color(our_vector.get_color()) our_words.scale(0.8).to_edge(RIGHT).shift(2*DOWN) our_words.shift_onto_screen() our_arrow = Arrow( our_words.get_top(), our_vector.get_bottom(), color = our_vector.get_color() ) self.play( Write(equation), Transform(self.A_copy, A) ) self.remove(self.A_copy) self.play( Write(her_words), ShowCreation(her_arrow) ) self.play( Write(our_words), ShowCreation(our_arrow) ) self.wait(2) self.play( VGroup(her_vector, equals).next_to, A_inv, LEFT, her_arrow.rotate, -np.pi/6, her_arrow.shift, MED_SMALL_BUFF*LEFT, Transform(A, A_inv, path_arc = np.pi) ) self.wait() class VectorsAreNotTheOnlyOnes(TeacherStudentsScene): def construct(self): self.teacher_says(""" \\centering Vectors aren't the only thing with coordinates """) self.play_student_changes("pondering", "confused", "erm") self.random_blink(3) class Prerequisites(Scene): def construct(self): title = OldTexText("Prerequisites") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title, h_line) prereqs = list(map(TexText, [ "Linear transformations", "Matrix multiplication", ])) for direction, words in zip([LEFT, RIGHT], prereqs): rect = Rectangle(height = 9, width = 16) rect.set_height(3.5) rect.next_to(ORIGIN, direction, buff = MED_SMALL_BUFF) rect.set_color(BLUE) words.next_to(rect, UP, buff = MED_SMALL_BUFF) self.play( Write(words), ShowCreation(rect) ) self.wait() class RotationExample(LinearTransformationScene): CONFIG = { "t_matrix" : [[0, 1], [-1, 0]] } def construct(self): words = OldTexText("$90^\\circ$ rotation") words.scale(1.2) words.add_background_rectangle() words.to_edge(UP) matrix = Matrix(self.t_matrix.T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.rect = BackgroundRectangle(matrix) matrix.add_to_back(matrix.rect) matrix.next_to(words, DOWN) matrix.shift(2*RIGHT) self.play(Write(words)) self.add_foreground_mobject(words) self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() self.play( self.i_hat.rotate, np.pi/12, self.j_hat.rotate, -np.pi/12, rate_func = wiggle, run_time = 2 ) self.wait() i_coords, j_coords = coord_arrays = list(map(Matrix, self.t_matrix)) for coords, vect in zip(coord_arrays, [self.i_hat, self.j_hat]): coords.scale(0.7) coords.rect = BackgroundRectangle(coords) coords.add_to_back(coords.rect) coords.set_color(vect.get_color()) direction = UP if vect is self.j_hat else RIGHT coords.next_to(vect.get_end(), direction, buff = MED_SMALL_BUFF) self.play(Write(coords)) self.wait() self.play( Transform(i_coords.rect, matrix.rect), Transform(i_coords.get_brackets(), matrix.get_brackets()), Transform( i_coords.get_entries(), VGroup(*matrix.get_mob_matrix()[:, 0]) ), ) self.play( FadeOut(j_coords.rect), FadeOut(j_coords.get_brackets()), Transform( j_coords.get_entries(), VGroup(*matrix.get_mob_matrix()[:, 1]) ), ) self.wait() self.add_words(matrix) def add_words(self, matrix): follow_basis = OldTexText( "Follow", "our choice", "\\\\ of basis vectors" ) follow_basis.set_color_by_tex("our choice", YELLOW) follow_basis.add_background_rectangle() follow_basis.next_to( matrix, LEFT, buff = MED_SMALL_BUFF, ) record = OldTexText( "Record using \\\\", "our coordinates" ) record.set_color_by_tex("our coordinates", YELLOW) record.add_background_rectangle() record.next_to( matrix, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT ) self.play(Write(follow_basis)) self.wait() self.play(Write(record)) self.wait() class JennyWatchesRotation(JenniferScene): def construct(self): jenny = self.jenny self.add(self.jenny_plane.copy().fade()) self.add(self.jenny_plane) self.add(jenny) for vect in self.b1, self.b2: self.add_vector(vect) matrix = Matrix([["?", "?"], ["?", "?"]]) matrix.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR) jenny.bubble = get_small_bubble(jenny) jenny.bubble.add_content(matrix) matrix.scale(0.8) self.play( jenny.change_mode, "sassy", ShowCreation(jenny.bubble), Write(matrix) ) self.play(*it.chain( [ Rotate(mob, np.pi/2, run_time = 3) for mob in (self.jenny_plane, self.b1, self.b2) ], list(map(Animation, [jenny, jenny.bubble, matrix])) )) self.play(jenny.change_mode, "pondering") self.play(Blink(jenny)) self.wait() class AksAboutTranslatingColumns(TeacherStudentsScene): def construct(self): matrix = Matrix([[0, -1], [1, 0]]) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.scale(0.7) words = OldTexText("Translate columns of") matrix.next_to(words, DOWN) words.add(matrix) self.student_says(words, index = 0) self.random_blink(2) student = self.get_students()[0] bubble = get_small_bubble(student) bubble.set_fill(opacity = 0) matrix.target = matrix.copy() bubble.add_content(matrix.target) self.play( Transform(student.bubble, bubble), FadeOut(student.bubble.content), MoveToTarget(matrix.copy()), student.change_mode, "pondering", ) self.remove(student.bubble) student.bubble = None self.add(bubble, matrix.target) self.random_blink() words = OldTexText( "\\centering Those columns still \\\\ represent ", "our basis", ", not ", "hers", arg_separator = "" ) words.set_color_by_tex("our basis", BLUE) words.set_color_by_tex("hers", MAROON_B) self.teacher_says(words) self.play_student_changes("erm", "pondering", "pondering") self.random_blink() class HowToTranslateAMatrix(Scene): def construct(self): self.add_title() arrays = VGroup(*list(map(Matrix, [ [["1/3", "-2/3"], ["5/3", "-1/3"]], [-1, 2], [[2, -1], [1, 1]], [[0, -1], [1, 0]], [[2, -1], [1, 1]], ]))) result, her_vector, cob_matrix, transform, inv_cob = arrays neg_1 = OldTex("-1") neg_1.next_to(inv_cob.get_corner(UP+RIGHT), RIGHT) inv_cob.add(neg_1) arrays.arrange(LEFT) arrays.to_edge(LEFT, buff = LARGE_BUFF/2.) for array in arrays: array.brace = Brace(array) array.top_brace = Brace(VGroup(array, her_vector), UP) for array in cob_matrix, inv_cob: submobs = array.split() submobs.sort(key=lambda m: m.get_center()[0]) array.submobjects = submobs her_vector.set_color(MAROON_B) cob_matrix.set_color_by_gradient(BLUE, MAROON_B) transform.set_column_colors(X_COLOR, Y_COLOR) transform.get_brackets().set_color(BLUE) inv_cob.set_color_by_gradient(MAROON_B, BLUE) result.set_column_colors(X_COLOR, Y_COLOR) result.get_brackets().set_color(MAROON_B) final_top_brace = Brace(VGroup(cob_matrix, inv_cob), UP) brace_text_pairs = [ (her_vector.brace, ("Vector in \\\\", "Jennifer's language")), (her_vector.top_brace, ("",)), (cob_matrix.brace, ("Change of basis \\\\", "matrix")), (cob_matrix.top_brace, ("Same vector \\\\", "in", "our", "language")), (transform.brace, ("Transformation matrix \\\\", "in", "our", "language")), (transform.top_brace, ("Transformed vector \\\\", "in", "our", "language")), (inv_cob.brace, ("Inverse \\\\", "change of basis \\\\", "matrix")), (inv_cob.top_brace, ("Transformed vector \\\\", "in", "her", "language")), (final_top_brace, ("Transformation matrix \\\\", "in", "her", "language")) ] for brace, text_args in brace_text_pairs: text_args = list(text_args) text_args[0] = "\\centering " + text_args[0] text = OldTexText(*text_args) text.set_color_by_tex("our", BLUE) text.set_color_by_tex("her", MAROON_B) brace.put_at_tip(text) brace.text = text brace = her_vector.brace bottom_words = her_vector.brace.text top_brace = cob_matrix.top_brace top_words = cob_matrix.top_brace.text def introduce(array): self.play( Write(array), Transform(brace, array.brace), Transform(bottom_words, array.brace.text) ) self.wait() def echo_introduce(array): self.play( Transform(top_brace, array.top_brace), Transform(top_words, array.top_brace.text) ) self.wait() self.play(Write(her_vector)) self.play( GrowFromCenter(brace), Write(bottom_words) ) self.wait() introduce(cob_matrix) self.play( GrowFromCenter(top_brace), Write(top_words) ) self.wait() introduce(transform) echo_introduce(transform) introduce(inv_cob), echo_introduce(inv_cob) #Genearlize to single matrix v = OldTex("\\vec{\\textbf{v}}") v.set_color(her_vector.get_color()) v.move_to(her_vector, aligned_edge = LEFT) self.play( Transform(her_vector, v), FadeOut(bottom_words), FadeOut(brace), ) self.wait() self.play( Transform(top_brace, final_top_brace), Transform(top_brace.text, final_top_brace.text), ) self.wait() equals = OldTex("=") equals.replace(v) result.next_to(equals, RIGHT) self.play( Transform(her_vector, equals), Write(result) ) self.wait(2) everything = VGroup(*self.get_mobjects()) self.play( FadeOut(everything), result.to_corner, UP+LEFT ) self.add(result) self.wait() def add_title(self): title = OldTexText("How to translate a matrix") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title) self.play(ShowCreation(h_line)) self.wait() class JennyWatchesRotationWithMatrixAndVector(JenniferScene): def construct(self): self.add(self.jenny_plane.copy().fade(0.8)) self.add(self.jenny_plane, self.jenny, self.b1, self.b2) matrix = Matrix([["1/3", "-2/3"], ["5/3", "-1/3"]]) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.to_corner(UP+LEFT) vector_coords = [1, 2] vector_array = Matrix(vector_coords) vector_array.set_color(YELLOW) vector_array.next_to(matrix, RIGHT) result = Matrix([-1, 1]) equals = OldTex("=") equals.next_to(vector_array) result.next_to(equals) for array in matrix, vector_array, result: array.add_to_back(BackgroundRectangle(array)) vector = Vector(np.dot(self.cob_matrix(), vector_coords)) self.add(matrix) self.play(Write(vector_array)) self.play(ShowCreation(vector)) self.play(Blink(self.jenny)) self.play(*it.chain( [ Rotate(mob, np.pi/2, run_time = 3) for mob in (self.jenny_plane, self.b1, self.b2, vector) ], list(map(Animation, [self.jenny, matrix, vector_array])), )) self.play( self.jenny.change_mode, "pondering", Write(equals), Write(result) ) self.play(Blink(self.jenny)) self.wait() class MathematicalEmpathy(TeacherStudentsScene): def construct(self): words = OldTexText( "\\centering An expression like", "$A^{-1} M A$", "\\\\ suggests a mathematical \\\\", "sort of empathy" ) A1, neg, one, M, A2 = words[1] As = VGroup(A1, neg, one, A2) VGroup(As, M).set_color(YELLOW) self.teacher_says(words) self.random_blink() for mob, color in (M, BLUE), (As, MAROON_B): self.play(mob.set_color, color) self.play(mob.scale, 1.2, rate_func = there_and_back) self.random_blink(2) class NextVideo(Scene): def construct(self): title = OldTexText(""" Next video: Eigenvectors and eigenvalues """) title.to_edge(UP, buff = MED_SMALL_BUFF) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait()
videos_3b1b/_2016/eola/chapter2.py
from manim_imports_ext import * from _2016.eola.chapter1 import plane_wave_homotopy class OpeningQuote(Scene): def construct(self): words = OldTexText(""" Mathematics requires a small dose, not of genius, but of an imaginative freedom which, in a larger dose, would be insanity. """) words.to_edge(UP) for mob in words.submobjects[49:49+18]: mob.set_color(GREEN) author = OldTexText("-Angus K. Rodgers") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(3) self.play(Write(author, run_time = 3)) self.wait() class CoordinatesWereFamiliar(TeacherStudentsScene): def construct(self): self.setup() self.student_says("I know this already") self.random_blink() self.teacher_says("Ah, but there is a subtlety") self.random_blink() self.wait() class CoordinatesAsScalars(VectorScene): CONFIG = { "vector_coords" : [3, -2] } def construct(self): self.lock_in_faded_grid() vector = self.add_vector(self.vector_coords) array, x_line, y_line = self.vector_to_coords(vector) self.add(array) self.wait() new_array = self.general_idea_of_scalars(array, vector) self.scale_basis_vectors(new_array) self.show_symbolic_sum(new_array, vector) def general_idea_of_scalars(self, array, vector): starting_mobjects = self.get_mobjects() title = OldTexText("Think of each coordinate as a scalar") title.to_edge(UP) x, y = array.get_mob_matrix().flatten() new_x = x.copy().scale(2).set_color(X_COLOR) new_x.move_to(3*LEFT+2*UP) new_y = y.copy().scale(2).set_color(Y_COLOR) new_y.move_to(3*RIGHT+2*UP) i_hat, j_hat = self.get_basis_vectors() new_i_hat = Vector( self.vector_coords[0]*i_hat.get_end(), color = X_COLOR ) new_j_hat = Vector( self.vector_coords[1]*j_hat.get_end(), color = Y_COLOR ) VMobject(i_hat, new_i_hat).shift(3*LEFT) VMobject(j_hat, new_j_hat).shift(3*RIGHT) new_array = Matrix([new_x.copy(), new_y.copy()]) new_array.scale(0.5) new_array.shift( -new_array.get_boundary_point(-vector.get_end()) + \ 1.1*vector.get_end() ) self.remove(*starting_mobjects) self.play( Transform(x, new_x), Transform(y, new_y), Write(title), ) self.play(FadeIn(i_hat), FadeIn(j_hat)) self.wait() self.play( Transform(i_hat, new_i_hat), Transform(j_hat, new_j_hat), run_time = 3 ) self.wait() starting_mobjects.remove(array) new_x, new_y = new_array.get_mob_matrix().flatten() self.play( Transform(x, new_x), Transform(y, new_y), FadeOut(i_hat), FadeOut(j_hat), Write(new_array.get_brackets()), FadeIn(VMobject(*starting_mobjects)), FadeOut(title) ) self.remove(x, y) self.add(new_array) return new_array def scale_basis_vectors(self, new_array): i_hat, j_hat = self.get_basis_vectors() self.add_vector(i_hat) i_hat_label = self.label_vector( i_hat, "\\hat{\\imath}", color = X_COLOR, label_scale_factor = 1 ) self.add_vector(j_hat) j_hat_label = self.label_vector( j_hat, "\\hat{\\jmath}", color = Y_COLOR, label_scale_factor = 1 ) self.wait() x, y = new_array.get_mob_matrix().flatten() for coord, v, label, factor, shift_right in [ (x, i_hat, i_hat_label, self.vector_coords[0], False), (y, j_hat, j_hat_label, self.vector_coords[1], True) ]: faded_v = v.copy().fade(0.7) scaled_v = Vector(factor*v.get_end(), color = v.get_color()) scaled_label = VMobject(coord.copy(), label.copy()) scaled_label.arrange(RIGHT, buff = 0.1) scaled_label.move_to(label, DOWN+RIGHT) scaled_label.shift((scaled_v.get_end()-v.get_end())/2) coord_copy = coord.copy() self.play( Transform(v.copy(), faded_v), Transform(v, scaled_v), Transform(VMobject(coord_copy, label), scaled_label), ) self.wait() if shift_right: group = VMobject(v, coord_copy, label) self.play(ApplyMethod( group.shift, self.vector_coords[0]*RIGHT )) self.wait() def show_symbolic_sum(self, new_array, vector): new_mob = OldTex([ "(%d)\\hat{\\imath}"%self.vector_coords[0], "+", "(%d)\\hat{\\jmath}"%self.vector_coords[1] ]) new_mob.move_to(new_array) new_mob.shift_onto_screen() i_hat, plus, j_hat = new_mob.split() i_hat.set_color(X_COLOR) j_hat.set_color(Y_COLOR) self.play(Transform(new_array, new_mob)) self.wait() class CoordinatesAsScalarsExample2(CoordinatesAsScalars): CONFIG = { "vector_coords" : [-5, 2] } def construct(self): self.lock_in_faded_grid() basis_vectors = self.get_basis_vectors() labels = self.get_basis_vector_labels() self.add(*basis_vectors) self.add(*labels) text = OldTexText(""" $\\hat{\\imath}$ and $\\hat{\\jmath}$ are the ``basis vectors'' \\\\ of the $xy$ coordinate system """) text.set_width(FRAME_X_RADIUS-1) text.to_corner(UP+RIGHT) VMobject(*text.split()[:2]).set_color(X_COLOR) VMobject(*text.split()[5:7]).set_color(Y_COLOR) self.play(Write(text)) self.wait(2) self.remove(*basis_vectors + labels) CoordinatesAsScalars.construct(self) class WhatIfWeChoseADifferentBasis(Scene): def construct(self): self.play(Write( "What if we chose different basis vectors?", run_time = 2 )) self.wait(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.8, 1.3), ], "leave_sum_vector_copies" : False, "start_with_non_sum_scaling" : True, "finish_with_standard_basis_comparison" : True, "finish_by_drawing_lines" : False, } def construct(self): self.lock_in_faded_grid() 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.last_scalar_pair = (1, 1) if self.start_with_non_sum_scaling: 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(label_anims, scalar_anims) if self.finish_by_drawing_lines: self.draw_lines(v1, v2, label_anims, 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 = get_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_factor = 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.wait() 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.wait() def scale_with_sum(self, v1, v2, label_anims, scalar_anims): v2_anim, sum_anim = self.get_sum_animations(v1, v2) 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}) if self.leave_sum_vector_copies: self.add(self.sum_vector.copy()) self.wait() self.last_scalar_pair = scalar_pair def get_sum_animations(self, v1, v2): 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()) ) return v2_anim, sum_anim def standard_basis_comparison(self, label_anims, scalar_anims): everything = self.get_mobjects() everything.remove(self.sum_vector) everything = VMobject(*everything) alt_coords = [a.mobject for a in scalar_anims] array = Matrix([ mob.copy().set_color(color) for mob, color in zip( alt_coords, [self.vector1_color, self.vector2_color] ) ]) array.scale(0.8) array.to_edge(UP) array.shift(RIGHT) brackets = array.get_brackets() anims = [ Transform(*pair) for pair in zip(alt_coords, array.get_mob_matrix().flatten()) ] # anims += [ # FadeOut(a.mobject) # for a in label_anims # ] self.play(*anims + [Write(brackets)]) self.wait() self.remove(brackets, *alt_coords) self.add(array) self.play( FadeOut(everything), Animation(array), ) self.add_axes(animate = True) ij_array, x_line, y_line = self.vector_to_coords( self.sum_vector, integer_labels = False ) self.add(ij_array, x_line, y_line) x, y = ij_array.get_mob_matrix().flatten() self.play( ApplyMethod(x.set_color, X_COLOR), ApplyMethod(y.set_color, Y_COLOR), ) neq = OldTex("\\neq") neq.next_to(array) self.play( ApplyMethod(ij_array.next_to, neq), Write(neq) ) self.wait() def draw_lines(self, v1, v2, label_anims, scalar_anims): sum_anims = self.get_sum_animations(v1, v2) aux_anims = list(sum_anims) + label_anims + scalar_anims scale_factor = 2 for w1, w2 in (v2, v1), (v1, v2): w1_vect = w1.get_end()-w1.get_start() w2_vect = w2.get_end()-w2.get_start() for num in scale_factor, -1, -1./scale_factor: curr_tip = self.sum_vector.get_end() line = Line(ORIGIN, curr_tip) self.play( ApplyMethod(w2.scale, num), UpdateFromFunc( line, lambda l : l.put_start_and_end_on(curr_tip, self.sum_vector.get_end()) ), *aux_anims ) self.add(line, v2) self.wait() class AltShowVaryingLinearCombinations(ShowVaryingLinearCombinations): CONFIG = { "scalar_pairs" : [ (1.5, 0.3), (0.64, 1.3), (-1, -1.5), (1, 1.13), (1.25, 0.5), (-0.8, 1.14), ], "finish_with_standard_basis_comparison" : False } class NameLinearCombinations(Scene): def construct(self): v_color = MAROON_C w_color = BLUE words = OldTexText([ "``Linear combination'' of", "$\\vec{\\textbf{v}}$", "and", "$\\vec{\\textbf{w}}$" ]) words.split()[1].set_color(v_color) words.split()[3].set_color(w_color) words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) equation = OldTex([ "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}" ]) equation.arrange(buff = 0.1, aligned_edge = DOWN) equation.split()[1].set_color(v_color) equation.split()[4].set_color(w_color) a, b = np.array(equation.split())[[0, 3]] equation.scale(2) equation.next_to(words, DOWN, buff = 1) scalars_word = OldTexText("Scalars") scalars_word.scale(1.5) scalars_word.next_to(equation, DOWN, buff = 2) arrows = [ Arrow(scalars_word, letter) for letter in (a, b) ] self.add(equation) self.play(Write(words)) self.play( ShowCreation(VMobject(*arrows)), Write(scalars_word) ) self.wait(2) class LinearCombinationsDrawLines(ShowVaryingLinearCombinations): CONFIG = { "scalar_pairs" : [ (1.5, 0.6), (0.7, 1.3), (1, 1), ], "start_with_non_sum_scaling" : False, "finish_with_standard_basis_comparison" : False, "finish_by_drawing_lines" : True, } class LinearCombinationsWithSumCopies(ShowVaryingLinearCombinations): CONFIG = { "scalar_pairs" : [ (1.5, 0.6), (0.7, 1.3), (-1, -1.5), (1, -1.13), (1.25, 0.5), (-0.8, 1.3), (-0.9, 1.4), (0.9, 2), ], "leave_sum_vector_copies" : True, "start_with_non_sum_scaling" : False, "finish_with_standard_basis_comparison" : False, "finish_by_drawing_lines" : False, } class LinearDependentVectors(ShowVaryingLinearCombinations): CONFIG = { "vector1" : [1, 2], "vector2" : [0.5, 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.25, 0.5), (-0.8, 1.3), (-0.9, 1.4), (0.9, 2), ], "leave_sum_vector_copies" : False, "start_with_non_sum_scaling" : False, "finish_with_standard_basis_comparison" : False, "finish_by_drawing_lines" : False, } def get_sum_animations(self, v1, v2): v2_anim, sum_anim = ShowVaryingLinearCombinations.get_sum_animations(self, v1, v2) self.remove(self.sum_vector) return v2_anim, Animation(VMobject()) class WhenVectorsLineUp(LinearDependentVectors): CONFIG = { "vector1" : [3, 2], "vector2" : [1.5, 1], "scalar_pairs" : [ (1.5, 0.6), (0.7, 1.3), ], } class AnimationUnderSpanDefinition(ShowVaryingLinearCombinations): CONFIG = { "scalar_pairs" : [ (1.5, 0.6), (0.7, 1.3), (-1, -1.5), (1.25, 0.5), (0.8, 1.3), (0.93, -1.4), (-2, -0.5), ], "leave_sum_vector_copies" : True, "start_with_non_sum_scaling" : False, "finish_with_standard_basis_comparison" : False, "finish_by_drawing_lines" : False, } class BothVectorsCouldBeZero(VectorScene): def construct(self): plane = self.add_plane() plane.fade(0.7) v1 = self.add_vector([1, 2], color = MAROON_C) v2 = self.add_vector([3, -1], color = BLUE) self.play(Transform(v1, Dot(ORIGIN))) self.play(Transform(v2, Dot(ORIGIN))) self.wait() class DefineSpan(Scene): def construct(self): v_color = MAROON_C w_color = BLUE definition = OldTexText(""" The ``span'' of $\\vec{\\textbf{v}}$ and $\\vec{\\textbf{w}}$ is the \\\\ set of all their linear combinations. """) definition.set_width(FRAME_WIDTH-1) definition.to_edge(UP) def_mobs = np.array(definition.split()) VMobject(*def_mobs[4:4+4]).set_color(PINK) VMobject(*def_mobs[11:11+2]).set_color(v_color) VMobject(*def_mobs[16:16+2]).set_color(w_color) VMobject(*def_mobs[-19:-1]).set_color(YELLOW) equation = OldTex([ "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}" ]) equation.arrange(buff = 0.1, aligned_edge = DOWN) equation.split()[1].set_color(v_color) equation.split()[4].set_color(w_color) a, b = np.array(equation.split())[[0, 3]] equation.scale(2) equation.next_to(definition, DOWN, buff = 1) vary_words = OldTexText( "Let $a$ and $b$ vary \\\\ over all real numbers" ) vary_words.scale(1.5) vary_words.next_to(equation, DOWN, buff = 2) arrows = [ Arrow(vary_words, letter) for letter in (a, b) ] self.play(Write(definition)) self.play(Write(equation)) self.wait() self.play( FadeIn(vary_words), ShowCreation(VMobject(*arrows)) ) self.wait() class VectorsVsPoints(Scene): def construct(self): self.play(Write("Vectors vs. Points")) self.wait(2) class VectorsToDotsScene(VectorScene): CONFIG = { "num_vectors" : 16, "start_color" : PINK, "end_color" : BLUE_E, } def construct(self): self.lock_in_faded_grid() vectors = self.get_vectors() colors = Color(self.start_color).range_to( self.end_color, len(vectors) ) for vect, color in zip(vectors, colors): vect.set_color(color) prototype_vector = vectors[3*len(vectors)/4] vector_group = VMobject(*vectors) self.play( ShowCreation( vector_group, run_time = 3 ) ) vectors.sort(key=lambda v: v.get_length()) self.add(*vectors) def v_to_dot(vector): return Dot(vector.get_end(), fill_color = vector.get_stroke_color()) self.wait() vectors.remove(prototype_vector) self.play(*list(map(FadeOut, vectors))+[Animation(prototype_vector)]) self.remove(vector_group) self.add(prototype_vector) self.wait() self.play(Transform(prototype_vector, v_to_dot(prototype_vector))) self.wait() self.play(*list(map(FadeIn, vectors)) + [Animation(prototype_vector)]) rate_functions = [ squish_rate_func(smooth, float(x)/(len(vectors)+2), 1) for x in range(len(vectors)) ] self.play(*[ Transform(v, v_to_dot(v), rate_func = rf, run_time = 2) for v, rf in zip(vectors, rate_functions) ]) self.wait() self.remove(prototype_vector) self.play_final_animation(vectors, rate_functions) self.wait() def get_vectors(self): raise Exception("Not implemented") def play_final_animation(self, vectors, rate_functions): raise Exception("Not implemented") class VectorsOnALine(VectorsToDotsScene): def get_vectors(self): return [ Vector(a*np.array([1.5, 1])) for a in np.linspace( -FRAME_Y_RADIUS, FRAME_Y_RADIUS, self.num_vectors ) ] def play_final_animation(self, vectors, rate_functions): line_copies = [ Line(vectors[0].get_end(), vectors[-1].get_end()) for v in vectors ] self.play(*[ Transform(v, mob, rate_func = rf, run_time = 2) for v, mob, rf in zip(vectors, line_copies, rate_functions) ]) class VectorsInThePlane(VectorsToDotsScene): CONFIG = { "num_vectors" : 16, "start_color" : PINK, "end_color" : BLUE_E, } def get_vectors(self): return [ Vector([x, y]) for x in np.arange(-int(FRAME_X_RADIUS)-0.5, int(FRAME_X_RADIUS)+0.5) for y in np.arange(-int(FRAME_Y_RADIUS)-0.5, int(FRAME_Y_RADIUS)+0.5) ] def play_final_animation(self, vectors, rate_functions): h_line = Line( FRAME_X_RADIUS*RIGHT, FRAME_X_RADIUS*LEFT, stroke_width = 0.5, color = BLUE_E ) v_line = Line( FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN, stroke_width = 0.5, color = BLUE_E ) line_pairs = [ VMobject(h_line.copy().shift(y), v_line.copy().shift(x)) for v in vectors for x, y, z in [v.get_center()] ] plane = NumberPlane() self.play( ShowCreation(plane), *[ Transform(v, p, rate_func = rf) for v, p, rf in zip(vectors, line_pairs, rate_functions) ] ) self.remove(*vectors) self.wait() class HowToThinkVectorsVsPoint(Scene): def construct(self): randy = Randolph().to_corner() bubble = randy.get_bubble(height = 3.8) text1 = OldTexText("Think of individual vectors as arrows") text2 = OldTexText("Think of sets of vectors as points") for text in text1, text2: text.to_edge(UP) single_vector = Vector([2, 1]) vector_group = VMobject(*[ Vector([x, 1]) for x in np.linspace(-2, 2, 5) ]) bubble.position_mobject_inside(single_vector) bubble.position_mobject_inside(vector_group) dots = VMobject(*[ Dot(v.get_end()) for v in vector_group.split() ]) self.add(randy) self.play( ApplyMethod(randy.change_mode, "pondering"), ShowCreation(bubble) ) self.play(FadeIn(text1)) self.play(ShowCreation(single_vector)) self.wait(3) self.play( Transform(text1, text2), Transform(single_vector, vector_group) ) self.remove(single_vector) self.add(vector_group) self.wait() self.play(Transform(vector_group, dots)) self.wait() class IntroduceThreeDSpan(Scene): pass class AskAboutThreeDSpan(Scene): def construct(self): self.play(Write("What does the span of two 3d vectors look like?")) self.wait(2) class ThreeDVectorSpan(Scene): pass class LinearCombinationOfThreeVectors(Scene): pass class VaryingLinearCombinationOfThreeVectors(Scene): pass class LinearCombinationOfThreeVectorsText(Scene): def construct(self): text = OldTexText(""" Linear combination of $\\vec{\\textbf{v}}$, $\\vec{\\textbf{w}}$, and $\\vec{\\textbf{u}}$: """) VMobject(*text.split()[-12:-10]).set_color(MAROON_C) VMobject(*text.split()[-9:-7]).set_color(BLUE) VMobject(*text.split()[-3:-1]).set_color(RED_C) VMobject(*text.split()[:17]).set_color(GREEN) text.set_width(FRAME_WIDTH - 1) text.to_edge(UP) equation = OldTexText("""$ a\\vec{\\textbf{v}} + b\\vec{\\textbf{w}} + c\\vec{\\textbf{u}} $""") VMobject(*equation.split()[-10:-8]).set_color(MAROON_C) VMobject(*equation.split()[-6:-4]).set_color(BLUE) VMobject(*equation.split()[-2:]).set_color(RED_C) a, b, c = np.array(equation.split())[[0, 4, 8]] equation.scale(1.5) equation.next_to(text, DOWN, buff = 1) span_comment = OldTexText("For span, let these constants vary") span_comment.scale(1.5) span_comment.next_to(equation, DOWN, buff = 2) VMobject(*span_comment.split()[3:7]).set_color(YELLOW) arrows = VMobject(*[ Arrow(span_comment, var) for var in (a, b, c) ]) self.play(Write(text)) self.play(Write(equation)) self.wait() self.play( ShowCreation(arrows), Write(span_comment) ) self.wait() class ThirdVectorOnSpanOfFirstTwo(Scene): pass class ThirdVectorOutsideSpanOfFirstTwo(Scene): pass class SpanCasesWords(Scene): def construct(self): words1 = OldTexText(""" Case 1: $\\vec{\\textbf{u}}$ is in the span of $\\vec{\\textbf{v}}$ and $\\vec{\\textbf{u}}$ """) VMobject(*words1.split()[6:8]).set_color(RED_C) VMobject(*words1.split()[-7:-5]).set_color(MAROON_C) VMobject(*words1.split()[-2:]).set_color(BLUE) words2 = OldTexText(""" Case 2: $\\vec{\\textbf{u}}$ is not in the span of $\\vec{\\textbf{v}}$ and $\\vec{\\textbf{u}}$ """) VMobject(*words2.split()[6:8]).set_color(RED_C) VMobject(*words2.split()[-7:-5]).set_color(MAROON_C) VMobject(*words2.split()[-2:]).set_color(BLUE) VMobject(*words2.split()[10:13]).set_color(RED) for words in words1, words2: words.set_width(FRAME_WIDTH - 1) self.play(Write(words1)) self.wait() self.play(Transform(words1, words2)) self.wait() class LinearDependentWords(Scene): def construct(self): words1 = OldTexText([ "$\\vec{\\textbf{v}}$", "and", "$\\vec{\\textbf{w}}$", "are", "``Linearly dependent'' ", ]) v, _and, w, are, rest = words1.split() v.set_color(MAROON_C) w.set_color(BLUE) rest.set_color(YELLOW) words2 = OldTexText([ "$\\vec{\\textbf{v}}$,", "$\\vec{\\textbf{w}}$", "and", "$\\vec{\\textbf{u}}$", "are", "``Linearly dependent'' ", ]) v, w, _and, u, are, rest = words2.split() v.set_color(MAROON_C) w.set_color(BLUE) u.set_color(RED_C) rest.set_color(YELLOW) for words in words1, words2: words.set_width(FRAME_WIDTH - 1) self.play(Write(words1)) self.wait() self.play(Transform(words1, words2)) self.wait() class LinearDependentEquations(Scene): def construct(self): title = OldTexText("``Linearly dependent'' ") title.set_color(YELLOW) title.scale(2) title.to_edge(UP) self.add(title) equation1 = OldTex([ "\\vec{\\textbf{w}}", "=", "a", "\\vec{\\textbf{v}}", ]) w, eq, a, v = equation1.split() w.set_color(BLUE) v.set_color(MAROON_C) equation1.scale(2) eq1_copy = equation1.copy() low_words1 = OldTexText("For some value of $a$") low_words1.scale(2) low_words1.to_edge(DOWN) arrow = Arrow(low_words1, a) arrow_copy = arrow.copy() equation2 = OldTex([ "\\vec{\\textbf{u}}", "=", "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}", ]) u, eq, a, v, plus, b, w = equation2.split() u.set_color(RED) w.set_color(BLUE) v.set_color(MAROON_C) equation2.scale(2) eq2_copy = equation2.copy() low_words2 = OldTexText("For some values of a and b") low_words2.scale(2) low_words2.to_edge(DOWN) arrows = VMobject(*[ Arrow(low_words2, var) for var in (a, b) ]) self.play(Write(equation1)) self.play( ShowCreation(arrow), Write(low_words1) ) self.wait() self.play( Transform(equation1, equation2), Transform(low_words1, low_words2), Transform(arrow, arrows) ) self.wait(2) new_title = OldTexText("``Linearly independent'' ") new_title.set_color(GREEN) new_title.replace(title) for eq_copy in eq1_copy, eq2_copy: neq = OldTex("\\neq") neq.replace(eq_copy.submobjects[1]) eq_copy.submobjects[1] = neq new_low_words1 = OldTexText(["For", "all", "values of a"]) new_low_words2 = OldTexText(["For", "all", "values of a and b"]) for low_words in new_low_words1, new_low_words2: low_words.split()[1].set_color(GREEN) low_words.scale(2) low_words.to_edge(DOWN) self.play( Transform(title, new_title), Transform(equation1, eq1_copy), Transform(arrow, arrow_copy), Transform(low_words1, new_low_words1) ) self.wait() self.play( Transform(equation1, eq2_copy), Transform(arrow, arrows), Transform(low_words1, new_low_words2) ) self.wait() class AlternateDefOfLinearlyDependent(Scene): def construct(self): title1 = OldTexText([ "$\\vec{\\textbf{v}}$,", "$\\vec{\\textbf{w}}$", "and", "$\\vec{\\textbf{u}}$", "are", "linearly dependent", "if", ]) title2 = OldTexText([ "$\\vec{\\textbf{v}}$,", "$\\vec{\\textbf{w}}$", "and", "$\\vec{\\textbf{u}}$", "are", "linearly independent", "if", ]) for title in title1, title2: v, w, _and, u, are, ld, _if = title.split() v.set_color(MAROON_C) w.set_color(BLUE) u.set_color(RED_C) title.to_edge(UP) title1.split()[-2].set_color(YELLOW) title2.split()[-2].set_color(GREEN) subtitle = OldTexText("the only solution to") subtitle.next_to(title2, DOWN, aligned_edge = LEFT) self.add(title1) equations = self.get_equations() added_words1 = OldTexText( "where at least one of $a$, $b$ and $c$ is not $0$" ) added_words2 = OldTexText( "is a = b = c = 0" ) scalar_specification = OldTexText( "For some choice of $a$ and $b$" ) scalar_specification.shift(1.5*DOWN) scalar_specification.add(*[ Arrow(scalar_specification, equations[0].split()[i]) for i in (2, 5) ]) brace = Brace(VMobject(*equations[2].split()[2:])) brace_words = OldTexText("Linear combination") brace_words.next_to(brace, DOWN) equation = equations[0] for added_words in added_words1, added_words2: added_words.next_to(title, DOWN, buff = 3.5, aligned_edge = LEFT) self.play(Write(equation)) for i, new_eq in enumerate(equations): if i == 0: self.play(FadeIn(scalar_specification)) self.wait(2) self.play(FadeOut(scalar_specification)) elif i == 3: self.play( GrowFromCenter(brace), Write(brace_words) ) self.wait(3) self.play(FadeOut(brace), FadeOut(brace_words)) self.play(Transform( equation, new_eq, path_arc = (np.pi/2 if i == 1 else 0) )) self.wait(3) self.play(Write(added_words1)) self.wait(2) self.play( Transform(title1, title2), Write(subtitle), Transform(added_words1, added_words2), ) self.wait(3) everything = VMobject(*self.get_mobjects()) self.play(ApplyFunction( lambda m : m.scale(0.5).to_corner(UP+LEFT), everything )) self.wait() def get_equations(self): equation1 = OldTex([ "\\vec{\\textbf{u}}", "=", "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}", ]) u = equation1.split()[0] equation1.submobjects = list(it.chain( [VectorizedPoint(u.get_center())], equation1.submobjects[1:], [VectorizedPoint(u.get_left())], [u] )) equation2 = OldTex([ "\\left[\\begin{array}{c} 0 \\\\ 0 \\\\ 0 \\end{array} \\right]", "=", "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}", "-", "\\vec{\\textbf{u}}", ]) equation3 = OldTex([ "\\vec{\\textbf{0}}", "=", "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}", "-", "\\vec{\\textbf{u}}", ]) equation4 = OldTex([ "\\vec{\\textbf{0}}", "=", "0", "\\vec{\\textbf{v}}", "+", "0", "\\vec{\\textbf{w}}", "+0", "\\vec{\\textbf{u}}", ]) equation5 = OldTex([ "\\vec{\\textbf{0}}", "=", "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}", "+(-1)", "\\vec{\\textbf{u}}", ]) equation5.split()[-2].set_color(YELLOW) equation6 = OldTex([ "\\vec{\\textbf{0}}", "=", "a", "\\vec{\\textbf{v}}", "+", "b", "\\vec{\\textbf{w}}", "+c", "\\vec{\\textbf{u}}", ]) result = [equation1, equation2, equation3, equation4, equation5, equation6] for eq in result: eq.split()[3].set_color(MAROON_C) eq.split()[6].set_color(BLUE) eq.split()[-1].set_color(RED_C) eq.scale(1.5) eq.shift(UP) return result class MathematiciansLikeToConfuse(TeacherStudentsScene): def construct(self): self.setup() self.teacher_says(""" We wouldn't want things to \\\\ be \\emph{understandable} would we? """) modes = "pondering", "sassy", "confused" self.play(*[ ApplyMethod(student.change_mode, mode) for student, mode in zip(self.get_students(), modes) ]) self.wait(2) class CheckYourUnderstanding(TeacherStudentsScene): def construct(self): self.setup() self.teacher_says("Quiz time!") self.random_blink() self.wait() self.random_blink() class TechnicalDefinitionOfBasis(Scene): def construct(self): title = OldTexText("Technical definition of basis:") title.to_edge(UP) definition = OldTexText([ "The", "basis", "of a vector space is a set of", "linearly independent", "vectors that", "span", "the full space", ]) t, b, oavsiaso, li, vt, s, tfs = definition.split() b.set_color(BLUE) li.set_color(GREEN) s.set_color(YELLOW) definition.set_width(FRAME_WIDTH-1) self.add(title) self.play(Write(definition)) self.wait() class NextVideo(Scene): def construct(self): title = OldTexText("Next video: Matrices as linear transformations") title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait()
videos_3b1b/_2016/eola/chapter11.py
from manim_imports_ext import * from _2016.eola.chapter1 import plane_wave_homotopy from _2016.eola.chapter3 import ColumnsToBasisVectors from _2016.eola.chapter5 import NameDeterminant, Blob from _2016.eola.chapter9 import get_small_bubble from _2016.eola.chapter10 import ExampleTranformationScene class Student(PiCreature): CONFIG = { "name" : "Student" } def get_name(self): text = OldTexText(self.name) text.add_background_rectangle() text.next_to(self, DOWN) return text class PhysicsStudent(Student): CONFIG = { "color" : PINK, "name" : "Physics student" } class CSStudent(Student): CONFIG = { "color" : PURPLE_E, "flip_at_start" : True, "name" : "CS Student" } class OpeningQuote(Scene): def construct(self): words = OldTexText( "``Such", "axioms,", "together with other unmotivated definitions,", "serve mathematicians mainly by making it", "difficult for the uninitiated", "to master their subject, thereby elevating its authority.''", enforce_new_line_structure = False, alignment = "", ) words.set_color_by_tex("axioms,", BLUE) words.set_color_by_tex("difficult for the uninitiated", RED) words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) author = OldTexText("-Vladmir Arnold") author.set_color(YELLOW) author.next_to(words, DOWN, buff = MED_LARGE_BUFF) self.play(Write(words, run_time = 8)) self.wait() self.play(FadeIn(author)) self.wait(3) class RevisitOriginalQuestion(TeacherStudentsScene): def construct(self): self.teacher_says("Let's revisit ", "\\\\ an old question") self.random_blink() question = OldTexText("What are ", "vectors", "?", arg_separator = "") question.set_color_by_tex("vectors", YELLOW) self.teacher_says( question, added_anims = [ ApplyMethod(self.get_students()[i].change_mode, mode) for i, mode in enumerate([ "pondering", "raise_right_hand", "erm" ]) ] ) self.random_blink(2) class WhatIsA2DVector(LinearTransformationScene): CONFIG = { "v_coords" : [1, 2], "show_basis_vectors" : False, "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, "secondary_line_ratio" : 1 }, } def construct(self): self.plane.fade() self.introduce_vector_and_space() self.bring_in_students() def introduce_vector_and_space(self): v = Vector(self.v_coords) coords = Matrix(self.v_coords) coords.add_to_back(BackgroundRectangle(coords)) coords.next_to(v.get_end(), RIGHT) two_d_vector = OldTexText( "``Two-dimensional ", "vector", "''", arg_separator = "" ) two_d_vector.set_color_by_tex("vector", YELLOW) two_d_vector.add_background_rectangle() two_d_vector.to_edge(UP) self.play( Write(two_d_vector), ShowCreation(v), Write(coords), run_time = 2 ) self.wait() self.v, self.coords = v, coords def bring_in_students(self): everything = self.get_mobjects() v, coords = self.v, self.coords physics_student = PhysicsStudent() cs_student = CSStudent() students = [physics_student, cs_student] for student, vect in zip(students, [LEFT, RIGHT]): student.change_mode("confused") student.to_corner(DOWN+vect, buff = MED_LARGE_BUFF) student.look_at(v) student.bubble = get_small_bubble( student, height = 4, width = 4, ) self.play(*list(map(FadeIn, students))) self.play(Blink(physics_student)) self.wait() for student, vect in zip(students, [RIGHT, LEFT]): for mob in v, coords: mob.target = mob.copy() mob.target.scale(0.7) arrow = OldTex("\\Rightarrow") group = VGroup(v.target, arrow, coords.target) group.arrange(vect) student.bubble.add_content(group) student.v, student.coords = v.copy(), coords.copy() student.arrow = arrow self.play( student.change_mode, "pondering", ShowCreation(student.bubble), Write(arrow), Transform(student.v, v.target), Transform(student.coords, coords.target), ) self.play(Blink(student)) self.wait() anims = [] for student in students: v, coords = student.v, student.coords v.target = v.copy() coords.target = coords.copy() group = VGroup(v.target, coords.target) group.arrange(DOWN) group.set_height(coords.get_height()) group.next_to(student.arrow, RIGHT) student.q_marks = OldTex("???") student.q_marks.set_color_by_gradient(BLUE, YELLOW) student.q_marks.next_to(student.arrow, LEFT) anims += [ Write(student.q_marks), MoveToTarget(v), MoveToTarget(coords), student.change_mode, "erm", student.look_at, student.bubble ] cs_student.v.save_state() cs_student.coords.save_state() self.play(*anims) for student in students: self.play(Blink(student)) self.wait() self.play(*it.chain( list(map(FadeOut, everything + [ physics_student.bubble, physics_student.v, physics_student.coords, physics_student.arrow, physics_student.q_marks, cs_student.q_marks, ])), [ApplyMethod(s.change_mode, "plain") for s in students], list(map(Animation, [cs_student.bubble, cs_student.arrow])), [mob.restore for mob in (cs_student.v, cs_student.coords)], )) bubble = cs_student.get_bubble(SpeechBubble, width = 4, height = 3) bubble.set_fill(BLACK, opacity = 1) bubble.next_to(cs_student, UP+LEFT) bubble.write("Consider higher \\\\ dimensions") self.play( cs_student.change_mode, "speaking", ShowCreation(bubble), Write(bubble.content) ) self.play(Blink(physics_student)) self.wait() class HigherDimensionalVectorsNumerically(Scene): def construct(self): words = VGroup(*list(map(TexText, [ "4D vector", "5D vector", "100D vector", ]))) words.arrange(RIGHT, buff = LARGE_BUFF*2) words.to_edge(UP) vectors = VGroup(*list(map(Matrix, [ [3, 1, 4, 1], [5, 9, 2, 6, 5], [3, 5, 8, "\\vdots", 0, 8, 6] ]))) colors = [YELLOW, MAROON_B, GREEN] for word, vector, color in zip(words, vectors, colors): vector.shift(word.get_center()[0]*RIGHT) word.set_color(color) vector.set_color(color) for word in words: self.play(FadeIn(word)) self.play(Write(vectors)) self.wait() for index, dim, direction in (0, 4, RIGHT), (2, 100, LEFT): v = vectors[index] v.target = v.copy() brace = Brace(v, direction) brace.move_to(v) v.target.next_to(brace, -direction) text = brace.get_text("%d numbers"%dim) self.play( MoveToTarget(v), GrowFromCenter(brace), Write(text) ) entries = v.get_entries() num_entries = len(list(entries)) self.play(*[ Transform( entries[i], entries[i].copy().scale(1.2).set_color(WHITE), rate_func = squish_rate_func( there_and_back, i/(2.*num_entries), i/(2.*num_entries)+0.5 ), run_time = 2 ) for i in range(num_entries) ]) self.wait() class HyperCube(VMobject): CONFIG = { "color" : BLUE_C, "color2" : BLUE_D, "dims" : 4, } def init_points(self): corners = np.array(list(map(np.array, it.product(*[(-1, 1)]*self.dims)))) def project(four_d_array): result = four_d_array[:3] w = four_d_array[self.dims-1] scalar = interpolate(0.8, 1.2 ,(w+1)/2.) return scalar*result for a1, a2 in it.combinations(corners, 2): if sum(a1==a2) != self.dims-1: continue self.add(Line(project(a1), project(a2))) self.pose_at_angle() self.set_color_by_gradient(self.color, self.color2) class AskAbout4DPhysicsStudent(Scene): def construct(self): physy = PhysicsStudent().to_edge(DOWN).shift(2*LEFT) compy = CSStudent().to_edge(DOWN).shift(2*RIGHT) for pi1, pi2 in (physy, compy), (compy, physy): pi1.look_at(pi2.eyes) physy.bubble = physy.get_bubble(SpeechBubble, width = 5, height = 4.5) line = Line(LEFT, RIGHT, color = BLUE_B) square = Square(color = BLUE_C) square.scale(0.5) cube = HyperCube(color = BLUE_D, dims = 3) hyper_cube = HyperCube() thought_mobs = [] for i, mob in enumerate([line, square, cube, hyper_cube]): mob.set_height(2) tex = OldTex("%dD"%(i+1)) tex.next_to(mob, UP) group = VGroup(mob, tex) thought_mobs.append(group) group.shift( physy.bubble.get_top() -\ tex.get_top() + MED_SMALL_BUFF*DOWN ) line.shift(DOWN) curr_mob = thought_mobs[0] self.add(compy, physy) self.play( compy.change_mode, "confused", physy.change_mode, "hooray", ShowCreation(physy.bubble), Write(curr_mob, run_time = 1), ) self.play(Blink(compy)) for i, mob in enumerate(thought_mobs[1:]): self.play(Transform(curr_mob, mob)) self.remove(curr_mob) curr_mob = mob self.add(curr_mob) if i%2 == 1: self.play(Blink(physy)) else: self.wait() self.play(Blink(compy)) self.wait() class ManyCoordinateSystems(LinearTransformationScene): CONFIG = { "v_coords" : [2, 1], "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 1 }, } def construct(self): self.title = OldTexText("Many possible coordinate systems") self.title.add_background_rectangle() self.title.to_edge(UP) self.add_foreground_mobject(self.title) self.v = Vector(self.v_coords) self.play(ShowCreation(self.v)) self.add_foreground_mobject(self.v) t_matrices = [ [[0.5, 0.5], [-0.5, 0.5]], [[1, -1], [-3, -1]], [[-1, 2], [-0.5, -1]], ] movers = [self.plane, self.i_hat, self.j_hat] for mover in movers: mover.save_state() for t_matrix in t_matrices: self.animate_coordinates() self.play(*it.chain( list(map(FadeOut, movers)), list(map(Animation, self.foreground_mobjects)) )) for mover in movers: mover.restore() self.apply_transposed_matrix(t_matrix, run_time = 0) self.play(*it.chain( list(map(FadeIn, movers)), list(map(Animation, self.foreground_mobjects)) )) self.animate_coordinates() def animate_coordinates(self): self.i_hat.save_state() self.j_hat.save_state() cob_matrix = np.array([ self.i_hat.get_end()[:2], self.j_hat.get_end()[:2] ]).T inv_cob = np.linalg.inv(cob_matrix) coords = np.dot(inv_cob, self.v_coords) array = Matrix(list(map(DecimalNumber, coords))) array.get_entries()[0].set_color(X_COLOR) array.get_entries()[1].set_color(Y_COLOR) array.add_to_back(BackgroundRectangle(array)) for entry in array.get_entries(): entry.add_to_back(BackgroundRectangle(entry)) array.next_to(self.title, DOWN) self.i_hat.target = self.i_hat.copy().scale(coords[0]) self.j_hat.target = self.j_hat.copy().scale(coords[1]) coord1, coord2 = array.get_entries().copy() for coord, vect in (coord1, self.i_hat), (coord2, self.j_hat): coord.target = coord.copy().next_to( vect.target.get_end()/2, rotate_vector(vect.get_end(), -np.pi/2) ) self.play(Write(array, run_time = 1)) self.wait() self.play(*list(map(MoveToTarget, [self.i_hat, coord1]))) self.play(*list(map(MoveToTarget, [self.j_hat, coord2]))) self.play(VGroup(self.j_hat, coord2).shift, self.i_hat.get_end()) self.wait(2) self.play( self.i_hat.restore, self.j_hat.restore, *list(map(FadeOut, [array, coord1, coord2])) ) class DeterminantAndEigenvectorDontCare(LinearTransformationScene): CONFIG = { "t_matrix" : [[3, 1], [1, 2]], "include_background_plane" : False, "show_basis_vectors" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, "secondary_line_ratio" : 1 }, } def construct(self): words = OldTexText( "Determinant", "and", "eigenvectors", "don't \\\\ care about the coordinate system" ) words.set_color_by_tex("Determinant", YELLOW) words.set_color_by_tex("eigenvectors", MAROON_B) words.add_background_rectangle() words.to_edge(UP) dark_yellow = Color(rgb = interpolate( color_to_rgb(YELLOW), color_to_rgb(BLACK), 0.5 )) blob = Blob( stroke_color = YELLOW, fill_color = dark_yellow, fill_opacity = 1, ) blob.shift(2*LEFT+UP) det_label = OldTex("A") det_label = VGroup( VectorizedPoint(det_label.get_left()).set_color(WHITE), det_label ) det_label_target = OldTex("\\det(M)\\cdot", "A") det_label.move_to(blob) eigenvectors = VGroup(*self.get_eigenvectors()) self.add_foreground_mobject(words) self.wait() self.play( FadeIn(blob), Write(det_label) ) self.play( ShowCreation( eigenvectors, run_time = 2, ), Animation(words) ) self.wait() self.add_transformable_mobject(blob) self.add_moving_mobject(det_label, det_label_target) for vector in eigenvectors: self.add_vector(vector, animate = False) self.remove(self.plane) non_plane_mobs = self.get_mobjects() self.add(self.plane, *non_plane_mobs) cob_matrices = [ None, [[1, -1], [-3, -1]], [[-1, 2], [-0.5, -1]], ] def special_rate_func(t): if t < 0.3: return smooth(t/0.3) if t > 0.7: return smooth((1-t)/0.3) return 1 for cob_matrix in cob_matrices: if cob_matrix is not None: self.play( FadeOut(self.plane), *list(map(Animation, non_plane_mobs)) ) transform = self.get_matrix_transformation(cob_matrix) self.plane.apply_function(transform) self.play( FadeIn(self.plane), *list(map(Animation, non_plane_mobs)) ) self.wait() self.apply_transposed_matrix( self.t_matrix, rate_func = special_rate_func, run_time = 8 ) def get_eigenvectors(self): vals, (eig_matrix) = np.linalg.eig(self.t_matrix.T) v1, v2 = eig_matrix.T result = [] for v in v1, v2: vectors = VGroup(*[ Vector(u*x*v) for x in range(7, 0, -1) for u in [-1, 1] ]) vectors.set_color_by_gradient(MAROON_A, MAROON_C) result += list(vectors) return result class WhatIsSpace(Scene): def construct(self): physy = PhysicsStudent() compy = CSStudent() physy.to_edge(DOWN).shift(4*LEFT) compy.to_edge(DOWN).shift(4*RIGHT) physy.make_eye_contact(compy) physy.bubble = get_small_bubble(physy) vector = Vector([1, 2]) physy.bubble.add_content(vector) compy.bubble = compy.get_bubble(SpeechBubble, width = 6, height = 4) compy.bubble.set_fill(BLACK, opacity = 1) compy.bubble.write("What exactly do\\\\ you mean by ``space''?") self.add(compy, physy) self.play( physy.change_mode, "pondering", ShowCreation(physy.bubble), ShowCreation(vector) ) self.play( compy.change_mode, "sassy", ShowCreation(compy.bubble), Write(compy.bubble.content) ) self.play(Blink(physy)) self.wait() self.play(Blink(compy)) self.wait() class OtherVectorishThings(TeacherStudentsScene): def construct(self): words = OldTexText( "There are other\\\\", "vectorish", "things..." ) words.set_color_by_tex("vectorish", YELLOW) self.teacher_says(words) self.play_student_changes( "pondering", "raise_right_hand", "erm" ) self.random_blink(2) words = OldTexText("...like", "functions") words.set_color_by_tex("functions", PINK) self.teacher_says(words) self.play_student_changes(*["pondering"]*3) self.random_blink(2) self.teacher_thinks("") self.zoom_in_on_thought_bubble(self.get_teacher().bubble) class FunctionGraphScene(Scene): CONFIG = { "graph_colors" : [RED, YELLOW, PINK], "default_functions" : [ lambda x : (x**3 - 9*x)/20., lambda x : -(x**2)/8.+1 ], "default_names" : ["f", "g", "h"], "x_min" : -4, "x_max" : 4, "line_to_line_buff" : 0.03 } def setup(self): self.axes = Axes( x_min = self.x_min, x_max = self.x_max, ) self.add(self.axes) self.graphs = [] def get_function_graph(self, func = None, animate = True, add = True, **kwargs): index = len(self.graphs) if func is None: func = self.default_functions[ index%len(self.default_functions) ] default_color = self.graph_colors[index%len(self.graph_colors)] kwargs["color"] = kwargs.get("color", default_color) kwargs["x_min"] = kwargs.get("x_min", self.x_min) kwargs["x_max"] = kwargs.get("x_max", self.x_max) graph = FunctionGraph(func, **kwargs) if animate: self.play(ShowCreation(graph)) if add: self.add(graph) self.graphs.append(graph) return graph def get_index(self, function_graph): if function_graph not in self.graphs: self.graphs.append(function_graph) return self.graphs.index(function_graph) def get_output_lines(self, function_graph, num_steps = None, nudge = True): index = self.get_index(function_graph) num_steps = num_steps or function_graph.num_steps lines = VGroup() nudge_size = index*self.line_to_line_buff x_min, x_max = function_graph.x_min, function_graph.x_max for x in np.linspace(x_min, x_max, num_steps): if nudge: x += nudge_size y = function_graph.function(x) lines.add(Line(x*RIGHT, x*RIGHT+y*UP)) lines.set_color(function_graph.get_color()) return lines def add_lines(self, output_lines): self.play(ShowCreation( output_lines, lag_ratio = 0.5, run_time = 2 )) def label_graph(self, function_graph, name = None, animate = True): index = self.get_index(function_graph) name = name or self.default_names[index%len(self.default_names)] label = OldTex("%s(x)"%name) label.next_to(function_graph.point_from_proportion(1), RIGHT) label.shift_onto_screen() label.set_color(function_graph.get_color()) if animate: self.play(Write(label)) else: self.add(label) return label class AddTwoFunctions(FunctionGraphScene): def construct(self): f_graph = self.get_function_graph() g_graph = self.get_function_graph() def sum_func(x): return f_graph.get_function()(x)+g_graph.get_function()(x) sum_graph = self.get_function_graph(sum_func, animate = False) self.remove(sum_graph) f_label = self.label_graph(f_graph) g_label = self.label_graph(g_graph) f_lines = self.get_output_lines(f_graph) g_lines = self.get_output_lines(g_graph) sum_lines = self.get_output_lines(sum_graph, nudge = False) curr_x_point = f_lines[0].get_start() sum_def = self.get_sum_definition(DecimalNumber(curr_x_point[0])) # sum_def.set_width(FRAME_X_RADIUS-1) sum_def.to_corner(UP+LEFT) arrow = Arrow(sum_def[2].get_bottom(), curr_x_point, color = WHITE) prefix = sum_def[0] suffix = VGroup(*sum_def[1:]) rect = BackgroundRectangle(sum_def) brace = Brace(prefix) brace.add(brace.get_text("New function").shift_onto_screen()) self.play( Write(prefix, run_time = 2), FadeIn(brace) ) self.wait() for lines in f_lines, g_lines: self.add_lines(lines) self.play(*list(map(FadeOut, [f_graph, g_graph]))) self.wait() self.play(FadeOut(brace)) fg_group = VGroup(*list(f_label)+list(g_label)) self.play( FadeIn(rect), Animation(prefix), Transform(fg_group, suffix), ) self.remove(prefix, fg_group) self.add(sum_def) self.play(ShowCreation(arrow)) self.show_line_addition(f_lines[0], g_lines[0], sum_lines[0]) self.wait() curr_x_point = f_lines[1].get_start() new_sum_def = self.get_sum_definition(DecimalNumber(curr_x_point[0])) new_sum_def.to_corner(UP+LEFT) new_arrow = Arrow(sum_def[2].get_bottom(), curr_x_point, color = WHITE) self.play( Transform(sum_def, new_sum_def), Transform(arrow, new_arrow), ) self.show_line_addition(f_lines[1], g_lines[1], sum_lines[1]) self.wait() final_sum_def = self.get_sum_definition(OldTex("x")) final_sum_def.to_corner(UP+LEFT) self.play( FadeOut(rect), Transform(sum_def, final_sum_def), FadeOut(arrow) ) self.show_line_addition(*it.starmap(VGroup, [ f_lines[2:], g_lines[2:], sum_lines[2:] ])) self.play(ShowCreation(sum_graph)) def get_sum_definition(self, input_mob): result = VGroup(*it.chain( OldTex("(f+g)", "("), [input_mob.copy()], OldTex(")", "=", "f("), [input_mob.copy()], OldTex(")", "+", "g("), [input_mob.copy()], OldTex(")") )) result.arrange() result[0].set_color(self.graph_colors[2]) VGroup(result[5], result[7]).set_color(self.graph_colors[0]) VGroup(result[9], result[11]).set_color(self.graph_colors[1]) return result def show_line_addition(self, f_lines, g_lines, sum_lines): g_lines.target = g_lines.copy() dots = VGroup() dots.target = VGroup() for f_line, g_line in zip(f_lines, g_lines.target): align_perfectly = f_line.get_end()[1]*g_line.get_end()[1] > 0 dot = Dot(g_line.get_end(), radius = 0.07) g_line.shift(f_line.get_end()-g_line.get_start()) dot.target = Dot(g_line.get_end()) if not align_perfectly: g_line.shift(self.line_to_line_buff*RIGHT) dots.add(dot) dots.target.add(dot.target) for group in dots, dots.target: group.set_color(sum_lines[0].get_color()) self.play(ShowCreation(dots)) if len(list(g_lines)) == 1: kwargs = {} else: kwargs = { "lag_ratio" : 0.5, "run_time" : 3 } self.play(*[ MoveToTarget(mob, **kwargs) for mob in (g_lines, dots) ]) # self.play( # *[mob.fade for mob in g_lines, f_lines]+[ # Animation(dots) # ]) self.wait() class AddVectorsCoordinateByCoordinate(Scene): def construct(self): v1 = Matrix(["x_1", "y_1", "z_1"]) v2 = Matrix(["x_2", "y_2", "z_2"]) v_sum = Matrix(["x_1 + x_2", "y_1 + y_2", "z_1 + z_2"]) for v in v1, v2, v_sum: v.get_entries()[0].set_color(X_COLOR) v.get_entries()[1].set_color(Y_COLOR) v.get_entries()[2].set_color(Z_COLOR) plus, equals = OldTex("+=") VGroup(v1, plus, v2, equals, v_sum).arrange() self.add(v1, plus, v2) self.wait() self.play( Write(equals), Write(v_sum.get_brackets()) ) self.play( Transform(v1.get_entries().copy(), v_sum.get_entries()), Transform(v2.get_entries().copy(), v_sum.get_entries()), ) self.wait() class ScaleFunction(FunctionGraphScene): def construct(self): graph = self.get_function_graph( lambda x : self.default_functions[0](x), animate = False ) scaled_graph = self.get_function_graph( lambda x : graph.get_function()(x)*2, animate = False, add = False ) graph_lines = self.get_output_lines(graph) scaled_lines = self.get_output_lines(scaled_graph, nudge = False) f_label = self.label_graph(graph, "f", animate = False) two_f_label = self.label_graph(scaled_graph, "(2f)", animate = False) self.remove(two_f_label) title = OldTex("(2f)", "(x) = 2", "f", "(x)") title.set_color_by_tex("(2f)", scaled_graph.get_color()) title.set_color_by_tex("f", graph.get_color()) title.next_to(ORIGIN, LEFT, buff = MED_SMALL_BUFF) title.to_edge(UP) self.add(title) self.add_lines(graph_lines) self.wait() self.play(Transform(graph_lines, scaled_lines)) self.play(ShowCreation(scaled_graph)) self.play(Write(two_f_label)) self.play(FadeOut(graph_lines)) self.wait() class ScaleVectorByCoordinates(Scene): def construct(self): two, dot, equals = OldTex("2 \\cdot =") v1 = Matrix(list("xyz")) v1.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR, Z_COLOR) v2 = v1.copy() two_targets = VGroup(*[ two.copy().next_to(entry, LEFT) for entry in v2.get_entries() ]) v2.get_brackets()[0].next_to(two_targets, LEFT) v2.add(two_targets) VGroup(two, dot, v1, equals, v2).arrange() self.add(two, dot, v1) self.play( Write(equals), Write(v2.get_brackets()) ) self.play( Transform(two.copy(), two_targets), Transform(v1.get_entries().copy(), v2.get_entries()) ) self.wait() class ShowSlopes(Animation): CONFIG = { "line_color" : YELLOW, "dx" : 0.01, "rate_func" : None, "run_time" : 5 } def __init__(self, graph, **kwargs): digest_config(self, kwargs, locals()) line = Line(LEFT, RIGHT, color = self.line_color) line.save_state() Animation.__init__(self, line, **kwargs) def interpolate_mobject(self, alpha): f = self.graph.point_from_proportion low, high = list(map(f, np.clip([alpha-self.dx, alpha+self.dx], 0, 1))) slope = (high[1]-low[1])/(high[0]-low[0]) self.mobject.restore() self.mobject.rotate(np.arctan(slope)) self.mobject.move_to(f(alpha)) class FromVectorsToFunctions(VectorScene): def construct(self): self.show_vector_addition_and_scaling() self.bring_in_functions() self.show_derivative() def show_vector_addition_and_scaling(self): self.plane = self.add_plane() self.plane.fade() words1 = OldTexText("Vector", "addition") words2 = OldTexText("Vector", "scaling") for words in words1, words2: words.add_background_rectangle() words.next_to(ORIGIN, RIGHT).to_edge(UP) self.add(words1) v = self.add_vector([2, -1], color = MAROON_B) w = self.add_vector([3, 2], color = YELLOW) w.save_state() self.play(w.shift, v.get_end()) vw_sum = self.add_vector(w.get_end(), color = PINK) self.wait() self.play( Transform(words1, words2), FadeOut(vw_sum), w.restore ) self.add( v.copy().fade(), w.copy().fade() ) self.play(v.scale, 2) self.play(w.scale, -0.5) self.wait() def bring_in_functions(self): everything = VGroup(*self.get_mobjects()) axes = Axes() axes.shift(FRAME_WIDTH*LEFT) fg_scene_config = FunctionGraphScene.CONFIG graph = FunctionGraph(fg_scene_config["default_functions"][0]) graph.set_color(MAROON_B) func_tex = OldTex("\\frac{1}{9}x^3 - x") func_tex.set_color(graph.get_color()) func_tex.shift(5.5*RIGHT+2*UP) words = VGroup(*[ OldTexText(words).add_background_rectangle() for words in [ "Linear transformations", "Null space", "Dot products", "Eigen-everything", ] ]) words.set_color_by_gradient(BLUE_B, BLUE_D) words.arrange(DOWN, aligned_edge = LEFT) words.to_corner(UP+LEFT) self.play(FadeIn( words, lag_ratio = 0.5, run_time = 3 )) self.wait() self.play(*[ ApplyMethod(mob.shift, FRAME_WIDTH*RIGHT) for mob in (axes, everything) ] + [Animation(words)] ) self.play(ShowCreation(graph), Animation(words)) self.play(Write(func_tex, run_time = 2)) self.wait(2) top_word = words[0] words.remove(top_word) self.play( FadeOut(words), top_word.shift, top_word.get_center()[0]*LEFT ) self.wait() self.func_tex = func_tex self.graph = graph def show_derivative(self): func_tex, graph = self.func_tex, self.graph new_graph = FunctionGraph(lambda x : (x**2)/3.-1) new_graph.set_color(YELLOW) func_tex.generate_target() lp, rp = parens = OldTex("()") parens.set_height(func_tex.get_height()) L, equals = OldTex("L=") deriv = OldTex("\\frac{d}{dx}") new_func = OldTex("\\frac{1}{3}x^2 - 1") new_func.set_color(YELLOW) group = VGroup( L, lp, func_tex.target, rp, equals, new_func ) group.arrange() group.shift(2*UP).to_edge(LEFT, buff = MED_LARGE_BUFF) rect = BackgroundRectangle(group) group.add_to_back(rect) deriv.move_to(L, aligned_edge = RIGHT) self.play( MoveToTarget(func_tex), *list(map(Write, [L, lp, rp, equals, new_func])) ) self.remove(func_tex) self.add(func_tex.target) self.wait() faded_graph = graph.copy().fade() self.add(faded_graph) self.play( Transform(graph, new_graph, run_time = 2), Animation(group) ) self.wait() self.play(Transform(L, deriv)) self.play(ShowSlopes(faded_graph)) self.wait() class TransformationsAndOperators(TeacherStudentsScene): def construct(self): self.student_says(""" Are these the same as ``linear operators''? """, index = 0) self.random_blink() teacher = self.get_teacher() bubble = teacher.get_bubble(SpeechBubble, height = 2, width = 2) bubble.set_fill(BLACK, opacity = 1) bubble.write("Yup!") self.play( teacher.change_mode, "hooray", ShowCreation(bubble), Write(bubble.content, run_time = 1) ) self.random_blink(2) class ManyFunctions(FunctionGraphScene): def construct(self): randy = Randolph().to_corner(DOWN+LEFT) self.add(randy) for i in range(100): if i < 3: run_time = 1 self.wait() elif i < 10: run_time = 0.4 else: run_time = 0.2 added_anims = [] if i == 3: added_anims = [randy.change_mode, "confused"] if i == 10: added_anims = [randy.change_mode, "pleading"] self.add_random_function( run_time = run_time, added_anims = added_anims ) def add_random_function(self, run_time = 1, added_anims = []): coefs = np.random.randint(-3, 3, np.random.randint(3, 8)) def func(x): return sum([c*x**(i) for i, c, in enumerate(coefs)]) graph = self.get_function_graph(func, animate = False) if graph.get_height() > FRAME_HEIGHT: graph.stretch_to_fit_height(FRAME_HEIGHT) graph.shift(graph.point_from_proportion(0.5)[1]*DOWN) graph.shift(interpolate(-3, 3, random.random())*UP) graph.set_color(random_bright_color()) self.play( ShowCreation(graph, run_time = run_time), *added_anims ) class WhatDoesLinearMean(TeacherStudentsScene): def construct(self): words = OldTexText(""" What does it mean for a transformation of functions to be """, "linear", "?", arg_separator = "" ) words.set_color_by_tex("linear", BLUE) self.student_says(words) self.play_student_changes("pondering") self.random_blink(4) class FormalDefinitionOfLinear(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "include_background_plane" : False, "t_matrix" : [[1, 1], [-0.5, 1]], "w_coords" : [1, 1], "v_coords" : [1, -2], "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, "secondary_line_ratio" : 1 }, } def construct(self): self.plane.fade() self.write_properties() self.show_additive_property() self.show_scaling_property() self.add_words() def write_properties(self): title = OldTexText( "Formal definition of linearity" ) title.add_background_rectangle() title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in "vw"] tex_sets = [ [ ("\\text{Additivity: }",), ("L(", v_tex, "+", w_tex, ")"), ("=", "L(", v_tex, ")", "+", "L(", w_tex, ")"), ], [ ("\\text{Scaling: }",), ("L(", "c", v_tex, ")"), ("=", "c", "L(", v_tex, ")"), ], ] properties = VGroup() for tex_set in tex_sets: words = VGroup(*it.starmap(Tex, tex_set)) for word in words: word.set_color_by_tex(v_tex, YELLOW) word.set_color_by_tex(w_tex, MAROON_B) word.set_color_by_tex("c", GREEN) words.arrange() words.lhs = words[1] words.rhs = words[2] words.add_to_back(BackgroundRectangle(words)) # words.scale(0.8) properties.add(words) properties.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) properties.next_to(h_line, DOWN, buff = MED_LARGE_BUFF).to_edge(LEFT) self.play(Write(title), ShowCreation(h_line)) self.wait() for words in properties: self.play(Write(words)) self.wait() self.add_foreground_mobject(title, h_line, *properties) self.additivity, self.scaling = properties def show_additive_property(self): self.plane.save_state() v = self.add_vector(self.v_coords) v_label = self.add_transformable_label(v, "v", direction = "right") w = self.add_vector(self.w_coords, color = MAROON_B) w_label = self.add_transformable_label(w, "w", direction = "left") w_group = VGroup(w, w_label) w_group.save_state() self.play(w_group.shift, v.get_end()) vw_sum = self.add_vector(w.get_end(), color = PINK) v_label_copy, w_label_copy = v_label.copy(), w_label.copy() v_label_copy.generate_target() w_label_copy.generate_target() plus = OldTex("+") vw_label = VGroup(v_label_copy.target, plus, w_label_copy.target) vw_label.arrange() vw_label.next_to(vw_sum.get_end(), RIGHT) self.play( MoveToTarget(v_label_copy), MoveToTarget(w_label_copy), Write(plus) ) vw_label_copy = vw_label.copy() vw_label = VGroup( VectorizedPoint(vw_label.get_left()), vw_label, VectorizedPoint(vw_label.get_right()), ) self.remove(v_label_copy, w_label_copy, plus) self.add(vw_label) self.play( w_group.restore, ) vw_label.target = VGroup( OldTex("L(").scale(0.8), vw_label_copy, OldTex(")").scale(0.8), ) vw_label.target.arrange() for mob in vw_label, vw_label.target: mob.add_to_back(BackgroundRectangle(mob)) transform = self.get_matrix_transformation(self.t_matrix) point = transform(vw_sum.get_end()) vw_label.target.next_to(point, UP) self.apply_transposed_matrix( self.t_matrix, added_anims = [MoveToTarget(vw_label)] ) self.wait() self.play(w_group.shift, v.get_end()) v_label_copy, w_label_copy = v_label.copy(), w_label.copy() v_label_copy.generate_target() w_label_copy.generate_target() equals, plus = OldTex("=+") rhs = VGroup( equals, v_label_copy.target, plus, w_label_copy.target ) rhs.arrange() rhs.next_to(vw_label, RIGHT) rect = BackgroundRectangle(rhs) self.play(*it.chain( list(map(Write, [rect, equals, plus])), list(map(MoveToTarget, [v_label_copy, w_label_copy])), )) to_fade = [self.plane, v, v_label, w_group, vw_label, vw_sum] to_fade += self.get_mobjects_from_last_animation() self.wait() self.play(*it.chain( list(map(FadeOut, to_fade)), list(map(Animation, self.foreground_mobjects)) )) self.plane.restore() self.play(FadeIn(self.plane), *list(map(Animation, self.foreground_mobjects))) self.transformable_mobjects = [] self.moving_vectors = [] self.transformable_labels = [] self.moving_mobjects = [] self.add_transformable_mobject(self.plane) self.add(*self.foreground_mobjects) def show_scaling_property(self): v = self.add_vector([1, -1]) v_label = self.add_transformable_label(v, "v") scaled_v = v.copy().scale(2) scaled_v_label = OldTex("c\\vec{\\textbf{v}}") scaled_v_label.set_color(YELLOW) scaled_v_label[0].set_color(GREEN) scaled_v_label.next_to(scaled_v.get_end(), RIGHT) scaled_v_label.add_background_rectangle() v_copy, v_label_copy = v.copy(), v_label.copy() self.play( Transform(v_copy, scaled_v), Transform(v_label_copy, scaled_v_label), ) self.remove(v_copy, v_label_copy) self.add(scaled_v_label) self.add_vector(scaled_v, animate = False) self.wait() transform = self.get_matrix_transformation(self.t_matrix) point = transform(scaled_v.get_end()) scaled_v_label.target = OldTex("L(", "c", "\\vec{\\textbf{v}}", ")") scaled_v_label.target.set_color_by_tex("c", GREEN) scaled_v_label.target.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW) scaled_v_label.target.scale(0.8) scaled_v_label.target.next_to(point, RIGHT) scaled_v_label.target.add_background_rectangle() self.apply_transposed_matrix( self.t_matrix, added_anims = [MoveToTarget(scaled_v_label)] ) self.wait() scaled_v = v.copy().scale(2) rhs = OldTex("=", "c", "L(", "\\vec{\\textbf{v}}", ")") rhs.set_color_by_tex("c", GREEN) rhs.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW) rhs.add_background_rectangle() rhs.scale(0.8) rhs.next_to(scaled_v_label, RIGHT) v_copy = v.copy() self.add(v_copy) self.play(Transform(v, scaled_v)) self.play(Write(rhs)) self.wait() faders = [ scaled_v_label, scaled_v, v_copy, v, rhs ] + self.transformable_labels + self.moving_vectors self.play(*list(map(FadeOut, faders))) def add_words(self): randy = Randolph().shift(LEFT).to_edge(DOWN) bubble = randy.get_bubble(SpeechBubble, width = 6, height = 4) bubble.set_fill(BLACK, opacity = 0.8) bubble.shift(0.5*DOWN) VGroup(randy, bubble).to_edge(RIGHT, buff = 0) words = OldTexText( "Linear transformations\\\\", "preserve", "addition and \\\\ scalar multiplication", ) words.scale(0.9) words.set_color_by_tex("preserve", YELLOW) bubble.add_content(words) self.play(FadeIn(randy)) self.play( ShowCreation(bubble), Write(words), randy.change_mode, "speaking", ) self.play(Blink(randy)) self.wait() class CalcStudentsKnowThatDerivIsLinear(TeacherStudentsScene): def construct(self): words = OldTexText( """Calc students subconsciously know that""", "$\\dfrac{d}{dx}$", "is linear" ) words.set_color_by_tex("$\\dfrac{d}{dx}$", BLUE) self.teacher_says(words) self.play_student_changes( "pondering", "confused", "erm" ) self.random_blink(3) class DerivativeIsLinear(Scene): def construct(self): self.add_title() self.prepare_text() self.show_additivity() self.show_scaling() def add_title(self): title = OldTexText("Derivative is linear") title.to_edge(UP) self.add(title) def prepare_text(self): v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in "vw"] additivity = OldTex( "L(", v_tex, "+", w_tex, ")", "=", "L(", v_tex, ")+L(", w_tex, ")" ) scaling = OldTex( "L(", "c", v_tex, ")=", "c", "L(", v_tex, ")" ) for text in additivity, scaling: text.set_color_by_tex(v_tex, YELLOW) text.set_color_by_tex(w_tex, MAROON_B) text.set_color_by_tex("c", GREEN) deriv_tex = "\\dfrac{d}{dx}" deriv_additivity = OldTex( deriv_tex, "(", "x^3", "+", "x^2", ")", "=", deriv_tex, "(", "x^3", ")", "+", deriv_tex, "(", "x^2", ")" ) deriv_scaling = OldTex( deriv_tex, "(", "4", "x^3", ")", "=", "4", deriv_tex, "(", "x^3", ")" ) for text in deriv_additivity, deriv_scaling: text.set_color_by_tex("x^3", YELLOW) text.set_color_by_tex("x^2", MAROON_B) text.set_color_by_tex("4", GREEN) self.additivity = additivity self.scaling = scaling self.deriv_additivity = deriv_additivity self.deriv_scaling = deriv_scaling def show_additivity(self): general, deriv = self.additivity, self.deriv_additivity group = VGroup(general, deriv ) group.arrange(DOWN, buff = 1.5) inner_sum = VGroup(*deriv[2:2+3]) outer_sum_deriv = VGroup(deriv[0], deriv[1], deriv[5]) inner_func1 = deriv[9] outer_deriv1 = VGroup(deriv[7], deriv[8], deriv[10]) plus = deriv[11] inner_func2 = deriv[14] outer_deriv2 = VGroup(deriv[12], deriv[13], deriv[15]) self.play(FadeIn(group)) self.wait() self.point_out(inner_sum) self.point_out(outer_sum_deriv) self.wait() self.point_out(outer_deriv1, outer_deriv2) self.point_out(inner_func1, inner_func2) self.point_out(plus) self.wait() self.play(FadeOut(group)) def show_scaling(self): general, deriv = self.scaling, self.deriv_scaling group = VGroup(general, deriv) group.arrange(DOWN, buff = 1.5) inner_scaling = VGroup(*deriv[2:4]) lhs_deriv = VGroup(deriv[0], deriv[1], deriv[4]) rhs_deriv = VGroup(*deriv[7:]) outer_scaling = deriv[6] self.play(FadeIn(group)) self.wait() self.point_out(inner_scaling) self.point_out(lhs_deriv) self.wait() self.point_out(rhs_deriv) self.point_out(outer_scaling) self.wait() def point_out(self, *terms): anims = [] for term in terms: anims += [ term.scale, 1.2, term.set_color, RED, ] self.play( *anims, run_time = 1, rate_func = there_and_back ) class ProposeDerivativeAsMatrix(TeacherStudentsScene): def construct(self): self.teacher_says( """ Let's describe the derivative with a matrix """, target_mode = "hooray" ) self.random_blink() self.play_student_changes("pondering", "confused", "erm") self.random_blink(3) class PolynomialsHaveArbitrarilyLargeDegree(Scene): def construct(self): polys = VGroup(*list(map(Tex, [ "x^{300} + 9x^2", "4x^{4{,}000{,}000{,}000} + 1", "3x^{\\left(10^{100}\\right)}", "\\vdots" ]))) polys.set_color_by_gradient(BLUE_B, BLUE_D) polys.arrange(DOWN, buff = MED_LARGE_BUFF) polys.scale(1.3) arrow = OldTex("\\Rightarrow").scale(1.5) brace = Brace( Line(UP, DOWN).scale(FRAME_Y_RADIUS).shift(FRAME_X_RADIUS*RIGHT), LEFT ) words = OldTexText("Infinitely many") words.scale(1.5) words.next_to(brace, LEFT) arrow.next_to(words, LEFT) polys.next_to(arrow, LEFT) self.play(Write(polys)) self.wait() self.play( FadeIn(arrow), Write(words), GrowFromCenter(brace) ) self.wait() class GeneneralPolynomialCoordinates(Scene): def construct(self): poly = OldTex( "a_n", "x^n", "+", "a_{n-1}", "x^{n-1}", "+", "\\cdots", "a_1", "x", "+", "a_0", ) poly.set_color_by_tex("a_n", YELLOW) poly.set_color_by_tex("a_{n-1}", MAROON_B) poly.set_color_by_tex("a_1", RED) poly.set_color_by_tex("a_0", GREEN) poly.scale(1.3) array = Matrix( ["a_0", "a_1", "\\vdots", "a_{n-1}", "a_n", "0", "\\vdots"] ) array.get_entries()[0].set_color(GREEN) array.get_entries()[1].set_color(RED) array.get_entries()[3].set_color(MAROON_B) array.get_entries()[4].set_color(YELLOW) array.scale(1.2) equals = OldTex("=").scale(1.3) group = VGroup(poly, equals, array) group.arrange() group.to_edge(RIGHT) pre_entries = VGroup( poly[-1], poly[-4], poly[-5], poly[3], poly[0], VectorizedPoint(poly.get_left()), VectorizedPoint(poly.get_left()), ) self.add(poly, equals, array.get_brackets()) self.wait() self.play( Transform(pre_entries.copy(), array.get_entries()) ) self.wait() class SimplePolynomialCoordinates(Scene): def construct(self): matrix = Matrix(["5", "3", "1", "0", "\\vdots"]) matrix.to_edge(LEFT) self.play(Write(matrix)) self.wait() class IntroducePolynomialSpace(Scene): def construct(self): self.add_title() self.show_polynomial_cloud() self.split_individual_polynomial() self.list_basis_functions() self.show_example_coordinates() self.derivative_as_matrix() def add_title(self): title = OldTexText("Our current space: ", "All polynomials") title.to_edge(UP) title[1].set_color(BLUE) self.play(Write(title)) self.wait() self.title = title def show_polynomial_cloud(self): cloud = ThoughtBubble()[-1] cloud.stretch_to_fit_height(6) cloud.center() polys = VGroup( OldTex("x^2", "+", "3", "x", "+", "5"), OldTex("4x^7-5x^2"), OldTex("x^{100}+2x^{99}+3x^{98}"), OldTex("3x-7"), OldTex("x^{1{,}000{,}000{,}000}+1"), OldTex("\\vdots"), ) polys.set_color_by_gradient(BLUE_B, BLUE_D) polys.arrange(DOWN, buff = MED_SMALL_BUFF) polys.next_to(cloud.get_top(), DOWN, buff = MED_LARGE_BUFF) self.play(ShowCreation(cloud)) for poly in polys: self.play(Write(poly), run_time = 1) self.wait() self.poly1, self.poly2 = polys[0], polys[1] polys.remove(self.poly1) self.play( FadeOut(cloud), FadeOut(polys), self.poly1.next_to, ORIGIN, LEFT, self.poly1.set_color, WHITE ) def split_individual_polynomial(self): leading_coef = OldTex("1") leading_coef.next_to(self.poly1[0], LEFT, aligned_edge = DOWN) self.poly1.add_to_back(leading_coef) one = OldTex("\\cdot", "1") one.next_to(self.poly1[-1], RIGHT, aligned_edge = DOWN) self.poly1.add(one) for mob in leading_coef, one: mob.set_color(BLACK) brace = Brace(self.poly1) brace.text = brace.get_text("Already written as \\\\ a linear combination") index_to_color = { 0 : WHITE, 1 : Z_COLOR, 4 : Y_COLOR, 7 : X_COLOR, } self.play( GrowFromCenter(brace), Write(brace.text), *[ ApplyMethod(self.poly1[index].set_color, color) for index, color in list(index_to_color.items()) ] ) self.wait() self.brace = brace def list_basis_functions(self): title = OldTexText("Basis functions") title.next_to(self.title, DOWN, buff = MED_SMALL_BUFF) title.to_edge(RIGHT) h_line = Line(ORIGIN, RIGHT).scale(title.get_width()) h_line.next_to(title, DOWN) x_cubed = OldTex("x^3") x_cubed.set_color(MAROON_B) x_cubed.to_corner(DOWN+RIGHT).shift(2*(DOWN+RIGHT)) basis_group = VGroup( self.poly1[7][1], self.poly1[4], self.poly1[1], x_cubed ).copy() basis_group.generate_target() basis_group.target.arrange( DOWN, buff = 0.75*LARGE_BUFF, aligned_edge = LEFT ) basis_group.target.to_edge(RIGHT, buff = MED_LARGE_BUFF) dots = OldTex("\\vdots") dots.next_to(basis_group.target, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT) basis_functions = [ OldTex("b_%d(x)"%i, "=") for i in range(len(list(basis_group))) ] for basis_func, term in zip(basis_functions, basis_group.target): basis_func.set_color(term.get_color()) basis_func.next_to(term, LEFT) for i in 2, 3: basis_functions[i].shift(SMALL_BUFF*DOWN) self.play( FadeIn(title), ShowCreation(h_line), MoveToTarget(basis_group), Write(dots) ) for basis_func in basis_functions: self.play(Write(basis_func, run_time = 1)) self.play(Write(dots)) self.wait() self.basis = basis_group self.basis_functions = basis_functions def show_example_coordinates(self): coords = Matrix(["5", "3", "1", "0", "0", "\\vdots"]) for i, color in enumerate([X_COLOR, Y_COLOR, Z_COLOR]): coords[i].set_color(color) self.poly1.generate_target() equals = OldTex("=").next_to(coords, LEFT) self.poly1.target.next_to(equals, LEFT) entries = coords.get_entries() entries.save_state() entries.set_fill(opacity = 0) self.play( MoveToTarget(self.poly1), Write(equals), FadeOut(self.brace), FadeOut(self.brace.text) ) for entry, index in zip(entries, [6, 3, 0]): entry.move_to(self.poly1[index]) self.play(Write(coords.get_brackets())) self.play( entries.restore, lag_ratio = 0.5, run_time = 3 ) self.wait() target = self.poly1.copy() terms = [ VGroup(*target[6:8]), VGroup(target[5], *target[3:5]), VGroup(target[2], *target[0:2]), ] target[5].next_to(target[3], LEFT) target[2].next_to(target[0], LEFT) more_terms = [ OldTex("+0", "x^3").set_color_by_tex("x^3", MAROON_B), OldTex("+0", "x^4").set_color_by_tex("x^4", YELLOW), OldTex("\\vdots") ] for entry, term in zip(entries, terms+more_terms): term.next_to(entry, LEFT, buff = LARGE_BUFF) more_terms[-1].shift(MED_SMALL_BUFF*LEFT) self.play(Transform(self.poly1, target)) self.wait() self.play(FadeIn( VGroup(*more_terms), lag_ratio = 0.5, run_time = 2 )) self.wait() self.play(*list(map(FadeOut, [self.poly1]+more_terms))) self.poly2.next_to(equals, LEFT) self.poly2.shift(MED_SMALL_BUFF*UP) self.poly2.set_color(WHITE) self.poly2[0].set_color(TEAL) VGroup(*self.poly2[3:5]).set_color(Z_COLOR) new_coords = Matrix(["0", "0", "-5", "0", "0", "0", "0", "4", "\\vdots"]) new_coords.get_entries()[2].set_color(Z_COLOR) new_coords.get_entries()[7].set_color(TEAL) new_coords.set_height(6) new_coords.move_to(coords, aligned_edge = LEFT) self.play( Write(self.poly2), Transform(coords, new_coords) ) self.wait() for i, mob in (2, VGroup(*self.poly2[3:5])), (7, self.poly2[0]): self.play( new_coords.get_entries()[i].scale, 1.3, mob.scale, 1.3, rate_func = there_and_back ) self.remove(*self.get_mobjects_from_last_animation()) self.add(self.poly2) self.wait() self.play(*list(map(FadeOut, [self.poly2, coords, equals]))) def derivative_as_matrix(self): matrix = Matrix([ [ str(j) if j == i+1 else "0" for j in range(4) ] + ["\\cdots"] for i in range(4) ] + [ ["\\vdots"]*4 + ["\\ddots"] ]) matrix.shift(2*LEFT) diag_entries = VGroup(*[ matrix.get_mob_matrix()[i, i+1] for i in range(3) ]) ##Horrible last_col = VGroup(*matrix.get_mob_matrix()[:,-1]) last_col_top = last_col.get_top() last_col.arrange(DOWN, buff = 0.83) last_col.move_to(last_col_top, aligned_edge = UP+RIGHT) ##End horrible matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR, MAROON_B) deriv = OldTex("\\dfrac{d}{dx}") equals = OldTex("=") equals.next_to(matrix, LEFT) deriv.next_to(equals, LEFT) self.play(FadeIn(deriv), FadeIn(equals)) self.play(Write(matrix)) self.wait() diag_entries.save_state() diag_entries.generate_target() diag_entries.target.scale(1.2) diag_entries.target.set_color(YELLOW) for anim in MoveToTarget(diag_entries), diag_entries.restore: self.play( anim, lag_ratio = 0.5, run_time = 1.5, ) self.wait() matrix.generate_target() matrix.target.to_corner(DOWN+LEFT).shift(0.25*UP) deriv.generate_target() deriv.target.next_to( matrix.target, UP, buff = MED_SMALL_BUFF, aligned_edge = LEFT ) deriv.target.shift(0.25*RIGHT) self.play( FadeOut(equals), *list(map(MoveToTarget, [matrix, deriv])) ) poly = OldTex( "(", "1", "x^3", "+", "5", "x^2", "+", "4", "x", "+", "5", ")" ) coefs = VGroup(*np.array(poly)[[10, 7, 4, 1]]) VGroup(*poly[1:3]).set_color(MAROON_B) VGroup(*poly[4:6]).set_color(Z_COLOR) VGroup(*poly[7:9]).set_color(Y_COLOR) VGroup(*poly[10:11]).set_color(X_COLOR) poly.next_to(deriv) self.play(FadeIn(poly)) array = Matrix(list(coefs.copy()) + [Tex("\\vdots")]) array.next_to(matrix, RIGHT) self.play(Write(array.get_brackets())) to_remove = [] for coef, entry in zip(coefs, array.get_entries()): self.play(Transform(coef.copy(), entry)) to_remove += self.get_mobjects_from_last_animation() self.play(Write(array.get_entries()[-1])) to_remove += self.get_mobjects_from_last_animation() self.remove(*to_remove) self.add(array) eq1, eq2 = OldTex("="), OldTex("=") eq1.next_to(poly) eq2.next_to(array) poly_result = OldTex( "3", "x^2", "+", "10", "x", "+", "4" ) poly_result.next_to(eq1) brace = Brace(poly_result, buff = 0) self.play(*list(map(Write, [eq1, eq2, brace]))) result_coefs = VGroup(*np.array(poly_result)[[6, 3, 0]]) VGroup(*poly_result[0:2]).set_color(MAROON_B) VGroup(*poly_result[3:5]).set_color(Z_COLOR) VGroup(*poly_result[6:]).set_color(Y_COLOR) result_terms = [ VGroup(*poly_result[6:]), VGroup(*poly_result[3:6]), VGroup(*poly_result[0:3]), ] relevant_entries = VGroup(*array.get_entries()[1:4]) dots = [Tex("\\cdot") for x in range(3)] result_entries = [] for entry, diag_entry, dot in zip(relevant_entries, diag_entries, dots): entry.generate_target() diag_entry.generate_target() group = VGroup(diag_entry.target, dot, entry.target) group.arrange() result_entries.append(group) result_array = Matrix( result_entries + [ OldTex("0"), OldTex("\\vdots") ] ) result_array.next_to(eq2) rects = [ Rectangle( color = YELLOW ).replace( VGroup(*matrix.get_mob_matrix()[i,:]), stretch = True ).stretch_in_place(1.1, 0).stretch_in_place(1.3, 1) for i in range(3) ] vert_rect = Rectangle(color = YELLOW) vert_rect.replace(array.get_entries(), stretch = True) vert_rect.stretch_in_place(1.1, 1) vert_rect.stretch_in_place(1.5, 0) tuples = list(zip( relevant_entries, diag_entries, result_entries, rects, result_terms, coefs[1:] )) self.play(Write(result_array.get_brackets())) for entry, diag_entry, result_entry, rect, result_term, coef in tuples: self.play(FadeIn(rect), FadeIn(vert_rect)) self.wait() self.play( entry.scale, 1.2, diag_entry.scale, 1.2, ) diag_entry_target, dot, entry_target = result_entry self.play( Transform(entry.copy(), entry_target), Transform(diag_entry.copy(), diag_entry_target), entry.scale, 1/1.2, diag_entry.scale, 1/1.2, Write(dot) ) self.wait() self.play(Transform(coef.copy(), VGroup(result_term))) self.wait() self.play(FadeOut(rect), FadeOut(vert_rect)) self.play(*list(map(Write, result_array.get_entries()[3:]))) self.wait() class MatrixVectorMultiplicationAndDerivative(TeacherStudentsScene): def construct(self): mv_mult = VGroup( Matrix([[3, 1], [0, 2]]).set_column_colors(X_COLOR, Y_COLOR), Matrix(["x", "y"]).set_column_colors(YELLOW) ) mv_mult.arrange() mv_mult.scale(0.75) arrow = OldTex("\\Leftrightarrow") deriv = OldTex("\\dfrac{df}{dx}") group = VGroup(mv_mult, arrow, deriv) group.arrange(buff = MED_SMALL_BUFF) arrow.set_color(BLACK) teacher = self.get_teacher() bubble = teacher.get_bubble(SpeechBubble, height = 4) bubble.add_content(group) self.play( teacher.change_mode, "speaking", ShowCreation(bubble), Write(group) ) self.random_blink() group.generate_target() group.target.scale(0.8) words = OldTexText("Linear transformations") h_line = Line(ORIGIN, RIGHT).scale(words.get_width()) h_line.next_to(words, DOWN) group.target.next_to(h_line, DOWN, buff = MED_SMALL_BUFF) group.target[1].set_color(WHITE) new_group = VGroup(words, h_line, group.target) bubble.add_content(new_group) self.play( MoveToTarget(group), ShowCreation(h_line), Write(words), self.get_teacher().change_mode, "hooray" ) self.play_student_changes(*["pondering"]*3) self.random_blink(3) class CompareTermsInLinearAlgebraToFunction(Scene): def construct(self): l_title = OldTexText("Linear algebra \\\\ concepts") r_title = OldTexText("Alternate names when \\\\ applied to functions") for title, vect in (l_title, LEFT), (r_title, RIGHT): title.to_edge(UP) title.shift(vect*FRAME_X_RADIUS/2) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.shift( VGroup(l_title, r_title).get_bottom()[1]*UP + SMALL_BUFF*DOWN ) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) VGroup(h_line, v_line).set_color(BLUE) self.add(l_title, r_title) self.play(*list(map(ShowCreation, [h_line, v_line]))) self.wait() lin_alg_concepts = VGroup(*list(map(TexText, [ "Linear transformations", "Dot products", "Eigenvectors", ]))) function_concepts = VGroup(*list(map(TexText, [ "Linear operators", "Inner products", "Eigenfunctions", ]))) for concepts, vect in (lin_alg_concepts, LEFT), (function_concepts, RIGHT): concepts.arrange(DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT) concepts.next_to(h_line, DOWN, buff = LARGE_BUFF) concepts.shift(vect*FRAME_X_RADIUS/2) concepts.set_color_by_gradient(YELLOW_B, YELLOW_C) for concept in concepts: self.play(Write(concept, run_time = 1)) self.wait() class BackToTheQuestion(TeacherStudentsScene): def construct(self): self.student_says( """ Wait...so how does this relate to what vectors really are? """, target_mode = "confused" ) self.random_blink(2) self.teacher_says( """ There are many different vector-ish things """ ) self.random_blink(2) class YouAsAMathematician(Scene): def construct(self): mathy = Mathematician() mathy.to_corner(DOWN+LEFT) words = OldTexText("You as a mathematician") words.shift(2*UP) arrow = Arrow(words.get_bottom(), mathy.get_corner(UP+RIGHT)) bubble = mathy.get_bubble() equations = self.get_content() bubble.add_content(equations) self.add(mathy) self.play(Write(words, run_time = 2)) self.play( ShowCreation(arrow), mathy.change_mode, "wave_1", mathy.look, OUT ) self.play(Blink(mathy)) self.wait() self.play( FadeOut(words), FadeOut(arrow), mathy.change_mode, "pondering", ShowCreation(bubble), ) self.play(Write(equations)) self.play(Blink(mathy)) self.wait() bubble.write("Does this make any sense \\\\ for functions too?") self.play( equations.next_to, mathy.eyes, RIGHT, 2*LARGE_BUFF, mathy.change_mode, "confused", mathy.look, RIGHT, Write(bubble.content) ) self.wait() self.play(Blink(mathy)) def get_content(self): v_tex = "\\vec{\\textbf{v}}" eigen_equation = OldTex("A", v_tex, "=", "\\lambda", v_tex) v_ne_zero = OldTex(v_tex, "\\ne \\vec{\\textbf{0}}") det_equation = OldTex("\\det(A-", "\\lambda", "I)=0") arrow = OldTex("\\Rightarrow") for tex in eigen_equation, v_ne_zero, det_equation: tex.set_color_by_tex(v_tex, YELLOW) tex.set_color_by_tex("\\lambda", MAROON_B) lhs = VGroup(eigen_equation, v_ne_zero) lhs.arrange(DOWN) group = VGroup(lhs, arrow, det_equation) group.arrange(buff = MED_SMALL_BUFF) return group class ShowVectorSpaces(Scene): def construct(self): title = OldTexText("Vector spaces") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) v_lines = [ Line( h_line.get_center(), FRAME_Y_RADIUS*DOWN ).shift(vect*FRAME_X_RADIUS/3.) for vect in (LEFT, RIGHT) ] vectors = self.get_vectors() vectors.shift(LEFT*FRAME_X_RADIUS*(2./3)) arrays = self.get_arrays() functions = self.get_functions() functions.shift(RIGHT*FRAME_X_RADIUS*(2./3)) self.add(h_line, *v_lines) self.play(ShowCreation( vectors, run_time = 3 )) self.play(Write(arrays)) self.play(Write(functions)) self.wait() self.play(Write(title)) def get_vectors(self, n_vectors = 10): vectors = VGroup(*[ Vector(RIGHT).scale(scalar).rotate(angle) for scalar, angle in zip( 2*np.random.random(n_vectors)+0.5, np.linspace(0, 6, n_vectors) ) ]) vectors.set_color_by_gradient(YELLOW, MAROON_B) return vectors def get_arrays(self): arrays = VGroup(*[ VGroup(*[ Matrix(np.random.randint(-9, 9, 2)) for x in range(4) ]) for x in range(3) ]) for subgroup in arrays: subgroup.arrange(DOWN, buff = MED_SMALL_BUFF) arrays.arrange(RIGHT) arrays.scale(0.7) arrays.set_color_by_gradient(YELLOW, MAROON_B) return arrays def get_functions(self): axes = Axes() axes.scale(0.3) functions = VGroup(*[ FunctionGraph(func, x_min = -4, x_max = 4) for func in [ lambda x : x**3 - 9*x, lambda x : x**3 - 4*x, lambda x : x**2 - 1, ] ]) functions.stretch_to_fit_width(FRAME_X_RADIUS/2.) functions.stretch_to_fit_height(6) functions.set_color_by_gradient(YELLOW, MAROON_B) functions.center() return VGroup(axes, functions) class ToolsOfLinearAlgebra(Scene): def construct(self): words = VGroup(*list(map(TexText, [ "Linear transformations", "Null space", "Eigenvectors", "Dot products", "$\\vdots$" ]))) words.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) words[-1].next_to(words[-2], DOWN) self.play(FadeIn( words, lag_ratio = 0.5, run_time = 3 )) self.wait() class MathematicianSpeakingToAll(Scene): def construct(self): mathy = Mathematician().to_corner(DOWN+LEFT) others = VGroup(*[ Randolph().flip().set_color(color) for color in (BLUE_D, GREEN_E, GOLD_E, BLUE_C) ]) others.arrange() others.scale(0.8) others.to_corner(DOWN+RIGHT) bubble = mathy.get_bubble(SpeechBubble) bubble.write(""" I don't want to think about all y'all's crazy vector spaces """) self.add(mathy, others) self.play( ShowCreation(bubble), Write(bubble.content), mathy.change_mode, "sassy", mathy.look_at, others ) self.play(Blink(others[3])) self.wait() thought_bubble = mathy.get_bubble(ThoughtBubble) self.play( FadeOut(bubble.content), Transform(bubble, thought_bubble), mathy.change_mode, "speaking", mathy.look_at, bubble, *[ApplyMethod(pi.look_at, bubble) for pi in others] ) vect = -bubble.get_bubble_center() def func(point): centered = point+vect return 10*centered/get_norm(centered) self.play(*[ ApplyPointwiseFunction(func, mob) for mob in self.get_mobjects() ]) class ListAxioms(Scene): def construct(self): title = OldTexText("Rules for vectors addition and scaling") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title, h_line) u_tex, v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in "uvw"] axioms = VGroup(*it.starmap(Tex, [ ( "1. \\,", u_tex, "+", "(", v_tex, "+", w_tex, ")=(", u_tex, "+", v_tex, ")+", w_tex ), ( "2. \\,", v_tex, "+", w_tex, "=", w_tex, "+", v_tex ), ( "3. \\,", "\\text{There is a vector }", "\\textbf{0}", "\\text{ such that }", "\\textbf{0}+", v_tex, "=", v_tex, "\\text{ for all }", v_tex ), ( "4. \\,", "\\text{For every vector }", v_tex, "\\text{ there is a vector }", "-", v_tex, "\\text{ so that }", v_tex, "+", "(-", v_tex, ")=\\textbf{0}" ), ( "5. \\,", "a", "(", "b", v_tex, ")=(", "a", "b", ")", v_tex ), ( "6. \\,", "1", v_tex, "=", v_tex ), ( "7. \\,", "a", "(", v_tex, "+", w_tex, ")", "=", "a", v_tex, "+", "a", w_tex ), ( "8. \\,", "(", "a", "+", "b", ")", v_tex, "=", "a", v_tex, "+", "b", v_tex ), ])) tex_color_pairs = [ (v_tex, YELLOW), (w_tex, MAROON_B), (u_tex, PINK), ("a", BLUE), ("b", GREEN) ] for axiom in axioms: for tex, color in tex_color_pairs: axiom.set_color_by_tex(tex, color) axioms.arrange( DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT ) axioms.set_width(FRAME_WIDTH-1) axioms.next_to(h_line, DOWN, buff = MED_SMALL_BUFF) self.play(FadeIn( axioms, lag_ratio = 0.5, run_time = 5 )) self.wait() axioms_word = OldTexText("``Axioms''") axioms_word.set_color(YELLOW) axioms_word.scale(2) axioms_word.shift(FRAME_X_RADIUS*RIGHT/2, FRAME_Y_RADIUS*DOWN/2) self.play(Write(axioms_word, run_time = 3)) self.wait() class AxiomsAreInterface(Scene): def construct(self): mathy = Mathematician().to_edge(LEFT) mathy.change_mode("pondering") others = [ Randolph().flip().set_color(color) for color in (BLUE_D, GREEN_E, GOLD_E, BLUE_C) ] others = VGroup( VGroup(*others[:2]), VGroup(*others[2:]), ) for group in others: group.arrange(RIGHT) others.arrange(DOWN) others.scale(0.8) others.to_edge(RIGHT) VGroup(mathy, others).to_edge(DOWN) double_arrow = DoubleArrow(mathy, others) axioms, are, rules_of_nature = words = OldTexText( "Axioms", "are", "rules of nature" ) words.to_edge(UP) axioms.set_color(YELLOW) an_interface = OldTexText("an interface") an_interface.next_to(rules_of_nature, DOWN) red_line = Line( rules_of_nature.get_left(), rules_of_nature.get_right(), color = RED ) self.play(Write(words)) self.wait() self.play(ShowCreation(red_line)) self.play(Transform( rules_of_nature.copy(), an_interface )) self.wait() self.play(FadeIn(mathy)) self.play( ShowCreation(double_arrow), FadeIn(others, lag_ratio = 0.5, run_time = 2) ) self.play(axioms.copy().next_to, double_arrow, UP) self.play(Blink(mathy)) self.wait() class VectorSpaceOfPiCreatures(Scene): def construct(self): creatures = self.add_creatures() self.show_sum(creatures) def add_creatures(self): creatures = VGroup(*[ VGroup(*[ PiCreature() for x in range(4) ]).arrange(RIGHT, buff = 1.5) for y in range(4) ]).arrange(DOWN, buff = 1.5) creatures = VGroup(*it.chain(*creatures)) creatures.set_height(FRAME_HEIGHT-1) for pi in creatures: pi.change_mode(random.choice([ "pondering", "pondering", "happy", "happy", "happy", "confused", "angry", "erm", "sassy", "hooray", "speaking", "tired", "plain", "plain" ])) if random.random() < 0.5: pi.flip() pi.shift(0.5*(random.random()-0.5)*RIGHT) pi.shift(0.5*(random.random()-0.5)*UP) pi.set_color(random.choice([ BLUE_B, BLUE_C, BLUE_D, BLUE_E, MAROON_B, MAROON_C, MAROON_D, MAROON_E, GREY_BROWN, GREY_BROWN, GREY, YELLOW_C, YELLOW_D, YELLOW_E ])) pi.scale(random.random()+0.5) self.play(FadeIn( creatures, lag_ratio = 0.5, run_time = 3 )) self.wait() return creatures def show_sum(self, creatures): def is_valid(pi1, pi2, pi3): if len(set([pi.get_color() for pi in (pi1, pi2, pi3)])) < 3: return False if pi1.is_flipped()^pi2.is_flipped(): return False return True pi1, pi2, pi3 = pis = [random.choice(creatures) for x in range(3)] while not is_valid(pi1, pi2, pi3): pi1, pi2, pi3 = pis = [random.choice(creatures) for x in range(3)] creatures.remove(*pis) transform = Transform(pi1.copy(), pi2.copy()) transform.update(0.5) sum_pi = transform.mobject sum_pi.set_height(pi1.get_height()+pi2.get_height()) for pi in pis: pi.generate_target() plus, equals = OldTex("+=") sum_equation = VGroup( pi1.target, plus, pi2.target, equals, sum_pi ) sum_equation.arrange().center() scaled_pi3 = pi3.copy().scale(2) equals2 = OldTex("=") two = OldTex("2 \\cdot") scale_equation = VGroup( two, pi3.target, equals2, scaled_pi3 ) scale_equation.arrange() VGroup(sum_equation, scale_equation).arrange( DOWN, buff = MED_SMALL_BUFF ) self.play(FadeOut(creatures)) self.play(*it.chain( list(map(MoveToTarget, [pi1, pi2, pi3])), list(map(Write, [plus, equals, two, equals2])), )) self.play( Transform(pi1.copy(), sum_pi), Transform(pi2.copy(), sum_pi), Transform(pi3.copy(), scaled_pi3) ) self.remove(*self.get_mobjects_from_last_animation()) self.add(sum_pi, scaled_pi3) for pi in pi1, sum_pi, scaled_pi3, pi3: self.play(Blink(pi)) class MathematicianDoesntHaveToThinkAboutThat(Scene): def construct(self): mathy = Mathematician().to_corner(DOWN+LEFT) bubble = mathy.get_bubble(ThoughtBubble, height = 4) words = OldTexText("I don't have to worry", "\\\\ about that madness!") bubble.add_content(words) new_words = OldTexText("So long as I", "\\\\ work abstractly") bubble.add_content(new_words) self.play( mathy.change_mode, "hooray", ShowCreation(bubble), Write(words) ) self.play(Blink(mathy)) self.wait() self.play( mathy.change_mode, "pondering", Transform(words, new_words) ) self.play(Blink(mathy)) self.wait() class TextbooksAreAbstract(TeacherStudentsScene): def construct(self): self.student_says( """ All the textbooks I found are pretty abstract. """, target_mode = "pleading" ) self.random_blink(3) self.teacher_says( """ For each new concept, contemplate it for 2d space with grid lines... """ ) self.play_student_changes("pondering") self.random_blink(2) self.teacher_says( "...then in some different\\\\", "context, like a function space" ) self.play_student_changes(*["pondering"]*2) self.random_blink() self.teacher_says( "Only then should you\\\\", "think from the axioms", target_mode = "surprised" ) self.play_student_changes(*["pondering"]*3) self.random_blink() class LastAskWhatAreVectors(TeacherStudentsScene): def construct(self): self.student_says( "So...what are vectors?", target_mode = "erm" ) self.random_blink() self.teacher_says( """ The form they take doesn't really matter """ ) self.random_blink() class WhatIsThree(Scene): def construct(self): what_is, three, q_mark = words = OldTexText( "What is ", "3", "?", arg_separator = "" ) words.scale(1.5) self.play(Write(words)) self.wait() self.play( FadeOut(what_is), FadeOut(q_mark), three.center ) triplets = [ VGroup(*[ PiCreature(color = color).scale(0.4) for color in (BLUE_E, BLUE_C, BLUE_D) ]), VGroup(*[HyperCube().scale(0.3) for x in range(3)]), VGroup(*[Vector(RIGHT) for x in range(3)]), OldTex(""" \\Big\\{ \\emptyset, \\{\\emptyset\\}, \\{\\{\\emptyset\\}, \\emptyset\\} \\Big\\} """) ] directions = [UP+LEFT, UP+RIGHT, DOWN+LEFT, DOWN+RIGHT] for group, vect in zip(triplets, directions): if isinstance(group, Tex): pass elif isinstance(group[0], Vector): group.arrange(RIGHT) group.set_color_by_gradient(YELLOW, MAROON_B) else: m1, m2, m3 = group m2.next_to(m1, buff = MED_SMALL_BUFF) m3.next_to(VGroup(m1, m2), DOWN, buff = MED_SMALL_BUFF) group.next_to(three, vect, buff = LARGE_BUFF) self.play(FadeIn(group)) self.wait() self.play(*[ Transform( trip, three, lag_ratio = 0.5, run_time = 2 ) for trip in triplets ]) class IStillRecommendConcrete(TeacherStudentsScene): def construct(self): self.teacher_says(""" I still recommend thinking concretely """) self.random_blink(2) self.student_thinks("") self.zoom_in_on_thought_bubble() class AbstractionIsThePrice(Scene): def construct(self): words = OldTexText( "Abstractness", "is the price\\\\" "of", "generality" ) words.set_color_by_tex("Abstractness", YELLOW) words.set_color_by_tex("generality", BLUE) self.play(Write(words)) self.wait() class ThatsAWrap(TeacherStudentsScene): def construct(self): self.teacher_says("That's all for now!") self.random_blink(2) class GoodLuck(TeacherStudentsScene): def construct(self): self.teacher_says( "Good luck with \\\\ your future learning!", target_mode = "hooray" ) self.play_student_changes(*["happy"]*3) self.random_blink(3)
videos_3b1b/_2016/eola/footnote2.py
from manim_imports_ext import * from ka_playgrounds.circuits import Resistor, Source, LongResistor class OpeningQuote(Scene): def construct(self): words = OldTexText( "``On this quiz, I asked you to find the determinant of a", "2x3 matrix.", "Some of you, to my great amusement, actually tried to do this.''" ) words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) words[1].set_color(GREEN) author = OldTexText("-(Via mathprofessorquotes.com, no name listed)") author.set_color(YELLOW) author.scale(0.7) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(2) self.play(Write(author, run_time = 3)) self.wait() class AnotherFootnote(TeacherStudentsScene): def construct(self): self.teacher.look(LEFT) self.teacher_says( "More footnotes!", target_mode = "surprised", run_time = 1 ) self.random_blink(2) class ColumnsRepresentBasisVectors(Scene): def construct(self): matrix = Matrix([[3, 1], [4, 1], [5, 9]]) i_hat_words, j_hat_words = [ OldTexText("Where $\\hat{\\%smath}$ lands"%char) for char in ("i", "j") ] i_hat_words.set_color(X_COLOR) i_hat_words.next_to(ORIGIN, LEFT).to_edge(UP) j_hat_words.set_color(Y_COLOR) j_hat_words.next_to(ORIGIN, RIGHT).to_edge(UP) question = OldTexText("How to interpret?") question.next_to(matrix, UP) question.set_color(YELLOW) self.add(matrix) self.play(Write(question, run_time = 2)) self.wait() self.play(FadeOut(question)) for i, words in enumerate([i_hat_words, j_hat_words]): arrow = Arrow( words.get_bottom(), matrix.get_mob_matrix()[0,i].get_top(), color = words.get_color() ) self.play( Write(words, run_time = 1), ShowCreation(arrow), *[ ApplyMethod(m.set_color, words.get_color()) for m in matrix.get_mob_matrix()[:,i] ] ) self.wait(2) self.put_in_thought_bubble() def put_in_thought_bubble(self): everything = VMobject(*self.get_mobjects()) randy = Randolph().to_corner() bubble = randy.get_bubble() self.play(FadeIn(randy)) self.play( ApplyFunction( lambda m : bubble.position_mobject_inside( m.set_height(2.5) ), everything ), ShowCreation(bubble), randy.change_mode, "pondering" ) self.play(Blink(randy)) self.wait() self.play(randy.change_mode, "surprised") self.wait() class Symbolic2To3DTransform(Scene): def construct(self): func = OldTex("L(", "\\vec{\\textbf{v}}", ")") input_array = Matrix([2, 7]) input_array.set_color(YELLOW) in_arrow = Arrow(LEFT, RIGHT, color = input_array.get_color()) func[1].set_color(input_array.get_color()) output_array = Matrix([1, 8, 2]) output_array.set_color(PINK) out_arrow = Arrow(LEFT, RIGHT, color = output_array.get_color()) VMobject( input_array, in_arrow, func, out_arrow, output_array ).arrange(RIGHT, buff = SMALL_BUFF) input_brace = Brace(input_array, DOWN) input_words = input_brace.get_text("2d input") output_brace = Brace(output_array, UP) output_words = output_brace.get_text("3d output") input_words.set_color(input_array.get_color()) output_words.set_color(output_array.get_color()) self.add(func, input_array) self.play( GrowFromCenter(input_brace), Write(input_words) ) mover = input_array.copy() self.play( Transform(mover, Dot().move_to(func)), ShowCreation(in_arrow), rate_func = rush_into ) self.play( Transform(mover, output_array), ShowCreation(out_arrow), rate_func = rush_from ) self.play( GrowFromCenter(output_brace), Write(output_words) ) self.wait() class PlaneStartState(LinearTransformationScene): def construct(self): self.add_title("Input space") labels = self.get_basis_vector_labels() self.play(*list(map(Write, labels))) self.wait() class OutputIn3dWords(Scene): def construct(self): words = OldTexText("Output in 3d") words.scale(1.5) self.play(Write(words)) self.wait() class OutputIn3d(Scene): pass class ShowSideBySide2dTo3d(Scene): pass class AnimationLaziness(Scene): def construct(self): self.add(OldTexText("But there is some animation laziness...")) class DescribeColumnsInSpecificTransformation(Scene): def construct(self): matrix = Matrix([ [2, 0], [-1, 1], [-2, 1], ]) matrix.set_column_colors(X_COLOR, Y_COLOR) mob_matrix = matrix.get_mob_matrix() i_col, j_col = [VMobject(*mob_matrix[:,i]) for i in (0, 1)] for col, char, vect in zip([i_col, j_col], ["i", "j"], [UP, DOWN]): color = col[0].get_color() col.words = OldTexText("Where $\\hat\\%smath$ lands"%char) col.words.next_to(matrix, vect, buff = LARGE_BUFF) col.words.set_color(color) col.arrow = Arrow( col.words.get_edge_center(-vect), col.get_edge_center(vect), color = color ) self.play(Write(matrix.get_brackets())) self.wait() for col in i_col, j_col: self.play( Write(col), ShowCreation(col.arrow), Write(col.words, run_time = 1) ) self.wait() class CountRowsAndColumns(Scene): def construct(self): matrix = Matrix([ [2, 0], [-1, 1], [-2, 1], ]) matrix.set_column_colors(X_COLOR, Y_COLOR) rows_brace = Brace(matrix, LEFT) rows_words = rows_brace.get_text("3", "rows") rows_words.set_color(PINK) cols_brace = Brace(matrix, UP) cols_words = cols_brace.get_text("2", "columns") cols_words.set_color(TEAL) title = OldTex("3", "\\times", "2", "\\text{ matrix}") title.to_edge(UP) self.add(matrix) self.play( GrowFromCenter(rows_brace), Write(rows_words, run_time = 2) ) self.play( GrowFromCenter(cols_brace), Write(cols_words, run_time = 2) ) self.wait() self.play( rows_words[0].copy().move_to, title[0], cols_words[0].copy().move_to, title[2], Write(VMobject(title[1], title[3])) ) self.wait() class WriteColumnSpaceDefinition(Scene): def construct(self): matrix = Matrix([ [2, 0], [-1, 1], [-2, 1], ]) matrix.set_column_colors(X_COLOR, Y_COLOR) brace = Brace(matrix) words = VMobject( OldTexText("Span", "of columns"), OldTex("\\Updownarrow"), OldTexText("``Column space''") ) words.arrange(DOWN, buff = 0.1) words.next_to(brace, DOWN) words[0][0].set_color(PINK) words[2].set_color(TEAL) words[0].add_background_rectangle() words[2].add_background_rectangle() VMobject(matrix, brace, words).center() self.add(matrix) self.play( GrowFromCenter(brace), Write(words, run_time = 2) ) self.wait() class MatrixInTheWild(Scene): def construct(self): randy = Randolph(color = PINK) randy.look(LEFT) randy.to_corner() matrix = Matrix([ [3, 1], [4, 1], [5, 9], ]) matrix.next_to(randy, RIGHT, buff = LARGE_BUFF, aligned_edge = DOWN) bubble = randy.get_bubble(height = 4) bubble.make_green_screen() VMobject(randy, bubble, matrix).to_corner(UP+LEFT, buff = MED_SMALL_BUFF) self.add(randy) self.play(Write(matrix)) self.play(randy.look, RIGHT, run_time = 0.5) self.play(randy.change_mode, "sassy") self.play(Blink(randy)) self.play( ShowCreation(bubble), randy.change_mode, "pondering" ) # self.play(matrix.set_column_colors, X_COLOR, Y_COLOR) self.wait() for x in range(3): self.play(Blink(randy)) self.wait(2) new_matrix = Matrix([[3, 1, 4], [1, 5, 9]]) new_matrix.move_to(matrix, aligned_edge = UP+LEFT) self.play( Transform(matrix, new_matrix), FadeOut(bubble) ) self.remove(matrix) matrix = new_matrix self.add(matrix) self.play(randy.look, DOWN+RIGHT, run_time = 0.5) self.play(randy.change_mode, "confused") self.wait() self.play(Blink(randy)) self.wait() top_brace = Brace(matrix, UP) top_words = top_brace.get_text("3 basis vectors") top_words.set_submobject_colors_by_gradient(GREEN, RED, BLUE) side_brace = Brace(matrix, RIGHT) side_words = side_brace.get_text(""" 2 coordinates for each landing spots """) side_words.set_color(YELLOW) self.play( GrowFromCenter(top_brace), Write(top_words), matrix.set_column_colors, X_COLOR, Y_COLOR, Z_COLOR ) self.play(randy.change_mode, "happy") self.play( GrowFromCenter(side_brace), Write(side_words, run_time = 2) ) self.play(Blink(randy)) self.wait() class ThreeDToTwoDInput(Scene): pass class ThreeDToTwoDInputWords(Scene): def construct(self): words = OldTexText("3d input") words.scale(2) self.play(Write(words)) self.wait() class ThreeDToTwoDOutput(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "foreground_plane_kwargs" : { "color" : GREY, "x_radius" : FRAME_X_RADIUS, "y_radius" : FRAME_Y_RADIUS, "secondary_line_ratio" : 0 }, } def construct(self): title = OldTexText("Output in 2d") title.to_edge(UP, buff = SMALL_BUFF) subwords = OldTexText(""" (only showing basis vectors, full 3d grid would be a mess) """) subwords.scale(0.75) subwords.next_to(title, DOWN) for words in title, subwords: words.add_background_rectangle() self.add(title) i, j, k = it.starmap(self.add_vector, [ ([3, 1], X_COLOR), ([1, 2], Y_COLOR), ([-2, -2], Z_COLOR) ]) pairs = [ (i, "L(\\hat\\imath)"), (j, "L(\\hat\\jmath)"), (k, "L(\\hat k)") ] for v, tex in pairs: self.label_vector(v, tex) self.play(Write(subwords)) self.wait() class ThreeDToTwoDSideBySide(Scene): pass class Symbolic2To1DTransform(Scene): def construct(self): func = OldTex("L(", "\\vec{\\textbf{v}}", ")") input_array = Matrix([2, 7]) input_array.set_color(YELLOW) in_arrow = Arrow(LEFT, RIGHT, color = input_array.get_color()) func[1].set_color(input_array.get_color()) output_array = Matrix([1.8]) output_array.set_color(PINK) out_arrow = Arrow(LEFT, RIGHT, color = output_array.get_color()) VMobject( input_array, in_arrow, func, out_arrow, output_array ).arrange(RIGHT, buff = SMALL_BUFF) input_brace = Brace(input_array, DOWN) input_words = input_brace.get_text("2d input") output_brace = Brace(output_array, UP) output_words = output_brace.get_text("1d output") input_words.set_color(input_array.get_color()) output_words.set_color(output_array.get_color()) self.add(func, input_array) self.play( GrowFromCenter(input_brace), Write(input_words) ) mover = input_array.copy() self.play( Transform(mover, Dot().move_to(func)), ShowCreation(in_arrow), rate_func = rush_into, run_time = 0.5 ) self.play( Transform(mover, output_array), ShowCreation(out_arrow), rate_func = rush_from, run_time = 0.5 ) self.play( GrowFromCenter(output_brace), Write(output_words) ) self.wait() class TwoDTo1DTransform(LinearTransformationScene): CONFIG = { "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_X_RADIUS, "y_radius" : FRAME_Y_RADIUS, "secondary_line_ratio" : 1 }, "t_matrix" : [[1, 0], [2, 0]], } def construct(self): line = NumberLine() plane_words = OldTexText("2d space") plane_words.next_to(self.j_hat, UP, buff = MED_SMALL_BUFF) plane_words.add_background_rectangle() line_words = OldTexText("1d space (number line)") line_words.next_to(line, UP) self.play(Write(plane_words)) self.wait() self.remove(plane_words) mobjects = self.get_mobjects() self.play( *list(map(FadeOut, mobjects)) + [ShowCreation(line)] ) self.play(Write(line_words)) self.wait() self.remove(line_words) self.play(*list(map(FadeIn, mobjects))) self.apply_transposed_matrix(self.t_matrix) self.play(Write(VMobject(*line.get_number_mobjects()))) self.wait() self.show_matrix() def show_matrix(self): for vect, char in zip([self.i_hat, self.j_hat], ["i", "j"]): vect.words = OldTexText( "$\\hat\\%smath$ lands on"%char, str(int(vect.get_end()[0])) ) direction = UP if vect is self.i_hat else DOWN vect.words.next_to(vect.get_end(), direction, buff = LARGE_BUFF) vect.words.set_color(vect.get_color()) matrix = Matrix([[1, 2]]) matrix_words = OldTexText("Transformation matrix: ") matrix_group = VMobject(matrix_words, matrix) matrix_group.arrange(buff = MED_SMALL_BUFF) matrix_group.to_edge(UP) entries = matrix.get_entries() self.play(Write(matrix_words), Write(matrix.get_brackets())) for i, vect in enumerate([self.i_hat, self.j_hat]): self.play(vect.rotate, np.pi/12, rate_func = wiggle) self.play(Write(vect.words)) self.wait() self.play(vect.words[1].copy().move_to, entries[i]) self.wait() class TwoDTo1DTransformWithDots(TwoDTo1DTransform): def construct(self): line = NumberLine() self.add(line, *self.get_mobjects()) offset = LEFT+DOWN vect = 2*RIGHT+UP dots = VMobject(*[ Dot(offset + a*vect, radius = 0.075) for a in np.linspace(-2, 3, 18) ]) dots.set_submobject_colors_by_gradient(YELLOW_B, YELLOW_C) func = self.get_matrix_transformation(self.t_matrix) new_dots = VMobject(*[ Dot( func(dot.get_center()), color = dot.get_color(), radius = dot.radius ) for dot in dots ]) words = OldTexText( "Line of dots remains evenly spaced" ) words.next_to(line, UP, buff = MED_SMALL_BUFF) self.play(Write(dots)) self.apply_transposed_matrix( self.t_matrix, added_anims = [Transform(dots, new_dots)] ) self.play(Write(words)) self.wait() class NextVideo(Scene): def construct(self): title = OldTexText(""" Next video: Dot products and duality """) title.set_width(FRAME_WIDTH - 2) title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class DotProductPreview(VectorScene): CONFIG = { "v_coords" : [3, 1], "w_coords" : [2, -1], "v_color" : YELLOW, "w_color" : MAROON_C, } def construct(self): self.lock_in_faded_grid() self.add_symbols() self.add_vectors() self.grow_number_line() self.project_w() self.show_scaling() def add_symbols(self): v = matrix_to_mobject(self.v_coords).set_color(self.v_color) w = matrix_to_mobject(self.w_coords).set_color(self.w_color) v.add_background_rectangle() w.add_background_rectangle() dot = OldTex("\\cdot") eq = VMobject(v, dot, w) eq.arrange(RIGHT, buff = SMALL_BUFF) eq.to_corner(UP+LEFT) self.play(Write(eq), run_time = 1) def add_vectors(self): self.v = Vector(self.v_coords, color = self.v_color) self.w = Vector(self.w_coords, color = self.w_color) self.play(ShowCreation(self.v)) self.play(ShowCreation(self.w)) def grow_number_line(self): line = NumberLine(stroke_width = 2).add_numbers() line.rotate(self.v.get_angle()) self.play(Write(line), Animation(self.v)) self.play( line.set_color, self.v.get_color(), Animation(self.v), rate_func = there_and_back ) self.wait() def project_w(self): dot_product = np.dot(self.v.get_end(), self.w.get_end()) v_norm, w_norm = [ get_norm(vect.get_end()) for vect in (self.v, self.w) ] projected_w = Vector( self.v.get_end()*dot_product/(v_norm**2), color = self.w.get_color() ) projection_line = Line( self.w.get_end(), projected_w.get_end(), color = GREY ) self.play(ShowCreation(projection_line)) self.add(self.w.copy().fade()) self.play(Transform(self.w, projected_w)) self.wait() def show_scaling(self): dot_product = np.dot(self.v.get_end(), self.w.get_end()) start_brace, interim_brace, final_brace = braces = [ Brace( Line(ORIGIN, norm*RIGHT), UP ) for norm in (1, self.v.get_length(), dot_product) ] length_texs = list(it.starmap(Tex, [ ("1",), ("\\text{Scale by }", "||\\vec{\\textbf{v}}||",), ("\\text{Length of}", "\\text{ scaled projection}",), ])) length_texs[1][1].set_color(self.v_color) length_texs[2][1].set_color(self.w_color) for brace, tex_mob in zip(braces, length_texs): tex_mob.add_background_rectangle() brace.put_at_tip(tex_mob, buff = SMALL_BUFF) brace.add(tex_mob) brace.rotate(self.v.get_angle()) new_w = self.w.copy().scale(self.v.get_length()) self.play(Write(start_brace)) self.wait() self.play( Transform(start_brace, interim_brace), Transform(self.w, new_w) ) self.wait() self.play( Transform(start_brace, final_brace) ) self.wait()
videos_3b1b/_2016/eola/chapter8.py
from manim_imports_ext import * from _2016.eola.chapter5 import get_det_text, RightHandRule U_COLOR = ORANGE V_COLOR = YELLOW W_COLOR = MAROON_B P_COLOR = RED def get_vect_tex(*strings): result = ["\\vec{\\textbf{%s}}"%s for s in strings] if len(result) == 1: return result[0] else: return result def get_perm_sign(*permutation): identity = np.identity(len(permutation)) return np.linalg.det(identity[list(permutation)]) class OpeningQuote(Scene): def construct(self): words = OldTexText("``Every dimension is special.''") words.to_edge(UP) author = OldTexText("-Jeff Lagarias") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(1) self.play(Write(author, run_time = 3)) self.wait() class LastVideo(Scene): def construct(self): title = OldTexText(""" Last video: Dot products and duality """) title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class DoTheSameForCross(TeacherStudentsScene): def construct(self): words = OldTexText("Let's do the same \\\\ for", "cross products") words.set_color_by_tex("cross products", YELLOW) self.teacher_says(words, target_mode = "surprised") self.random_blink(2) self.play_student_changes("pondering") self.random_blink() class ListSteps(Scene): CONFIG = { "randy_corner" : DOWN+RIGHT } def construct(self): title = OldTexText("Two part chapter") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) randy = Randolph().flip().to_corner(DOWN+RIGHT) randy.look(UP+LEFT) step_1 = OldTexText("This video: Standard introduction") step_2 = OldTexText("Next video: Deeper understanding with ", "linear transformations") step_2.set_color_by_tex("linear transformations", BLUE) steps = VGroup(step_1, step_2) steps.arrange(DOWN, aligned_edge = LEFT, buff = LARGE_BUFF) steps.next_to(randy, UP) steps.to_edge(LEFT, buff = LARGE_BUFF) self.add(title) self.play(ShowCreation(h_line)) for step in steps: self.play(Write(step)) self.wait() for step in steps: target = step.copy() target.scale(1.1) target.set_color(YELLOW) target.set_color_by_tex("linear transformations", BLUE) step.target = target step.save_state() self.play(FadeIn(randy)) self.play(Blink(randy)) self.play( MoveToTarget(step_1), step_2.fade, randy.change_mode, "happy" ) self.play(Blink(randy)) self.play( Transform(step_1, step_1.copy().restore().fade()), MoveToTarget(step_2), randy.look, LEFT ) self.play(randy.change_mode, "erm") self.wait(2) self.play(randy.change_mode, "pondering") self.play(Blink(randy)) class SimpleDefine2dCrossProduct(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "v_coords" : [3, 2], "w_coords" : [2, -1], } def construct(self): self.add_vectors() self.show_area() self.write_area_words() self.show_sign() self.swap_v_and_w() def add_vectors(self): self.plane.fade() v = self.add_vector(self.v_coords, color = V_COLOR) w = self.add_vector(self.w_coords, color = W_COLOR) for vect, name, direction in (v, "v", "left"), (w, "w", "right"): color = vect.get_color() vect.label = self.label_vector( vect, name, color = color, direction = direction, ) self.v, self.w = v, w def show_area(self): self.add_unit_square() transform = self.get_matrix_transformation(np.array([ self.v_coords, self.w_coords, ])) self.square.apply_function(transform) self.play( ShowCreation(self.square), *list(map(Animation, [self.v, self.w])) ) self.wait() self.play(FadeOut(self.square)) v_copy = self.v.copy() w_copy = self.w.copy() self.play(v_copy.shift, self.w.get_end()) self.play(w_copy.shift, self.v.get_end()) self.wait() self.play( FadeIn(self.square), *list(map(Animation, [self.v, self.w, v_copy, w_copy])) ) self.wait() self.play(*list(map(FadeOut, [v_copy, w_copy]))) def write_area_words(self): times = OldTex("\\times") for vect in self.v, self.w: vect.label.target = vect.label.copy() vect.label.target.save_state() cross = VGroup(self.v.label.target, times, self.w.label.target) cross.arrange(aligned_edge = DOWN) cross.scale(1.5) cross.shift(2.5*UP).to_edge(LEFT) cross_rect = BackgroundRectangle(cross) equals = OldTex("=") equals.add_background_rectangle() equals.next_to(cross, buff = MED_SMALL_BUFF/2) words = OldTexText("Area of parallelogram") words.add_background_rectangle() words.next_to(equals, buff = MED_SMALL_BUFF/2) arrow = Arrow( words.get_bottom(), self.square.get_center(), color = WHITE ) self.play( FadeIn(cross_rect), Write(times), *[ ApplyMethod( vect.label.target.restore, rate_func = lambda t : smooth(1-t) ) for vect in (self.v, self.w) ] ) self.wait() self.play(ApplyFunction( lambda m : m.scale(1.2).set_color(RED), times, rate_func = there_and_back )) self.wait() self.play(Write(words), Write(equals)) self.play(ShowCreation(arrow)) self.wait() self.play(FadeOut(arrow)) self.area_words = words self.cross = cross def show_sign(self): for vect, angle in (self.v, -np.pi/2), (self.w, np.pi/2): vect.add(vect.label) vect.save_state() vect.target = vect.copy() vect.target.rotate(angle) vect.target.label.rotate(-angle) vect.target.label.background_rectangle.set_fill(opacity = 0) square = self.square square.save_state() self.add_unit_square(animate = False, opacity = 0.15) transform = self.get_matrix_transformation([ self.v.target.get_end()[:2], self.w.target.get_end()[:2], ]) self.square.apply_function(transform) self.remove(self.square) square.target = self.square self.square = square positive = OldTexText("Positive").set_color(GREEN) negative = OldTexText("Negative").set_color(RED) for word in positive, negative: word.add_background_rectangle() word.arrow = Arrow( word.get_top(), word.get_top() + 1.5*UP, color = word.get_color() ) VGroup(word, word.arrow).next_to( self.area_words, DOWN, aligned_edge = LEFT, buff = SMALL_BUFF ) minus_sign = OldTex("-") minus_sign.set_color(RED) minus_sign.move_to(self.area_words, aligned_edge = LEFT) self.area_words.target = self.area_words.copy() self.area_words.target.next_to(minus_sign, RIGHT) self.play(*list(map(MoveToTarget, [square, self.v, self.w]))) arc = self.get_arc(self.v, self.w, radius = 1.5) arc.set_color(GREEN) self.play(ShowCreation(arc)) self.wait() self.play(Write(positive), ShowCreation(positive.arrow)) self.remove(arc) self.play( FadeOut(positive), FadeOut(positive.arrow), *[mob.restore for mob in (square, self.v, self.w)] ) arc = self.get_arc(self.v, self.w, radius = 1.5) arc.set_color(RED) self.play(ShowCreation(arc)) self.play( Write(negative), ShowCreation(negative.arrow), Write(minus_sign), MoveToTarget(self.area_words) ) self.wait() self.play(*list(map(FadeOut, [negative, negative.arrow, arc]))) def swap_v_and_w(self): new_cross = self.cross.copy() new_cross.arrange(LEFT, aligned_edge = DOWN) new_cross.move_to(self.area_words, aligned_edge = LEFT) for vect in self.v, self.w: vect.remove(vect.label) self.play( FadeOut(self.area_words), Transform(self.cross.copy(), new_cross, path_arc = np.pi/2) ) self.wait() curr_matrix = np.array([self.v.get_end()[:2], self.w.get_end()[:2]]) new_matrix = np.array(list(reversed(curr_matrix))) transform = self.get_matrix_transformation( np.dot(new_matrix.T, np.linalg.inv(curr_matrix.T)).T ) self.square.target = self.square.copy().apply_function(transform) self.play( MoveToTarget(self.square), Transform(self.v, self.w), Transform(self.w, self.v), rate_func = there_and_back, run_time = 3 ) self.wait() def get_arc(self, v, w, radius = 2): v_angle, w_angle = v.get_angle(), w.get_angle() nudge = 0.05 arc = Arc( (1-2*nudge)*(w_angle - v_angle), start_angle = interpolate(v_angle, w_angle, nudge), radius = radius, stroke_width = 8, ) arc.add_tip() return arc class CrossBasisVectors(LinearTransformationScene): def construct(self): self.plane.fade() i_label = self.get_vector_label( self.i_hat, "\\hat{\\imath}", direction = "right", color = X_COLOR, ) j_label = self.get_vector_label( self.j_hat, "\\hat{\\jmath}", direction = "left", color = Y_COLOR, ) for label in i_label, j_label: self.play(Write(label)) label.target = label.copy() i_label.target.scale(1.5) j_label.target.scale(1.2) self.wait() times = OldTex("\\times") cross = VGroup(i_label.target, times, j_label.target) cross.arrange() cross.next_to(ORIGIN).shift(1.5*UP) cross_rect = BackgroundRectangle(cross) eq = OldTex("= + 1") eq.add_background_rectangle() eq.next_to(cross, RIGHT) self.play( ShowCreation(cross_rect), MoveToTarget(i_label.copy()), MoveToTarget(j_label.copy()), Write(times), ) self.play(Write(eq)) self.wait() arc = self.get_arc(self.i_hat, self.j_hat, radius = 1) # arc.set_color(GREEN) self.play(ShowCreation(arc)) self.wait() def get_arc(self, v, w, radius = 2): v_angle, w_angle = v.get_angle(), w.get_angle() nudge = 0.05 arc = Arc( (1-2*nudge)*(w_angle - v_angle), start_angle = interpolate(v_angle, w_angle, nudge), radius = radius, stroke_width = 8, ) arc.add_tip() return arc class VisualExample(SimpleDefine2dCrossProduct): CONFIG = { "show_basis_vectors" : False, "v_coords" : [3, 1], "w_coords" : [1, -2], } def construct(self): self.add_vectors() # self.show_coords() self.show_area() self.write_area_words() result = np.linalg.det([self.v_coords, self.w_coords]) val = OldTex(str(int(abs(result)))).scale(2) val.move_to(self.square.get_center()) arc = self.get_arc(self.v, self.w, radius = 1) arc.set_color(RED) minus = OldTex("-").set_color(RED) minus.scale(1.5) minus.move_to(self.area_words, aligned_edge = LEFT) self.play(ShowCreation(val)) self.wait() self.play(ShowCreation(arc)) self.wait() self.play(FadeOut(self.area_words)) self.play( Transform(arc, minus), val.next_to, minus, RIGHT ) self.wait() def show_coords(self): for vect, edge in (self.v, DOWN), (self.w, UP): color = vect.get_color() vect.coord_array = vector_coordinate_label( vect, color = color, ) vect.coord_array.move_to( vect.coord_array.get_center(), aligned_edge = edge ) self.play(Write(vect.coord_array, run_time = 1)) class HowDoYouCompute(TeacherStudentsScene): def construct(self): self.student_says( "How do you \\\\ compute this?", target_mode = "raise_left_hand" ) self.random_blink(2) class ContrastDotAndCross(Scene): def construct(self): self.add_t_chart() self.add_dot_products() self.add_cross_product() self.add_2d_cross_product() self.emphasize_output_type() def add_t_chart(self): for word, vect, color in ("Dot", LEFT, BLUE_C), ("Cross", RIGHT, YELLOW): title = OldTexText("%s product"%word) title.shift(vect*FRAME_X_RADIUS/2) title.to_edge(UP) title.set_color(color) self.add(title) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) l_h_line = Line(LEFT, ORIGIN).scale(FRAME_X_RADIUS) r_h_line = Line(ORIGIN, RIGHT).scale(FRAME_X_RADIUS) r_h_line.next_to(title, DOWN) l_h_line.next_to(r_h_line, LEFT, buff = 0) self.add(v_line, l_h_line, r_h_line) self.l_h_line, self.r_h_line = l_h_line, r_h_line def add_dot_products(self, max_width = FRAME_X_RADIUS-1, dims = [2, 5]): colors = [X_COLOR, Y_COLOR, Z_COLOR, MAROON_B, TEAL] last_mob = self.l_h_line dot_products = [] for dim in dims: arrays = [ [random.randint(0, 9) for in_count in range(dim)] for out_count in range(2) ] m1, m2 = list(map(Matrix, arrays)) for matrix in m1, m2: for entry, color in zip(matrix.get_entries(), colors): entry.set_color(color) entry.target = entry.copy() syms = VGroup(*list(map(Tex, ["="] + ["+"]*(dim-1)))) def get_dot(): dot = OldTex("\\cdot") syms.add(dot) return dot result = VGroup(*it.chain(*list(zip( syms, [ VGroup( e1.target, get_dot(), e2.target ).arrange() for e1, e2 in zip(m1.get_entries(), m2.get_entries()) ] )))) result.arrange(RIGHT) dot_prod = VGroup( m1, OldTex("\\cdot"), m2, result ) dot_prod.arrange(RIGHT) if dot_prod.get_width() > max_width: dot_prod.set_width(max_width) dot_prod.next_to(last_mob, DOWN, buff = MED_SMALL_BUFF) last_mob = dot_prod dot_prod.to_edge(LEFT) dot_prod.remove(result) dot_prod.syms = syms dot_prod.entries = list(m1.get_entries())+list(m2.get_entries()) dot_products.append(dot_prod) self.add(*dot_products) for dot_prod in dot_products: self.play( Write(dot_prod.syms), *[ Transform( e.copy(), e.target, path_arc = -np.pi/6 ) for e in dot_prod.entries ], run_time = 2 ) self.wait() def add_cross_product(self): colors = [X_COLOR, Y_COLOR, Z_COLOR] arrays = [ [random.randint(0, 9) for in_count in range(3)] for out_count in range(2) ] matrices = list(map(Matrix, arrays)) for matrix in matrices: for entry, color in zip(matrix.get_entries(), colors): entry.set_color(color) m1, m2 = matrices cross_product = VGroup(m1, OldTex("\\times"), m2) cross_product.arrange() index_to_cross_enty = {} syms = VGroup() movement_sets = [] for a, b, c in it.permutations(list(range(3))): e1, e2 = m1.get_entries()[b], m2.get_entries()[c] for e in e1, e2: e.target = e.copy() movement_sets.append([e1, e1.target, e2, e2.target]) dot = OldTex("\\cdot") syms.add(dot) cross_entry = VGroup(e1.target, dot, e2.target) cross_entry.arrange() if a not in index_to_cross_enty: index_to_cross_enty[a] = [] index_to_cross_enty[a].append(cross_entry) result_entries = [] for a in range(3): prod1, prod2 = index_to_cross_enty[a] if a == 1: prod1, prod2 = prod2, prod1 prod2.arrange(LEFT) minus = OldTex("-") syms.add(minus) entry = VGroup(prod1, minus, prod2) entry.arrange(RIGHT) result_entries.append(entry) result = Matrix(result_entries) full_cross_product = VGroup( cross_product, OldTex("="), result ) full_cross_product.arrange() full_cross_product.scale(0.75) full_cross_product.next_to(self.r_h_line, DOWN, buff = MED_SMALL_BUFF/2) full_cross_product.remove(result) self.play( Write(full_cross_product), ) movements = [] for e1, e1_target, e2, e2_target in movement_sets: movements += [ e1.copy().move_to, e1_target, e2.copy().move_to, e2_target, ] brace = Brace(cross_product) brace_text = brace.get_text("Only 3d") self.play( GrowFromCenter(brace), Write(brace_text) ) self.play( Write(result.get_brackets()), Write(syms), *movements, run_time = 2 ) self.wait() self.cross_result = result self.only_3d_text = brace_text def add_2d_cross_product(self): h_line = DashedLine(ORIGIN, FRAME_X_RADIUS*RIGHT) h_line.next_to(self.only_3d_text, DOWN, buff = MED_SMALL_BUFF/2) h_line.to_edge(RIGHT, buff = 0) arrays = np.random.randint(0, 9, (2, 2)) m1, m2 = matrices = list(map(Matrix, arrays)) for m in matrices: for e, color in zip(m.get_entries(), [X_COLOR, Y_COLOR]): e.set_color(color) cross_product = VGroup(m1, OldTex("\\times"), m2) cross_product.arrange() (x1, x2), (x3, x4) = tuple(m1.get_entries()), tuple(m2.get_entries()) entries = [x1, x2, x3, x4] for entry in entries: entry.target = entry.copy() eq, dot1, minus, dot2 = syms = list(map(Tex, ["=", "\\cdot", "-", "\\cdot"] )) result = VGroup( eq, x1.target, dot1, x4.target, minus, x3.target, dot2, x2.target, ) result.arrange(RIGHT) full_cross_product = VGroup(cross_product, result) full_cross_product.arrange(RIGHT) full_cross_product.next_to(h_line, DOWN, buff = MED_SMALL_BUFF/2) self.play(ShowCreation(h_line)) self.play(Write(cross_product)) self.play( Write(VGroup(*syms)), *[ Transform(entry.copy(), entry.target) for entry in entries ] ) self.wait() self.two_d_result = VGroup(*result[1:]) def emphasize_output_type(self): three_d_brace = Brace(self.cross_result) two_d_brace = Brace(self.two_d_result) vector = three_d_brace.get_text("Vector") number = two_d_brace.get_text("Number") self.play( GrowFromCenter(two_d_brace), Write(number) ) self.wait() self.play( GrowFromCenter(three_d_brace), Write(vector) ) self.wait() class PrereqDeterminant(Scene): def construct(self): title = OldTexText(""" Prerequisite: Understanding determinants """) title.set_width(FRAME_WIDTH - 2) title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class Define2dCrossProduct(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "v_coords" : [3, 1], "w_coords" : [2, -1], } def construct(self): self.initial_definition() self.show_transformation() self.transform_square() self.show_orientation_rule() def initial_definition(self): self.plane.save_state() self.plane.fade() v = self.add_vector(self.v_coords, color = V_COLOR) w = self.add_vector(self.w_coords, color = W_COLOR) self.moving_vectors.remove(v) self.moving_vectors.remove(w) for vect, name, direction in (v, "v", "left"), (w, "w", "right"): color = vect.get_color() vect.label = self.label_vector( vect, name, color = color, direction = direction, ) vect.coord_array = vector_coordinate_label( vect, color = color, ) vect.coords = vect.coord_array.get_entries() for vect, edge in (v, DOWN), (w, UP): vect.coord_array.move_to( vect.coord_array.get_center(), aligned_edge = edge ) self.play(Write(vect.coord_array, run_time = 1)) movers = [v.label, w.label, v.coords, w.coords] for mover in movers: mover.target = mover.copy() times = OldTex("\\times") cross_product = VGroup( v.label.target, times, w.label.target ) cross_product.arrange() matrix = Matrix(np.array([ list(v.coords.target), list(w.coords.target) ]).T) det_text = get_det_text(matrix) full_det = VGroup(det_text, matrix) equals = OldTex("=") equation = VGroup(cross_product, equals, full_det) equation.arrange() equation.to_corner(UP+LEFT) matrix_background = BackgroundRectangle(matrix) cross_background = BackgroundRectangle(cross_product) disclaimer = OldTexText("$^*$ See ``Note on conventions'' in description") disclaimer.scale(0.7) disclaimer.set_color(RED) disclaimer.next_to( det_text.get_corner(UP+RIGHT), RIGHT, buff = 0 ) disclaimer.add_background_rectangle() self.play( FadeIn(cross_background), Transform(v.label.copy(), v.label.target), Transform(w.label.copy(), w.label.target), Write(times), ) self.wait() self.play( ShowCreation(matrix_background), Write(matrix.get_brackets()), run_time = 1 ) self.play(Transform(v.coords.copy(), v.coords.target)) self.play(Transform(w.coords.copy(), w.coords.target)) matrix.add_to_back(matrix_background) self.wait() self.play( Write(equals), Write(det_text), Animation(matrix), ) self.wait() self.play(FadeIn(disclaimer)) self.wait() self.play(FadeOut(disclaimer)) self.wait() cross_product.add_to_back(cross_background) cross_product.add(equals) self.cross_product = cross_product self.matrix = matrix self.det_text = det_text self.v, self.w = v, w def show_transformation(self): matrix = self.matrix.copy() everything = self.get_mobjects() everything.remove(self.plane) everything.remove(self.background_plane) self.play( *list(map(FadeOut, everything)) + [ Animation(self.background_plane), self.plane.restore, Animation(matrix), ]) i_hat, j_hat = self.get_basis_vectors() for vect in i_hat, j_hat: vect.save_state() basis_labels = self.get_basis_vector_labels() self.play( ShowCreation(i_hat), ShowCreation(j_hat), Write(basis_labels) ) self.wait() side_brace = Brace(matrix, RIGHT) transform_words = side_brace.get_text("Linear transformation") transform_words.add_background_rectangle() col1, col2 = [ VGroup(*matrix.get_mob_matrix()[i,:]) for i in (0, 1) ] both_words = [] for char, color, col in ("i", X_COLOR, col1), ("j", Y_COLOR, col2): words = OldTexText("Where $\\hat\\%smath$ lands"%char) words.set_color(color) words.add_background_rectangle() words.next_to(col, DOWN, buff = LARGE_BUFF) words.arrow = Arrow(words.get_top(), col.get_bottom(), color = color) both_words.append(words) i_words, j_words = both_words self.play( GrowFromCenter(side_brace), Write(transform_words) ) self.play( Write(i_words), ShowCreation(i_words.arrow), col1.set_color, X_COLOR ) self.wait() self.play( Transform(i_words, j_words), Transform(i_words.arrow, j_words.arrow), col2.set_color, Y_COLOR ) self.wait() self.play(*list(map(FadeOut, [i_words, i_words.arrow, basis_labels]))) self.add_vector(i_hat, animate = False) self.add_vector(j_hat, animate = False) self.play(*list(map(FadeOut, [side_brace, transform_words]))) self.add_foreground_mobject(matrix) self.apply_transposed_matrix([self.v_coords, self.w_coords]) self.wait() self.play( FadeOut(self.plane), *list(map(Animation, [ self.background_plane, matrix, i_hat, j_hat, ])) ) self.play( ShowCreation(self.v), ShowCreation(self.w), FadeIn(self.v.label), FadeIn(self.w.label), FadeIn(self.v.coord_array), FadeIn(self.w.coord_array), matrix.set_column_colors, V_COLOR, W_COLOR ) self.wait() self.i_hat, self.j_hat = i_hat, j_hat self.matrix = matrix def transform_square(self): self.play(Write(self.det_text)) self.matrix.add(self.det_text) vect_stuffs = VGroup(*it.chain(*[ [m, m.label, m.coord_array] for m in (self.v, self.w) ])) to_restore = [self.plane, self.i_hat, self.j_hat] for mob in to_restore: mob.fade(1) self.play(*list(map(FadeOut, vect_stuffs))) self.play( *[m.restore for m in to_restore] + [ Animation(self.matrix) ] ) self.add_unit_square(animate = True, opacity = 0.2) self.square.save_state() self.wait() self.apply_transposed_matrix( [self.v_coords, self.w_coords] ) self.wait() self.play( FadeOut(self.plane), Animation(self.matrix), *list(map(FadeIn, vect_stuffs)) ) self.play(Write(self.cross_product)) det_text_brace = Brace(self.det_text) area_words = det_text_brace.get_text("Area of this parallelogram") area_words.add_background_rectangle() area_arrow = Arrow( area_words.get_bottom(), self.square.get_center(), color = WHITE ) self.play( GrowFromCenter(det_text_brace), Write(area_words), ShowCreation(area_arrow) ) self.wait() pm = VGroup(*list(map(Tex, ["+", "-"]))) pm.set_color_by_gradient(GREEN, RED) pm.arrange(DOWN, buff = SMALL_BUFF) pm.add_to_back(BackgroundRectangle(pm)) pm.next_to(area_words[0], LEFT, aligned_edge = DOWN) self.play( Transform(self.square.get_point_mobject(), pm), path_arc = -np.pi/2 ) self.wait() self.play(*list(map(FadeOut, [ area_arrow, self.v.coord_array, self.w.coord_array ]))) def show_orientation_rule(self): self.remove(self.i_hat, self.j_hat) for vect in self.v, self.w: vect.add(vect.label) vect.target = vect.copy() angle = np.pi/3 self.v.target.rotate(-angle) self.w.target.rotate(angle) self.v.target.label.rotate(angle) self.w.target.label.rotate(-angle) for vect in self.v, self.w: vect.target.label[0].set_fill(opacity = 0) self.square.target = self.square.copy().restore() transform = self.get_matrix_transformation([ self.v.target.get_end()[:2], self.w.target.get_end()[:2], ]) self.square.target.apply_function(transform) movers = VGroup(self.square, self.v, self.w) movers.target = VGroup(*[m.target for m in movers]) movers.save_state() self.remove(self.square) self.play(Transform(movers, movers.target)) self.wait() v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in ("v", "w")] positive_words, negative_words = words_list = [ OldTex(v_tex, "\\times", w_tex, "\\text{ is }", word) for word in ("\\text{positive}", "\\text{negative}") ] for words in words_list: words.set_color_by_tex(v_tex, V_COLOR) words.set_color_by_tex(w_tex, W_COLOR) words.set_color_by_tex("\\text{positive}", GREEN) words.set_color_by_tex("\\text{negative}", RED) words.add_background_rectangle() words.next_to(self.square, UP) arc = self.get_arc(self.v, self.w) arc.set_color(GREEN) self.play( Write(positive_words), ShowCreation(arc) ) self.wait() self.remove(arc) self.play(movers.restore) arc = self.get_arc(self.v, self.w) arc.set_color(RED) self.play( Transform(positive_words, negative_words), ShowCreation(arc) ) self.wait() anticommute = OldTex( v_tex, "\\times", w_tex, "=-", w_tex, "\\times", v_tex ) anticommute.shift(FRAME_X_RADIUS*RIGHT/2) anticommute.to_edge(UP) anticommute.set_color_by_tex(v_tex, V_COLOR) anticommute.set_color_by_tex(w_tex, W_COLOR) anticommute.add_background_rectangle() for v1, v2 in (self.v, self.w), (self.w, self.v): v1.label[0].set_fill(opacity = 0) v1.target = v1.copy() v1.target.label.rotate(v1.get_angle()-v2.get_angle()) v1.target.label.scale(v1.get_length()/v2.get_length()) v1.target.rotate(v2.get_angle()-v1.get_angle()) v1.target.scale(v2.get_length()/v1.get_length()) v1.target.label.move_to(v2.label) self.play( FadeOut(arc), Transform(positive_words, anticommute) ) self.play( Transform(self.v, self.v.target), Transform(self.w, self.w.target), rate_func = there_and_back, run_time = 2, ) self.wait() def get_arc(self, v, w, radius = 2): v_angle, w_angle = v.get_angle(), w.get_angle() nudge = 0.05 arc = Arc( (1-2*nudge)*(w_angle - v_angle), start_angle = interpolate(v_angle, w_angle, nudge), radius = radius, stroke_width = 8, ) arc.add_tip() return arc class TwoDCrossProductExample(Define2dCrossProduct): CONFIG = { "v_coords" : [-3, 1], "w_coords" : [2, 1], } def construct(self): self.plane.fade() v = Vector(self.v_coords, color = V_COLOR) w = Vector(self.w_coords, color = W_COLOR) v.coords = Matrix(self.v_coords) w.coords = Matrix(self.w_coords) v.coords.next_to(v.get_end(), LEFT) w.coords.next_to(w.get_end(), RIGHT) v.coords.set_color(v.get_color()) w.coords.set_color(w.get_color()) for coords in v.coords, w.coords: coords.background_rectangle = BackgroundRectangle(coords) coords.add_to_back(coords.background_rectangle) v.label = self.get_vector_label(v, "v", "left", color = v.get_color()) w.label = self.get_vector_label(w, "w", "right", color = w.get_color()) matrix = Matrix(np.array([ list(v.coords.copy().get_entries()), list(w.coords.copy().get_entries()), ]).T) matrix_background = BackgroundRectangle(matrix) col1, col2 = it.starmap(Group, matrix.get_mob_matrix().T) det_text = get_det_text(matrix) v_tex, w_tex = get_vect_tex("v", "w") cross_product = OldTex(v_tex, "\\times", w_tex, "=") cross_product.set_color_by_tex(v_tex, V_COLOR) cross_product.set_color_by_tex(w_tex, W_COLOR) cross_product.add_background_rectangle() equation_start = VGroup( cross_product, VGroup(matrix_background, det_text, matrix) ) equation_start.arrange() equation_start.next_to(ORIGIN, DOWN).to_edge(LEFT) for vect in v, w: self.play( ShowCreation(vect), Write(vect.coords), Write(vect.label) ) self.wait() self.play( Transform(v.coords.background_rectangle, matrix_background), Transform(w.coords.background_rectangle, matrix_background), Transform(v.coords.get_entries(), col1), Transform(w.coords.get_entries(), col2), Transform(v.coords.get_brackets(), matrix.get_brackets()), Transform(w.coords.get_brackets(), matrix.get_brackets()), ) self.play(*list(map(Write, [det_text, cross_product]))) v1, v2 = v.coords.get_entries() w1, w2 = w.coords.get_entries() entries = v1, v2, w1, w2 for entry in entries: entry.target = entry.copy() det = np.linalg.det([self.v_coords, self.w_coords]) equals, dot1, minus, dot2, equals_result = syms = VGroup(*list(map( Tex, ["=", "\\cdot", "-", "\\cdot", "=%d"%det] ))) equation_end = VGroup( equals, v1.target, dot1, w2.target, minus, w1.target, dot2, v2.target, equals_result ) equation_end.arrange() equation_end.next_to(equation_start) syms_rect = BackgroundRectangle(syms) syms.add_to_back(syms_rect) equation_end.add_to_back(syms_rect) syms.remove(equals_result) self.play( Write(syms), Transform( VGroup(v1, w2).copy(), VGroup(v1.target, w2.target), rate_func = squish_rate_func(smooth, 0, 1./3), path_arc = np.pi/2 ), Transform( VGroup(v2, w1).copy(), VGroup(v2.target, w1.target), rate_func = squish_rate_func(smooth, 2./3, 1), path_arc = np.pi/2 ), run_time = 3 ) self.wait() self.play(Write(equals_result)) self.add_foreground_mobject(equation_start, equation_end) self.show_transformation(v, w) det_sym = OldTex(str(int(abs(det)))) det_sym.scale(1.5) det_sym.next_to(v.get_end()+w.get_end(), DOWN+RIGHT, buff = MED_SMALL_BUFF/2) arc = self.get_arc(v, w, radius = 1) arc.set_color(RED) self.play(Write(det_sym)) self.play(ShowCreation(arc)) self.wait() def show_transformation(self, v, w): i_hat, j_hat = self.get_basis_vectors() self.play(*list(map(ShowCreation, [i_hat, j_hat]))) self.add_unit_square(animate = True, opacity = 0.2) self.apply_transposed_matrix( [v.get_end()[:2], w.get_end()[:2]], added_anims = [ Transform(i_hat, v), Transform(j_hat, w) ] ) class PlayAround(TeacherStudentsScene): def construct(self): self.teacher_says(""" \\centering Play with the idea if you wish to understand it """) self.play_student_changes("pondering", "happy", "happy") self.random_blink(2) self.student_thinks("", index = 0) self.zoom_in_on_thought_bubble() class BiggerWhenPerpendicular(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, } def construct(self): self.lock_in_faded_grid() self.add_unit_square(animate = False) square = self.square self.remove(square) start_words = OldTexText("More perpendicular") end_words = OldTexText("Similar direction") arrow = OldTexText("\\Rightarrow") v_tex, w_tex = get_vect_tex("v", "w") cross_is = OldTex(v_tex, "\\times", w_tex, "\\text{ is }") cross_is.set_color_by_tex(v_tex, V_COLOR) cross_is.set_color_by_tex(w_tex, W_COLOR) bigger = OldTexText("bigger") smaller = OldTexText("smaller") bigger.scale(1.5) smaller.scale(0.75) bigger.set_color(PINK) smaller.set_color(TEAL) group = VGroup(start_words, arrow, cross_is, bigger) group.arrange() group.to_edge(UP) end_words.move_to(start_words, aligned_edge = RIGHT) smaller.next_to(cross_is, buff = MED_SMALL_BUFF/2, aligned_edge = DOWN) for mob in list(group) + [end_words, smaller]: mob.add_background_rectangle() v = Vector([2, 2], color = V_COLOR) w = Vector([2, -2], color = W_COLOR) v.target = v.copy().rotate(-np.pi/5) w.target = w.copy().rotate(np.pi/5) transforms = [ self.get_matrix_transformation([v1.get_end()[:2], v2.get_end()[:2]]) for v1, v2 in [(v, w), (v.target, w.target)] ] start_square, end_square = [ square.copy().apply_function(transform) for transform in transforms ] for vect in v, w: self.play(ShowCreation(vect)) group.remove(bigger) self.play( FadeIn(group), ShowCreation(start_square), *list(map(Animation, [v, w])) ) self.play(GrowFromCenter(bigger)) self.wait() self.play( Transform(start_square, end_square), Transform(v, v.target), Transform(w, w.target), ) self.play( Transform(start_words, end_words), Transform(bigger, smaller) ) self.wait() class ScalingRule(LinearTransformationScene): CONFIG = { "v_coords" : [2, -1], "w_coords" : [1, 1], "show_basis_vectors" : False } def construct(self): self.lock_in_faded_grid() self.add_unit_square(animate = False) self.remove(self.square) square = self.square v = Vector(self.v_coords, color = V_COLOR) w = Vector(self.w_coords, color = W_COLOR) v.label = self.get_vector_label(v, "v", "right", color = V_COLOR) w.label = self.get_vector_label(w, "w", "left", color = W_COLOR) new_v = v.copy().scale(3) new_v.label = self.get_vector_label( new_v, "3\\vec{\\textbf{v}}", "right", color = V_COLOR ) for vect in v, w, new_v: vect.add(vect.label) transform = self.get_matrix_transformation( [self.v_coords, self.w_coords] ) square.apply_function(transform) new_squares = VGroup(*[ square.copy().shift(m*v.get_end()) for m in range(3) ]) v_tex, w_tex = get_vect_tex("v", "w") cross_product = OldTex(v_tex, "\\times", w_tex) rhs = OldTex("=3(", v_tex, "\\times", w_tex, ")") three_v = OldTex("(3", v_tex, ")") for tex_mob in cross_product, rhs, three_v: tex_mob.set_color_by_tex(v_tex, V_COLOR) tex_mob.set_color_by_tex(w_tex, W_COLOR) equation = VGroup(cross_product, rhs) equation.arrange() equation.to_edge(UP) v_tex_mob = cross_product[0] three_v.move_to(v_tex_mob, aligned_edge = RIGHT) for tex_mob in cross_product, rhs: tex_mob.add_background_rectangle() self.add(cross_product) self.play(ShowCreation(v)) self.play(ShowCreation(w)) self.play( ShowCreation(square), *list(map(Animation, [v, w])) ) self.wait() self.play( Transform(v, new_v), Transform(v_tex_mob, three_v), ) self.wait() self.play( Transform(square, new_squares), *list(map(Animation, [v, w])), path_arc = -np.pi/6 ) self.wait() self.play(Write(rhs)) self.wait() class TechnicallyNotTheDotProduct(TeacherStudentsScene): def construct(self): self.teacher_says(""" That was technically not the cross product """) self.play_student_changes("confused") self.play_student_changes("confused", "angry") self.play_student_changes("confused", "angry", "sassy") self.random_blink(3) class ThreeDShowParallelogramAndCrossProductVector(Scene): pass class WriteAreaOfParallelogram(Scene): def construct(self): words = OldTexText( "Area of ", "parallelogram", " $=$ ", "$2.5$", arg_separator = "" ) words.set_color_by_tex("parallelogram", BLUE) words.set_color_by_tex("$2.5$", BLUE) result = words[-1] words.remove(result) self.play(Write(words)) self.wait() self.play(Write(result, run_time = 1)) self.wait() class WriteCrossProductProperties(Scene): def construct(self): v_tex, w_tex, p_tex = texs = get_vect_tex(*"vwp") v_cash, w_cash, p_cash = ["$%s$"%tex for tex in texs] cross_product = OldTex(v_tex, "\\times", w_tex, "=", p_tex) cross_product.set_color_by_tex(v_tex, V_COLOR) cross_product.set_color_by_tex(w_tex, W_COLOR) cross_product.set_color_by_tex(p_tex, P_COLOR) cross_product.to_edge(UP, buff = LARGE_BUFF) p_mob = cross_product[-1] brace = Brace(p_mob) brace.do_in_place(brace.stretch, 2, 0) vector = brace.get_text("vector") vector.set_color(P_COLOR) length_words = OldTexText( "Length of ", p_cash, "\\\\ = ", "(parallelogram's area)" ) length_words.set_color_by_tex(p_cash, P_COLOR) length_words.set_width(FRAME_X_RADIUS - 1) length_words.set_color_by_tex("(parallelogram's area)", BLUE) length_words.next_to(VGroup(cross_product, vector), DOWN, buff = LARGE_BUFF) perpendicular = OldTexText( "\\centering Perpendicular to", v_cash, "and", w_cash ) perpendicular.set_width(FRAME_X_RADIUS - 1) perpendicular.set_color_by_tex(v_cash, V_COLOR) perpendicular.set_color_by_tex(w_cash, W_COLOR) perpendicular.next_to(length_words, DOWN, buff = LARGE_BUFF) self.play(Write(cross_product)) self.play( GrowFromCenter(brace), Write(vector, run_time = 1) ) self.wait() self.play(Write(length_words, run_time = 1)) self.wait() self.play(Write(perpendicular)) self.wait() def get_cross_product_right_hand_rule_labels(): v_tex, w_tex = get_vect_tex(*"vw") return [ v_tex, w_tex, "%s \\times %s"%(v_tex, w_tex) ] class CrossProductRightHandRule(RightHandRule): CONFIG = { "flip" : False, "labels_tex" : get_cross_product_right_hand_rule_labels(), "colors" : [U_COLOR, W_COLOR, P_COLOR], } class LabelingExampleVectors(Scene): def construct(self): v_tex, w_tex = texs = get_vect_tex(*"vw") colors = [U_COLOR, W_COLOR, P_COLOR] equations = [ OldTex(v_tex, "=%s"%matrix_to_tex_string([0, 0, 2])), OldTex(w_tex, "=%s"%matrix_to_tex_string([0, 2, 0])), OldTex( v_tex, "\\times", w_tex, "=%s"%matrix_to_tex_string([-4, 0, 0]) ), ] for eq, color in zip(equations, colors): eq.set_color(color) eq.scale(2) area_words = OldTexText("Area", "=4") area_words[0].set_color(BLUE) area_words.scale(2) for mob in equations[:2] + [area_words, equations[2]]: self.fade_in_out(mob) def fade_in_out(self, mob): self.play(FadeIn(mob)) self.wait() self.play(FadeOut(mob)) class ThreeDTwoPossiblePerpendicularVectors(Scene): pass class ThreeDCrossProductExample(Scene): pass class ShowCrossProductFormula(Scene): def construct(self): colors = [X_COLOR, Y_COLOR, Z_COLOR] arrays = [ ["%s_%d"%(s, i) for i in range(1, 4)] for s in ("v", "w") ] matrices = list(map(Matrix, arrays)) for matrix in matrices: for entry, color in zip(matrix.get_entries(), colors): entry.set_color(color) m1, m2 = matrices cross_product = VGroup(m1, OldTex("\\times"), m2) cross_product.arrange() cross_product.shift(2*LEFT) entry_dicts = [{} for x in range(3)] movement_sets = [] for a, b, c in it.permutations(list(range(3))): sign = get_perm_sign(a, b, c) e1, e2 = m1.get_entries()[b], m2.get_entries()[c] for e in e1, e2: e.target = e.copy() dot = OldTex("\\cdot") syms = VGroup(dot) if sign < 0: minus = OldTex("-") syms.add(minus) cross_entry = VGroup(minus, e2.target, dot, e1.target) cross_entry.arrange() entry_dicts[a]["negative"] = cross_entry else: cross_entry = VGroup(e1.target, dot, e2.target) cross_entry.arrange() entry_dicts[a]["positive"] = cross_entry cross_entry.arrange() movement_sets.append([ e1, e1.target, e2, e2.target, syms ]) result = Matrix([ VGroup( entry_dict["positive"], entry_dict["negative"], ).arrange() for entry_dict in entry_dicts ]) equals = OldTex("=").next_to(cross_product) result.next_to(equals) self.play(FadeIn(cross_product)) self.play( Write(equals), Write(result.get_brackets()) ) self.wait() movement_sets[2], movement_sets[3] = movement_sets[3], movement_sets[2] for e1, e1_target, e2, e2_target, syms in movement_sets: e1.save_state() e2.save_state() self.play( e1.scale, 1.5, e2.scale, 1.5, ) self.play( Transform(e1.copy(), e1_target), Transform(e2.copy(), e2_target), Write(syms), e1.restore, e2.restore, path_arc = -np.pi/2 ) self.wait() class ThisGetsWeird(TeacherStudentsScene): def construct(self): self.teacher_says( "This gets weird...", target_mode = "sassy" ) self.random_blink(2) class DeterminantTrick(Scene): def construct(self): v_terms, w_terms = [ ["%s_%d"%(s, d) for d in range(1, 4)] for s in ("v", "w") ] v = Matrix(v_terms) w = Matrix(w_terms) v.set_color(V_COLOR) w.set_color(W_COLOR) matrix = Matrix(np.array([ [ OldTex("\\hat{%s}"%s) for s in ("\\imath", "\\jmath", "k") ], list(v.get_entries().copy()), list(w.get_entries().copy()), ]).T) colors = [X_COLOR, Y_COLOR, Z_COLOR] col1, col2, col3 = it.starmap(Group, matrix.get_mob_matrix().T) i, j, k = col1 v1, v2, v3 = col2 w1, w2, w3 = col3 ##Really should fix Matrix mobject... j.shift(0.1*UP) k.shift(0.2*UP) VGroup(v2, w2).shift(0.1*DOWN) VGroup(v3, w3).shift(0.2*DOWN) ## for color, entry in zip(colors, col1): entry.set_color(color) det_text = get_det_text(matrix) equals = OldTex("=") equation = VGroup( v, OldTex("\\times"), w, equals, VGroup(det_text, matrix) ) equation.arrange() self.add(*equation[:-2]) self.wait() self.play(Write(matrix.get_brackets())) for col, vect in (col2, v), (col3, w): col.save_state() col.move_to(vect.get_entries()) self.play( col.restore, path_arc = -np.pi/2, ) for entry in col1: self.play(Write(entry)) self.wait() self.play(*list(map(Write, [equals, det_text]))) self.wait() disclaimer = OldTexText("$^*$ See ``Note on conventions'' in description") disclaimer.scale(0.7) disclaimer.set_color(RED) disclaimer.next_to(equation, DOWN) self.play(FadeIn(disclaimer)) self.wait() self.play(FadeOut(disclaimer)) circle = Circle() circle.stretch_to_fit_height(col1.get_height()+1) circle.stretch_to_fit_width(col1.get_width()+1) circle.move_to(col1) randy = Randolph() randy.scale(0.9) randy.to_corner() randy.to_edge(DOWN, buff = SMALL_BUFF) self.play(FadeIn(randy)) self.play( randy.change_mode, "confused", ShowCreation(circle) ) self.play(randy.look, RIGHT) self.wait() self.play(FadeOut(circle)) self.play( equation.to_corner, UP+LEFT, ApplyFunction( lambda r : r.change_mode("plain").look(UP+RIGHT), randy ) ) quints = [ (i, v2, w3, v3, w2), (j, v3, w1, v1, w3), (k, v1, w2, v2, w1), ] last_mob = None paren_sets = [] for quint in quints: for mob in quint: mob.t = mob.copy() mob.save_state() basis = quint[0] basis.t.scale(1/0.8) lp, minus, rp = syms = VGroup(*list(map(Tex, "(-)"))) term = VGroup( basis.t, lp, quint[1].t, quint[2].t, minus, quint[3].t, quint[4].t, rp ) term.arrange() if last_mob: plus = OldTex("+") syms.add(plus) plus.next_to(term, LEFT, buff = MED_SMALL_BUFF/2) term.add_to_back(plus) term.next_to(last_mob, RIGHT, buff = MED_SMALL_BUFF/2) else: term.next_to(equation, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT) last_mob = term self.play(*it.chain(*[ [mob.scale, 1.2] for mob in quint ])) self.wait() self.play(*[ Transform(mob.copy(), mob.t) for mob in quint ] + [ mob.restore for mob in quint ] + [ Write(syms) ], run_time = 2 ) self.wait() paren_sets.append(VGroup(lp, rp)) self.wait() self.play(randy.change_mode, "pondering") for parens in paren_sets: brace = Brace(parens) text = brace.get_text("Some number") text.set_width(brace.get_width()) self.play( GrowFromCenter(brace), Write(text, run_time = 2) ) self.wait() class ThereIsAReason(TeacherStudentsScene): def construct(self): self.teacher_says( "\\centering Sure, it's a \\\\", "notational", "trick", ) self.random_blink(2) words = OldTexText( "\\centering but there is a\\\\", "reason", "for doing it" ) words.set_color_by_tex("reason", YELLOW) self.teacher_says(words, target_mode = "surprised") self.play_student_changes( "raise_right_hand", "confused", "raise_left_hand" ) self.random_blink() class RememberDuality(TeacherStudentsScene): def construct(self): words = OldTexText("Remember ", "duality", "?", arg_separator = "") words[1].set_color_by_gradient(BLUE, YELLOW) self.teacher_says(words, target_mode = "sassy") self.random_blink(2) class NextVideo(Scene): def construct(self): title = OldTexText(""" Next video: Cross products in the light of linear transformations """) title.set_height(1.2) title.to_edge(UP, buff = MED_SMALL_BUFF/2) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class CrossAndDualWords(Scene): def construct(self): v_tex, w_tex, p_tex = get_vect_tex(*"vwp") vector_word = OldTexText("Vector:") transform_word = OldTexText("Dual transform:") cross = OldTex( p_tex, "=", v_tex, "\\times", w_tex ) for tex, color in zip([v_tex, w_tex, p_tex], [U_COLOR, W_COLOR, P_COLOR]): cross.set_color_by_tex(tex, color) input_array_tex = matrix_to_tex_string(["x", "y", "z"]) func = OldTex("L\\left(%s\\right) = "%input_array_tex) matrix = Matrix(np.array([ ["x", "y", "z"], ["v_1", "v_2", "v_3"], ["w_1", "w_2", "w_3"], ]).T) matrix.set_column_colors(WHITE, U_COLOR, W_COLOR) det_text = get_det_text(matrix, background_rect = False) det_text.add(matrix) dot_with_cross = OldTex( "%s \\cdot ( "%input_array_tex, v_tex, "\\times", w_tex, ")" ) dot_with_cross.set_color_by_tex(v_tex, U_COLOR) dot_with_cross.set_color_by_tex(w_tex, W_COLOR) transform = VGroup(func, det_text) transform.arrange() VGroup(transform, dot_with_cross).scale(0.7) VGroup(vector_word, cross).arrange( RIGHT, buff = MED_SMALL_BUFF ).center().shift(LEFT).to_edge(UP) transform_word.next_to(vector_word, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT) transform.next_to(transform_word, DOWN, buff = MED_SMALL_BUFF, aligned_edge = LEFT) dot_with_cross.next_to(func, RIGHT) self.add(vector_word) self.play(Write(cross)) self.wait() self.play(FadeIn(transform_word)) self.play(Write(transform)) self.wait() self.play(Transform(det_text, dot_with_cross)) self.wait()
videos_3b1b/_2016/eola/chapter10.py
from manim_imports_ext import * from _2016.eola.chapter1 import plane_wave_homotopy from _2016.eola.chapter3 import ColumnsToBasisVectors from _2016.eola.chapter5 import get_det_text from _2016.eola.chapter9 import get_small_bubble class OpeningQuote(Scene): def construct(self): words = OldTexText( "``Last time, I asked: `What does", "mathematics", """ mean to you?', and some people answered: `The manipulation of numbers, the manipulation of structures.' And if I had asked what""", "music", """means to you, would you have answered: `The manipulation of notes?' '' """, enforce_new_line_structure = False, alignment = "", ) words.set_color_by_tex("mathematics", BLUE) words.set_color_by_tex("music", BLUE) words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) author = OldTexText("-Serge Lang") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(Write(words, run_time = 10)) self.wait() self.play(FadeIn(author)) self.wait(3) class StudentsFindThisConfusing(TeacherStudentsScene): def construct(self): title = OldTexText("Eigenvectors and Eigenvalues") title.to_edge(UP) students = self.get_students() self.play( Write(title), *[ ApplyMethod(pi.look_at, title) for pi in self.get_pi_creatures() ] ) self.play( self.get_teacher().look_at, students[-1].eyes, students[0].change_mode, "confused", students[1].change_mode, "tired", students[2].change_mode, "sassy", ) self.random_blink() self.student_says( "Why are we doing this?", index = 0, run_time = 2, ) question1 = students[0].bubble.content.copy() self.student_says( "What does this actually mean?", index = 2, added_anims = [ question1.scale, 0.8, question1.to_edge, LEFT, question1.shift, DOWN, ] ) question2 = students[2].bubble.content.copy() question2.target = question2.copy() question2.target.next_to( question1, DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF ) equation = OldTex( "\\det\\left( %s \\right)=0"%matrix_to_tex_string([ ["a-\\lambda", "b"], ["c", "d-\\lambda"], ]) ) equation.set_color(YELLOW) self.teacher_says( equation, added_anims = [MoveToTarget(question2)] ) self.play_student_changes(*["confused"]*3) self.random_blink(3) class ShowComments(Scene): pass #TODO class EigenThingsArentAllThatBad(TeacherStudentsScene): def construct(self): self.teacher_says( "Eigen-things aren't \\\\ actually so bad", target_mode = "hooray" ) self.play_student_changes( "pondering", "pondering", "erm" ) self.random_blink(4) class ManyPrerequisites(Scene): def construct(self): title = OldTexText("Many prerequisites") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) self.add(title) self.play(ShowCreation(h_line)) rect = Rectangle(height = 9, width = 16, color = BLUE) rect.set_width(FRAME_X_RADIUS-2) rects = [rect]+[rect.copy() for i in range(3)] words = [ "Linear transformations", "Determinants", "Linear systems", "Change of basis", ] for rect, word in zip(rects, words): word_mob = OldTexText(word) word_mob.next_to(rect, UP, buff = MED_SMALL_BUFF) rect.add(word_mob) Matrix(np.array(rects).reshape((2, 2))) rects = VGroup(*rects) rects.set_height(FRAME_HEIGHT - 1.5) rects.next_to(h_line, DOWN, buff = MED_SMALL_BUFF) self.play(Write(rects[0])) self.wait() self.play(*list(map(FadeIn, rects[1:]))) self.wait() class ExampleTranformationScene(LinearTransformationScene): CONFIG = { "t_matrix" : [[3, 0], [1, 2]] } def setup(self): LinearTransformationScene.setup(self) self.add_matrix() def add_matrix(self): matrix = Matrix(self.t_matrix.T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(ORIGIN, LEFT, buff = MED_SMALL_BUFF) matrix.to_edge(UP) matrix.rect = BackgroundRectangle(matrix) matrix.add_to_back(matrix.rect) self.add_foreground_mobject(matrix) self.matrix = matrix def remove_matrix(self): self.remove(self.matrix) self.foreground_mobjects.remove(self.matrix) class IntroduceExampleTransformation(ExampleTranformationScene): def construct(self): self.remove_matrix() i_coords = Matrix(self.t_matrix[0]) j_coords = Matrix(self.t_matrix[1]) self.apply_transposed_matrix(self.t_matrix) for coords, vect in (i_coords, self.i_hat), (j_coords, self.j_hat): coords.set_color(vect.get_color()) coords.scale(0.8) coords.rect = BackgroundRectangle(coords) coords.add_to_back(coords.rect) coords.next_to(vect.get_end(), RIGHT) self.play(Write(coords)) self.wait() i_coords_copy = i_coords.copy() self.play(*[ Transform(*pair) for pair in [ (i_coords_copy.rect, self.matrix.rect), (i_coords_copy.get_brackets(), self.matrix.get_brackets()), ( i_coords_copy.get_entries(), VGroup(*self.matrix.get_mob_matrix()[:,0]) ) ] ]) to_remove = self.get_mobjects_from_last_animation() self.play(Transform( j_coords.copy().get_entries(), VGroup(*self.matrix.get_mob_matrix()[:,1]) )) to_remove += self.get_mobjects_from_last_animation() self.wait() self.remove(*to_remove) self.add(self.matrix) class VectorKnockedOffSpan(ExampleTranformationScene): def construct(self): vector = Vector([2, 1]) line = Line(vector.get_end()*-4, vector.get_end()*4, color = MAROON_B) vector.scale(0.7) top_words, off, span_label = all_words = OldTexText( "\\centering Vector gets knocked", "\\\\ off", "Span" ) all_words.shift( line.point_from_proportion(0.75) - \ span_label.get_corner(DOWN+RIGHT) + \ MED_SMALL_BUFF*LEFT ) for text in all_words: text.add_to_back(BackgroundRectangle(text)) self.add_vector(vector) self.wait() self.play( ShowCreation(line), Write(span_label), Animation(vector), ) self.add_foreground_mobject(span_label) self.wait() self.apply_transposed_matrix(self.t_matrix) self.play(Animation(span_label.copy()), Write(all_words)) self.wait() class VectorRemainsOnSpan(ExampleTranformationScene): def construct(self): vector = Vector([1, -1]) v_end = vector.get_end() line = Line(-4*v_end, 4*v_end, color = MAROON_B) words = OldTexText("Vector remains on", "\\\\its own span") words.next_to(ORIGIN, DOWN+LEFT) for part in words: part.add_to_back(BackgroundRectangle(part)) self.add_vector(vector) self.play(ShowCreation(line), Animation(vector)) self.wait() self.apply_transposed_matrix(self.t_matrix) self.play(Write(words)) self.wait() target_vectors = [ vector.copy().scale(scalar) for scalar in (2, -2, 1) ] for target, time in zip(target_vectors, [1, 2, 2]): self.play(Transform(vector, target, run_time = time)) self.wait() class IHatAsEigenVector(ExampleTranformationScene): def construct(self): self.set_color_first_column() self.set_color_x_axis() self.apply_transposed_matrix(self.t_matrix, path_arc = 0) self.label_i_hat_landing_spot() def set_color_first_column(self): faders = VGroup(self.plane, self.i_hat, self.j_hat) faders.save_state() column1 = VGroup(*self.matrix.get_mob_matrix()[:,0]) self.play(faders.fade, 0.7, Animation(self.matrix)) self.play(column1.scale, 1.3, rate_func = there_and_back) self.wait() self.play(faders.restore, Animation(self.matrix)) self.wait() def set_color_x_axis(self): x_axis = self.plane.axes[0] targets = [ self.i_hat.copy().scale(val) for val in (-FRAME_X_RADIUS, FRAME_X_RADIUS, 1) ] lines = [ Line(v1.get_end(), v2.get_end(), color = YELLOW) for v1, v2 in adjacent_pairs([self.i_hat]+targets) ] for target, line in zip(targets, lines): self.play( ShowCreation(line), Transform(self.i_hat, target), ) self.wait() self.remove(*lines) x_axis.set_color(YELLOW) def label_i_hat_landing_spot(self): array = Matrix(self.t_matrix[0]) array.set_color(X_COLOR) array.rect = BackgroundRectangle(array) array.add_to_back(array.rect) brace = Brace(self.i_hat, buff = 0) brace.put_at_tip(array) self.play(GrowFromCenter(brace)) matrix = self.matrix.copy() self.play( Transform(matrix.rect, array.rect), Transform(matrix.get_brackets(), array.get_brackets()), Transform( VGroup(*matrix.get_mob_matrix()[:,0]), array.get_entries() ), ) self.wait() class AllXAxisVectorsAreEigenvectors(ExampleTranformationScene): def construct(self): vectors = VGroup(*[ self.add_vector(u*x*RIGHT, animate = False) for x in reversed(list(range(1, int(FRAME_X_RADIUS)+1))) for u in [-1, 1] ]) vectors.set_color_by_gradient(YELLOW, X_COLOR) self.play(ShowCreation(vectors)) self.wait() self.apply_transposed_matrix(self.t_matrix, path_arc = 0) self.wait() class SneakierEigenVector(ExampleTranformationScene): def construct(self): coords = [-1, 1] vector = Vector(coords) array = Matrix(coords) array.scale(0.7) array.set_color(vector.get_color()) array.add_to_back(BackgroundRectangle(array)) array.target = array.copy() array.next_to(vector.get_end(), LEFT) array.target.next_to(2*vector.get_end(), LEFT) two_times = OldTex("2 \\cdot") two_times.add_background_rectangle() two_times.next_to(array.target, LEFT) span_line = Line(-4*vector.get_end(), 4*vector.get_end()) span_line.set_color(MAROON_B) self.matrix.shift(-2*self.matrix.get_center()[0]*RIGHT) self.add_vector(vector) self.play(Write(array)) self.play( ShowCreation(span_line), Animation(vector), Animation(array), ) self.wait() self.apply_transposed_matrix( self.t_matrix, added_anims = [ MoveToTarget(array), Transform(VectorizedPoint(array.get_left()), two_times) ], path_arc = 0, ) self.wait() class FullSneakyEigenspace(ExampleTranformationScene): def construct(self): self.matrix.shift(-2*self.matrix.get_center()[0]*RIGHT) vectors = VGroup(*[ self.add_vector(u*x*(LEFT+UP), animate = False) for x in reversed(np.arange(0.5, 5, 0.5)) for u in [-1, 1] ]) vectors.set_color_by_gradient(MAROON_B, YELLOW) words = OldTexText("Stretch by 2") words.add_background_rectangle() words.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF) words.shift(MED_SMALL_BUFF*LEFT) words.rotate(vectors[0].get_angle()) words.start = words.copy() words.start.scale(0.5) words.start.set_fill(opacity = 0) self.play(ShowCreation(vectors)) self.wait() self.apply_transposed_matrix( self.t_matrix, added_anims = [Transform(words.start, words)], path_arc = 0 ) self.wait() class NameEigenvectorsAndEigenvalues(ExampleTranformationScene): CONFIG = { "show_basis_vectors" : False } def construct(self): self.remove(self.matrix) self.foreground_mobjects.remove(self.matrix) x_vectors = VGroup(*[ self.add_vector(u*x*RIGHT, animate = False) for x in range(int(FRAME_X_RADIUS)+1, 0, -1) for u in [-1, 1] ]) x_vectors.set_color_by_gradient(YELLOW, X_COLOR) self.remove(x_vectors) sneak_vectors = VGroup(*[ self.add_vector(u*x*(LEFT+UP), animate = False) for x in np.arange(int(FRAME_Y_RADIUS), 0, -0.5) for u in [-1, 1] ]) sneak_vectors.set_color_by_gradient(MAROON_B, YELLOW) self.remove(sneak_vectors) x_words = OldTexText("Stretched by 3") sneak_words = OldTexText("Stretched by 2") for words in x_words, sneak_words: words.add_background_rectangle() words.next_to(x_vectors, DOWN) words.next_to(words.get_center(), LEFT, buff = 1.5) eigen_word = OldTexText("Eigenvectors") eigen_word.add_background_rectangle() eigen_word.replace(words) words.target = eigen_word eigen_val_words = OldTexText( "with eigenvalue ", "%s"%words.get_tex()[-1] ) eigen_val_words.add_background_rectangle() eigen_val_words.next_to(words, DOWN, aligned_edge = RIGHT) words.eigen_val_words = eigen_val_words x_words.eigen_val_words.set_color(X_COLOR) sneak_words.eigen_val_words.set_color(YELLOW) VGroup( sneak_words, sneak_words.target, sneak_words.eigen_val_words, ).rotate(sneak_vectors[0].get_angle()) non_eigen = Vector([1, 1], color = PINK) non_eigen_span = Line( -FRAME_Y_RADIUS*non_eigen.get_end(), FRAME_Y_RADIUS*non_eigen.get_end(), color = RED ) non_eigen_words = OldTexText(""" Knocked off its own span """) non_eigen_words.add_background_rectangle() non_eigen_words.scale(0.7) non_eigen_words.next_to(non_eigen.get_end(), RIGHT) non_eigen_span.fade() for vectors in x_vectors, sneak_vectors: self.play(ShowCreation(vectors, run_time = 1)) self.wait() for words in x_words, sneak_words: self.play(Write(words, run_time = 1.5)) self.add_foreground_mobject(words) self.wait() self.play(ShowCreation(non_eigen)) self.play( ShowCreation(non_eigen_span), Write(non_eigen_words), Animation(non_eigen) ) self.add_vector(non_eigen, animate = False) self.wait() self.apply_transposed_matrix( self.t_matrix, added_anims = [FadeOut(non_eigen_words)], path_arc = 0, ) self.wait(2) self.play(*list(map(FadeOut, [non_eigen, non_eigen_span]))) self.play(*list(map(MoveToTarget, [x_words, sneak_words]))) self.wait() for words in x_words, sneak_words: self.play(Write(words.eigen_val_words), run_time = 2) self.wait() class CanEigenvaluesBeNegative(TeacherStudentsScene): def construct(self): self.student_says("Can eigenvalues be negative?") self.random_blink() self.teacher_says("But of course!", target_mode = "hooray") self.random_blink() class EigenvalueNegativeOneHalf(LinearTransformationScene): CONFIG = { "t_matrix" : [[0.5, -1], [-1, 0.5]], "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 0 }, "include_background_plane" : False } def construct(self): matrix = Matrix(self.t_matrix.T) matrix.add_to_back(BackgroundRectangle(matrix)) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(ORIGIN, LEFT) matrix.to_edge(UP) self.add_foreground_mobject(matrix) vector = self.add_vector([1, 1]) words = OldTexText("Eigenvector with \\\\ eigenvalue $-\\frac{1}{2}$") words.add_background_rectangle() words.next_to(vector.get_end(), RIGHT) span = Line( -FRAME_Y_RADIUS*vector.get_end(), FRAME_Y_RADIUS*vector.get_end(), color = MAROON_B ) self.play(Write(words)) self.play( ShowCreation(span), Animation(vector), Animation(words), ) self.wait() self.apply_transposed_matrix( self.t_matrix, added_anims = [FadeOut(words)] ) self.wait() self.play( Rotate(span, np.pi/12, rate_func = wiggle), Animation(vector), ) self.wait() class ThreeDRotationTitle(Scene): def construct(self): title = OldTexText("3D Rotation") title.scale(2) self.play(Write(title)) self.wait() class ThreeDShowRotation(Scene): pass class ThreeDShowRotationWithEigenvector(Scene): pass class EigenvectorToAxisOfRotation(Scene): def construct(self): words = [ OldTexText("Eigenvector"), OldTexText("Axis of rotation"), ] for word in words: word.scale(2) self.play(Write(words[0])) self.wait() self.play(Transform(*words)) self.wait() class EigenvalueOne(Scene): def construct(self): text = OldTexText("Eigenvalue = $1$") text.set_color(MAROON_B) self.play(Write(text)) self.wait() class ContrastMatrixUnderstandingWithEigenvalue(TeacherStudentsScene): def construct(self): axis_and_rotation = OldTexText( "Rotate", "$30^\\circ$", "around", "$%s$"%matrix_to_tex_string([2, 3, 1]) ) axis_and_rotation[1].set_color(BLUE) axis_and_rotation[-1].set_color(MAROON_B) matrix = Matrix([ [ "\\cos(\\theta)\\cos(\\phi)", "-\\sin(\\phi)", "\\cos(\\theta)\\sin(\\phi)", ], [ "\\sin(\\theta)\\cos(\\phi)", "\\cos(\\theta)", "\\sin(\\theta)\\sin(\\phi)", ], [ "-\\sin(\\phi)", "0", "\\cos(\\phi)" ] ]) matrix.scale(0.7) for mob in axis_and_rotation, matrix: mob.to_corner(UP+RIGHT) everyone = self.get_pi_creatures() self.play( Write(axis_and_rotation), *it.chain(*list(zip( [pi.change_mode for pi in everyone], ["hooray"]*4, [pi.look_at for pi in everyone], [axis_and_rotation]*4, ))), run_time = 2 ) self.random_blink(2) self.play( Transform(axis_and_rotation, matrix), *it.chain(*list(zip( [pi.change_mode for pi in everyone], ["confused"]*4, [pi.look_at for pi in everyone], [matrix]*4, ))) ) self.random_blink(3) class CommonPattern(TeacherStudentsScene): def construct(self): self.teacher_says(""" This is a common pattern in linear algebra. """) self.random_blink(2) class DeduceTransformationFromMatrix(ColumnsToBasisVectors): def construct(self): self.setup() self.move_matrix_columns([[3, 0], [1, 2]]) words = OldTexText(""" This gives too much weight to our coordinate system """) words.add_background_rectangle() words.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF) words.shift_onto_screen() self.play(Write(words)) self.wait() class WordsOnComputation(TeacherStudentsScene): def construct(self): self.teacher_says( "I won't cover the full\\\\", "details of computation...", target_mode = "guilty" ) self.play_student_changes("angry", "sassy", "angry") self.random_blink() self.teacher_says( "...but I'll hit the \\\\", "important parts" ) self.play_student_changes(*["happy"]*3) self.random_blink(3) class SymbolicEigenvectors(Scene): def construct(self): self.introduce_terms() self.contrast_multiplication_types() self.rewrite_righthand_side() self.reveal_as_linear_system() self.bring_in_determinant() def introduce_terms(self): self.expression = OldTex( "A", "\\vec{\\textbf{v}}", "=", "\\lambda", "\\vec{\\textbf{v}}" ) self.expression.scale(1.5) self.expression.shift(UP+2*LEFT) A, v1, equals, lamb, v2 = self.expression vs = VGroup(v1, v2) vs.set_color(YELLOW) lamb.set_color(MAROON_B) A_brace = Brace(A, UP, buff = 0) A_text = OldTexText("Transformation \\\\ matrix") A_text.next_to(A_brace, UP) lamb_brace = Brace(lamb, UP, buff = 0) lamb_text = OldTexText("Eigenvalue") lamb_text.set_color(lamb.get_color()) lamb_text.next_to(lamb_brace, UP, aligned_edge = LEFT) v_text = OldTexText("Eigenvector") v_text.set_color(vs.get_color()) v_text.next_to(vs, DOWN, buff = 1.5*LARGE_BUFF) v_arrows = VGroup(*[ Arrow(v_text.get_top(), v.get_bottom()) for v in vs ]) self.play(Write(self.expression)) self.wait() self.play( GrowFromCenter(A_brace), Write(A_text) ) self.wait() self.play( Write(v_text), ShowCreation(v_arrows) ) self.wait() self.play( GrowFromCenter(lamb_brace), Write(lamb_text) ) self.wait(2) self.play(*list(map(FadeOut, [ A_brace, A_text, lamb_brace, lamb_text, v_text, v_arrows ]))) def contrast_multiplication_types(self): A, v1, equals, lamb, v2 = self.expression left_group = VGroup(A, v1) left_group.brace = Brace(left_group, UP) left_group.text = left_group.brace.get_text("Matrix-vector multiplication") right_group = VGroup(lamb, v2) right_group.brace = Brace(right_group, DOWN) right_group.text = right_group.brace.get_text("Scalar multiplication") right_group.text.set_color(lamb.get_color()) for group in left_group, right_group: self.play( GrowFromCenter(group.brace), Write(group.text, run_time = 2) ) self.play(group.scale, 1.2, rate_func = there_and_back) self.wait() morty = Mortimer().to_edge(DOWN) morty.change_mode("speaking") bubble = morty.get_bubble(SpeechBubble, width = 5, direction = LEFT) VGroup(morty, bubble).to_edge(RIGHT) solve_text = OldTexText( "Solve for \\\\", "$\\lambda$", "and", "$\\vec{\\textbf{v}}$" ) solve_text.set_color_by_tex("$\\lambda$", lamb.get_color()) solve_text.set_color_by_tex("$\\vec{\\textbf{v}}$", v1.get_color()) bubble.add_content(solve_text) self.play( FadeIn(morty), FadeIn(bubble), Write(solve_text) ) self.play(Blink(morty)) self.wait(2) bubble.write("Fix different", "\\\\ multiplication", "types") self.play( Transform(solve_text, bubble.content), morty.change_mode, "sassy" ) self.play(Blink(morty)) self.wait() self.play(*list(map(FadeOut, [ left_group.brace, left_group.text, right_group.brace, right_group.text, morty, bubble, solve_text ]))) def rewrite_righthand_side(self): A, v1, equals, lamb, v2 = self.expression lamb_copy = lamb.copy() scaling_by = VGroup( OldTexText("Scaling by "), lamb_copy ) scaling_by.arrange() arrow = OldTex("\\Updownarrow") matrix_multiplication = OldTexText( "Matrix multiplication by" ) matrix = Matrix(np.identity(3, dtype = int)) corner_group = VGroup( scaling_by, arrow, matrix_multiplication, matrix ) corner_group.arrange(DOWN) corner_group.to_corner(UP+RIGHT) q_marks = VGroup(*[ OldTex("?").replace(entry) for entry in matrix.get_entries() ]) q_marks.set_color_by_gradient(X_COLOR, Y_COLOR, Z_COLOR) diag_entries = VGroup(*[ matrix.get_mob_matrix()[i,i] for i in range(3) ]) diag_entries.save_state() for entry in diag_entries: new_lamb = OldTex("\\lambda") new_lamb.move_to(entry) new_lamb.set_color(lamb.get_color()) Transform(entry, new_lamb).update(1) new_lamb = lamb.copy() new_lamb.next_to(matrix, LEFT) id_brace = Brace(matrix) id_text = OldTex("I").scale(1.5) id_text.next_to(id_brace, DOWN) self.play( Transform(lamb.copy(), lamb_copy), Write(scaling_by) ) self.remove(*self.get_mobjects_from_last_animation()) self.add(scaling_by) self.play(Write(VGroup( matrix_multiplication, arrow, matrix.get_brackets(), q_marks, ), run_time = 2 )) self.wait() self.play(Transform( q_marks, matrix.get_entries(), lag_ratio = 0.5, run_time = 2 )) self.remove(q_marks) self.add(*matrix.get_entries()) self.wait() self.play( Transform(diag_entries.copy(), new_lamb), diag_entries.restore ) self.remove(*self.get_mobjects_from_last_animation()) self.add(new_lamb, diag_entries) self.play( GrowFromCenter(id_brace), Write(id_text) ) self.wait() id_text_copy = id_text.copy() self.add(id_text_copy) l_paren, r_paren = parens = OldTex("()").scale(1.5) for mob in lamb, id_text, v2: mob.target = mob.copy() VGroup( l_paren, lamb.target, id_text.target, r_paren, v2.target ).arrange().next_to(equals).shift(SMALL_BUFF*UP) self.play( Write(parens), *list(map(MoveToTarget, [lamb, id_text, v2])) ) self.wait() self.play(*list(map(FadeOut, [ corner_group, id_brace, id_text_copy, new_lamb ]))) self.expression = VGroup( A, v1, equals, VGroup(l_paren, lamb, id_text, r_paren), v2 ) def reveal_as_linear_system(self): A, v1, equals, lamb_group, v2 = self.expression l_paren, lamb, I, r_paren = lamb_group zero = OldTex("\\vec{\\textbf{0}}") zero.scale(1.3) zero.next_to(equals, RIGHT) zero.shift(SMALL_BUFF*UP/2) minus = OldTex("-").scale(1.5) movers = A, v1, lamb_group, v2 for mob in movers: mob.target = mob.copy() VGroup( A.target, v1.target, minus, lamb_group.target, v2.target ).arrange().next_to(equals, LEFT) self.play( Write(zero), Write(minus), *list(map(MoveToTarget, movers)), path_arc = np.pi/3 ) self.wait() A.target.next_to(minus, LEFT) l_paren.target = l_paren.copy() l_paren.target.next_to(A.target, LEFT) self.play( MoveToTarget(A), MoveToTarget(l_paren), Transform(v1, v2, path_arc = np.pi/3) ) self.remove(v1) self.wait() brace = Brace(VGroup(l_paren, r_paren)) brace.text = OldTexText("This matrix looks \\\\ something like") brace.text.next_to(brace, DOWN) brace.text.to_edge(LEFT) matrix = Matrix([ ["3-\\lambda", "1", "4"], ["1", "5-\\lambda", "9"], ["2", "6", "5-\\lambda"], ]) matrix.scale(0.7) VGroup( matrix.get_brackets()[1], *matrix.get_mob_matrix()[:,2] ).shift(0.5*RIGHT) matrix.next_to(brace.text, DOWN) for entry in matrix.get_entries(): if len(entry.get_tex()) > 1: entry[-1].set_color(lamb.get_color()) self.play( GrowFromCenter(brace), Write(brace.text), Write(matrix) ) self.wait() vect_words = OldTexText( "We want a nonzero solution for" ) v_copy = v2.copy().next_to(vect_words) vect_words.add(v_copy) vect_words.to_corner(UP+LEFT) arrow = Arrow(vect_words.get_bottom(), v2.get_top()) self.play( Write(vect_words), ShowCreation(arrow) ) self.wait() def bring_in_determinant(self): randy = Randolph(mode = "speaking").to_edge(DOWN) randy.flip() randy.look_at(self.expression) bubble = randy.get_bubble(SpeechBubble, direction = LEFT, width = 5) words = OldTexText("We need") equation = OldTex( "\\det(A-", "\\lambda", "I)", "=0" ) equation.set_color_by_tex("\\lambda", MAROON_B) equation.next_to(words, DOWN) words.add(equation) bubble.add_content(words) self.play( FadeIn(randy), ShowCreation(bubble), Write(words) ) self.play(Blink(randy)) self.wait() everything = self.get_mobjects() equation_copy = equation.copy() self.play( FadeOut(VGroup(*everything)), Animation(equation_copy) ) self.play( equation_copy.center, equation_copy.scale, 1.5 ) self.wait() class NonZeroSolutionsVisually(LinearTransformationScene): CONFIG = { "t_matrix" : [[1, 1], [2, 2]], "v_coords" : [2, -1] } def construct(self): equation = OldTex( "(A-", "\\lambda", "I)", "\\vec{\\textbf{v}}", "= \\vec{\\textbf{0}}" ) equation_matrix = VGroup(*equation[:3]) equation.set_color_by_tex("\\lambda", MAROON_B) equation.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW) equation.add_background_rectangle() equation.next_to(ORIGIN, DOWN, buff = MED_SMALL_BUFF) equation.to_edge(LEFT) det_equation = OldTex( "\\text{Squishification} \\Rightarrow", "\\det", "(A-", "\\lambda", "I", ")", "=0" ) det_equation_matrix = VGroup(*det_equation[2:2+4]) det_equation.set_color_by_tex("\\lambda", MAROON_B) det_equation.next_to(equation, DOWN, buff = MED_SMALL_BUFF) det_equation.to_edge(LEFT) det_equation.add_background_rectangle() self.add_foreground_mobject(equation) v = self.add_vector(self.v_coords) self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() transform = Transform( equation_matrix.copy(), det_equation_matrix ) self.play(Write(det_equation), transform) self.wait() class TweakLambda(LinearTransformationScene): CONFIG = { "t_matrix" : [[2, 1], [2, 3]], "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 1 }, } def construct(self): matrix = Matrix([ ["2-0.00", "2"], ["1", "3-0.00"], ]) matrix.add_to_back(BackgroundRectangle(matrix)) matrix.next_to(ORIGIN, LEFT, buff = LARGE_BUFF) matrix.to_edge(UP) self.lambda_vals = [] for i in range(2): entry = matrix.get_mob_matrix()[i,i] place_holders = VGroup(*entry[2:]) entry.remove(*place_holders) place_holders.set_color(MAROON_B) self.lambda_vals.append(place_holders) brace = Brace(matrix) brace_text = OldTex("(A-", "\\lambda", "I)") brace_text.set_color_by_tex("\\lambda", MAROON_B) brace_text.next_to(brace, DOWN) brace_text.add_background_rectangle() det_text = get_det_text(matrix) equals = OldTex("=").next_to(det_text) det = DecimalNumber(np.linalg.det(self.t_matrix)) det.set_color(YELLOW) det.next_to(equals) det.rect = BackgroundRectangle(det) self.det = det self.matrix = VGroup(matrix, brace, brace_text) self.add_foreground_mobject( self.matrix, *self.lambda_vals ) self.add_unit_square() self.plane_mobjects = [ self.plane, self.square, ] for mob in self.plane_mobjects: mob.save_state() self.apply_transposed_matrix(self.t_matrix) self.play( Write(det_text), Write(equals), ShowCreation(det.rect), Write(det) ) self.matrix.add(det_text, equals, det.rect) self.wait() self.range_lambda(0, 3, run_time = 5) self.wait() self.range_lambda(3, 0.5, run_time = 5) self.wait() self.range_lambda(0.5, 1.5, run_time = 3) self.wait() self.range_lambda(1.5, 1, run_time = 2) self.wait() def get_t_matrix(self, lambda_val): return self.t_matrix - lambda_val*np.identity(2) def range_lambda(self, start_val, end_val, run_time = 3): alphas = np.linspace(0, 1, run_time/self.frame_duration) matrix_transform = self.get_matrix_transformation( self.get_t_matrix(end_val) ) transformations = [] for mob in self.plane_mobjects: mob.target = mob.copy().restore().apply_function(matrix_transform) transformations.append(MoveToTarget(mob)) transformations += [ Transform( self.i_hat, Vector(matrix_transform(RIGHT), color = X_COLOR) ), Transform( self.j_hat, Vector(matrix_transform(UP), color = Y_COLOR) ), ] for alpha in alphas: self.clear() val = interpolate(start_val, end_val, alpha) new_t_matrix = self.get_t_matrix(val) for transformation in transformations: transformation.update(alpha) self.add(transformation.mobject) self.add(self.matrix) new_lambda_vals = [] for lambda_val in self.lambda_vals: new_lambda = DecimalNumber(val) new_lambda.move_to(lambda_val, aligned_edge = LEFT) new_lambda.set_color(lambda_val.get_color()) new_lambda_vals.append(new_lambda) self.lambda_vals = new_lambda_vals self.add(*self.lambda_vals) new_det = DecimalNumber( np.linalg.det([ self.i_hat.get_end()[:2], self.j_hat.get_end()[:2], ]) ) new_det.move_to(self.det, aligned_edge = LEFT) new_det.set_color(self.det.get_color()) self.det = new_det self.add(self.det) self.wait(self.frame_duration) class ShowEigenVectorAfterComputing(LinearTransformationScene): CONFIG = { "t_matrix" : [[2, 1], [2, 3]], "v_coords" : [2, -1], "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 1 }, } def construct(self): matrix = Matrix(self.t_matrix.T) matrix.add_to_back(BackgroundRectangle(matrix)) matrix.next_to(ORIGIN, RIGHT) matrix.shift(self.v_coords[0]*RIGHT) self.add_foreground_mobject(matrix) v_label = OldTex( "\\vec{\\textbf{v}}", "=", "1", "\\vec{\\textbf{v}}", ) v_label.next_to(matrix, RIGHT) v_label.set_color_by_tex("\\vec{\\textbf{v}}", YELLOW) v_label.set_color_by_tex("1", MAROON_B) v_label.add_background_rectangle() v = self.add_vector(self.v_coords) eigenvector = OldTexText("Eigenvector") eigenvector.add_background_rectangle() eigenvector.next_to(ORIGIN, DOWN+RIGHT) eigenvector.rotate(v.get_angle()) self.play(Write(eigenvector)) self.add_foreground_mobject(eigenvector) line = Line(v.get_end()*(-4), v.get_end()*4, color = MAROON_B) self.play(Write(v_label)) self.add_foreground_mobject(v_label) self.play(ShowCreation(line), Animation(v)) self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() class LineOfReasoning(Scene): def construct(self): v_tex = "\\vec{\\textbf{v}}" expressions = VGroup(*it.starmap(Tex, [ ("A", v_tex, "=", "\\lambda", v_tex), ("A", v_tex, "-", "\\lambda", "I", v_tex, "=", "0"), ("(", "A", "-", "\\lambda", "I)", v_tex, "=", "0"), ("\\det(A-", "\\lambda", "I)", "=", "0") ])) expressions.arrange(DOWN, buff = LARGE_BUFF/2.) for expression in expressions: for i, expression_part in enumerate(expression.expression_parts): if expression_part == "=": equals = expression[i] expression.shift(equals.get_center()[0]*LEFT) break expression.set_color_by_tex(v_tex, YELLOW) expression.set_color_by_tex("\\lambda", MAROON_B) self.play(FadeIn(expression)) self.wait() class IfYouDidntKnowDeterminants(TeacherStudentsScene): def construct(self): expression = OldTex("\\det(A-", "\\lambda", "I" ")=0") expression.set_color_by_tex("\\lambda", MAROON_B) expression.scale(1.3) self.teacher_says(expression) self.random_blink() student = self.get_students()[0] bubble = get_small_bubble(student) bubble.write("Wait...why?") self.play( ShowCreation(bubble), Write(bubble.content), student.change_mode, "confused" ) self.random_blink(4) class RevisitExampleTransformation(ExampleTranformationScene): def construct(self): self.introduce_matrix() seeking_eigenvalue = OldTexText("Seeking eigenvalue") seeking_eigenvalue.add_background_rectangle() lamb = OldTex("\\lambda") lamb.set_color(MAROON_B) words = VGroup(seeking_eigenvalue, lamb) words.arrange() words.next_to(self.matrix, DOWN, buff = LARGE_BUFF) self.play(Write(words)) self.wait() self.play(*self.get_lambda_to_diag_movements(lamb.copy())) self.add_foreground_mobject(*self.get_mobjects_from_last_animation()) self.wait() self.show_determinant(to_fade = words) self.show_diagonally_altered_transform() self.show_unaltered_transform() def introduce_matrix(self): self.matrix.shift(2*LEFT) for mob in self.plane, self.i_hat, self.j_hat: mob.save_state() self.remove_matrix() i_coords = Matrix(self.t_matrix[0]) j_coords = Matrix(self.t_matrix[1]) self.apply_transposed_matrix(self.t_matrix) for coords, vect in (i_coords, self.i_hat), (j_coords, self.j_hat): coords.set_color(vect.get_color()) coords.scale(0.8) coords.rect = BackgroundRectangle(coords) coords.add_to_back(coords.rect) coords.next_to( vect.get_end(), RIGHT+DOWN if coords is i_coords else RIGHT ) self.play( Write(i_coords), Write(j_coords), ) self.wait() self.play(*[ Transform(*pair) for pair in [ (i_coords.rect, self.matrix.rect), (i_coords.get_brackets(), self.matrix.get_brackets()), ( i_coords.get_entries(), VGroup(*self.matrix.get_mob_matrix()[:,0]) ) ] ]) to_remove = self.get_mobjects_from_last_animation() self.play( FadeOut(j_coords.get_brackets()), FadeOut(j_coords.rect), Transform( j_coords.get_entries(), VGroup(*self.matrix.get_mob_matrix()[:,1]) ), ) to_remove += self.get_mobjects_from_last_animation() self.wait() self.remove(*to_remove) self.add_foreground_mobject(self.matrix) def get_lambda_to_diag_movements(self, lamb): three, two = [self.matrix.get_mob_matrix()[i, i] for i in range(2)] l_bracket, r_bracket = self.matrix.get_brackets() rect = self.matrix.rect lamb_copy = lamb.copy() movers = [rect, three, two, l_bracket, r_bracket, lamb, lamb_copy] for mover in movers: mover.target = mover.copy() minus1, minus2 = [Tex("-") for x in range(2)] new_three = VGroup(three.target, minus1, lamb.target) new_three.arrange() new_three.move_to(three) new_two = VGroup(two.target, minus2, lamb_copy.target) new_two.arrange() new_two.move_to(two) l_bracket.target.next_to(VGroup(new_three, new_two), LEFT) r_bracket.target.next_to(VGroup(new_three, new_two), RIGHT) rect.target = BackgroundRectangle( VGroup(l_bracket.target, r_bracket.target) ) result = list(map(MoveToTarget, movers)) result += list(map(Write, [minus1, minus2])) result += list(map(Animation, [ self.matrix.get_mob_matrix()[i, 1-i] for i in range(2) ])) self.diag_entries = [ VGroup(three, minus1, lamb), VGroup(two, minus2, lamb_copy), ] return result def show_determinant(self, to_fade = None): det_text = get_det_text(self.matrix) equals = OldTex("=").next_to(det_text) three_minus_lamb, two_minus_lamb = diag_entries = [ entry.copy() for entry in self.diag_entries ] one = self.matrix.get_mob_matrix()[0, 1].copy() zero = self.matrix.get_mob_matrix()[1, 0].copy() for entry in diag_entries + [one, zero]: entry.target = entry.copy() lp1, rp1, lp2, rp2 = parens = OldTex("()()") minus = OldTex("-") cdot = OldTex("\\cdot") VGroup( lp1, three_minus_lamb.target, rp1, lp2, two_minus_lamb.target, rp2, minus, one.target, cdot, zero.target ).arrange().next_to(equals) parens.add_background_rectangle() new_rect = BackgroundRectangle(VGroup(minus, zero.target)) brace = Brace(new_rect, buff = 0) brace_text = brace.get_text("Equals 0, so ", "ignore") brace_text.add_background_rectangle() brace.target = Brace(parens) brace_text.target = brace.target.get_text( "Quadratic polynomial in ", "$\\lambda$" ) brace_text.target.set_color_by_tex("$\\lambda$", MAROON_B) brace_text.target.add_background_rectangle() equals_0 = OldTex("=0") equals_0.next_to(parens, RIGHT) equals_0.add_background_rectangle() final_brace = Brace(VGroup(parens, equals_0)) final_text = OldTex( "\\lambda", "=2", "\\text{ or }", "\\lambda", "=3" ) final_text.set_color_by_tex("\\lambda", MAROON_B) final_text.next_to(final_brace, DOWN) lambda_equals_two = VGroup(*final_text[:2]).copy() lambda_equals_two.add_to_back(BackgroundRectangle(lambda_equals_two)) final_text.add_background_rectangle() self.play( Write(det_text), Write(equals) ) self.wait() self.play( Write(parens), MoveToTarget(three_minus_lamb), MoveToTarget(two_minus_lamb), run_time = 2 ) self.wait() self.play( FadeIn(new_rect), MoveToTarget(one), MoveToTarget(zero), Write(minus), Write(cdot), run_time = 2 ) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play(*it.chain( list(map(MoveToTarget, [brace, brace_text])), list(map(FadeOut, [one, zero, minus, cdot, new_rect])) )) self.wait() self.play(Write(equals_0)) self.wait() self.play( Transform(brace, final_brace), Transform(brace_text, final_text) ) self.wait() faders = [ det_text, equals, parens, three_minus_lamb, two_minus_lamb, brace, brace_text, equals_0, ] if to_fade is not None: faders.append(to_fade) self.play(*it.chain( list(map(FadeOut, faders)), [ lambda_equals_two.scale, 1.3, lambda_equals_two.next_to, self.matrix, DOWN ] )) self.add_foreground_mobject(lambda_equals_two) self.lambda_equals_two = lambda_equals_two self.wait() def show_diagonally_altered_transform(self): for entry in self.diag_entries: lamb = entry[-1] two = OldTex("2") two.set_color(lamb.get_color()) two.move_to(lamb) self.play(Transform(lamb, two)) self.play(*it.chain( [mob.restore for mob in (self.plane, self.i_hat, self.j_hat)], list(map(Animation, self.foreground_mobjects)), )) xy_array = Matrix(["x", "y"]) xy_array.set_color(YELLOW) zero_array = Matrix([0, 0]) for array in xy_array, zero_array: array.set_height(self.matrix.get_height()) array.add_to_back(BackgroundRectangle(array)) xy_array.next_to(self.matrix) equals = OldTex("=").next_to(xy_array) equals.add_background_rectangle() zero_array.next_to(equals) self.play(*list(map(Write, [xy_array, equals, zero_array]))) self.wait() vectors = VGroup(*[ self.add_vector(u*x*(LEFT+UP), animate = False) for x in range(4, 0, -1) for u in [-1, 1] ]) vectors.set_color_by_gradient(MAROON_B, YELLOW) vectors.save_state() self.play( ShowCreation( vectors, lag_ratio = 0.5, run_time = 2 ), *list(map(Animation, self.foreground_mobjects)) ) self.wait() self.apply_transposed_matrix( self.t_matrix - 2*np.identity(2) ) self.wait() self.play(*it.chain( [mob.restore for mob in (self.plane, self.i_hat, self.j_hat, vectors)], list(map(FadeOut, [xy_array, equals, zero_array])), list(map(Animation, self.foreground_mobjects)) )) def show_unaltered_transform(self): movers = [] faders = [] for entry in self.diag_entries: mover = entry[0] faders += list(entry[1:]) mover.target = mover.copy() mover.target.move_to(entry) movers.append(mover) brace = Brace(self.matrix) brace_text = brace.get_text("Unaltered matrix") brace_text.add_background_rectangle() self.lambda_equals_two.target = brace_text movers.append(self.lambda_equals_two) self.play(*it.chain( list(map(MoveToTarget, movers)), list(map(FadeOut, faders)), [GrowFromCenter(brace)] )) VGroup(*faders).set_fill(opacity = 0) self.add_foreground_mobject(brace) self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() class ThereMightNotBeEigenvectors(TeacherStudentsScene): def construct(self): self.teacher_says(""" There could be \\emph{no} eigenvectors """) self.random_blink(3) class Rotate90Degrees(LinearTransformationScene): CONFIG = { "t_matrix" : [[0, 1], [-1, 0]], "example_vector_coords" : None, } def setup(self): LinearTransformationScene.setup(self) matrix = Matrix(self.t_matrix.T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(ORIGIN, LEFT) matrix.to_edge(UP) matrix.rect = BackgroundRectangle(matrix) matrix.add_to_back(matrix.rect) self.add_foreground_mobject(matrix) self.matrix = matrix if self.example_vector_coords is not None: v = self.add_vector(self.example_vector_coords, animate = False) line = Line(v.get_end()*(-4), v.get_end()*4, color = MAROON_B) self.play(ShowCreation(line), Animation(v)) self.add_foreground_mobject(line) def construct(self): self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() class Rotate90DegreesWithVector(Rotate90Degrees): CONFIG = { "example_vector_coords" : [1, 2] } class SolveRotationEigenvalues(Rotate90Degrees): def construct(self): self.apply_transposed_matrix(self.t_matrix, run_time = 0) self.wait() diag_entries = [ self.matrix.get_mob_matrix()[i, i] for i in range(2) ] off_diag_entries = [ self.matrix.get_mob_matrix()[i, 1-i] for i in range(2) ] for entry in diag_entries: minus_lambda = OldTex("-\\lambda") minus_lambda.set_color(MAROON_B) minus_lambda.move_to(entry) self.play(Transform(entry, minus_lambda)) self.wait() det_text = get_det_text(self.matrix) equals = OldTex("=").next_to(det_text) self.play(*list(map(Write, [det_text, equals]))) self.wait() minus = OldTex("-") for entries, sym in (diag_entries, equals), (off_diag_entries, minus): lp1, rp1, lp2, rp2 = parens = OldTex("()()") for entry in entries: entry.target = entry.copy() group = VGroup( lp1, entries[0].target, rp1, lp2, entries[1].target, rp2, ) group.arrange() group.next_to(sym) parens.add_background_rectangle() self.play( Write(parens), *[MoveToTarget(entry.copy()) for entry in entries], run_time = 2 ) self.wait() if entries == diag_entries: minus.next_to(parens) self.play(Write(minus)) polynomial = OldTex( "=", "\\lambda^2", "+1=0" ) polynomial.set_color_by_tex("\\lambda^2", MAROON_B) polynomial.add_background_rectangle() polynomial.next_to(equals, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT) self.play(Write(polynomial)) self.wait() result = OldTex( "\\lambda", "= i", "\\text{ or }", "\\lambda", "= -i" ) result.set_color_by_tex("\\lambda", MAROON_B) result.add_background_rectangle() result.next_to(polynomial, DOWN, buff = MED_LARGE_BUFF, aligned_edge = LEFT) self.play(Write(result)) self.wait() interesting_tidbit = OldTexText(""" Interestingly, though, the fact that multiplication by i in the complex plane looks like a 90 degree rotation is related to the fact that i is an eigenvalue of this transformation of 2d real vectors. The specifics of this are a little beyond what I want to talk about today, but note that that eigenvalues which are complex numbers generally correspond to some kind of rotation in the transformation. """, alignment = "") interesting_tidbit.add_background_rectangle() interesting_tidbit.set_height(FRAME_Y_RADIUS-0.5) interesting_tidbit.to_corner(DOWN+RIGHT) self.play(FadeIn(interesting_tidbit)) self.wait() class ShearExample(RevisitExampleTransformation): CONFIG = { "t_matrix" : [[1, 0], [1, 1]], "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, "secondary_line_ratio" : 1 }, } def construct(self): self.plane.fade() self.introduce_matrix() self.point_out_eigenvectors() lamb = OldTex("\\lambda") lamb.set_color(MAROON_B) lamb.next_to(self.matrix, DOWN) self.play(FadeIn(lamb)) self.play(*self.get_lambda_to_diag_movements(lamb)) self.add_foreground_mobject(*self.get_mobjects_from_last_animation()) self.wait() self.show_determinant() def point_out_eigenvectors(self): vectors = VGroup(*[ self.add_vector(u*x*RIGHT, animate = False) for x in range(int(FRAME_X_RADIUS)+1, 0, -1) for u in [-1, 1] ]) vectors.set_color_by_gradient(YELLOW, X_COLOR) words = VGroup( OldTexText("Eigenvectors"), OldTexText("with eigenvalue", "1") ) for word in words: word.set_color_by_tex("1", MAROON_B) word.add_to_back(BackgroundRectangle(word)) words.arrange(DOWN, buff = MED_SMALL_BUFF) words.next_to(ORIGIN, DOWN+RIGHT, buff = MED_SMALL_BUFF) self.play(ShowCreation(vectors), run_time = 2) self.play(Write(words)) self.wait() def show_determinant(self): det_text = get_det_text(self.matrix) equals = OldTex("=").next_to(det_text) three_minus_lamb, two_minus_lamb = diag_entries = [ entry.copy() for entry in self.diag_entries ] one = self.matrix.get_mob_matrix()[0, 1].copy() zero = self.matrix.get_mob_matrix()[1, 0].copy() for entry in diag_entries + [one, zero]: entry.target = entry.copy() lp1, rp1, lp2, rp2 = parens = OldTex("()()") minus = OldTex("-") cdot = OldTex("\\cdot") VGroup( lp1, three_minus_lamb.target, rp1, lp2, two_minus_lamb.target, rp2, minus, one.target, cdot, zero.target ).arrange().next_to(equals) parens.add_background_rectangle() new_rect = BackgroundRectangle(VGroup(minus, zero.target)) brace = Brace(new_rect, buff = 0) brace_text = brace.get_text("Equals 0, so ", "ignore") brace_text.add_background_rectangle() brace.target = Brace(parens) brace_text.target = brace.target.get_text( "Quadratic polynomial in ", "$\\lambda$" ) brace_text.target.set_color_by_tex("$\\lambda$", MAROON_B) brace_text.target.add_background_rectangle() equals_0 = OldTex("=0") equals_0.next_to(parens, RIGHT) equals_0.add_background_rectangle() final_brace = Brace(VGroup(parens, equals_0)) final_text = OldTex("\\lambda", "=1") final_text.set_color_by_tex("\\lambda", MAROON_B) final_text.next_to(final_brace, DOWN) lambda_equals_two = VGroup(*final_text[:2]).copy() lambda_equals_two.add_to_back(BackgroundRectangle(lambda_equals_two)) final_text.add_background_rectangle() self.play( Write(det_text), Write(equals) ) self.wait() self.play( Write(parens), MoveToTarget(three_minus_lamb), MoveToTarget(two_minus_lamb), run_time = 2 ) self.wait() self.play( FadeIn(new_rect), MoveToTarget(one), MoveToTarget(zero), Write(minus), Write(cdot), run_time = 2 ) self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() self.play(* list(map(FadeOut, [ one, zero, minus, cdot, new_rect, brace, brace_text ]))) self.wait() self.play(Write(equals_0)) self.wait() self.play( FadeIn(final_brace), FadeIn(final_text) ) self.wait() # faders = [ # det_text, equals, parens, # three_minus_lamb, two_minus_lamb, # brace, brace_text, equals_0, # ] # if to_fade is not None: # faders.append(to_fade) # self.play(*it.chain( # map(FadeOut, faders), # [ # lambda_equals_two.scale, 1.3, # lambda_equals_two.next_to, self.matrix, DOWN # ] # )) # self.add_foreground_mobject(lambda_equals_two) # self.lambda_equals_two = lambda_equals_two # self.wait() class EigenvalueCanHaveMultipleEigenVectors(TeacherStudentsScene): def construct(self): self.teacher_says(""" A single eigenvalue can have more that a line full of eigenvectors """) self.play_student_changes(*["pondering"]*3) self.random_blink(2) class ScalingExample(LinearTransformationScene): CONFIG = { "t_matrix" : [[2, 0], [0, 2]] } def construct(self): matrix = Matrix(self.t_matrix.T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.add_to_back(BackgroundRectangle(matrix)) matrix.next_to(ORIGIN, LEFT) matrix.to_edge(UP) words = OldTexText("Scale everything by 2") words.add_background_rectangle() words.next_to(matrix, RIGHT) self.add_foreground_mobject(matrix, words) for coords in [2, 1], [-2.5, -1], [1, -1]: self.add_vector(coords, color = random_color()) self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() class IntroduceEigenbasis(TeacherStudentsScene): def construct(self): words1, words2 = list(map(TexText, [ "Finish with ``eigenbasis.''", """Make sure you've watched the last video""" ])) words1.set_color(YELLOW) self.teacher_says(words1) self.play_student_changes( "pondering", "raise_right_hand", "erm" ) self.random_blink() new_words = VGroup(words1.copy(), words2) new_words.arrange(DOWN, buff = MED_SMALL_BUFF) new_words.scale(0.8) self.teacher.bubble.add_content(new_words) self.play( self.get_teacher().change_mode, "sassy", Write(words2), Transform(words1, new_words[0]) ) student = self.get_students()[0] self.play( student.change_mode, "guilty", student.look, LEFT ) self.random_blink(2) class BasisVectorsAreEigenvectors(LinearTransformationScene): CONFIG = { "t_matrix" : [[-1, 0], [0, 2]] } def construct(self): matrix = Matrix(self.t_matrix.T) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(ORIGIN, LEFT) matrix.to_edge(UP) words = OldTexText( "What if both basis vectors \\\\", "are eigenvectors?" ) for word in words: word.add_to_back(BackgroundRectangle(word)) words.to_corner(UP+RIGHT) self.play(Write(words)) self.add_foreground_mobject(words) self.wait() self.apply_transposed_matrix([self.t_matrix[0], [0, 1]]) self.wait() self.apply_transposed_matrix([[1, 0], self.t_matrix[1]]) self.wait() i_coords = Matrix(self.t_matrix[0]) i_coords.next_to(self.i_hat.get_end(), DOWN+LEFT) i_coords.set_color(X_COLOR) j_coords = Matrix(self.t_matrix[1]) j_coords.next_to(self.j_hat.get_end(), RIGHT) j_coords.set_color(Y_COLOR) for array in matrix, i_coords, j_coords: array.rect = BackgroundRectangle(array) array.add_to_back(array.rect) self.play(*list(map(Write, [i_coords, j_coords]))) self.wait() self.play( Transform(i_coords.rect, matrix.rect), Transform(i_coords.get_brackets(), matrix.get_brackets()), i_coords.get_entries().move_to, VGroup( *matrix.get_mob_matrix()[:,0] ) ) self.play( FadeOut(j_coords.rect), FadeOut(j_coords.get_brackets()), j_coords.get_entries().move_to, VGroup( *matrix.get_mob_matrix()[:,1] ) ) self.remove(i_coords, j_coords) self.add(matrix) self.wait() diag_entries = VGroup(*[ matrix.get_mob_matrix()[i, i] for i in range(2) ]) off_diag_entries = VGroup(*[ matrix.get_mob_matrix()[1-i, i] for i in range(2) ]) for entries in diag_entries, off_diag_entries: self.play( entries.scale, 1.3, entries.set_color, YELLOW, run_time = 2, rate_func = there_and_back ) self.wait() class DefineDiagonalMatrix(Scene): def construct(self): n_dims = 4 numerical_matrix = np.identity(n_dims, dtype = 'int') for x in range(n_dims): numerical_matrix[x, x] = random.randint(-9, 9) matrix = Matrix(numerical_matrix) diag_entries = VGroup(*[ matrix.get_mob_matrix()[i,i] for i in range(n_dims) ]) off_diag_entries = VGroup(*[ matrix.get_mob_matrix()[i, j] for i in range(n_dims) for j in range(n_dims) if i != j ]) title = OldTexText("``Diagonal matrix''") title.to_edge(UP) self.add(matrix) self.wait() for entries in off_diag_entries, diag_entries: self.play( entries.scale, 1.1, entries.set_color, YELLOW, rate_func = there_and_back, ) self.wait() self.play(Write(title)) self.wait() self.play( matrix.set_column_colors, X_COLOR, Y_COLOR, Z_COLOR, YELLOW ) self.wait() self.play(diag_entries.set_color, MAROON_B) self.play( diag_entries.scale, 1.1, rate_func = there_and_back, ) self.wait() class RepeatedMultiplicationInAction(Scene): def construct(self): vector = Matrix(["x", "y"]) vector.set_color(YELLOW) vector.scale(1.2) vector.shift(RIGHT) matrix, scalars = self.get_matrix(vector) #First multiplication for v_entry, scalar in zip(vector.get_entries(), scalars): scalar.target = scalar.copy() scalar.target.next_to(v_entry, LEFT) l_bracket = vector.get_brackets()[0] l_bracket.target = l_bracket.copy() l_bracket.target.next_to(VGroup(*[ scalar.target for scalar in scalars ]), LEFT) self.add(vector) self.play(*list(map(FadeIn, [matrix]+scalars))) self.wait() self.play( FadeOut(matrix), *list(map(MoveToTarget, scalars + [l_bracket])) ) self.wait() #nth multiplications for scalar in scalars: scalar.exp = VectorizedPoint(scalar.get_corner(UP+RIGHT)) scalar.exp.shift(SMALL_BUFF*RIGHT/2.) for new_exp in range(2, 6): matrix, new_scalars = self.get_matrix(vector) new_exp_mob = OldTex(str(new_exp)).scale(0.7) movers = [] to_remove = [] for v_entry, scalar, new_scalar in zip(vector.get_entries(), scalars, new_scalars): scalar.exp.target = new_exp_mob.copy() scalar.exp.target.set_color(scalar.get_color()) scalar.exp.target.move_to(scalar.exp, aligned_edge = LEFT) new_scalar.target = scalar.exp.target scalar.target = scalar.copy() VGroup(scalar.target, scalar.exp.target).next_to( v_entry, LEFT, aligned_edge = DOWN ) movers += [scalar, scalar.exp, new_scalar] to_remove.append(new_scalar) l_bracket.target.next_to(VGroup(*[ scalar.target for scalar in scalars ]), LEFT) movers.append(l_bracket) self.play(*list(map(FadeIn, [matrix]+new_scalars))) self.wait() self.play( FadeOut(matrix), *list(map(MoveToTarget, movers)) ) self.remove(*to_remove) self.wait() def get_matrix(self, vector): matrix = Matrix([[3, 0], [0, 2]]) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(vector, LEFT) scalars = [matrix.get_mob_matrix()[i, i] for i in range(2)] matrix.remove(*scalars) return matrix, scalars class RepeatedMultilpicationOfMatrices(Scene): CONFIG = { "matrix" : [[3, 0], [0, 2]], "diagonal" : True, } def construct(self): vector = Matrix(["x", "y"]) vector.set_color(YELLOW) matrix = Matrix(self.matrix) matrix.set_column_colors(X_COLOR, Y_COLOR) matrices = VGroup(*[ matrix.copy(), OldTex("\\dots\\dots"), matrix.copy(), matrix.copy(), matrix.copy(), ]) last_matrix = matrices[-1] group = VGroup(*list(matrices) + [vector]) group.arrange() brace = Brace(matrices) brace_text = brace.get_text("100", "times") hundred = brace_text[0] hundred_copy = hundred.copy() self.add(vector) for matrix in reversed(list(matrices)): self.play(FadeIn(matrix)) self.wait() self.play( GrowFromCenter(brace), Write(brace_text) ) self.wait() if self.diagonal: last_matrix.target = last_matrix.copy() for i, hund in enumerate([hundred, hundred_copy]): entry = last_matrix.target.get_mob_matrix()[i, i] hund.target = hund.copy() hund.target.scale(0.5) hund.target.next_to(entry, UP+RIGHT, buff = 0) hund.target.set_color(entry.get_color()) VGroup(hund.target, entry).move_to(entry, aligned_edge = DOWN) lb, rb = last_matrix.target.get_brackets() lb.shift(SMALL_BUFF*LEFT) rb.shift(SMALL_BUFF*RIGHT) VGroup( last_matrix.target, hundred.target, hundred_copy.target ).next_to(vector, LEFT) self.play(*it.chain( list(map(FadeOut, [brace, brace_text[1]] + list(matrices[:-1]))), list(map(MoveToTarget, [hundred, hundred_copy, last_matrix])) ), run_time = 2) self.wait() else: randy = Randolph().to_corner() self.play(FadeIn(randy)) self.play(randy.change_mode, "angry") self.play(Blink(randy)) self.wait() self.play(Blink(randy)) self.wait() class RepeatedMultilpicationOfNonDiagonalMatrices(RepeatedMultilpicationOfMatrices): CONFIG = { "matrix" : [[3, 4], [1, 1]], "diagonal" : False, } class WhatAreTheOddsOfThat(TeacherStudentsScene): def construct(self): self.student_says(""" Sure, but what are the odds of that happening? """) self.random_blink() self.play_student_changes("pondering") self.random_blink(3) class LastVideo(Scene): def construct(self): title = OldTexText("Last chapter: Change of basis") title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN, buff = MED_SMALL_BUFF) self.add(title) self.play(ShowCreation(rect)) self.wait() class ChangeToEigenBasis(ExampleTranformationScene): CONFIG = { "show_basis_vectors" : False, "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, "secondary_line_ratio" : 0 }, } def construct(self): self.plane.fade() self.introduce_eigenvectors() self.write_change_of_basis_matrix() self.ask_about_power() def introduce_eigenvectors(self): x_vectors, v_vectors = [ VGroup(*[ self.add_vector(u*x*vect, animate = False) for x in range(num, 0, -1) for u in [-1, 1] ]) for vect, num in [(RIGHT, 7), (UP+LEFT, 4)] ] x_vectors.set_color_by_gradient(YELLOW, X_COLOR) v_vectors.set_color_by_gradient(MAROON_B, YELLOW) self.remove(x_vectors, v_vectors) self.play(ShowCreation(x_vectors, run_time = 2)) self.play(ShowCreation(v_vectors, run_time = 2)) self.wait() self.plane.save_state() self.apply_transposed_matrix( self.t_matrix, rate_func = there_and_back, path_arc = 0 ) x_vector = x_vectors[-1] v_vector = v_vectors[-1] x_vectors.remove(x_vector) v_vectors.remove(v_vector) words = OldTexText("Eigenvectors span space") new_words = OldTexText("Use eigenvectors as basis") for text in words, new_words: text.add_background_rectangle() text.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF) # text.to_edge(RIGHT) self.play(Write(words)) self.play( FadeOut(x_vectors), FadeOut(v_vectors), Animation(x_vector), Animation(v_vector), ) self.wait() self.play(Transform(words, new_words)) self.wait() self.b1, self.b2 = x_vector, v_vector self.moving_vectors = [self.b1, self.b2] self.to_fade = [words] def write_change_of_basis_matrix(self): b1, b2 = self.b1, self.b2 for vect in b1, b2: vect.coords = vector_coordinate_label(vect) vect.coords.set_color(vect.get_color()) vect.entries = vect.coords.get_entries() vect.entries.target = vect.entries.copy() b1.coords.next_to(b1.get_end(), DOWN+RIGHT) b2.coords.next_to(b2.get_end(), LEFT) for vect in b1, b2: self.play(Write(vect.coords)) self.wait() cob_matrix = Matrix(np.array([ list(vect.entries.target) for vect in (b1, b2) ]).T) cob_matrix.rect = BackgroundRectangle(cob_matrix) cob_matrix.add_to_back(cob_matrix.rect) cob_matrix.set_height(self.matrix.get_height()) cob_matrix.next_to(self.matrix) brace = Brace(cob_matrix) brace_text = brace.get_text("Change of basis matrix") brace_text.next_to(brace, DOWN, aligned_edge = LEFT) brace_text.add_background_rectangle() copies = [vect.coords.copy() for vect in (b1, b2)] self.to_fade += copies self.add(*copies) self.play( Transform(b1.coords.rect, cob_matrix.rect), Transform(b1.coords.get_brackets(), cob_matrix.get_brackets()), MoveToTarget(b1.entries) ) to_remove = self.get_mobjects_from_last_animation() self.play(MoveToTarget(b2.entries)) to_remove += self.get_mobjects_from_last_animation() self.remove(*to_remove) self.add(cob_matrix) self.to_fade += [b2.coords] self.play( GrowFromCenter(brace), Write(brace_text) ) self.to_fade += [brace, brace_text] self.wait() inv_cob = cob_matrix.copy() inv_cob.target = inv_cob.copy() neg_1 = OldTex("-1") neg_1.add_background_rectangle() inv_cob.target.next_to( self.matrix, LEFT, buff = neg_1.get_width()+2*SMALL_BUFF ) neg_1.next_to( inv_cob.target.get_corner(UP+RIGHT), RIGHT, ) self.play( MoveToTarget(inv_cob, path_arc = -np.pi/2), Write(neg_1) ) self.wait() self.add_foreground_mobject(cob_matrix, inv_cob, neg_1) self.play(*list(map(FadeOut, self.to_fade))) self.wait() self.play(FadeOut(self.plane)) cob_transform = self.get_matrix_transformation([[1, 0], [-1, 1]]) ApplyMethod(self.plane.apply_function, cob_transform).update(1) self.planes.set_color(BLUE_D) self.plane.axes.set_color(WHITE) self.play( FadeIn(self.plane), *list(map(Animation, self.foreground_mobjects+self.moving_vectors)) ) self.add(self.plane.copy().set_color(GREY).set_stroke(width = 2)) self.apply_transposed_matrix(self.t_matrix) equals = OldTex("=").next_to(cob_matrix) final_matrix = Matrix([[3, 0], [0, 2]]) final_matrix.add_to_back(BackgroundRectangle(final_matrix)) for i in range(2): final_matrix.get_mob_matrix()[i, i].set_color(MAROON_B) final_matrix.next_to(equals, RIGHT) self.play( Write(equals), Write(final_matrix) ) self.wait() eigenbasis = OldTexText("``Eigenbasis''") eigenbasis.add_background_rectangle() eigenbasis.next_to(ORIGIN, DOWN) self.play(Write(eigenbasis)) self.wait() def ask_about_power(self): morty = Mortimer() morty.to_edge(DOWN).shift(LEFT) bubble = morty.get_bubble( "speech", height = 3, width = 5, direction = RIGHT ) bubble.set_fill(BLACK, opacity = 1) matrix_copy = self.matrix.copy().scale(0.7) hundred = OldTex("100").scale(0.7) hundred.next_to(matrix_copy.get_corner(UP+RIGHT), RIGHT) compute = OldTexText("Compute") compute.next_to(matrix_copy, LEFT, buff = MED_SMALL_BUFF) words = VGroup(compute, matrix_copy, hundred) bubble.add_content(words) self.play(FadeIn(morty)) self.play( morty.change_mode, "speaking", ShowCreation(bubble), Write(words) ) for x in range(2): self.play(Blink(morty)) self.wait(2) class CannotDoWithWithAllTransformations(TeacherStudentsScene): def construct(self): self.teacher_says(""" Not all matrices can become diagonal """) self.play_student_changes(*["tired"]*3) self.random_blink(2)
videos_3b1b/_2016/eola/chapter7.py
from manim_imports_ext import * from _2016.eola.footnote2 import TwoDTo1DTransformWithDots V_COLOR = YELLOW W_COLOR = MAROON_B SUM_COLOR = PINK def get_projection(vector_to_project, stable_vector): v1, v2 = stable_vector, vector_to_project return v1*np.dot(v1, v2)/(get_norm(v1)**2) def get_vect_mob_projection(vector_to_project, stable_vector): return Vector( get_projection( vector_to_project.get_end(), stable_vector.get_end() ), color = vector_to_project.get_color() ).fade() class OpeningQuote(Scene): def construct(self): words = OldTexText( "\\small Calvin:", "You know, I don't think math is a science, I think it's a religion.", "\\\\Hobbes:", "A religion?", "\\\\Calvin:" , "Yeah. All these equations are like miracles." "You take two numbers and when you add them, " "they magically become one NEW number! " "No one can say how it happens. " "You either believe it or you don't.", ) words.set_width(FRAME_WIDTH - 1) words.to_edge(UP) words[0].set_color(YELLOW) words[2].set_color("#fd9c2b") words[4].set_color(YELLOW) for i in range(3): speaker, quote = words[2*i:2*i+2] self.play(FadeIn(speaker, run_time = 0.5)) rt = max(1, len(quote.split())/18) self.play(Write( quote, run_time = rt, )) self.wait(2) class TraditionalOrdering(RandolphScene): def construct(self): title = OldTexText("Traditional ordering:") title.set_color(YELLOW) title.scale(1.2) title.to_corner(UP+LEFT) topics = VMobject(*list(map(TexText, [ "Topic 1: Vectors", "Topic 2: Dot products", "\\vdots", "(everything else)", "\\vdots", ]))) topics.arrange(DOWN, aligned_edge = LEFT, buff = SMALL_BUFF) # topics.next_to(title, DOWN+RIGHT) self.play( Write(title, run_time = 1), FadeIn( topics, run_time = 3, lag_ratio = 0.5 ), ) self.play(topics[1].set_color, PINK) self.wait() class ThisSeriesOrdering(RandolphScene): def construct(self): title = OldTexText("Essence of linear algebra") self.randy.rotate(np.pi, UP) title.scale(1.2).set_color(BLUE) title.to_corner(UP+LEFT) line = Line(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT, color = WHITE) line.next_to(title, DOWN, buff = SMALL_BUFF) line.to_edge(LEFT, buff = 0) chapters = VMobject(*[ OldTexText("\\small " + text) for text in [ "Chapter 1: Vectors, what even are they?", "Chapter 2: Linear combinations, span and bases", "Chapter 3: Matrices as linear transformations", "Chapter 4: Matrix multiplication as composition", "Chapter 5: The determinant", "Chapter 6: Inverse matrices, column space and null space", "Chapter 7: Dot products and duality", "Chapter 8: Cross products via transformations", "Chapter 9: Change of basis", "Chapter 10: Eigenvectors and eigenvalues", "Chapter 11: Abstract vector spaces", ] ]) chapters.arrange( DOWN, buff = SMALL_BUFF, aligned_edge = LEFT ) chapters.set_height(1.5*FRAME_Y_RADIUS) chapters.next_to(line, DOWN, buff = SMALL_BUFF) chapters.to_edge(RIGHT) self.add(title) self.play( ShowCreation(line), ) self.play( FadeIn( chapters, lag_ratio = 0.5, run_time = 3 ), self.randy.change_mode, "sassy" ) self.play(self.randy.look, UP+LEFT) self.play(chapters[6].set_color, PINK) self.wait(6) class OneMustViewThroughTransformations(TeacherStudentsScene): def construct(self): words = OldTexText( "Only with" , "transformations", "\n can we truly understand", ) words.set_color_by_tex("transformations", BLUE) self.teacher_says(words) self.play_student_changes( "pondering", "plain", "raise_right_hand" ) self.random_blink(2) words = OldTexText( "First, the ", "standard view...", arg_separator = "\n" ) self.teacher_says(words) self.random_blink(2) class ShowNumericalDotProduct(Scene): CONFIG = { "v1" : [2, 7, 1], "v2" : [8, 2, 8], "write_dot_product_words" : True, } def construct(self): v1 = Matrix(self.v1) v2 = Matrix(self.v2) inter_array_dot = OldTex("\\cdot").scale(1.5) dot_product = VGroup(v1, inter_array_dot, v2) dot_product.arrange(RIGHT, buff = MED_SMALL_BUFF/2) dot_product.to_edge(LEFT) pairs = list(zip(v1.get_entries(), v2.get_entries())) for pair, color in zip(pairs, [X_COLOR, Y_COLOR, Z_COLOR, PINK]): VGroup(*pair).set_color(color) dot = OldTex("\\cdot") products = VGroup(*[ VGroup( p1.copy(), dot.copy(), p2.copy() ).arrange(RIGHT, buff = SMALL_BUFF) for p1, p2 in pairs ]) products.arrange(DOWN, buff = LARGE_BUFF) products.next_to(dot_product, RIGHT, buff = LARGE_BUFF) products.target = products.copy() plusses = ["+"]*(len(self.v1)-1) symbols = VGroup(*list(map(Tex, ["="] + plusses))) final_sum = VGroup(*it.chain(*list(zip( symbols, products.target )))) final_sum.arrange(RIGHT, buff = SMALL_BUFF) final_sum.next_to(dot_product, RIGHT) title = OldTexText("Two vectors of the same dimension") title.to_edge(UP) arrow = Arrow(DOWN, UP).next_to(inter_array_dot, DOWN) dot_product_words = OldTexText("Dot product") dot_product_words.set_color(YELLOW) dot_product_words.next_to(arrow, DOWN) dot_product_words.shift_onto_screen() self.play( Write(v1), Write(v2), FadeIn(inter_array_dot), FadeIn(title) ) self.wait() if self.write_dot_product_words: self.play( inter_array_dot.set_color, YELLOW, ShowCreation(arrow), Write(dot_product_words, run_time = 2) ) self.wait() self.play(Transform( VGroup(*it.starmap(Group, pairs)).copy(), products, path_arc = -np.pi/2, run_time = 2 )) self.remove(*self.get_mobjects_from_last_animation()) self.add(products) self.wait() self.play( Write(symbols), Transform(products, products.target, path_arc = np.pi/2) ) self.wait() class TwoDDotProductExample(ShowNumericalDotProduct): CONFIG = { "v1" : [1, 2], "v2" : [3, 4], } class FourDDotProductExample(ShowNumericalDotProduct): CONFIG = { "v1" : [6, 2, 8, 3], "v2" : [1, 8, 5, 3], "write_dot_product_words" : False, } class GeometricInterpretation(VectorScene): CONFIG = { "v_coords" : [4, 1], "w_coords" : [2, -1], "v_color" : V_COLOR, "w_color" : W_COLOR, "project_onto_v" : True, } def construct(self): self.lock_in_faded_grid() self.add_symbols() self.add_vectors() self.line() self.project() self.show_lengths() self.handle_possible_negative() def add_symbols(self): v = matrix_to_mobject(self.v_coords).set_color(self.v_color) w = matrix_to_mobject(self.w_coords).set_color(self.w_color) v.add_background_rectangle() w.add_background_rectangle() dot = OldTex("\\cdot") eq = VMobject(v, dot, w) eq.arrange(RIGHT, buff = SMALL_BUFF) eq.to_corner(UP+LEFT) self.play(Write(eq), run_time = 1) for array, char in zip([v, w], ["v", "w"]): brace = Brace(array, DOWN) label = brace.get_text("$\\vec{\\textbf{%s}}$"%char) label.set_color(array.get_color()) self.play( GrowFromCenter(brace), Write(label), run_time = 1 ) self.dot_product = eq def add_vectors(self): self.v = Vector(self.v_coords, color = self.v_color) self.w = Vector(self.w_coords, color = self.w_color) self.play(ShowCreation(self.v)) self.play(ShowCreation(self.w)) for vect, char, direction in zip( [self.v, self.w], ["v", "w"], [DOWN+RIGHT, DOWN] ): label = OldTex("\\vec{\\textbf{%s}}"%char) label.next_to(vect.get_end(), direction) label.set_color(vect.get_color()) self.play(Write(label, run_time = 1)) self.stable_vect = self.v if self.project_onto_v else self.w self.proj_vect = self.w if self.project_onto_v else self.v def line(self): line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) line.rotate(self.stable_vect.get_angle()) self.play(ShowCreation(line), Animation(self.stable_vect)) self.wait() def project(self): dot_product = np.dot(self.v.get_end(), self.w.get_end()) v_norm, w_norm = [ get_norm(vect.get_end()) for vect in (self.v, self.w) ] projected = Vector( self.stable_vect.get_end()*dot_product/( self.stable_vect.get_length()**2 ), color = self.proj_vect.get_color() ) projection_line = Line( self.proj_vect.get_end(), projected.get_end(), color = GREY ) self.play(ShowCreation(projection_line)) self.add(self.proj_vect.copy().fade()) self.play(Transform(self.proj_vect, projected)) self.wait() def show_lengths(self): stable_char = "v" if self.project_onto_v else "w" proj_char = "w" if self.project_onto_v else "v" product = OldTexText( "=", "(", "Length of projected $\\vec{\\textbf{%s}}$"%proj_char, ")", "(", "Length of $\\vec{\\textbf{%s}}$"%stable_char, ")", arg_separator = "" ) product.scale(0.9) product.next_to(self.dot_product, RIGHT) proj_words = product[2] proj_words.set_color(self.proj_vect.get_color()) stable_words = product[5] stable_words.set_color(self.stable_vect.get_color()) product.remove(proj_words, stable_words) for words in stable_words, proj_words: words.add_to_back(BackgroundRectangle(words)) words.start = words.copy() proj_brace, stable_brace = braces = [ Brace(Line(ORIGIN, vect.get_length()*RIGHT*sgn), UP) for vect in (self.proj_vect, self.stable_vect) for sgn in [np.sign(np.dot(vect.get_end(), self.stable_vect.get_end()))] ] proj_brace.put_at_tip(proj_words.start) proj_brace.words = proj_words.start stable_brace.put_at_tip(stable_words.start) stable_brace.words = stable_words.start for brace in braces: brace.rotate(self.stable_vect.get_angle()) brace.words.rotate(self.stable_vect.get_angle()) self.play( GrowFromCenter(proj_brace), Write(proj_words.start, run_time = 2) ) self.wait() self.play( Transform(proj_words.start, proj_words), FadeOut(proj_brace) ) self.play( GrowFromCenter(stable_brace), Write(stable_words.start, run_time = 2), Animation(self.stable_vect) ) self.wait() self.play( Transform(stable_words.start, stable_words), Write(product) ) self.wait() product.add(stable_words.start, proj_words.start) self.product = product def handle_possible_negative(self): if np.dot(self.w.get_end(), self.v.get_end()) > 0: return neg = OldTex("-").set_color(RED) neg.next_to(self.product[0], RIGHT) words = OldTexText("Should be negative") words.set_color(RED) words.next_to( VMobject(*self.product[2:]), DOWN, buff = LARGE_BUFF, aligned_edge = LEFT ) words.add_background_rectangle() arrow = Arrow(words.get_left(), neg, color = RED) self.play( Write(neg), ShowCreation(arrow), VMobject(*self.product[1:]).next_to, neg, Write(words) ) self.wait() class GeometricInterpretationNegative(GeometricInterpretation): CONFIG = { "v_coords" : [3, 1], "w_coords" : [-1, -2], "v_color" : YELLOW, "w_color" : MAROON_B, } class ShowQualitativeDotProductValues(VectorScene): def construct(self): self.lock_in_faded_grid() v_sym, dot, w_sym, comp, zero = ineq = OldTex( "\\vec{\\textbf{v}}", "\\cdot", "\\vec{\\textbf{w}}", ">", "0", ) ineq.to_edge(UP) ineq.add_background_rectangle() comp.set_color(GREEN) equals = OldTex("=").set_color(PINK).move_to(comp) less_than = OldTex("<").set_color(RED).move_to(comp) v_sym.set_color(V_COLOR) w_sym.set_color(W_COLOR) words = list(map(TexText, [ "Similar directions", "Perpendicular", "Opposing directions" ])) for word, sym in zip(words, [comp, equals, less_than]): word.add_background_rectangle() word.next_to(sym, DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) word.set_color(sym.get_color()) v = Vector([1.5, 1.5], color = V_COLOR) w = Vector([2, 2], color = W_COLOR) w.rotate(-np.pi/6) shadow = Vector( v.get_end()*np.dot(v.get_end(), w.get_end())/(v.get_length()**2), color = MAROON_E, preserve_tip_size_when_scaling = False ) shadow_opposite = shadow.copy().scale(-1) line = Line(LEFT, RIGHT, color = WHITE) line.scale(FRAME_X_RADIUS) line.rotate(v.get_angle()) proj_line = Line(w.get_end(), shadow.get_end(), color = GREY) word = words[0] self.add(ineq) for mob in v, w, line, proj_line: self.play( ShowCreation(mob), Animation(v) ) self.play(Transform(w.copy(), shadow)) self.remove(*self.get_mobjects_from_last_animation()) self.add(shadow) self.play(FadeOut(proj_line)) self.play(Write(word, run_time = 1)) self.wait() self.play( Rotate(w, -np.pi/3), shadow.scale, 0 ) self.play( Transform(comp, equals), Transform(word, words[1]) ) self.wait() self.play( Rotate(w, -np.pi/3), Transform(shadow, shadow_opposite) ) self.play( Transform(comp, less_than), Transform(word, words[2]) ) self.wait() class AskAboutSymmetry(TeacherStudentsScene): def construct(self): v, w = "\\vec{\\textbf{v}}", "\\vec{\\textbf{w}}", question = OldTex( "\\text{Why does }", v, "\\cdot", w, "=", w, "\\cdot", v, "\\text{?}" ) VMobject(question[1], question[7]).set_color(V_COLOR) VMobject(question[3], question[5]).set_color(W_COLOR) self.student_says( question, target_mode = "raise_left_hand" ) self.play_student_changes("confused") self.play(self.get_teacher().change_mode, "pondering") self.play(self.get_teacher().look, RIGHT) self.play(self.get_teacher().look, LEFT) self.random_blink() class GeometricInterpretationSwapVectors(GeometricInterpretation): CONFIG = { "project_onto_v" : False, } class SymmetricVAndW(VectorScene): def construct(self): self.lock_in_faded_grid() v = Vector([3, 1], color = V_COLOR) w = Vector([1, 3], color = W_COLOR) for vect, char in zip([v, w], ["v", "w"]): vect.label = OldTex("\\vec{\\textbf{%s}}"%char) vect.label.set_color(vect.get_color()) vect.label.next_to(vect.get_end(), DOWN+RIGHT) for v1, v2 in (v, w), (w, v): v1.proj = get_vect_mob_projection(v1, v2) v1.proj_line = Line( v1.get_end(), v1.proj.get_end(), color = GREY ) line_of_symmetry = DashedLine(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) line_of_symmetry.rotate(np.mean([v.get_angle(), w.get_angle()])) line_of_symmetry_words = OldTexText("Line of symmetry") line_of_symmetry_words.add_background_rectangle() line_of_symmetry_words.next_to(ORIGIN, UP+LEFT) line_of_symmetry_words.rotate(line_of_symmetry.get_angle()) for vect in v, w: self.play(ShowCreation(vect)) self.play(Write(vect.label, run_time = 1)) self.wait() angle = (v.get_angle()-w.get_angle())/2 self.play( Rotate(w, angle), Rotate(v, -angle), rate_func = there_and_back, run_time = 2 ) self.wait() self.play( ShowCreation(line_of_symmetry), Write(line_of_symmetry_words, run_time = 1) ) self.wait(0.5) self.remove(line_of_symmetry_words) self.play(*list(map(Uncreate, line_of_symmetry_words))) for vect in w, v: self.play(ShowCreation(vect.proj_line)) vect_copy = vect.copy() self.play(Transform(vect_copy, vect.proj)) self.remove(vect_copy) self.add(vect.proj) self.wait() self.play(*list(map(FadeOut,[ v.proj, v.proj_line, w.proj, w.proj_line ]))) self.show_doubling(v, w) def show_doubling(self, v, w): scalar = 2 new_v = v.copy().scale(scalar) new_v.label = VMobject(OldTex("2"), v.label.copy()) new_v.label.arrange(aligned_edge = DOWN) new_v.label.next_to(new_v.get_end(), DOWN+RIGHT) new_v.proj = v.proj.copy().scale(scalar) new_v.proj.fade() new_v.proj_line = Line( new_v.get_end(), new_v.proj.get_end(), color = GREY ) v_tex, w_tex = ["\\vec{\\textbf{%s}}"%c for c in ("v", "w")] equation = OldTex( "(", "2", v_tex, ")", "\\cdot", w_tex, "=", "2(", v_tex, "\\cdot", w_tex, ")" ) equation.set_color_by_tex(v_tex, V_COLOR) equation.set_color_by_tex(w_tex, W_COLOR) equation.next_to(ORIGIN, DOWN).to_edge(RIGHT) words = OldTexText("Symmetry is broken") words.next_to(ORIGIN, LEFT) words.to_edge(UP) v.save_state() v.proj.save_state() v.proj_line.save_state() self.play(Transform(*[ VGroup(mob, mob.label) for mob in (v, new_v) ]), run_time = 2) last_mob = self.get_mobjects_from_last_animation()[0] self.remove(last_mob) self.add(*last_mob) Transform( VGroup(v.proj, v.proj_line), VGroup(new_v.proj, new_v.proj_line) ).update(1)##Hacky self.play(Write(words)) self.wait() two_v_parts = equation[1:3] equation.remove(*two_v_parts) for full_v, projector, stable in zip([False, True], [w, v], [v, w]): self.play( Transform(projector.copy(), projector.proj), ShowCreation(projector.proj_line) ) self.remove(self.get_mobjects_from_last_animation()[0]) self.add(projector.proj) self.wait() if equation not in self.get_mobjects(): self.play( Write(equation), Transform(new_v.label.copy(), VMobject(*two_v_parts)) ) self.wait() v_parts = [v] if full_v: v_parts += [v.proj, v.proj_line] self.play( *[v_part.restore for v_part in v_parts], rate_func = there_and_back, run_time = 2 ) self.wait() self.play(*list(map(FadeOut, [ projector.proj, projector.proj_line ]))) class LurkingQuestion(TeacherStudentsScene): def construct(self): # self.teacher_says("That's the standard intro") # self.wait() # self.student_says( # """ # Wait, why are the # two views connected? # """, # index = 2, # target_mode = "raise_left_hand", # width = 6, # ) self.play_student_changes( "raise_right_hand", "confused", "raise_left_hand" ) self.random_blink(5) answer = OldTexText(""" The most satisfactory answer comes from""", "duality" ) answer[-1].set_color_by_gradient(BLUE, YELLOW) self.teacher_says(answer) self.random_blink(2) self.teacher_thinks("") everything = VMobject(*self.get_mobjects()) self.play(ApplyPointwiseFunction( lambda p : 10*(p+2*DOWN)/get_norm(p+2*DOWN), everything )) class TwoDToOneDScene(LinearTransformationScene): CONFIG = { "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_X_RADIUS, "y_radius" : FRAME_Y_RADIUS, "secondary_line_ratio" : 1 }, "t_matrix" : [[2, 0], [1, 0]] } def setup(self): self.number_line = NumberLine() self.add(self.number_line) LinearTransformationScene.setup(self) class Introduce2Dto1DLinearTransformations(TwoDToOneDScene): def construct(self): number_line_words = OldTexText("Number line") number_line_words.next_to(self.number_line, UP, buff = MED_SMALL_BUFF) numbers = VMobject(*self.number_line.get_number_mobjects()) self.remove(self.number_line) self.apply_transposed_matrix(self.t_matrix) self.play( ShowCreation(number_line), *[Animation(v) for v in (self.i_hat, self.j_hat)] ) self.play(*list(map(Write, [numbers, number_line_words]))) self.wait() class Symbolic2To1DTransform(Scene): def construct(self): func = OldTex("L(", "\\vec{\\textbf{v}}", ")") input_array = Matrix([2, 7]) input_array.set_color(YELLOW) in_arrow = Arrow(LEFT, RIGHT, color = input_array.get_color()) func[1].set_color(input_array.get_color()) output_array = Matrix([1.8]) output_array.set_color(PINK) out_arrow = Arrow(LEFT, RIGHT, color = output_array.get_color()) VMobject( input_array, in_arrow, func, out_arrow, output_array ).arrange(RIGHT, buff = SMALL_BUFF) input_brace = Brace(input_array, DOWN) input_words = input_brace.get_text("2d input") output_brace = Brace(output_array, UP) output_words = output_brace.get_text("1d output") input_words.set_color(input_array.get_color()) output_words.set_color(output_array.get_color()) special_words = OldTexText("Linear", "functions are quite special") special_words.set_color_by_tex("Linear", BLUE) special_words.to_edge(UP) self.add(func, input_array) self.play( GrowFromCenter(input_brace), Write(input_words) ) mover = input_array.copy() self.play( Transform(mover, Dot().move_to(func)), ShowCreation(in_arrow), rate_func = rush_into, run_time = 0.5 ) self.play( Transform(mover, output_array), ShowCreation(out_arrow), rate_func = rush_from, run_time = 0.5 ) self.play( GrowFromCenter(output_brace), Write(output_words) ) self.wait() self.play(Write(special_words)) self.wait() class RecommendChapter3(Scene): def construct(self): title = OldTexText(""" Definitely watch Chapter 3 if you haven't already """) title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class OkayToIgnoreFormalProperties(Scene): def construct(self): title = OldTexText("Formal linearity properties") title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) v_tex, w_tex = ["\\vec{\\textbf{%s}}"%s for s in ("v", "w")] additivity = OldTex( "L(", v_tex, "+", w_tex, ") = ", "L(", v_tex, ") + L(", w_tex, ")", ) scaling = OldTex( "L(", "c", v_tex, ") =", "c", "L(", v_tex, ")", ) for tex_mob in additivity, scaling: tex_mob.set_color_by_tex(v_tex, V_COLOR) tex_mob.set_color_by_tex(w_tex, W_COLOR) tex_mob.set_color_by_tex("c", GREEN) additivity.next_to(h_line, DOWN, buff = MED_SMALL_BUFF) scaling.next_to(additivity, DOWN, buff = MED_SMALL_BUFF) words = OldTexText("We'll ignore these") words.set_color(RED) arrow = Arrow(DOWN, UP, color = RED) arrow.next_to(scaling, DOWN) words.next_to(arrow, DOWN) randy = Randolph().to_corner(DOWN+LEFT) morty = Mortimer().to_corner(DOWN+RIGHT) self.add(randy, morty, title) self.play(ShowCreation(h_line)) for tex_mob in additivity, scaling: self.play(Write(tex_mob, run_time = 2)) self.play( FadeIn(words), ShowCreation(arrow), ) self.play( randy.look, LEFT, morty.look, RIGHT, ) self.wait() class FormalVsVisual(Scene): def construct(self): title = OldTexText("Linearity") title.set_color(BLUE) title.to_edge(UP) line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) line.next_to(title, DOWN) v_line = Line(line.get_center(), FRAME_Y_RADIUS*DOWN) formal = OldTexText("Formal definition") visual = OldTexText("Visual intuition") formal.next_to(line, DOWN).shift(FRAME_X_RADIUS*LEFT/2) visual.next_to(line, DOWN).shift(FRAME_X_RADIUS*RIGHT/2) v_tex, w_tex = ["\\vec{\\textbf{%s}}"%c for c in ("v", "w")] additivity = OldTex( "L(", v_tex, "+", w_tex, ") = ", "L(", v_tex, ")+", "L(", w_tex, ")" ) additivity.set_color_by_tex(v_tex, V_COLOR) additivity.set_color_by_tex(w_tex, W_COLOR) scaling = OldTex( "L(", "c", v_tex, ")=", "c", "L(", v_tex, ")" ) scaling.set_color_by_tex(v_tex, V_COLOR) scaling.set_color_by_tex("c", GREEN) visual_statement = OldTexText(""" Line of dots evenly spaced dots remains evenly spaced """) visual_statement.set_submobject_colors_by_gradient(YELLOW, MAROON_B) properties = VMobject(additivity, scaling) properties.arrange(DOWN, buff = MED_SMALL_BUFF) for text, mob in (formal, properties), (visual, visual_statement): mob.scale(0.75) mob.next_to(text, DOWN, buff = MED_SMALL_BUFF) self.add(title) self.play(*list(map(ShowCreation, [line, v_line]))) for mob in formal, visual, additivity, scaling, visual_statement: self.play(Write(mob, run_time = 2)) self.wait() class AdditivityProperty(TwoDToOneDScene): CONFIG = { "show_basis_vectors" : False, "sum_before" : True } def construct(self): v = Vector([2, 1], color = V_COLOR) w = Vector([-1, 1], color = W_COLOR) L, sum_tex, r_paren = symbols = self.get_symbols() symbols.shift(4*RIGHT+2*UP) self.add_foreground_mobject(sum_tex) self.play(ShowCreation(v)) self.play(ShowCreation(w)) if self.sum_before: sum_vect = self.play_sum(v, w) else: self.add_vector(v, animate = False) self.add_vector(w, animate = False) self.apply_transposed_matrix(self.t_matrix) if not self.sum_before: sum_vect = self.play_sum(v, w) symbols.target = symbols.copy().next_to(sum_vect, UP) VGroup(L, r_paren).set_color(BLACK) self.play(Transform(symbols, symbols.target)) self.wait() def play_sum(self, v, w): sum_vect = Vector(v.get_end()+w.get_end(), color = SUM_COLOR) self.play(w.shift, v.get_end(), path_arc = np.pi/4) self.play(ShowCreation(sum_vect)) for vect in v, w: vect.target = vect.copy() vect.target.set_fill(opacity = 0) vect.target.set_stroke(width = 0) sum_vect.target = sum_vect self.play(*[ Transform(mob, mob.target) for mob in (v, w, sum_vect) ]) self.add_vector(sum_vect, animate = False) return sum_vect def get_symbols(self): v_tex, w_tex = ["\\vec{\\textbf{%s}}"%c for c in ("v", "w")] if self.sum_before: tex_mob = OldTex( "L(", v_tex, "+", w_tex, ")" ) result = VGroup( tex_mob[0], VGroup(*tex_mob[1:4]), tex_mob[4] ) else: tex_mob = OldTex( "L(", v_tex, ")", "+", "L(", w_tex, ")" ) result = VGroup( VectorizedPoint(tex_mob.get_left()), tex_mob, VectorizedPoint(tex_mob.get_right()), ) tex_mob.set_color_by_tex(v_tex, V_COLOR) tex_mob.set_color_by_tex(w_tex, W_COLOR) result[1].add_to_back(BackgroundRectangle(result[1])) return result class AdditivityPropertyPart2(AdditivityProperty): CONFIG = { "sum_before" : False } class ScalingProperty(TwoDToOneDScene): CONFIG = { "show_basis_vectors" : False, "scale_before" : True, "scalar" : 2, } def construct(self): v = Vector([-1, 1], color = V_COLOR) self.play(ShowCreation(v)) if self.scale_before: scaled_vect = self.show_scaling(v) self.add_vector(v, animate = False) self.apply_transposed_matrix(self.t_matrix) if not self.scale_before: scaled_vect = self.show_scaling(v) self.wait() self.write_symbols(scaled_vect) def show_scaling(self, v): self.add_vector(v.copy().fade(), animate = False) self.play(v.scale, self.scalar) return v def write_symbols(self, scaled_vect): v_tex = "\\vec{\\textbf{v}}" if self.scale_before: tex_mob = OldTex( "L(", "c", v_tex, ")" ) tex_mob.next_to(scaled_vect, UP) else: tex_mob = OldTex( "c", "L(", v_tex, ")", ) tex_mob.next_to(scaled_vect, DOWN) tex_mob.set_color_by_tex(v_tex, V_COLOR) tex_mob.set_color_by_tex("c", GREEN) self.play(Write(tex_mob)) self.wait() class ScalingPropertyPart2(ScalingProperty): CONFIG = { "scale_before" : False } class ThisTwoDTo1DTransformWithDots(TwoDTo1DTransformWithDots): pass class NonLinearFailsDotTest(TwoDTo1DTransformWithDots): def construct(self): line = NumberLine() self.add(line, *self.get_mobjects()) offset = LEFT+DOWN vect = 2*RIGHT+UP dots = VMobject(*[ Dot(offset + a*vect, radius = 0.075) for a in np.linspace(-2, 3, 18) ]) dots.set_submobject_colors_by_gradient(YELLOW_B, YELLOW_C) func = lambda p : (p[0]**2 - p[1]**2)*RIGHT new_dots = VMobject(*[ Dot( func(dot.get_center()), color = dot.get_color(), radius = dot.radius ) for dot in dots ]) words = OldTexText( "Line of dots", "do not", "remain evenly spaced" ) words.set_color_by_tex("do not", RED) words.next_to(line, UP, buff = MED_SMALL_BUFF) array_tex = matrix_to_tex_string(["x", "y"]) equation = OldTex( "f", "\\left(%s \\right)"%array_tex, " = x^2 - y^2" ) for part in equation: part.add_to_back(BackgroundRectangle(part)) equation.to_corner(UP+LEFT) self.add_foreground_mobject(equation) self.play(Write(dots)) self.apply_nonlinear_transformation( func, added_anims = [Transform(dots, new_dots)] ) self.play(Write(words)) self.wait() class AlwaysfollowIHatJHat(TeacherStudentsScene): def construct(self): i_tex, j_tex = ["$\\hat{\\%smath}$"%c for c in ("i", "j")] words = OldTexText( "Always follow", i_tex, "and", j_tex ) words.set_color_by_tex(i_tex, X_COLOR) words.set_color_by_tex(j_tex, Y_COLOR) self.teacher_says(words) students = VMobject(*self.get_students()) ponderers = VMobject(*[ pi.copy().change_mode("pondering") for pi in students ]) self.play(Transform( students, ponderers, lag_ratio = 0.5, run_time = 2 )) self.random_blink(2) class ShowMatrix(TwoDToOneDScene): def construct(self): self.apply_transposed_matrix(self.t_matrix) self.play(Write(self.number_line.get_numbers())) self.show_matrix() def show_matrix(self): for vect, char in zip([self.i_hat, self.j_hat], ["i", "j"]): vect.words = OldTexText( "$\\hat\\%smath$ lands on"%char, str(int(vect.get_end()[0])) ) direction = UP if vect is self.i_hat else DOWN vect.words.next_to(vect.get_end(), direction, buff = LARGE_BUFF) vect.words.set_color(vect.get_color()) matrix = Matrix([[1, 2]]) matrix_words = OldTexText("Transformation matrix: ") matrix_group = VMobject(matrix_words, matrix) matrix_group.arrange() matrix_group.to_edge(UP) entries = matrix.get_entries() self.play( Write(matrix_words), Write(matrix.get_brackets()), run_time = 1 ) for i, vect in enumerate([self.i_hat, self.j_hat]): self.play( Write(vect.words, run_time = 1), ApplyMethod(vect.shift, 0.5*UP, rate_func = there_and_back) ) self.wait() self.play(vect.words[1].copy().move_to, entries[i]) self.wait() class FollowVectorViaCoordinates(TwoDToOneDScene): CONFIG = { "t_matrix" : [[1, 0], [-2, 0]], "v_coords" : [3, 3], "written_v_coords" : ["x", "y"], "concrete" : False, } def construct(self): v = Vector(self.v_coords) array = Matrix(self.v_coords if self.concrete else self.written_v_coords) array.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR) array.add_to_back(BackgroundRectangle(array)) v_label = OldTex("\\vec{\\textbf{v}}", "=") v_label[0].set_color(YELLOW) v_label.next_to(v.get_end(), RIGHT) v_label.add_background_rectangle() array.next_to(v_label, RIGHT) bases = self.i_hat, self.j_hat basis_labels = self.get_basis_vector_labels(direction = "right") scaling_anim_tuples = self.get_scaling_anim_tuples( basis_labels, array, [DOWN, RIGHT] ) self.play(*list(map(Write, basis_labels))) self.play( ShowCreation(v), Write(array), Write(v_label) ) self.add_foreground_mobject(v_label, array) self.add_vector(v, animate = False) self.wait() to_fade = basis_labels for i, anim_tuple in enumerate(scaling_anim_tuples): self.play(*anim_tuple) movers = self.get_mobjects_from_last_animation() to_fade += movers[:-1] if i == 1: self.play(*[ ApplyMethod(m.shift, self.v_coords[0]*RIGHT) for m in movers ]) self.wait() self.play( *list(map(FadeOut, to_fade)) + [ vect.restore for vect in (self.i_hat, self.j_hat) ] ) self.apply_transposed_matrix(self.t_matrix) self.play(Write(self.number_line.get_numbers(), run_time = 1)) self.play( self.i_hat.shift, 0.5*UP, self.j_hat.shift, DOWN, ) if self.concrete: new_labels = [ OldTex("(%d)"%num) for num in self.t_matrix[:,0] ] else: new_labels = [ OldTex("L(\\hat{\\%smath})"%char) for char in ("i", "j") ] new_labels[0].set_color(X_COLOR) new_labels[1].set_color(Y_COLOR) new_labels.append( OldTex("L(\\vec{\\textbf{v}})").set_color(YELLOW) ) for label, vect, direction in zip(new_labels, list(bases) + [v], [UP, DOWN, UP]): label.next_to(vect, direction) self.play(*list(map(Write, new_labels))) self.wait() scaling_anim_tuples = self.get_scaling_anim_tuples( new_labels, array, [UP, DOWN] ) for i, anim_tuple in enumerate(scaling_anim_tuples): self.play(*anim_tuple) movers = VMobject(*self.get_mobjects_from_last_animation()) self.wait() self.play(movers.shift, self.i_hat.get_end()[0]*RIGHT) self.wait() if self.concrete: final_label = OldTex(str(int(v.get_end()[0]))) final_label.move_to(new_labels[-1]) final_label.set_color(new_labels[-1].get_color()) self.play(Transform(new_labels[-1], final_label)) self.wait() def get_scaling_anim_tuples(self, labels, array, directions): scaling_anim_tuples = [] bases = self.i_hat, self.j_hat quints = list(zip( bases, self.v_coords, labels, array.get_entries(), directions )) for basis, scalar, label, entry, direction in quints: basis.save_state() basis.scaled = basis.copy().scale(scalar) basis.scaled.shift(basis.get_start() - basis.scaled.get_start()) scaled_label = VMobject(entry.copy(), label.copy()) entry.target, label.target = scaled_label.split() entry.target.next_to(label.target, LEFT) scaled_label.next_to( basis.scaled, direction ) scaling_anim_tuples.append(( ApplyMethod(label.move_to, label.target), ApplyMethod(entry.copy().move_to, entry.target), Transform(basis, basis.scaled), )) return scaling_anim_tuples class FollowVectorViaCoordinatesConcrete(FollowVectorViaCoordinates): CONFIG = { "v_coords" : [4, 3], "concrete" : True } class TwoDOneDMatrixMultiplication(Scene): CONFIG = { "matrix" : [[1, -2]], "vector" : [4, 3], "order_left_to_right" : False, } def construct(self): matrix = Matrix(self.matrix) matrix.label = "Transform" vector = Matrix(self.vector) vector.label = "Vector" matrix.next_to(vector, LEFT, buff = 0.2) self.color_matrix_and_vector(matrix, vector) for m, vect in zip([matrix, vector], [UP, DOWN]): m.brace = Brace(m, vect) m.label = m.brace.get_text(m.label) matrix.label.set_color(BLUE) vector.label.set_color(MAROON_B) for m in vector, matrix: self.play(Write(m)) self.play( GrowFromCenter(m.brace), Write(m.label), run_time = 1 ) self.wait() self.show_product(matrix, vector) def show_product(self, matrix, vector): starter_pairs = list(zip(vector.get_entries(), matrix.get_entries())) pairs = [ VMobject( e1.copy(), OldTex("\\cdot"), e2.copy() ).arrange( LEFT if self.order_left_to_right else RIGHT, ) for e1, e2 in starter_pairs ] symbols = list(map(Tex, ["=", "+"])) equation = VMobject(*it.chain(*list(zip(symbols, pairs)))) equation.arrange(align_using_submobjects = True) equation.next_to(vector, RIGHT) self.play(Write(VMobject(*symbols))) for starter_pair, pair in zip(starter_pairs, pairs): self.play(Transform( VMobject(*starter_pair).copy(), pair, path_arc = -np.pi/2 )) self.wait() def color_matrix_and_vector(self, matrix, vector): for m in matrix, vector: x, y = m.get_entries() x.set_color(X_COLOR) y.set_color(Y_COLOR) class AssociationBetweenMatricesAndVectors(Scene): CONFIG = { "matrices" : [ [[2, 7]], [[1, -2]] ] } def construct(self): matrices_words = OldTexText("$1\\times 2$ matrices") matrices_words.set_color(BLUE) vectors_words = OldTexText("2d vectors") vectors_words.set_color(YELLOW) arrow = DoubleArrow(LEFT, RIGHT, color = WHITE) VGroup( matrices_words, arrow, vectors_words ).arrange(buff = MED_SMALL_BUFF) matrices = VGroup(*list(map(Matrix, self.matrices))) vectors = VGroup(*list(map(Matrix, [m[0] for m in self.matrices]))) for m in list(matrices) + list(vectors): x, y = m.get_entries() x.set_color(X_COLOR) y.set_color(Y_COLOR) matrices.words = matrices_words vectors.words = vectors_words for group in matrices, vectors: for m, direction in zip(group, [UP, DOWN]): m.next_to(group.words, direction, buff = MED_SMALL_BUFF) self.play(*list(map(Write, [matrices_words, vectors_words]))) self.play(ShowCreation(arrow)) self.wait() self.play(FadeIn(vectors)) vectors.save_state() self.wait() self.play(Transform( vectors, matrices, path_arc = np.pi/2, lag_ratio = 0.5, run_time = 2, )) self.wait() self.play( vectors.restore, path_arc = -np.pi/2, lag_ratio = 0.5, run_time = 2 ) self.wait() class WhatAboutTheGeometricView(TeacherStudentsScene): def construct(self): self.student_says(""" What does this association mean geometrically? """, target_mode = "raise_right_hand" ) self.play_student_changes("pondering", "raise_right_hand", "pondering") self.random_blink(2) class SomeKindOfConnection(Scene): CONFIG = { "v_coords" : [2, 3] } def construct(self): width = FRAME_X_RADIUS-1 plane = NumberPlane(x_radius = 4, y_radius = 6) squish_plane = plane.copy() i_hat = Vector([1, 0], color = X_COLOR) j_hat = Vector([0, 1], color = Y_COLOR) vect = Vector(self.v_coords, color = YELLOW) plane.add(vect, i_hat, j_hat) plane.set_width(FRAME_X_RADIUS) plane.to_edge(LEFT, buff = 0) plane.remove(vect, i_hat, j_hat) squish_plane.apply_function( lambda p : np.dot(p, [4, 1, 0])*RIGHT ) squish_plane.add(Vector(self.v_coords[1]*RIGHT, color = Y_COLOR)) squish_plane.add(Vector(self.v_coords[0]*RIGHT, color = X_COLOR)) squish_plane.scale(width/(FRAME_WIDTH)) plane.add(j_hat, i_hat) number_line = NumberLine().stretch_to_fit_width(width) number_line.to_edge(RIGHT) squish_plane.move_to(number_line) numbers = number_line.get_numbers(*list(range(-6, 8, 2))) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.set_color(GREY) v_line.set_stroke(width = 10) matrix = Matrix([self.v_coords]) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(number_line, UP, buff = LARGE_BUFF) v_coords = Matrix(self.v_coords) v_coords.set_column_colors(YELLOW) v_coords.scale(0.75) v_coords.next_to(vect.get_end(), RIGHT) for array in matrix, v_coords: array.add_to_back(BackgroundRectangle(array)) self.play(*list(map(ShowCreation, [ plane, number_line, v_line ]))+[ Write(numbers, run_time = 2) ]) self.play(Write(matrix, run_time = 1)) mover = plane.copy() interim = plane.copy().scale(0.8).move_to(number_line) for target in interim, squish_plane: self.play( Transform(mover, target), Animation(plane), run_time = 1, ) self.wait() self.play(ShowCreation(vect)) self.play(Transform(matrix.copy(), v_coords)) self.wait() class AnExampleWillClarify(TeacherStudentsScene): def construct(self): self.teacher_says("An example will clarify...") self.play_student_changes(*["happy"]*3) self.random_blink(3) class ImagineYouDontKnowThis(Scene): def construct(self): words = OldTexText("Imagine you don't know this") words.set_color(RED) words.scale(1.5) self.play(Write(words)) self.wait() class ProjectOntoUnitVectorNumberline(VectorScene): CONFIG = { "randomize_dots" : True, "animate_setup" : True, "zoom_factor" : 1, "u_hat_color" : YELLOW, "tilt_angle" : np.pi/6, } def setup(self): plane = self.add_plane() plane.fade() u_hat = Vector([1, 0], color = self.u_hat_color) u_brace = Brace(u_hat, UP) u_hat.rotate(self.tilt_angle) u_hat.label = OldTex("\\hat{\\textbf{u}}") u_hat.label.set_color(u_hat.get_color()) u_hat.label.next_to(u_hat.get_end(), UP+LEFT) one = OldTex("1") u_brace.put_at_tip(one) u_brace.add(one) u_brace.rotate(u_hat.get_angle()) one.rotate(-u_hat.get_angle()) number_line = NumberLine(x_min = -9, x_max = 9) numbers = number_line.get_numbers() VGroup(number_line, numbers).rotate(u_hat.get_angle()) if self.animate_setup: self.play( ShowCreation(number_line), Write(numbers), run_time = 3 ) self.wait() self.play(ShowCreation(u_hat)) self.play(FadeIn(u_brace)) self.play(FadeOut(u_brace)) self.play(Write(u_hat.label)) self.wait() else: self.add(number_line, numbers, u_hat) if self.zoom_factor != 1: for mob in plane, u_hat: mob.target = mob.copy().scale(self.zoom_factor) number_line.target = number_line.copy() number_line.target.rotate(-u_hat.get_angle()) number_line.target.stretch(self.zoom_factor, 0) numbers.target = number_line.target.get_numbers() number_line.target.rotate(u_hat.get_angle()) numbers.target.rotate(u_hat.get_angle()) self.play(*[ Transform(mob, mob.target) for mob in self.get_mobjects() ]) self.wait() self.number_line, self.numbers, self.u_hat = number_line, numbers, u_hat def construct(self): vectors = self.get_vectors(randomize = self.randomize_dots) dots = self.get_dots(vectors) proj_dots = self.get_proj_dots(dots) proj_lines = self.get_proj_lines(dots, proj_dots) self.wait() self.play(FadeIn(vectors, lag_ratio = 0.5)) self.wait() self.play(Transform(vectors, dots)) self.wait() self.play(ShowCreation(proj_lines)) self.wait() self.play( self.number_line.set_stroke, None, 2, Transform(vectors, proj_dots), Transform(proj_lines, proj_dots), Animation(self.u_hat), lag_ratio = 0.5, run_time = 2 ) self.wait() def get_vectors(self, num_vectors = 10, randomize = True): x_max = FRAME_X_RADIUS - 1 y_max = FRAME_Y_RADIUS - 1 x_vals = np.linspace(-x_max, x_max, num_vectors) y_vals = np.linspace(y_max, -y_max, num_vectors) if randomize: random.shuffle(y_vals) vectors = VGroup(*[ Vector(x*RIGHT + y*UP) for x, y in zip(x_vals, y_vals) ]) vectors.set_color_by_gradient(PINK, MAROON_B) return vectors def get_dots(self, vectors): return VGroup(*[ Dot(v.get_end(), color = v.get_color(), radius = 0.075) for v in vectors ]) def get_proj_dots(self, dots): return VGroup(*[ dot.copy().move_to(get_projection( dot.get_center(), self.u_hat.get_end() )) for dot in dots ]) def get_proj_lines(self, dots, proj_dots): return VGroup(*[ DashedLine( d1.get_center(), d2.get_center(), buff = 0, color = d1.get_color(), dash_length = 0.15 ) for d1, d2 in zip(dots, proj_dots) ]) class ProjectionFunctionSymbol(Scene): def construct(self): v_tex = "\\vec{\\textbf{v}}" equation = OldTex( "P(", v_tex, ")=", "\\text{number }", v_tex, "\\text{ lands on}" ) equation.set_color_by_tex(v_tex, YELLOW) equation.shift(2*UP) words = OldTexText( "This projection function is", "linear" ) words.set_color_by_tex("linear", BLUE) arrow = Arrow( words.get_top(), equation[0].get_bottom(), color = BLUE ) self.add(VGroup(*equation[:3])) self.play(Write(VGroup(*equation[3:]))) self.wait() self.play(Write(words), ShowCreation(arrow)) self.wait() class ProjectLineOfDots(ProjectOntoUnitVectorNumberline): CONFIG = { "randomize_dots" : False, "animate_setup" : False, } class ProjectSingleVectorOnUHat(ProjectOntoUnitVectorNumberline): CONFIG = { "animate_setup" : False } def construct(self): v = Vector([-3, 1], color = PINK) v.proj = get_vect_mob_projection(v, self.u_hat) v.proj_line = DashedLine(v.get_end(), v.proj.get_end()) v.proj_line.set_color(v.get_color()) v_tex = "\\vec{\\textbf{v}}" u_tex = self.u_hat.label.get_tex() v.label = OldTex(v_tex) v.label.set_color(v.get_color()) v.label.next_to(v.get_end(), LEFT) dot_product = OldTex(v_tex, "\\cdot", u_tex) dot_product.set_color_by_tex(v_tex, v.get_color()) dot_product.set_color_by_tex(u_tex, self.u_hat.get_color()) dot_product.next_to(ORIGIN, UP, buff = MED_SMALL_BUFF) dot_product.rotate(self.tilt_angle) dot_product.shift(v.proj.get_end()) dot_product.add_background_rectangle() v.label.add_background_rectangle() self.play( ShowCreation(v), Write(v.label), ) self.wait() self.play( ShowCreation(v.proj_line), Transform(v.copy(), v.proj) ) self.wait() self.play( FadeOut(v), FadeOut(v.proj_line), FadeOut(v.label), Write(dot_product) ) self.wait() class AskAboutProjectionMatrix(Scene): def construct(self): matrix = Matrix([["?", "?"]]) matrix.set_column_colors(X_COLOR, Y_COLOR) words = OldTexText("Projection matrix:") VMobject(words, matrix).arrange(buff = MED_SMALL_BUFF).shift(UP) basis_words = [ OldTexText("Where", "$\\hat{\\%smath}$"%char, "lands") for char in ("i", "j") ] for b_words, q_mark, direction in zip(basis_words, matrix.get_entries(), [UP, DOWN]): b_words.next_to(q_mark, direction, buff = 1.5) b_words.arrow = Arrow(b_words, q_mark, color = q_mark.get_color()) b_words.set_color(q_mark.get_color()) self.play( Write(words), Write(matrix) ) self.wait() for b_words in basis_words: self.play( Write(b_words), ShowCreation(b_words.arrow) ) self.wait() class ProjectBasisVectors(ProjectOntoUnitVectorNumberline): CONFIG = { "animate_setup" : False, "zoom_factor" : 3, "u_hat_color" : YELLOW, "tilt_angle" : np.pi/5, } def construct(self): basis_vectors = self.get_basis_vectors() i_hat, j_hat = basis_vectors for vect in basis_vectors: vect.scale(self.zoom_factor) dots = self.get_dots(basis_vectors) proj_dots = self.get_proj_dots(dots) proj_lines = self.get_proj_lines(dots, proj_dots) for dot in proj_dots: dot.scale(0.1) proj_basis = VGroup(*[ get_vect_mob_projection(vector, self.u_hat) for vector in basis_vectors ]) i_tex, j_tex = ["$\\hat{\\%smath}$"%char for char in ("i", "j")] question = OldTexText( "Where do", i_tex, "and", j_tex, "land?" ) question.set_color_by_tex(i_tex, X_COLOR) question.set_color_by_tex(j_tex, Y_COLOR) question.add_background_rectangle() matrix = Matrix([["u_x", "u_y"]]) VGroup(question, matrix).arrange(DOWN).to_corner( UP+LEFT, buff = MED_SMALL_BUFF/2 ) matrix_rect = BackgroundRectangle(matrix) i_label = OldTex(i_tex[1:-1]) j_label = OldTex(j_tex[1:-1]) u_label = OldTex("\\hat{\\textbf{u}}") trips = list(zip( (i_label, j_label, u_label), (i_hat, j_hat, self.u_hat), (DOWN+RIGHT, UP+LEFT, UP), )) for label, vect, direction in trips: label.set_color(vect.get_color()) label.scale(1.2) label.next_to(vect.get_end(), direction, buff = MED_SMALL_BUFF/2) self.play(Write(u_label, run_time = 1)) self.play(*list(map(ShowCreation, basis_vectors))) self.play(*list(map(Write, [i_label, j_label])), run_time = 1) self.play(ShowCreation(proj_lines)) self.play( Write(question), ShowCreation(matrix_rect), Write(matrix.get_brackets()), run_time = 2, ) to_remove = [proj_lines] quads = list(zip(basis_vectors, proj_basis, proj_lines, proj_dots)) for vect, proj_vect, proj_line, proj_dot in quads: self.play(Transform(vect.copy(), proj_vect)) to_remove += self.get_mobjects_from_last_animation() self.wait() self.play(*list(map(FadeOut, to_remove))) # self.show_u_coords(u_label) u_x, u_y = [ OldTex("u_%s"%c).set_color(self.u_hat.get_color()) for c in ("x", "y") ] matrix_x, matrix_y = matrix.get_entries() self.remove(j_hat, j_label) self.show_symmetry(i_hat, u_x, matrix_x) self.add(j_hat, j_label) self.remove(i_hat, i_label) self.show_symmetry(j_hat, u_y, matrix_y) # def show_u_coords(self, u_label): # coords = Matrix(["u_x", "u_y"]) # x, y = coords.get_entries() # x.set_color(X_COLOR) # y.set_color(Y_COLOR) # coords.add_to_back(BackgroundRectangle(coords)) # eq = OldTex("=") # eq.next_to(u_label, RIGHT) # coords.next_to(eq, RIGHT) # self.play(*map(FadeIn, [eq, coords])) # self.wait() # self.u_coords = coords def show_symmetry(self, vect, coord, coord_landing_spot): starting_mobjects = list(self.get_mobjects()) line = DashedLine(FRAME_X_RADIUS*LEFT, FRAME_X_RADIUS*RIGHT) words = OldTexText("Line of symmetry") words.next_to(ORIGIN, UP+LEFT) words.shift(LEFT) words.add_background_rectangle() angle = np.mean([vect.get_angle(), self.u_hat.get_angle()]) VGroup(line, words).rotate(angle) self.play(ShowCreation(line)) if vect.get_end()[0] > 0.1:#is ihat self.play(Write(words, run_time = 1)) vect.proj = get_vect_mob_projection(vect, self.u_hat) self.u_hat.proj = get_vect_mob_projection(self.u_hat, vect) for v in vect, self.u_hat: v.proj_line = DashedLine( v.get_end(), v.proj.get_end(), color = v.get_color() ) v.proj_line.fade() v.tick = Line(0.1*DOWN, 0.1*UP, color = WHITE) v.tick.rotate(v.proj.get_angle()) v.tick.shift(v.proj.get_end()) v.q_mark = OldTexText("?") v.q_mark.next_to(v.tick, v.proj.get_end()-v.get_end()) self.play(ShowCreation(v.proj_line)) self.play(Transform(v.copy(), v.proj)) self.remove(*self.get_mobjects_from_last_animation()) self.add(v.proj) self.wait() for v in vect, self.u_hat: self.play( ShowCreation(v.tick), Write(v.q_mark) ) self.wait() for v in self.u_hat, vect: coord_copy = coord.copy().move_to(v.q_mark) self.play(Transform(v.q_mark, coord_copy)) self.wait() final_coord = coord_copy.copy() self.play(final_coord.move_to, coord_landing_spot) added_mobjects = [ mob for mob in self.get_mobjects() if mob not in starting_mobjects + [final_coord] ] self.play(*list(map(FadeOut, added_mobjects))) class ShowSingleProjection(ProjectBasisVectors): CONFIG = { "zoom_factor" : 1 } def construct(self): vector = Vector([5, - 1], color = MAROON_B) proj = get_vect_mob_projection(vector, self.u_hat) proj_line = DashedLine( vector.get_end(), proj.get_end(), color = vector.get_color() ) coords = Matrix(["x", "y"]) coords.get_entries().set_color(vector.get_color()) coords.add_to_back(BackgroundRectangle(coords)) coords.next_to(vector.get_end(), RIGHT) u_label = OldTex("\\hat{\\textbf{u}}") u_label.next_to(self.u_hat.get_end(), UP) u_label.add_background_rectangle() self.add(u_label) self.play(ShowCreation(vector)) self.play(Write(coords)) self.wait() self.play(ShowCreation(proj_line)) self.play( Transform(vector.copy(), proj), Animation(self.u_hat) ) self.wait() class GeneralTwoDOneDMatrixMultiplication(TwoDOneDMatrixMultiplication): CONFIG = { "matrix" : [["u_x", "u_y"]], "vector" : ["x", "y"], "order_left_to_right" : True, } def construct(self): TwoDOneDMatrixMultiplication.construct(self) everything = VGroup(*self.get_mobjects()) to_fade = [m for m in everything if isinstance(m, Brace) or isinstance(m, TexText)] u = Matrix(self.matrix[0]) v = Matrix(self.vector) self.color_matrix_and_vector(u, v) dot_product = VGroup(u, OldTex("\\cdot"), v) dot_product.arrange() dot_product.shift(2*RIGHT+DOWN) words = VGroup( OldTexText("Matrix-vector product"), OldTex("\\Updownarrow"), OldTexText("Dot product") ) words[0].set_color(BLUE) words[2].set_color(GREEN) words.arrange(DOWN) words.to_edge(LEFT) self.play( everything.to_corner, UP+RIGHT, *list(map(FadeOut, to_fade)) ) self.remove(everything) self.add(*everything) self.remove(*to_fade) self.play(Write(words, run_time = 2)) self.play(ShowCreation(dot_product)) self.show_product(u, v) def color_matrix_and_vector(self, matrix, vector): colors = [X_COLOR, Y_COLOR] for coord, color in zip(matrix.get_entries(), colors): coord[0].set_color(YELLOW) coord[1].set_color(color) vector.get_entries().set_color(MAROON_B) class UHatIsTransformInDisguise(Scene): def construct(self): u_tex = "$\\hat{\\textbf{u}}$" words = OldTexText( u_tex, "is secretly a \\\\", "transform", "in disguise", ) words.set_color_by_tex(u_tex, YELLOW) words.set_color_by_tex("transform", BLUE) words.scale(2) self.play(Write(words)) self.wait() class AskAboutNonUnitVectors(TeacherStudentsScene): def construct(self): self.student_says( "What about \\\\ non-unit vectors", target_mode = "raise_left_hand" ) self.random_blink(2) class ScaleUpUHat(ProjectOntoUnitVectorNumberline) : CONFIG = { "animate_setup" : False, "u_hat_color" : YELLOW, "tilt_angle" : np.pi/6, "scalar" : 3, } def construct(self): self.scale_u_hat() self.show_matrix() self.transform_basis_vectors() self.transform_some_vector() def scale_u_hat(self): self.u_hat.coords = Matrix(["u_x", "u_y"]) new_u = self.u_hat.copy().scale(self.scalar) new_u.coords = Matrix([ "%du_x"%self.scalar, "%du_y"%self.scalar, ]) for v in self.u_hat, new_u: v.coords.get_entries().set_color(YELLOW) v.coords.add_to_back(BackgroundRectangle(v.coords)) v.coords.next_to(v.get_end(), UP+LEFT) self.play(Write(self.u_hat.coords)) self.play( Transform(self.u_hat, new_u), Transform(self.u_hat.coords, new_u.coords) ) self.wait() def show_matrix(self): matrix = Matrix([list(self.u_hat.coords.get_entries().copy())]) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.add_to_back(BackgroundRectangle(matrix)) brace = Brace(matrix) words = OldTexText( "\\centering Associated\\\\", "transformation" ) words.set_color_by_tex("transformation", BLUE) words.add_background_rectangle() brace.put_at_tip(words) VGroup(matrix, brace, words).to_corner(UP+LEFT) self.play(Transform( self.u_hat.coords, matrix )) self.play( GrowFromCenter(brace), Write(words, run_time = 2) ) self.wait() self.matrix_words = words def transform_basis_vectors(self): start_state = list(self.get_mobjects()) bases = self.get_basis_vectors() for b, char in zip(bases, ["x", "y"]): b.proj = get_vect_mob_projection(b, self.u_hat) b.proj_line = DashedLine( b.get_end(), b.proj.get_end(), dash_length = 0.05 ) b.proj.label = OldTex("u_%s"%char) b.proj.label.set_color(b.get_color()) b.scaled_proj = b.proj.copy().scale(self.scalar) b.scaled_proj.label = OldTex("3u_%s"%char) b.scaled_proj.label.set_color(b.get_color()) for v, direction in zip([b.proj, b.scaled_proj], [UP, UP+LEFT]): v.label.add_background_rectangle() v.label.next_to(v.get_end(), direction) self.play(*list(map(ShowCreation, bases))) for b in bases: mover = b.copy() self.play(ShowCreation(b.proj_line)) self.play(Transform(mover, b.proj)) self.play(Write(b.proj.label)) self.wait() self.play( Transform(mover, b.scaled_proj), Transform(b.proj.label, b.scaled_proj.label) ) self.wait() self.play(*list(map(FadeOut, [ mob for mob in self.get_mobjects() if mob not in start_state ]))) def transform_some_vector(self): words = OldTexText( "\\centering Project\\\\", "then scale" ) project, then_scale = words.split() words.add_background_rectangle() words.move_to(self.matrix_words, aligned_edge = UP) v = Vector([3, -1], color = MAROON_B) proj = get_vect_mob_projection(v, self.u_hat) proj_line = DashedLine( v.get_end(), proj.get_end(), color = v.get_color() ) mover = v.copy() self.play(ShowCreation(v)) self.play(Transform(self.matrix_words, words)) self.play(ShowCreation(proj_line)) self.play( Transform(mover, proj), project.set_color, YELLOW ) self.wait() self.play( mover.scale, self.scalar, then_scale.set_color, YELLOW ) self.wait() class NoticeWhatHappenedHere(TeacherStudentsScene): def construct(self): self.teacher_says(""" Notice what happened here """) self.play_student_changes(*["pondering"]*3) self.random_blink() class AbstractNumericAssociation(AssociationBetweenMatricesAndVectors): CONFIG = { "matrices" : [ [["u_x", "u_y"]] ] } class TwoDOneDTransformationSeparateSpace(Scene): CONFIG = { "v_coords" : [4, 1] } def construct(self): width = FRAME_X_RADIUS-1 plane = NumberPlane(x_radius = 6, y_radius = 7) squish_plane = plane.copy() i_hat = Vector([1, 0], color = X_COLOR) j_hat = Vector([0, 1], color = Y_COLOR) vect = Vector(self.v_coords, color = YELLOW) plane.add(vect, i_hat, j_hat) plane.set_width(FRAME_X_RADIUS) plane.to_edge(LEFT, buff = 0) plane.remove(vect, i_hat, j_hat) squish_plane.apply_function( lambda p : np.dot(p, [4, 1, 0])*RIGHT ) squish_plane.add(Vector(self.v_coords[0]*RIGHT, color = X_COLOR)) squish_plane.add(Vector(self.v_coords[1]*RIGHT, color = Y_COLOR)) squish_plane.scale(width/(FRAME_WIDTH)) plane.add(i_hat, j_hat) number_line = NumberLine().stretch_to_fit_width(width) number_line.to_edge(RIGHT) squish_plane.move_to(number_line) numbers = number_line.get_numbers(*list(range(-6, 8, 2))) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.set_color(GREY) v_line.set_stroke(width = 10) matrix = Matrix([self.v_coords]) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(number_line, UP, buff = LARGE_BUFF) v_coords = Matrix(self.v_coords) v_coords.set_column_colors(YELLOW) v_coords.scale(0.75) v_coords.next_to(vect.get_end(), RIGHT) for array in matrix, v_coords: array.add_to_back(BackgroundRectangle(array)) start_words = OldTexText( "\\centering Any time you have a \\\\", "2d-to-1d linear transform..." ) end_words = OldTexText( "\\centering ...it's associated \\\\", "with some vector", ) for words in start_words, end_words: words.add_background_rectangle() words.scale(0.8) start_words.next_to(ORIGIN, RIGHT, buff = MED_SMALL_BUFF).to_edge(UP) end_words.next_to(ORIGIN, DOWN+LEFT, buff = MED_SMALL_BUFF/2) self.play(*list(map(ShowCreation, [ plane, number_line, v_line ]))+[ Write(numbers, run_time = 2) ]) self.play(Write(start_words, run_time = 2)) self.play(Write(matrix, run_time = 1)) mover = plane.copy() interim = plane.copy().scale(0.8).move_to(number_line) for target in interim, squish_plane: self.play( Transform(mover, target), Animation(plane), Animation(start_words), run_time = 1, ) self.wait() self.play(Transform(start_words.copy(), end_words)) self.play(ShowCreation(vect)) self.play(Transform(matrix.copy(), v_coords)) self.wait() class IsntThisBeautiful(TeacherStudentsScene): def construct(self): self.teacher.look(DOWN+LEFT) self.teacher_says( "Isn't this", "beautiful", target_mode = "surprised" ) for student in self.get_students(): self.play(student.change_mode, "happy") self.random_blink() duality_words = OldTexText( "It's called", "duality" ) duality_words[1].set_color_by_gradient(BLUE, YELLOW) self.teacher_says(duality_words) self.random_blink() class RememberGraphDuality(Scene): def construct(self): words = OldTexText(""" \\centering Some of you may remember an early video I did on graph duality """) words.to_edge(UP) self.play(Write(words)) self.wait() class LooseDualityDescription(Scene): def construct(self): duality = OldTexText("Duality") duality.set_color_by_gradient(BLUE, YELLOW) arrow = OldTex("\\Leftrightarrow") words = OldTexText("Natural-but-surprising", "correspondence") words[1].set_color_by_gradient(BLUE, YELLOW) VGroup(duality, arrow, words).arrange(buff = MED_SMALL_BUFF) self.add(duality) self.play(Write(arrow)) self.play(Write(words)) self.wait() class DualOfAVector(ScaleUpUHat): pass #Exact copy class DualOfATransform(TwoDOneDTransformationSeparateSpace): pass #Exact copy class UnderstandingProjection(ProjectOntoUnitVectorNumberline): pass ##Copy class ShowQualitativeDotProductValuesCopy(ShowQualitativeDotProductValues): pass class TranslateToTheWorldOfTransformations(TwoDOneDMatrixMultiplication): CONFIG = { "order_left_to_right" : True, } def construct(self): v1, v2 = [ Matrix(["x_%d"%n, "y_%d"%n]) for n in (1, 2) ] v1.set_column_colors(V_COLOR) v2.set_column_colors(W_COLOR) dot = OldTex("\\cdot") matrix = Matrix([["x_1", "y_1"]]) matrix.set_column_colors(X_COLOR, Y_COLOR) dot_product = VGroup(v1, dot, v2) dot_product.arrange(RIGHT) matrix.next_to(v2, LEFT) brace = Brace(matrix, UP) word = OldTexText("Transform") word.set_width(brace.get_width()) brace.put_at_tip(word) word.set_color(BLUE) self.play(Write(dot_product)) self.wait() self.play( dot.set_fill, BLACK, 0, Transform(v1, matrix), ) self.play( GrowFromCenter(brace), Write(word) ) self.wait() self.show_product(v1, v2) self.wait() class NumericalAssociationSilliness(GeneralTwoDOneDMatrixMultiplication): pass #copy class YouMustKnowPersonality(TeacherStudentsScene): def construct(self): self.teacher_says(""" You should learn a vector's personality """) self.random_blink() self.play_student_changes("pondering") self.random_blink() self.play_student_changes("pondering", "plain", "pondering") self.random_blink() class WhatTheVectorWantsToBe(Scene): CONFIG = { "v_coords" : [2, 4] } def construct(self): width = FRAME_X_RADIUS-1 plane = NumberPlane(x_radius = 6, y_radius = 7) squish_plane = plane.copy() i_hat = Vector([1, 0], color = X_COLOR) j_hat = Vector([0, 1], color = Y_COLOR) vect = Vector(self.v_coords, color = YELLOW) plane.add(vect, i_hat, j_hat) plane.set_width(FRAME_X_RADIUS) plane.to_edge(LEFT, buff = 0) plane.remove(vect, i_hat, j_hat) squish_plane.apply_function( lambda p : np.dot(p, [4, 1, 0])*RIGHT ) squish_plane.add(Vector(self.v_coords[1]*RIGHT, color = Y_COLOR)) squish_plane.add(Vector(self.v_coords[0]*RIGHT, color = X_COLOR)) squish_plane.scale(width/(FRAME_WIDTH)) plane.add(j_hat, i_hat) number_line = NumberLine().stretch_to_fit_width(width) number_line.to_edge(RIGHT) squish_plane.move_to(number_line) numbers = number_line.get_numbers(*list(range(-6, 8, 2))) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) v_line.set_color(GREY) v_line.set_stroke(width = 10) matrix = Matrix([self.v_coords]) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(number_line, UP, buff = LARGE_BUFF) v_coords = Matrix(self.v_coords) v_coords.set_column_colors(YELLOW) v_coords.scale(0.75) v_coords.next_to(vect.get_end(), RIGHT) for array in matrix, v_coords: array.add_to_back(BackgroundRectangle(array)) words = OldTexText( "What the vector", "\\\\ wants", "to be" ) words[1].set_color(BLUE) words.next_to(matrix, UP, buff = MED_SMALL_BUFF) self.add(plane, v_line, number_line, numbers) self.play(ShowCreation(vect)) self.play(Write(v_coords)) self.wait() self.play( Transform(v_coords.copy(), matrix), Write(words) ) self.play( Transform(plane.copy(), squish_plane, run_time = 3), *list(map(Animation, [ words, matrix, plane, vect, v_coords ])) ) self.wait() class NextVideo(Scene): def construct(self): title = OldTexText(""" Next video: Cross products in the light of linear transformations """) title.set_height(1.2) title.to_edge(UP, buff = MED_SMALL_BUFF/2) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) VGroup(title, rect).show() self.add(title) self.play(ShowCreation(rect)) self.wait()
videos_3b1b/_2016/eola/chapter5.py
from manim_imports_ext import * from _2016.eola.chapter3 import MatrixVectorMultiplicationAbstract class Blob(Circle): CONFIG = { "stroke_color" : TEAL, "fill_color" : BLUE_E, "fill_opacity" : 1, "random_seed" : 1, "random_nudge_size" : 0.5, "height" : 2, } def __init__(self, **kwargs): Circle.__init__(self, **kwargs) random.seed(self.random_seed) self.apply_complex_function( lambda z : z*(1+self.random_nudge_size*(random.random()-0.5)) ) self.set_height(self.height).center() def probably_contains(self, point): border_points = np.array(self.get_anchors_and_handles()[0]) distances = [get_norm(p-point) for p in border_points] min3 = border_points[np.argsort(distances)[:3]] center_direction = self.get_center() - point in_center_direction = [np.dot(p-point, center_direction) > 0 for p in min3] return sum(in_center_direction) <= 2 class RightHand(VMobject): def __init__(self, **kwargs): hand = SVGMobject("RightHandOutline") self.inlines = VMobject(*hand.split()[:-4]) self.outline = VMobject(*hand.split()[-4:]) self.outline.set_stroke(color = WHITE, width = 5) self.inlines.set_stroke(color = GREY_D, width = 3) VMobject.__init__(self, self.outline, self.inlines) self.center().set_height(3) class OpeningQuote(Scene): def construct(self): words = OldTexText([ "``The purpose of computation is \\\\", "insight", ", not ", "numbers.", "''", ], arg_separator = "") # words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) words.split()[1].set_color(BLUE) words.split()[3].set_color(GREEN) author = OldTexText("-Richard Hamming") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(2) self.play(Write(author, run_time = 3)) self.wait() class MovingForward(TeacherStudentsScene): def construct(self): self.setup() student = self.get_students()[1] bubble = student.get_bubble(direction = RIGHT, width = 5) bubble.rotate(-np.pi/12) bubble.next_to(student, UP, aligned_edge = RIGHT) bubble.shift(0.5*LEFT) bubble.make_green_screen() self.teacher_says(""" Y'all know about linear transformations, right? """, width = 7) self.play( ShowCreation(bubble), student.change_mode, "pondering" ) self.wait(2) class StretchingTransformation(LinearTransformationScene): def construct(self): self.setup() self.add_title("Generally stretches space") self.apply_transposed_matrix([[3, 1], [-1, 2]]) self.wait() class SquishingTransformation(LinearTransformationScene): CONFIG = { "foreground_plane_kwargs" : { "x_radius" : 3*FRAME_X_RADIUS, "y_radius" : 3*FRAME_X_RADIUS, "secondary_line_ratio" : 0 }, } def construct(self): self.setup() self.add_title("Generally squishes space") self.apply_transposed_matrix([[1./2, -0.5], [1, 1./3]]) self.wait() class AskAboutStretching(LinearTransformationScene): def construct(self): self.setup() words = OldTexText(""" Exactly how much are things being stretched? """) words.add_background_rectangle() words.to_corner(UP+RIGHT) words.set_color(YELLOW) self.apply_transposed_matrix( [[2, 1], [-1, 3]], added_anims = [Write(words)] ) self.wait() class AskAboutStretchingSpecifically(LinearTransformationScene): def construct(self): self.setup() self.add_title(["How much are", "areas", "scaled?"]) hma, areas, scaled = self.title.split()[1].split() areas.set_color(YELLOW) blob = Blob().shift(UP+RIGHT) label = OldTexText("Area") label.set_color(YELLOW) label = VMobject(VectorizedPoint(label.get_left()), label) label.move_to(blob) target_label = OldTex(["c \\cdot", "\\text{Area}"]) target_label.split()[1].set_color(YELLOW) self.add_transformable_mobject(blob) self.add_moving_mobject(label, target_label) self.wait() self.apply_transposed_matrix([[2, -1], [1, 1]]) arrow = Arrow(scaled, label.target.split()[0]) self.play(ShowCreation(arrow)) self.wait() class BeautyNowUsesLater(TeacherStudentsScene): def construct(self): self.setup() self.teacher_says("Beauty now, uses later") self.wait() class DiagonalExample(LinearTransformationScene): CONFIG = { "show_square" : False, "show_coordinates" : True, "transposed_matrix" : [[3, 0], [0, 2]] } def construct(self): self.setup() matrix = Matrix(np.array(self.transposed_matrix).transpose()) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(ORIGIN, LEFT).to_edge(UP) matrix_background = BackgroundRectangle(matrix) self.play(ShowCreation(matrix_background), Write(matrix)) if self.show_square: self.add_unit_square(animate = True) self.add_foreground_mobject(matrix_background, matrix) self.wait() self.apply_transposed_matrix([self.transposed_matrix[0], [0, 1]]) self.apply_transposed_matrix([[1, 0], self.transposed_matrix[1]]) self.wait() if self.show_square: bottom_brace = Brace(self.i_hat, DOWN) right_brace = Brace(self.square, RIGHT) width = OldTex(str(self.transposed_matrix[0][0])) height = OldTex(str(self.transposed_matrix[1][1])) width.next_to(bottom_brace, DOWN) height.next_to(right_brace, RIGHT) for mob in bottom_brace, width, right_brace, height: mob.add_background_rectangle() self.play(Write(mob, run_time = 0.5)) self.wait() width_target, height_target = width.copy(), height.copy() det = np.linalg.det(self.transposed_matrix) times, eq_det = list(map(Tex, ["\\times", "=%d"%det])) words = OldTexText("New area $=$") equation = VMobject( words, width_target, times, height_target, eq_det ) equation.arrange(RIGHT, buff = 0.2) equation.next_to(self.square, UP, aligned_edge = LEFT) equation.shift(0.5*RIGHT) background_rect = BackgroundRectangle(equation) self.play( ShowCreation(background_rect), Transform(width.copy(), width_target), Transform(height.copy(), height_target), *list(map(Write, [words, times, eq_det])) ) self.wait() class DiagonalExampleWithSquare(DiagonalExample): CONFIG = { "show_square" : True } class ShearExample(DiagonalExample): CONFIG = { "show_square" : False, "show_coordinates" : True, "transposed_matrix" : [[1, 0], [1, 1]] } class ShearExampleWithSquare(DiagonalExample): CONFIG = { "show_square" : True, "show_coordinates" : True, "show_coordinates" : False, "transposed_matrix" : [[1, 0], [1, 1]] } class ThisSquareTellsEverything(LinearTransformationScene): def construct(self): self.setup() self.add_unit_square() words = OldTexText(""" This square gives you everything you need. """) words.to_corner(UP+RIGHT) words.set_color(YELLOW) words.add_background_rectangle() arrow = Arrow( words.get_bottom(), self.square.get_right(), color = WHITE ) self.play(Write(words, run_time = 2)) self.play(ShowCreation(arrow)) self.add_foreground_mobject(words, arrow) self.wait() self.apply_transposed_matrix([[1.5, -0.5], [1, 1.5]]) self.wait() class WhatHappensToOneSquareHappensToAll(LinearTransformationScene): def construct(self): self.setup() self.add_unit_square() pairs = [ (2*RIGHT+UP, 1), (3*LEFT, 2), (2*LEFT+DOWN, 0.5), (3.5*RIGHT+2.5*UP, 1.5), (RIGHT+2*DOWN, 0.25), (3*LEFT+3*DOWN, 1), ] squares = VMobject() for position, side_length in pairs: square = self.square.copy() square.scale(side_length) square.shift(position) squares.add(square) self.play(FadeIn( squares, lag_ratio = 0.5, run_time = 3 )) self.add_transformable_mobject(squares) self.apply_transposed_matrix([[1, -1], [0.5, 1]]) self.wait() class BreakBlobIntoGridSquares(LinearTransformationScene): CONFIG = { "square_size" : 0.5, "blob_height" : 3, } def construct(self): self.setup() blob = Blob( height = self.blob_height, random_seed = 5, random_nudge_size = 0.2, ) blob.next_to(ORIGIN, UP+RIGHT) self.add_transformable_mobject(blob) arange = np.arange( 0, self.blob_height + self.square_size, self.square_size ) square = Square(side_length = self.square_size) square.set_stroke(YELLOW, width = 2) square.set_fill(YELLOW, opacity = 0.3) squares = VMobject() for x, y in it.product(*[arange]*2): point = x*RIGHT + y*UP if blob.probably_contains(point): squares.add(square.copy().shift(point)) self.play(ShowCreation( squares, lag_ratio = 0.5, run_time = 2, )) self.add_transformable_mobject(squares) self.wait() self.apply_transposed_matrix([[1, -1], [0.5, 1]]) self.wait() class BreakBlobIntoGridSquaresGranular(BreakBlobIntoGridSquares): CONFIG = { "square_size" : 0.25 } class BreakBlobIntoGridSquaresMoreGranular(BreakBlobIntoGridSquares): CONFIG = { "square_size" : 0.15 } class BreakBlobIntoGridSquaresVeryGranular(BreakBlobIntoGridSquares): CONFIG = { "square_size" : 0.1 } class NameDeterminant(LinearTransformationScene): CONFIG = { "t_matrix" : [[3, 0], [2, 2]] } def construct(self): self.setup() self.plane.fade(0.3) self.add_unit_square(color = YELLOW_E, opacity = 0.5) self.add_title( ["The", "``determinant''", "of a transformation"], scale_factor = 1 ) self.title.split()[1].split()[1].set_color(YELLOW) matrix_background, matrix, det_text = self.get_matrix() self.add_foreground_mobject(matrix_background, matrix) A = OldTex("A") area_label = VMobject(A.copy(), A.copy(), A) area_label.move_to(self.square) det = np.linalg.det(self.t_matrix) if np.round(det) == det: det = int(det) area_label_target = VMobject( OldTex(str(det)), OldTex("\\cdot"), A.copy() ) if det < 1 and det > 0: area_label_target.scale(det) area_label_target.arrange(RIGHT, buff = 0.1) self.add_moving_mobject(area_label, area_label_target) self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() det_mob_copy = area_label.split()[0].copy() new_det_mob = det_mob_copy.copy().set_height( det_text.split()[0].get_height() ) new_det_mob.next_to(det_text, RIGHT, buff = 0.2) new_det_mob.add_background_rectangle() det_mob_copy.add_background_rectangle(opacity = 0) self.play(Write(det_text)) self.play(Transform(det_mob_copy, new_det_mob)) self.wait() def get_matrix(self): matrix = Matrix(np.array(self.t_matrix).transpose()) matrix.set_column_colors(X_COLOR, Y_COLOR) matrix.next_to(self.title, DOWN, buff = 0.5) matrix.shift(2*LEFT) matrix_background = BackgroundRectangle(matrix) det_text = get_det_text(matrix, 0) det_text.remove(det_text.split()[-1]) return matrix_background, matrix, det_text class SecondDeterminantExample(NameDeterminant): CONFIG = { "t_matrix" : [[-1, -1], [1, -1]] } class DeterminantIsThree(NameDeterminant): CONFIG = { "t_matrix" : [[0, -1.5], [2, 1]] } class DeterminantIsOneHalf(NameDeterminant): CONFIG = { "t_matrix" : [[0.5, -0.5], [0.5, 0.5]], "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 0 }, } class DeterminantIsZero(NameDeterminant): CONFIG = { "t_matrix" : [[4, 2], [2, 1]], } class SecondDeterminantIsZeroExamlpe(NameDeterminant): CONFIG = { "t_matrix" : [[0, 0], [0, 0]], "show_basis_vectors" : False } class NextFewVideos(Scene): def construct(self): icon = SVGMobject("video_icon") icon.center() icon.set_width(FRAME_WIDTH/12.) icon.set_stroke(color = WHITE, width = 0) icon.set_fill(WHITE, opacity = 1) icons = VMobject(*[icon.copy() for x in range(10)]) icons.set_submobject_colors_by_gradient(BLUE_A, BLUE_D) icons.arrange(RIGHT) icons.to_edge(LEFT) self.play( FadeIn(icons, lag_ratio = 0.5), run_time = 3 ) self.wait() class UnderstandingBeforeApplication(TeacherStudentsScene): def construct(self): self.setup() self.teacher_says(""" Just the visual understanding for now """) self.random_blink() self.wait() class WhatIveSaidSoFar(TeacherStudentsScene): def construct(self): self.setup() self.teacher_says(""" What I've said so far is not quite right... """) self.wait() class NegativeDeterminant(Scene): def construct(self): numerical_matrix = [[1, 2], [3, 4]] matrix = Matrix(numerical_matrix) matrix.set_column_colors(X_COLOR, Y_COLOR) det_text = get_det_text(matrix, np.linalg.det(numerical_matrix)) words = OldTexText(""" How can you scale area by a negative number? """) words.set_color(YELLOW) words.to_corner(UP+RIGHT) det_num = det_text.split()[-1] arrow = Arrow(words.get_bottom(), det_num) self.add(matrix) self.play(Write(det_text)) self.wait() self.play( Write(words, run_time = 2), ShowCreation(arrow) ) self.play(det_num.set_color, YELLOW) self.wait() class FlipSpaceOver(Scene): def construct(self): plane1 = NumberPlane(y_radius = FRAME_X_RADIUS) plane2 = NumberPlane( y_radius = FRAME_X_RADIUS, color = RED_D, secondary_color = RED_E ) axis = UP for word, plane in ("Front", plane1), ("Back", plane2): text = OldTexText(word) if word == "Back": text.rotate(np.pi, axis = axis) text.scale(2) text.next_to(ORIGIN, RIGHT).to_edge(UP) text.add_background_rectangle() plane.add(text) self.play(ShowCreation( plane1, lag_ratio = 0.5, run_time = 1 )) self.wait() self.play(Rotate( plane1, axis = axis, rate_func = lambda t : smooth(t/2), run_time = 1.5, path_arc = np.pi/2, )) self.remove(plane1) self.play(Rotate( plane2, axis = axis, rate_func = lambda t : smooth((t+1)/2), run_time = 1.5, path_arc = np.pi/2, )) self.wait() class RandyThinking(Scene): def construct(self): randy = Randolph().to_corner() bubble = randy.get_bubble() bubble.make_green_screen() self.play( randy.change_mode, "pondering", ShowCreation(bubble) ) self.wait() self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) class NegativeDeterminantTransformation(LinearTransformationScene): CONFIG = { "t_matrix" : [[1, 1], [2, -1]], } def construct(self): self.setup() self.add_title("Feels like flipping space") self.wait() self.apply_transposed_matrix(self.t_matrix) self.wait() class ThinkAboutFlippingPaper(Scene): def construct(self): pass class NegativeDeterminantTransformation2(NegativeDeterminantTransformation): CONFIG ={ "t_matrix" : [[-2, 1], [2, 1]] } class IHatJHatOrientation(NegativeDeterminantTransformation): def construct(self): self.setup() i_label, j_label = self.get_basis_vector_labels() self.add_transformable_label(self.i_hat, i_label, color = X_COLOR) self.add_transformable_label(self.j_hat, j_label, color = Y_COLOR) arc = Arc(start_angle = 0, angle = np.pi/2, color = YELLOW) arc.shift(0.5*(RIGHT+UP)).scale(1/1.6) arc.add_tip() words1 = OldTexText([ "$\\hat{\\jmath}$", "is to the", "left", "of", "$\\hat{\\imath}$", ]) words1.split()[0].set_color(Y_COLOR) words1.split()[2].set_color(YELLOW) words1.split()[-1].set_color(X_COLOR) words1.add_background_rectangle() words1.next_to(arc, UP+RIGHT) words2 = OldTexText([ "$L(\\hat{\\jmath})$", "is to the \\\\", "\\emph{right}", "of", "$L(\\hat{\\imath})$", ]) words2.split()[0].set_color(Y_COLOR) words2.split()[2].set_color(YELLOW) words2.split()[-1].set_color(X_COLOR) words2.add_background_rectangle() self.play(ShowCreation(arc)) self.play(Write(words1)) self.wait() self.remove(words1, arc) self.apply_transposed_matrix(self.t_matrix) arc.submobjects = [] arc.apply_function(self.get_matrix_transformation(self.t_matrix)) arc.add_tip() words2.next_to(arc, RIGHT) self.play( ShowCreation(arc), Write(words2, run_time = 2), ) self.wait() title = OldTexText("Orientation has been reversed") title.to_edge(UP) title.add_background_rectangle() self.play(Write(title, run_time = 1)) self.wait() class WriteNegativeDeterminant(NegativeDeterminantTransformation): def construct(self): self.setup() self.add_unit_square() matrix = Matrix(np.array(self.t_matrix).transpose()) matrix.next_to(ORIGIN, LEFT) matrix.to_edge(UP) matrix.set_column_colors(X_COLOR, Y_COLOR) det_text = get_det_text( matrix, determinant = np.linalg.det(self.t_matrix) ) three = VMobject(*det_text.split()[-1].split()[1:]) for mob in det_text.split(): if isinstance(mob, Tex): mob.add_background_rectangle() matrix_background = BackgroundRectangle(matrix) self.play( ShowCreation(matrix_background), Write(matrix), Write(det_text), ) self.add_foreground_mobject(matrix_background, matrix, det_text) self.wait() self.apply_transposed_matrix(self.t_matrix) self.play(three.copy().move_to, self.square) self.wait() class AltWriteNegativeDeterminant(WriteNegativeDeterminant): CONFIG = { "t_matrix" : [[2, -1], [1, -3]] } class WhyNegativeScaling(TeacherStudentsScene): def construct(self): self.setup() self.student_says(""" Why does negative area relate to orientation-flipping? """) other_students = np.array(self.get_students())[[0, 2]] self.play(*[ ApplyMethod(student.change_mode, "confused") for student in other_students ]) self.random_blink() self.wait() self.random_blink() class SlowlyRotateIHat(LinearTransformationScene): def construct(self): self.setup() self.add_unit_square() self.apply_transposed_matrix( [[-1, 0], [0, 1]], path_arc = np.pi, run_time = 30, rate_func=linear, ) class DeterminantGraphForRotatingIHat(Scene): def construct(self): t_axis = NumberLine( numbers_with_elongated_ticks = [], x_min = 0, x_max = 10, color = WHITE, ) det_axis = NumberLine( numbers_with_elongated_ticks = [], x_min = -2, x_max = 2, color = WHITE ) det_axis.rotate(np.pi/2) t_axis.next_to(ORIGIN, RIGHT, buff = 0) det_axis.move_to(t_axis.get_left()) axes = VMobject(det_axis, t_axis) graph = FunctionGraph(np.cos, x_min = 0, x_max = np.pi) graph.next_to(det_axis, RIGHT, buff = 0) graph.set_color(YELLOW) det_word = OldTexText("Det") det_word.next_to(det_axis, RIGHT, aligned_edge = UP) time_word = OldTexText("time") time_word.next_to(t_axis, UP) time_word.to_edge(RIGHT) everything = VMobject(axes, det_word, time_word, graph) everything.scale(1.5) self.add(axes, det_word, time_word) self.play(ShowCreation( graph, rate_func=linear, run_time = 10 )) class WhatAboutThreeDimensions(TeacherStudentsScene): def construct(self): self.setup() self.student_says(""" What about 3D transformations? """) self.random_blink() self.wait() self.random_blink() class Transforming3DCube(Scene): def construct(self): pass class NameParallelepiped(Scene): def construct(self): word = OldTexText("``Parallelepiped''") word.scale(2) pp_part1 = VMobject(*word.split()[:len(word.split())/2]) pp_part2 = VMobject(*word.split()[len(word.split())/2:]) pp_part1.set_submobject_colors_by_gradient(X_COLOR, Y_COLOR) pp_part2.set_submobject_colors_by_gradient(Y_COLOR, Z_COLOR) self.play(Write(word)) self.wait(2) class DeterminantIsVolumeOfParallelepiped(Scene): def construct(self): matrix = Matrix([[1, 0, 0.5], [0.5, 1, 0], [1, 0, 1]]) matrix.shift(3*LEFT) matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR) det_text = get_det_text(matrix) eq = OldTex("=") eq.next_to(det_text, RIGHT) words = OldTexText([ "Volume of this\\\\", "parallelepiped" ]) pp = words.split()[1] pp_part1 = VMobject(*pp.split()[:len(pp.split())/2]) pp_part2 = VMobject(*pp.split()[len(pp.split())/2:]) pp_part1.set_submobject_colors_by_gradient(X_COLOR, Y_COLOR) pp_part2.set_submobject_colors_by_gradient(Y_COLOR, Z_COLOR) words.next_to(eq, RIGHT) self.play(Write(matrix)) self.wait() self.play(Write(det_text), Write(words), Write(eq)) self.wait() class Degenerate3DTransformation(Scene): def construct(self): pass class WriteZeroDeterminant(Scene): def construct(self): matrix = Matrix([[1, 0, 1], [0.5, 1, 1.5], [1, 0, 1]]) matrix.shift(2*LEFT) matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR) det_text = get_det_text(matrix, 0) brace = Brace(matrix, DOWN) words = OldTexText(""" Columns must be linearly dependent """) words.set_color(YELLOW) words.next_to(brace, DOWN) self.play(Write(matrix)) self.wait() self.play(Write(det_text)) self.wait() self.play( GrowFromCenter(brace), Write(words, run_time = 2) ) self.wait() class AskAboutNegaive3DDeterminant(TeacherStudentsScene): def construct(self): self.setup() self.student_says(""" What would det$(M) < 0$ mean? """) self.random_blink() self.play(self.teacher.change_mode, "pondering") self.wait() self.random_blink() class OrientationReversing3DTransformation(Scene): def construct(self): pass class RightHandRule(Scene): CONFIG = { "flip" : False, "labels_tex" : ["\\hat{\\imath}", "\\hat{\\jmath}", "\\hat{k}"], "colors" : [X_COLOR, Y_COLOR, Z_COLOR], } def construct(self): hand = RightHand() v1 = Vector([-1.75, 0.5]) v2 = Vector([-1.4, -0.7]) v3 = Vector([0, 1.7]) vects = [v1, v2, v3] if self.flip: VMobject(hand, *vects).flip() v1_label, v2_label, v3_label = [ OldTex(label_tex).scale(1.5) for label_tex in self.labels_tex ] v1_label.next_to(v1.get_end(), UP) v2_label.next_to(v2.get_end(), DOWN) v3_label.next_to(v3.get_end(), UP) labels = [v1_label, v2_label, v3_label] # self.add(NumberPlane()) self.play( ShowCreation(hand.outline, run_time = 2, rate_func=linear), FadeIn(hand.inlines) ) self.wait() for vect, label, color in zip(vects, labels, self.colors): vect.set_color(color) label.set_color(color) vect.set_stroke(width = 8) self.play(ShowCreation(vect)) self.play(Write(label)) self.wait() class LeftHandRule(RightHandRule): CONFIG = { "flip" : True } class AskHowToCompute(TeacherStudentsScene): def construct(self): self.setup() student = self.get_students()[1] self.student_says("How do you \\\\ compute this?") self.play(student.change_mode, "confused") self.random_blink() self.wait() self.random_blink() class TwoDDeterminantFormula(Scene): def construct(self): eq = OldTexText("=") matrix = Matrix([["a", "b"], ["c", "d"]]) matrix.set_column_colors(X_COLOR, Y_COLOR) ma, mb, mc, md = matrix.get_entries().split() ma.shift(0.1*DOWN) mc.shift(0.7*mc.get_height()*DOWN) det_text = get_det_text(matrix) VMobject(matrix, det_text).next_to(eq, LEFT) formula = OldTex(list("ad-bc")) formula.next_to(eq, RIGHT) formula.shift(0.1*UP) a, d, minus, b, c = formula.split() VMobject(a, c).set_color(X_COLOR) VMobject(b, d).set_color(Y_COLOR) for mob in mb, mc, b, c: if mob is c: mob.zero = OldTex("\\cdot 0") else: mob.zero = OldTex("0") mob.zero.move_to(mob, aligned_edge = DOWN+LEFT) mob.zero.set_color(mob.get_color()) mob.original = mob.copy() c.zero.shift(0.1*RIGHT) self.add(matrix) self.play(Write(det_text, run_time = 1)) self.play(Write(eq), Write(formula)) self.wait() self.play(*[ Transform(m, m.zero) for m in (mb, mc, b, c) ]) self.wait() for pair in (mb, b), (mc, c): self.play(*[ Transform(m, m.original) for m in pair ]) self.wait() class TwoDDeterminantFormulaIntuition(LinearTransformationScene): def construct(self): self.setup() self.add_unit_square() a, b, c, d = 3, 2, 3.5, 2 self.wait() self.apply_transposed_matrix([[a, 0], [0, 1]]) i_brace = Brace(self.i_hat, DOWN) width = OldTex("a").scale(1.5) i_brace.put_at_tip(width) width.set_color(X_COLOR) width.add_background_rectangle() self.play(GrowFromCenter(i_brace), Write(width)) self.wait() self.apply_transposed_matrix([[1, 0], [0, d]]) side_brace = Brace(self.square, RIGHT) height = OldTex("d").scale(1.5) side_brace.put_at_tip(height) height.set_color(Y_COLOR) height.add_background_rectangle() self.play(GrowFromCenter(side_brace), Write(height)) self.wait() self.apply_transposed_matrix( [[1, 0], [float(b)/d, 1]], added_anims = [ ApplyMethod(m.shift, b*RIGHT) for m in (side_brace, height) ] ) self.wait() self.play(*list(map(FadeOut, [i_brace, side_brace, width, height]))) matrix1 = np.dot( [[a, b], [c, d]], np.linalg.inv([[a, b], [0, d]]) ) matrix2 = np.dot( [[a, b], [-c, d]], np.linalg.inv([[a, b], [c, d]]) ) self.apply_transposed_matrix(matrix1.transpose(), path_arc = 0) self.wait() self.apply_transposed_matrix(matrix2.transpose(), path_arc = 0) self.wait() class FullFormulaExplanation(LinearTransformationScene): def construct(self): self.setup() self.add_unit_square() self.apply_transposed_matrix([[3, 1], [1, 2]], run_time = 0) self.add_braces() self.add_polygons() self.show_formula() def get_matrix(self): matrix = Matrix([["a", "b"], ["c", "d"]]) matrix.set_column_colors(X_COLOR, Y_COLOR) ma, mb, mc, md = matrix.get_entries().split() ma.shift(0.1*DOWN) mc.shift(0.7*mc.get_height()*DOWN) matrix.shift(2*DOWN+4*LEFT) return matrix def add_polygons(self): a = self.i_hat.get_end()[0]*RIGHT b = self.j_hat.get_end()[0]*RIGHT c = self.i_hat.get_end()[1]*UP d = self.j_hat.get_end()[1]*UP shapes_colors_and_tex = [ (Polygon(ORIGIN, a, a+c), MAROON, "ac/2"), (Polygon(ORIGIN, d+b, d, d), TEAL, "\\dfrac{bd}{2}"), (Polygon(a+c, a+b+c, a+b+c, a+b+c+d), TEAL, "\\dfrac{bd}{2}"), (Polygon(b+d, a+b+c+d, b+c+d), MAROON, "ac/2"), (Polygon(a, a+b, a+b+c, a+c), PINK, "bc"), (Polygon(d, d+b, d+b+c, d+c), PINK, "bc"), ] everyone = VMobject() for shape, color, tex in shapes_colors_and_tex: shape.set_stroke(width = 0) shape.set_fill(color = color, opacity = 0.7) tex_mob = OldTex(tex) tex_mob.scale(0.7) tex_mob.move_to(shape.get_center_of_mass()) everyone.add(shape, tex_mob) self.play(FadeIn( everyone, lag_ratio = 0.5, run_time = 1 )) def add_braces(self): a = self.i_hat.get_end()[0]*RIGHT b = self.j_hat.get_end()[0]*RIGHT c = self.i_hat.get_end()[1]*UP d = self.j_hat.get_end()[1]*UP quads = [ (ORIGIN, a, DOWN, "a"), (a, a+b, DOWN, "b"), (a+b, a+b+c, RIGHT, "c"), (a+b+c, a+b+c+d, RIGHT, "d"), (a+b+c+d, b+c+d, UP, "a"), (b+c+d, d+c, UP, "b"), (d+c, d, LEFT, "c"), (d, ORIGIN, LEFT, "d"), ] everyone = VMobject() for p1, p2, direction, char in quads: line = Line(p1, p2) brace = Brace(line, direction, buff = 0) text = brace.get_text(char) text.add_background_rectangle() if char in ["a", "c"]: text.set_color(X_COLOR) else: text.set_color(Y_COLOR) everyone.add(brace, text) self.play(Write(everyone), run_time = 1) def show_formula(self): matrix = self.get_matrix() det_text = get_det_text(matrix) f_str = "=(a+b)(c+d)-ac-bd-2bc=ad-bc" formula = OldTex(f_str) formula.next_to(det_text, RIGHT) everyone = VMobject(det_text, matrix, formula) everyone.set_width(FRAME_WIDTH - 1) everyone.next_to(DOWN, DOWN) background_rect = BackgroundRectangle(everyone) self.play( ShowCreation(background_rect), Write(everyone) ) self.wait() class ThreeDDetFormula(Scene): def construct(self): matrix = Matrix([list("abc"), list("def"), list("ghi")]) matrix.set_column_colors(X_COLOR, Y_COLOR, Z_COLOR) m1 = Matrix([["e", "f"], ["h", "i"]]) m1.set_column_colors(Y_COLOR, Z_COLOR) m2 = Matrix([["d", "f"], ["g", "i"]]) m2.set_column_colors(X_COLOR, Z_COLOR) m3 = Matrix([["d", "e"], ["g", "h"]]) m3.set_column_colors(X_COLOR, Y_COLOR) for m in matrix, m1, m2, m3: m.add(get_det_text(m)) a, b, c = matrix.get_entries().split()[:3] parts = it.starmap(VMobject, [ [matrix], [Tex("="), a.copy(), m1], [Tex("-"), b.copy(), m2], [Tex("+"), c.copy(), m3], ]) parts = list(parts) for part in parts: part.arrange(RIGHT, buff = 0.2) parts[1].next_to(parts[0], RIGHT) parts[2].next_to(parts[1], DOWN, aligned_edge = LEFT) parts[3].next_to(parts[2], DOWN, aligned_edge = LEFT) everyone = VMobject(*parts) everyone.center().to_edge(UP) for part in parts: self.play(Write(part)) self.wait(2) class QuizTime(TeacherStudentsScene): def construct(self): self.setup() self.teacher_says("Quiz time!") self.random_blink() self.wait() self.random_blink() class ProductProperty(Scene): def construct(self): lhs = OldTex([ "\\text{det}(", "M_1", "M_2", ")" ]) det, m1, m2, rp = lhs.split() m1.set_color(TEAL) m2.set_color(PINK) rhs = OldTex([ "=\\text{det}(", "M_1", ")\\text{det}(", "M_2", ")" ]) rhs.split()[1].set_color(TEAL) rhs.split()[3].set_color(PINK) rhs.next_to(lhs, RIGHT) formula = VMobject(lhs, rhs) formula.center() title = OldTexText("Explain in one sentence") title.set_color(YELLOW) title.next_to(formula, UP, buff = 0.5) self.play(Write(m1)) self.play(Write(m2)) self.wait() self.play(Write(det), Write(rp)) self.play(Write(rhs)) self.wait(2) self.play(Write(title)) self.wait(2) class NextVideo(Scene): def construct(self): title = OldTexText(""" Next video: Inverse matrices, column space and null space """) title.set_width(FRAME_WIDTH - 2) title.to_edge(UP) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait()
videos_3b1b/_2016/eola/thumbnails.py
from manim_imports_ext import * from _2016.eola.chapter9 import Jennifer, You class Chapter0(LinearTransformationScene): CONFIG = { "include_background_plane" : False, "t_matrix" : [[3, 1], [2, -1]] } def construct(self): self.setup() self.plane.fade() for mob in self.get_mobjects(): mob.set_stroke(width = 6) self.apply_transposed_matrix(self.t_matrix, run_time = 0) class Chapter1(Scene): def construct(self): arrow = Vector(2*UP+RIGHT) vs = OldTexText("vs.") array = Matrix([1, 2]) array.set_color(TEAL) everyone = VMobject(arrow, vs, array) everyone.arrange(RIGHT, buff = 0.5) everyone.set_height(4) self.add(everyone) class Chapter2(LinearTransformationScene): def construct(self): self.lock_in_faded_grid() vectors = VMobject(*[ Vector([x, y]) for x in np.arange(-int(FRAME_X_RADIUS)+0.5, int(FRAME_X_RADIUS)+0.5) for y in np.arange(-int(FRAME_Y_RADIUS)+0.5, int(FRAME_Y_RADIUS)+0.5) ]) vectors.set_submobject_colors_by_gradient(PINK, BLUE_E) words = OldTexText("Span") words.scale(3) words.to_edge(UP) words.add_background_rectangle() self.add(vectors, words) class Chapter3(Chapter0): CONFIG = { "t_matrix" : [[3, 0], [2, -1]] } class Chapter4p1(Chapter0): CONFIG = { "t_matrix" : [[1, 0], [1, 1]] } class Chapter4p2(Chapter0): CONFIG = { "t_matrix" : [[1, 2], [-1, 1]] } class Chapter5(LinearTransformationScene): def construct(self): self.plane.fade() self.add_unit_square() self.plane.set_stroke(width = 6) VMobject(self.i_hat, self.j_hat).set_stroke(width = 10) self.square.set_fill(YELLOW, opacity = 0.7) self.square.set_stroke(width = 0) self.apply_transposed_matrix(self.t_matrix, run_time = 0) class Chapter9(Scene): def construct(self): you = You() jenny = Jennifer() you.change_mode("erm") jenny.change_mode("speaking") you.shift(LEFT) jenny.shift(2*RIGHT) vector = Vector([3, 2]) vector.center().shift(2*DOWN) vector.set_stroke(width = 8) vector.tip.scale(2) you.coords = Matrix([3, 2]) jenny.coords = Matrix(["5/3", "1/3"]) for pi in jenny, you: pi.bubble = pi.get_bubble(SpeechBubble, width = 3, height = 3) if pi is you: pi.bubble.shift(MED_SMALL_BUFF*RIGHT) else: pi.coords.scale(0.8) pi.bubble.shift(MED_SMALL_BUFF*LEFT) pi.bubble.add_content(pi.coords) pi.add(pi.bubble, pi.coords) pi.look_at(vector) self.add(you, jenny, vector) class Chapter10(LinearTransformationScene): CONFIG = { "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_HEIGHT, "secondary_line_ratio" : 1 }, "include_background_plane" : False, } def construct(self): v_tex = "\\vec{\\textbf{v}}" eq = OldTex("A", v_tex, "=", "\\lambda", v_tex) eq.set_color_by_tex(v_tex, YELLOW) eq.set_color_by_tex("\\lambda", MAROON_B) eq.scale(3) eq.add_background_rectangle() eq.shift(2*DOWN) title = OldTexText( "Eigen", "vectors \\\\", "Eigen", "values" , arg_separator = "") title.scale(2.5) title.to_edge(UP) # title.set_color_by_tex("Eigen", MAROON_B) title[0].set_color(YELLOW) title[2].set_color(MAROON_B) title.add_background_rectangle() self.add_vector([-1, 1], color = YELLOW, animate = False) self.apply_transposed_matrix([[3, 0], [1, 2]]) self.plane.fade() self.remove(self.j_hat) self.add(eq, title)
videos_3b1b/_2016/eola/chapter8p2.py
from manim_imports_ext import * from _2016.eola.chapter5 import get_det_text from _2016.eola.chapter8 import * class OpeningQuote(Scene): def construct(self): words = OldTexText( "From [Grothendieck], I have also learned not", "to take glory in the ", "difficulty of a proof:", "difficulty means we have not understood.", "The idea is to be able to ", "paint a landscape", "in which the proof is obvious.", arg_separator = " " ) words.set_color_by_tex("difficulty of a proof:", RED) words.set_color_by_tex("paint a landscape", GREEN) words.set_width(FRAME_WIDTH - 2) words.to_edge(UP) author = OldTexText("-Pierre Deligne") author.set_color(YELLOW) author.next_to(words, DOWN, buff = 0.5) self.play(FadeIn(words)) self.wait(4) self.play(Write(author, run_time = 3)) self.wait() class CrossProductSymbols(Scene): def construct(self): v_tex, w_tex, p_tex = get_vect_tex(*"vwp") equation = OldTex( v_tex, "\\times", w_tex, "=", p_tex ) equation.set_color_by_tex(v_tex, V_COLOR) equation.set_color_by_tex(w_tex, W_COLOR) equation.set_color_by_tex(p_tex, P_COLOR) brace = Brace(equation[-1]) brace.stretch_to_fit_width(0.7) vector_text = brace.get_text("Vector") vector_text.set_color(RED) self.add(equation) self.play(*list(map(Write, [brace, vector_text]))) self.wait() class DeterminantTrickCopy(DeterminantTrick): pass class BruteForceVerification(Scene): def construct(self): v = Matrix(["v_1", "v_2", "v_3"]) w = Matrix(["w_1", "w_2", "w_3"]) v1, v2, v3 = v.get_entries() w1, w2, w3 = w.get_entries() v.set_color(V_COLOR) w.set_color(W_COLOR) def get_term(e1, e2, e3, e4): group = VGroup( e1.copy(), e2.copy(), OldTex("-"), e3.copy(), e4.copy(), ) group.arrange() return group cross = Matrix(list(it.starmap(get_term, [ (v2, w3, v3, w2), (v3, w1, v1, w3), (v2, w3, v3, w2), ]))) cross_product = VGroup( v.copy(), OldTex("\\times"), w.copy(), OldTex("="), cross.copy() ) cross_product.arrange() cross_product.scale(0.75) formula_word = OldTexText("Numerical formula") computation_words = OldTexText(""" Facts you could (painfully) verify computationally """) computation_words.scale(0.75) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) v_line = Line(UP, DOWN).scale(FRAME_Y_RADIUS) computation_words.to_edge(UP, buff = MED_SMALL_BUFF/2) h_line.next_to(computation_words, DOWN) formula_word.next_to(h_line, UP, buff = MED_SMALL_BUFF) computation_words.shift(FRAME_X_RADIUS*RIGHT/2) formula_word.shift(FRAME_X_RADIUS*LEFT/2) cross_product.next_to(formula_word, DOWN, buff = LARGE_BUFF) self.add(formula_word, computation_words) self.play( ShowCreation(h_line), ShowCreation(v_line), Write(cross_product) ) v_tex, w_tex = get_vect_tex(*"vw") v_dot, w_dot = [ OldTex( tex, "\\cdot", "(", v_tex, "\\times", w_tex, ")", "= 0" ) for tex in (v_tex, w_tex) ] theta_def = OldTex( "\\theta", "= \\cos^{-1} \\big(", v_tex, "\\cdot", w_tex, "/", "(||", v_tex, "||", "\\cdot", "||", w_tex, "||)", "\\big)" ) length_check = OldTex( "||", "(", v_tex, "\\times", w_tex, ")", "|| = ", "(||", v_tex, "||)", "(||", w_tex, "||)", "\\sin(", "\\theta", ")" ) last_point = h_line.get_center()+FRAME_X_RADIUS*RIGHT/2 max_width = FRAME_X_RADIUS-1 for mob in v_dot, w_dot, theta_def, length_check: mob.set_color_by_tex(v_tex, V_COLOR) mob.set_color_by_tex(w_tex, W_COLOR) mob.set_color_by_tex("\\theta", GREEN) mob.next_to(last_point, DOWN, buff = MED_SMALL_BUFF) if mob.get_width() > max_width: mob.set_width(max_width) last_point = mob self.play(FadeIn(mob)) self.wait() class ButWeCanDoBetter(TeacherStudentsScene): def construct(self): self.teacher_says("But we can do \\\\ better than that") self.play_student_changes(*["happy"]*3) self.random_blink(3) class Prerequisites(Scene): def construct(self): title = OldTexText("Prerequisites") title.to_edge(UP) title.set_color(YELLOW) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_width(FRAME_X_RADIUS - 1) left_rect, right_rect = [ rect.copy().shift(DOWN/2).to_edge(edge) for edge in (LEFT, RIGHT) ] chapter5 = OldTexText(""" \\centering Chapter 5 Determinants """) chapter7 = OldTexText(""" \\centering Chapter 7: Dot products and duality """) self.add(title) for chapter, rect in (chapter5, left_rect), (chapter7, right_rect): if chapter.get_width() > rect.get_width(): chapter.set_width(rect.get_width()) chapter.next_to(rect, UP) self.play( Write(chapter5), ShowCreation(left_rect) ) self.play( Write(chapter7), ShowCreation(right_rect) ) self.wait() class DualityReview(TeacherStudentsScene): def construct(self): words = OldTexText("Quick", "duality", "review") words[1].set_color_by_gradient(BLUE, YELLOW) self.teacher_says(words, target_mode = "surprised") self.play_student_changes("pondering") self.random_blink(2) class DotProductToTransformSymbol(Scene): CONFIG = { "vect_coords" : [2, 1] } def construct(self): v_mob = OldTex(get_vect_tex("v")) v_mob.set_color(V_COLOR) matrix = Matrix([self.vect_coords]) vector = Matrix(self.vect_coords) matrix.set_column_colors(X_COLOR, Y_COLOR) vector.set_column_colors(YELLOW) _input = Matrix(["x", "y"]) _input.get_entries().set_color_by_gradient(X_COLOR, Y_COLOR) left_input, right_input = [_input.copy() for x in range(2)] dot, equals = list(map(Tex, ["\\cdot", "="])) equation = VGroup( vector, dot, left_input, equals, matrix, right_input ) equation.arrange() left_brace = Brace(VGroup(vector, left_input)) right_brace = Brace(matrix, UP) left_words = left_brace.get_text("Dot product") right_words = right_brace.get_text("Transform") right_words.set_width(right_brace.get_width()) right_v_brace = Brace(right_input, UP) right_v_mob = v_mob.copy() right_v_brace.put_at_tip(right_v_mob) right_input.add(right_v_brace, right_v_mob) left_v_brace = Brace(left_input, UP) left_v_mob = v_mob.copy() left_v_brace.put_at_tip(left_v_mob) left_input.add(left_v_brace, left_v_mob) self.add(matrix, right_input) self.play( GrowFromCenter(right_brace), Write(right_words, run_time = 1) ) self.wait() self.play( Write(equals), Write(dot), Transform(matrix.copy(), vector), Transform(right_input.copy(), left_input) ) self.play( GrowFromCenter(left_brace), Write(left_words, run_time = 1) ) self.wait() class MathematicalWild(Scene): def construct(self): title = OldTexText("In the mathematical wild") title.to_edge(UP) self.add(title) randy = Randolph() randy.shift(DOWN) bubble = ThoughtBubble(width = 5, height = 4) bubble.write(""" \\centering Some linear transformation to the number line """) bubble.content.set_color(BLUE) bubble.content.shift(MED_SMALL_BUFF*UP/2) bubble.remove(*bubble[:-1]) bubble.add(bubble.content) bubble.next_to(randy.get_corner(UP+RIGHT), RIGHT) vector = Vector([1, 2]) vector.move_to(randy.get_corner(UP+LEFT), aligned_edge = DOWN+LEFT) dual_words = OldTexText("Dual vector") dual_words.set_color_by_gradient(BLUE, YELLOW) dual_words.next_to(vector, LEFT) self.add(randy) self.play(Blink(randy)) self.play(FadeIn(bubble)) self.play(randy.change_mode, "sassy") self.play(Blink(randy)) self.wait() self.play(randy.look, UP+LEFT) self.play( ShowCreation(vector), randy.change_mode, "raise_right_hand" ) self.wait() self.play(Write(dual_words)) self.play(Blink(randy)) self.wait() class ThreeStepPlan(Scene): def construct(self): title = OldTexText("The plan") title.set_color(YELLOW) title.to_edge(UP) h_line = Line(LEFT, RIGHT).scale(FRAME_X_RADIUS) h_line.next_to(title, DOWN) v_tex, w_tex = get_vect_tex(*"vw") v_text, w_text, cross_text = [ "$%s$"%s for s in (v_tex, w_tex, v_tex + "\\times" + w_tex) ] steps = [ OldTexText( "1. Define a 3d-to-1d", "linear \\\\", "transformation", "in terms of", v_text, "and", w_text ), OldTexText( "2. Find its", "dual vector" ), OldTexText( "3. Show that this dual is", cross_text ) ] linear, transformation = steps[0][1:1+2] steps[0].set_color_by_tex(v_text, V_COLOR) steps[0].set_color_by_tex(w_text, W_COLOR) steps[1][1].set_color_by_gradient(BLUE, YELLOW) steps[2].set_color_by_tex(cross_text, P_COLOR) VGroup(*steps).arrange( DOWN, aligned_edge = LEFT, buff = LARGE_BUFF ).next_to(h_line, DOWN, buff = MED_SMALL_BUFF) self.add(title) self.play(ShowCreation(h_line)) for step in steps: self.play(Write(step, run_time = 2)) self.wait() linear_transformation = OldTexText("Linear", "transformation") linear_transformation.next_to(h_line, DOWN, MED_SMALL_BUFF) det = self.get_det() rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(3.5) left_right_arrow = OldTex("\\Leftrightarrow") left_right_arrow.shift(DOWN) det.next_to(left_right_arrow, LEFT) rect.next_to(left_right_arrow, RIGHT) steps[0].remove(linear, transformation) self.play( Transform( VGroup(linear, transformation), linear_transformation ), *list(map(FadeOut, steps)) ) self.wait() self.play(Write(left_right_arrow)) self.play(Write(det)) self.play(ShowCreation(rect)) self.wait(0) def get_det(self): matrix = Matrix(np.array([ ["\\hat{\\imath}", "\\hat{\\jmath}", "\\hat{k}"], ["v_%d"%d for d in range(1, 4)], ["w_%d"%d for d in range(1, 4)], ]).T) matrix.set_column_colors(X_COLOR, V_COLOR, W_COLOR) matrix.get_mob_matrix()[1, 0].set_color(Y_COLOR) matrix.get_mob_matrix()[2, 0].set_color(Z_COLOR) VGroup(*matrix.get_mob_matrix()[1, 1:]).shift(0.15*DOWN) VGroup(*matrix.get_mob_matrix()[2, 1:]).shift(0.35*DOWN) det_text = get_det_text(matrix) det_text.add(matrix) return det_text class DefineDualTransform(Scene): def construct(self): self.add_title() self.show_triple_cross_product() self.write_function() self.introduce_dual_vector() self.expand_dot_product() self.ask_question() def add_title(self): title = OldTexText("What a student might think") title.not_real = OldTexText("Not the real cross product") for mob in title, title.not_real: mob.set_width(FRAME_X_RADIUS - 1) mob.set_color(RED) mob.to_edge(UP) self.add(title) self.title = title def show_triple_cross_product(self): colors = [WHITE, ORANGE, W_COLOR] tex_mobs = list(map(Tex, get_vect_tex(*"uvw"))) u_tex, v_tex, w_tex = tex_mobs arrays = [ Matrix(["%s_%d"%(s, d) for d in range(1, 4)]) for s in "uvw" ] defs_equals = VGroup() definitions = VGroup() for array, tex_mob, color in zip(arrays, tex_mobs, colors): array.set_column_colors(color) tex_mob.set_color(color) equals = OldTex("=") definition = VGroup(tex_mob, equals, array) definition.arrange(RIGHT) definitions.add(definition) defs_equals.add(equals) definitions.arrange(buff = MED_SMALL_BUFF) definitions.shift(2*DOWN) mobs_with_targets = list(it.chain( tex_mobs, *[a.get_entries() for a in arrays] )) for mob in mobs_with_targets: mob.target = mob.copy() matrix = Matrix(np.array([ [e.target for e in array.get_entries()] for array in arrays ]).T) det_text = get_det_text(matrix, background_rect = False) syms = times1, times2, equals = [ OldTex(sym) for sym in ("\\times", "\\times", "=",) ] triple_cross = VGroup( u_tex.target, times1, v_tex.target, times2, w_tex.target, equals ) triple_cross.arrange() final_mobs = VGroup(triple_cross, VGroup(det_text, matrix)) final_mobs.arrange() final_mobs.next_to(self.title, DOWN, buff = MED_SMALL_BUFF) for mob in definitions, final_mobs: mob.set_width(FRAME_X_RADIUS - 1) for array in arrays: brackets = array.get_brackets() brackets.target = matrix.get_brackets() mobs_with_targets.append(brackets) for def_equals in defs_equals: def_equals.target = equals mobs_with_targets.append(def_equals) self.play(FadeIn( definitions, run_time = 2, lag_ratio = 0.5 )) self.wait(2) self.play(*[ Transform(mob.copy(), mob.target) for mob in tex_mobs ] + [ Write(times1), Write(times2), ]) triple_cross.add(*self.get_mobjects_from_last_animation()[:3]) self.play(*[ Transform(mob.copy(), mob.target) for mob in mobs_with_targets if mob not in tex_mobs ]) u_entries = self.get_mobjects_from_last_animation()[:3] v_entries = self.get_mobjects_from_last_animation()[3:6] w_entries = self.get_mobjects_from_last_animation()[6:9] self.play(Write(det_text)) self.wait(2) self.det_text = det_text self.definitions = definitions self.u_entries = u_entries self.v_entries = v_entries self.w_entries = w_entries self.matrix = matrix self.triple_cross = triple_cross self.v_tex, self.w_tex = v_tex, w_tex self.equals = equals def write_function(self): brace = Brace(self.det_text, DOWN) number_text = brace.get_text("Number") self.play(Transform(self.title, self.title.not_real)) self.wait() self.play(FadeOut(self.definitions)) self.play( GrowFromCenter(brace), Write(number_text) ) self.wait() x, y, z = variables = list(map(Tex, "xyz")) for var, entry in zip(variables, self.u_entries): var.scale(0.8) var.move_to(entry) entry.target = var brace.target = Brace(z) brace.target.stretch_to_fit_width(0.5) number_text.target = brace.target.get_text("Variable") v_brace = Brace(self.matrix.get_mob_matrix()[0, 1], UP) w_brace = Brace(self.matrix.get_mob_matrix()[0, 2], UP) for vect_brace, tex in (v_brace, self.v_tex), (w_brace, self.w_tex): vect_brace.stretch_to_fit_width(brace.target.get_width()) new_tex = tex.copy() vect_brace.put_at_tip(new_tex) vect_brace.tex = new_tex func_tex = OldTex( "f\\left(%s\\right)"%matrix_to_tex_string(list("xyz")) ) func_tex.scale(0.7) func_input = Matrix(list("xyz")) func_input_template = VGroup(*func_tex[3:-2]) func_input.set_height(func_input_template.get_height()) func_input.next_to(VGroup(*func_tex[:3]), RIGHT) VGroup(*func_tex[-2:]).next_to(func_input, RIGHT) func_tex[0].scale(1.5) func_tex = VGroup( VGroup(*[func_tex[i] for i in (0, 1, 2, -2, -1)]), func_input ) func_tex.next_to(self.equals, LEFT) self.play( FadeOut(self.title), FadeOut(self.triple_cross), *[ Transform(mob, mob.target) for mob in [brace, number_text] ] ) self.play(*[ Transform(mob, mob.target) for mob in self.u_entries ]) self.play(*[ Write(VGroup(vect_brace, vect_brace.tex)) for vect_brace in (v_brace, w_brace) ]) self.wait() self.play(Write(func_tex)) self.wait() self.func_tex = func_tex self.variables_text = VGroup(brace, number_text) def introduce_dual_vector(self): everything = VGroup(*self.get_mobjects()) colors = [X_COLOR, Y_COLOR, Z_COLOR] q_marks = VGroup(*list(map(TexText, "???"))) q_marks.scale(2) q_marks.set_color_by_gradient(*colors) title = VGroup(OldTexText("This function is linear")) title.set_color(GREEN) title.to_edge(UP) matrix = Matrix([list(q_marks.copy())]) matrix.set_height(self.func_tex.get_height()/2) dual_vector = Matrix(list(q_marks)) dual_vector.set_height(self.func_tex.get_height()) dual_vector.get_brackets()[0].shift(0.2*LEFT) dual_vector.get_entries().shift(0.1*LEFT) dual_vector.scale(1.25) dual_dot = VGroup( dual_vector, OldTex("\\cdot").next_to(dual_vector) ) matrix_words = OldTexText(""" $1 \\times 3$ matrix encoding the 3d-to-1d linear transformation """) self.play( Write(title, run_time = 2), everything.shift, DOWN ) self.remove(everything) self.add(*everything) self.wait() func, func_input = self.func_tex func_input.target = func_input.copy() func_input.target.scale(1.2) func_input.target.move_to(self.func_tex, aligned_edge = RIGHT) matrix.next_to(func_input.target, LEFT) dual_dot.next_to(func_input.target, LEFT) matrix_words.next_to(matrix, DOWN, buff = 1.5) matrix_words.shift_onto_screen() matrix_arrow = Arrow( matrix_words.get_top(), matrix.get_bottom(), color = WHITE ) self.play( Transform(func, matrix), MoveToTarget(func_input), FadeOut(self.variables_text), ) self.wait() self.play( Write(matrix_words), ShowCreation(matrix_arrow) ) self.wait(2) self.play(*list(map(FadeOut, [matrix_words, matrix_arrow]))) self.play( Transform(func, dual_vector), Write(dual_dot[1]) ) self.wait() p_coords = VGroup(*list(map(Tex, [ "p_%d"%d for d in range(1, 4) ]))) p_coords.set_color(RED) p_array = Matrix(list(p_coords)) p_array.set_height(dual_vector.get_height()) p_array.move_to(dual_vector, aligned_edge = RIGHT) p_brace = Brace(p_array, UP) p_tex = OldTex(get_vect_tex("p")) p_tex.set_color(P_COLOR) p_brace.put_at_tip(p_tex) self.play( GrowFromCenter(p_brace), Write(p_tex) ) self.play(Transform( func, p_array, run_time = 2, lag_ratio = 0.5 )) self.remove(func) self.add(p_array) self.wait() self.play(FadeOut(title)) self.wait() self.p_array = p_array self.input_array = func_input def expand_dot_product(self): everything = VGroup(*self.get_mobjects()) self.play(everything.to_edge, UP) self.remove(everything) self.add(*everything) to_fade = VGroup() p_entries = self.p_array.get_entries() input_entries = self.input_array.get_entries() dot_components = VGroup() for p, x, i in zip(p_entries, input_entries, it.count()): if i == 2: x.sym = OldTex("=") else: x.sym = OldTex("+") p.sym = OldTex("\\cdot") p.target = p.copy().scale(2) x.target = x.copy().scale(2) component = VGroup(p.target, p.sym, x.target, x.sym) component.arrange() dot_components.add(component) dot_components.arrange() dot_components.next_to(ORIGIN, LEFT) dot_components.shift(1.5*DOWN) dot_arrow = Arrow(self.p_array.get_corner(DOWN+RIGHT), dot_components) to_fade.add(dot_arrow) self.play(ShowCreation(dot_arrow)) new_ps = VGroup() for p, x in zip(p_entries, input_entries): self.play( MoveToTarget(p.copy()), MoveToTarget(x.copy()), Write(p.sym), Write(x.sym) ) mobs = self.get_mobjects_from_last_animation() new_ps.add(mobs[0]) to_fade.add(*mobs[1:]) self.wait() x, y, z = self.u_entries v1, v2, v3 = self.v_entries w1, w2, w3 = self.w_entries cross_components = VGroup() quints = [ (x, v2, w3, v3, w2), (y, v3, w1, v1, w3), (z, v1, w2, v2, w1), ] quints = [ [m.copy() for m in quint] for quint in quints ] for i, quint in enumerate(quints): sym_strings = ["(", "\\cdot", "-", "\\cdot", ")"] if i < 2: sym_strings[-1] += "+" syms = list(map(Tex, sym_strings)) for mob, sym in zip(quint, syms): mob.target = mob.copy() mob.target.scale(1.5) mob.sym = sym quint_targets = [mob.target for mob in quint] component = VGroup(*it.chain(*list(zip(quint_targets, syms)))) component.arrange() cross_components.add(component) to_fade.add(syms[0], syms[-1], quint[0]) cross_components.arrange(DOWN, aligned_edge = LEFT, buff = MED_SMALL_BUFF) cross_components.next_to(dot_components, RIGHT) for quint in quints: self.play(*[ ApplyMethod(mob.set_color, YELLOW) for mob in quint ]) self.wait(0.5) self.play(*[ MoveToTarget(mob) for mob in quint ] + [ Write(mob.sym) for mob in quint ]) self.wait() self.play( ApplyFunction( lambda m : m.arrange( DOWN, buff = MED_SMALL_BUFF+SMALL_BUFF ).next_to(cross_components, LEFT), new_ps ), *list(map(FadeOut, to_fade)) ) self.play(*[ Write(OldTex("=").next_to(p, buff = 2*SMALL_BUFF)) for p in new_ps ]) equals = self.get_mobjects_from_last_animation() self.wait(2) everything = everything.copy() self.play( FadeOut(VGroup(*self.get_mobjects())), Animation(everything) ) self.clear() self.add(everything) def ask_question(self): everything = VGroup(*self.get_mobjects()) p_tex = "$%s$"%get_vect_tex("p") question = OldTexText( "What vector", p_tex, "has \\\\ the property that" ) question.to_edge(UP) question.set_color(YELLOW) question.set_color_by_tex(p_tex, P_COLOR) everything.target = everything.copy() everything.target.next_to( question, DOWN, buff = MED_SMALL_BUFF ) self.play( MoveToTarget(everything), Write(question) ) self.wait() class WhyAreWeDoingThis(TeacherStudentsScene): def construct(self): self.student_says( "Um...why are \\\\ we doing this?", target_mode = "confused" ) self.random_blink() self.play(self.get_teacher().change_mode, "erm") self.play_student_changes("plain", "confused", "raise_left_hand") self.random_blink() self.play_student_changes("pondering", "confused", "raise_left_hand") self.random_blink(5) class ThreeDTripleCrossProduct(Scene): pass #Simple parallelepiped class ThreeDMovingVariableVector(Scene): pass #white u moves around class ThreeDMovingVariableVectorWithCrossShowing(Scene): pass #white u moves around, red p is present class NowForTheCoolPart(TeacherStudentsScene): def construct(self): self.teacher_says( "Now for the\\\\", "cool part" ) self.play_student_changes(*["happy"]*3) self.random_blink(2) self.teacher_says( "Let's answer the same question,\\\\", "but this time geometrically" ) self.play_student_changes(*["pondering"]*3) self.random_blink(2) class ThreeDDotProductProjection(Scene): pass # class DotProductWords(Scene): def construct(self): p_tex = "$%s$"%get_vect_tex("p") p_mob = OldTexText(p_tex) p_mob.scale(1.5) p_mob.set_color(P_COLOR) input_array = Matrix(list("xyz")) dot_product = VGroup(p_mob, Dot(radius = 0.07), input_array) dot_product.arrange(buff = MED_SMALL_BUFF/2) equals = OldTex("=") dot_product.next_to(equals, LEFT) words = VGroup(*it.starmap(TexText, [ ("(Length of projection)",), ("(Length of ", p_tex, ")",) ])) times = OldTex("\\times") words[1].set_color_by_tex(p_tex, P_COLOR) words[0].next_to(equals, RIGHT) words[1].next_to(words[0], DOWN, aligned_edge = LEFT) times.next_to(words[0], RIGHT) everyone = VGroup(dot_product, equals, times, words) everyone.center().set_width(FRAME_X_RADIUS - 1) self.add(dot_product) self.play(Write(equals)) self.play(Write(words[0])) self.wait() self.play( Write(times), Write(words[1]) ) self.wait() class ThreeDProjectToPerpendicular(Scene): pass # class GeometricVolumeWords(Scene): def construct(self): v_tex, w_tex = [ "$%s$"%s for s in get_vect_tex(*"vw") ] words = VGroup( OldTexText("(Area of", "parallelogram", ")$\\times$"), OldTexText( "(Component of $%s$"%matrix_to_tex_string(list("xyz")), "perpendicular to", v_tex, "and", w_tex, ")" ) ) words[0].set_color_by_tex("parallelogram", BLUE) words[1].set_color_by_tex(v_tex, ORANGE) words[1].set_color_by_tex(w_tex, W_COLOR) words.arrange(RIGHT) words.set_width(FRAME_WIDTH - 1) words.to_edge(DOWN, buff = SMALL_BUFF) for word in words: self.play(Write(word)) self.wait() class WriteXYZ(Scene): def construct(self): self.play(Write(Matrix(list("xyz")))) self.wait() class ThreeDDotProductWithCross(Scene): pass class CrossVectorEmphasisWords(Scene): def construct(self): v_tex, w_tex = ["$%s$"%s for s in get_vect_tex(*"vw")] words = [ OldTexText("Perpendicular to", v_tex, "and", w_tex), OldTexText("Length = (Area of ", "parallelogram", ")") ] for word in words: word.set_color_by_tex(v_tex, ORANGE) word.set_color_by_tex(w_tex, W_COLOR) word.set_color_by_tex("parallelogram", BLUE) self.play(Write(word)) self.wait() self.play(FadeOut(word)) class NextVideo(Scene): def construct(self): title = OldTexText(""" Next video: Change of basis """) title.to_edge(UP, buff = MED_SMALL_BUFF/2) rect = Rectangle(width = 16, height = 9, color = BLUE) rect.set_height(6) rect.next_to(title, DOWN) self.add(title) self.play(ShowCreation(rect)) self.wait() class ChangeOfBasisPreview(LinearTransformationScene): CONFIG = { "include_background_plane" : False, "foreground_plane_kwargs" : { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "secondary_line_ratio" : 0 }, "t_matrix" : [[2, 1], [-1, 1]], "i_target_color" : YELLOW, "j_target_color" : MAROON_B, "sum_color" : PINK, "vector" : [-1, 2], } def construct(self): randy = Randolph() pinky = Mortimer(color = PINK) randy.to_corner(DOWN+LEFT) pinky.to_corner(DOWN+RIGHT) self.plane.fade() self.add_foreground_mobject(randy, pinky) coords = Matrix(self.vector) coords.add_to_back(BackgroundRectangle(coords)) self.add_foreground_mobject(coords) coords.move_to( randy.get_corner(UP+RIGHT), aligned_edge = DOWN+LEFT ) coords.target = coords.copy() coords.target.move_to( pinky.get_corner(UP+LEFT), aligned_edge = DOWN+RIGHT ) self.play( Write(coords), randy.change_mode, "speaking" ) self.scale_basis_vectors() self.apply_transposed_matrix( self.t_matrix, added_anims = [ MoveToTarget(coords), ApplyMethod(pinky.change_mode, "speaking"), ApplyMethod(randy.change_mode, "plain"), ] ) self.play( randy.change_mode, "erm", self.i_hat.set_color, self.i_target_color, self.j_hat.set_color, self.j_target_color, ) self.i_hat.color = self.i_target_color self.j_hat.color = self.j_target_color self.scale_basis_vectors() def scale_basis_vectors(self): for vect in self.i_hat, self.j_hat: vect.save_state() self.play(self.i_hat.scale, self.vector[0]) self.play(self.j_hat.scale, self.vector[1]) self.play(self.j_hat.shift, self.i_hat.get_end()) sum_vect = Vector(self.j_hat.get_end(), color = self.sum_color) self.play(ShowCreation(sum_vect)) self.wait(2) self.play( FadeOut(sum_vect), self.i_hat.restore, self.j_hat.restore, ) self.wait()