file_path
stringclasses
1 value
content
stringlengths
0
219k
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 *
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
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" window_position: UR window_monitor: 0 full_screen: False embed_exception_mode: "Minimal"
#!/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)
from manim_imports_ext import * from _2022.wordle.simulations import * # Scene types class WordleScene(Scene): n_letters = 5 grid_height = 6 font_to_square_height = 65 grid_center = ORIGIN secret_word = None color_map = { 0: "#797C7E", # GREY 1: "#C6B566", # YELLOW 2: GREEN_D, # GREEN } uniform_prior = False wordle_based_prior = False freq_prior = True reveal_run_time = 2 reveal_lag_ratio = 0.5 CONFIG = {"random_seed": None} def setup(self): self.all_words = self.get_word_list() self.priors = self.get_priors() if self.secret_word is None: s_words = get_word_list(short=True) self.secret_word = random.choice(s_words) self.guesses = [] self.patterns = [] self.possibilities = self.get_initial_possibilities() self.add_grid() def get_word_list(self): return get_word_list() def get_initial_possibilities(self): return get_word_list() def get_priors(self): words = self.all_words if self.uniform_prior: return dict((w, 1) for w in words) elif self.wordle_based_prior: return get_true_wordle_prior() else: return get_frequency_based_priors() def get_pattern(self, guess): return get_pattern(guess, self.secret_word) def get_current_entropy(self): weights = get_weights(self.possibilities, self.priors) return entropy_of_distributions(weights) ## def add_grid(self): buff = 0.1 row = Square(side_length=1).get_grid(1, self.n_letters, buff=buff) grid = row.get_grid(6, 1, buff=buff) grid.set_height(self.grid_height) grid.move_to(self.grid_center) grid.set_stroke(WHITE, 2) grid.words = VGroup() grid.pending_word = VGroup() grid.add(grid.words, grid.pending_word) grid.pending_pattern = None grid.add_updater(lambda m: m) self.grid = grid self.add(grid) def get_curr_row(self): return self.grid[len(self.grid.words)] def get_curr_square(self): row = self.get_curr_row() return row[len(self.grid.pending_word)] def add_letter(self, letter): grid = self.grid if len(grid.pending_word) == len(grid[0]): return letter_mob = self.get_letter_in_square(letter, self.get_curr_square()) grid.pending_word.add(letter_mob) def get_letter_in_square(self, letter, square): font_size = self.font_to_square_height * square.get_height() letter_mob = Text(letter.upper(), font="Consolas", font_size=font_size) letter_mob.move_to(square) return letter_mob def delete_letter(self): if len(self.grid.pending_word) == 0: return letter_mob = self.grid.pending_word[-1] self.grid.pending_word.remove(letter_mob) def add_word(self, word, wait_time_per_letter=0.1): for letter in word: self.add_letter(letter) self.wait( wait_time_per_letter, ignore_presenter_mode=True ) def pending_word_as_string(self): return "".join( t.text.lower() for t in self.grid.pending_word ) def is_valid_guess(self): guess = self.pending_word_as_string() return guess in self.all_words def reveal_pattern(self, pattern=None, animate=True): grid = self.grid guess = self.pending_word_as_string() if not self.is_valid_guess(): self.shake_word_out() return False if pattern is None: pattern = self.get_pattern(guess) if pattern is None: return False self.show_pattern(pattern, animate=animate) self.guesses.append(guess) self.patterns.append(pattern) grid.words.add(grid.pending_word.copy()) grid.pending_word.set_submobjects([]) grid.pending_pattern = None self.refresh_possibilities(guess, pattern) # Win condition if self.has_won(): self.win_animation() return True def refresh_possibilities(self, guess, pattern): self.possibilities = get_possible_words( guess, pattern, self.possibilities ) def shake_word_out(self): row = self.get_curr_row() c = row.get_center().copy() func = bezier([0, 0, 1, 1, -1, -1, 0, 0]) self.play(UpdateFromAlphaFunc( VGroup(row, self.grid.pending_word), lambda m, a: m.move_to(c + func(a) * RIGHT), run_time=0.5, )) self.grid.pending_word.set_submobjects([]) def show_pattern(self, pattern, animate=False, added_anims=[]): row = self.get_curr_row() colors = self.get_colors(pattern) if animate: self.animate_color_change(row, self.grid.pending_word, colors, added_anims) else: self.set_row_colors(row, colors) self.grid.pending_pattern = pattern def set_row_colors(self, row, colors): for square, color in zip(row, colors): square.set_fill(color, 1) def animate_color_change(self, row, word, colors, added_anims=[]): colors.extend((len(row) - len(colors)) * [self.color_map[0]]) for square, color in zip(row, colors): square.future_color = color def alpha_func(mob, alpha): if not hasattr(mob, 'initial_height'): mob.initial_height = mob.get_height() mob.set_height( mob.initial_height * max(abs(interpolate(1, -1, alpha)), 1e-6), stretch=True ) if isinstance(mob, Square) and alpha > 0.5: mob.set_fill(mob.future_color, 1) mobjects = self.mobjects self.play( *( LaggedStart( *( UpdateFromAlphaFunc(sm, alpha_func) for sm in mob ), lag_ratio=self.reveal_lag_ratio, run_time=self.reveal_run_time, ) for mob in (row, word) ), *added_anims ) self.clear() self.add(*mobjects) def get_colors(self, pattern): return [self.color_map[key] for key in pattern_to_int_list(pattern)] def win_animation(self): grid = self.grid row = grid[len(grid.words) - 1] letters = grid.words[-1] mover = VGroup(*( VGroup(square, letter) for square, letter in zip(row, letters) )) y = row.get_y() bf = bezier([0, 0, 1, 1, -1, -1, 0, 0]) self.play( LaggedStart(*( UpdateFromAlphaFunc(sm, lambda m, a: m.set_y(y + 0.2 * bf(a))) for sm in mover ), lag_ratio=0.1, run_time=1.5), LaggedStart(*( Flash(letter, line_length=0.1, flash_radius=0.4) for letter in letters ), lag_ratio=0.3, run_time=1.5), ) def has_won(self): return len(self.patterns) > 0 and self.patterns[-1] == 3**5 - 1 @staticmethod def get_grid_of_words(all_words, n_rows, n_cols, dots_index=-5, sort_key=None, font_size=24): if sort_key: all_words = list(sorted(all_words, key=sort_key)) subset = all_words[:n_rows * n_cols] show_ellipsis = len(subset) < len(all_words) if show_ellipsis: subset[dots_index] = "..." if n_cols == 1 else "....." subset[dots_index + 1:] = all_words[dots_index + 1:] full_string = "" for i, word in zip(it.count(1), subset): full_string += str(word) if i % n_cols == 0: full_string += " \n" else: full_string += " " full_text_mob = Text(full_string, font="Consolas", font_size=font_size) result = VGroup() for word in subset: part = full_text_mob.get_part_by_text(word) part.text = word result.add(part) if show_ellipsis and n_cols == 1: result[dots_index].rotate(PI / 2) result[dots_index].next_to(result[dots_index - 1], DOWN, SMALL_BUFF) result[dots_index + 1:].next_to(result[dots_index], DOWN, SMALL_BUFF) result.set_color(GREY_A) result.words = subset return result @staticmethod def patterns_to_squares(patterns, color_map=None): if color_map is None: color_map = WordleScene.color_map row = Square().get_grid(1, 5, buff=SMALL_BUFF) rows = row.get_grid(len(patterns), 1, buff=SMALL_BUFF) rows.set_stroke(WHITE, 1) for pattern, row in zip(patterns, rows): for square, key in zip(row, pattern_to_int_list(pattern)): square.set_fill(color_map[key], 1) return rows # Interactive parts def on_key_press(self, symbol, modifiers): try: char = chr(symbol) except OverflowError: log.warning("The value of the pressed key is too large.") return is_letter = (ord('a') <= ord(char) <= ord('z')) if is_letter: self.add_letter(char) elif symbol == 65288: # Delete self.delete_letter() elif symbol == 65293: # Enter self.reveal_pattern() if char == 'q' and modifiers == 1: self.delete_letter() self.quit_interaction = True if not is_letter: super().on_key_press(symbol, modifiers) class WordleSceneWithAnalysis(WordleScene): grid_center = [-1.75, 1, 0] grid_height = 4.5 look_two_ahead = False show_prior = True n_top_picks = 13 entropy_color = TEAL_C prior_color = BLUE_C weight_to_prob = 3.0 pre_computed_first_guesses = [] def setup(self): self.wait_to_proceed = True super().setup() self.show_possible_words() self.add_count_title() self.add_guess_value_grid_title() self.init_guess_value_grid() self.info_labels = VGroup() self.add(self.info_labels) def construct(self): self.show_guess_values() def add_guess_value_grid_title(self): titles = VGroup( Text("Top picks"), Text("E[Info.]", color=self.entropy_color), ) if self.look_two_ahead: titles.add(OldTexText("E[Info$_2$]", color=self.entropy_color)[0]) if self.show_prior: titles.add(OldTex("p(\\text{word})", color=self.prior_color)) titles.scale(0.7) titles.arrange(RIGHT, buff=MED_LARGE_BUFF) titles.set_max_width(5) low_y = titles[0][0].get_bottom()[1] for title in titles: first = title.family_members_with_points()[0] title.shift((low_y - first.get_bottom()[1]) * UP) underline = Underline(title) underline.match_y(first.get_bottom() + 0.025 * DOWN) underline.set_stroke(WHITE, 2) underline.scale(1.1) title.add_to_back(underline) title.set_backstroke() underline.set_stroke(GREY_C, 2) titles.to_edge(UP, buff=MED_SMALL_BUFF) titles.to_edge(RIGHT, buff=MED_SMALL_BUFF) self.add(titles) self.guess_value_grid_titles = titles def add_count_title(self): title = VGroup( Text("# Possibilities"), Text("/"), Text("Uncertainty", color=self.entropy_color), ) title.arrange(RIGHT, buff=SMALL_BUFF) title.match_width(self.count_label).scale(1.1) title.next_to(self.count_label, UP, buff=MED_LARGE_BUFF) self.count_title = title self.add(title) def init_guess_value_grid(self): titles = self.guess_value_grid_titles line = Line().match_width(titles) line.set_stroke(GREY_C, 1) lines = line.get_grid(self.n_top_picks, 1, buff=0.5) lines.next_to(titles, DOWN, buff=0.75) self.guess_value_grid_lines = lines self.guess_value_grid = VGroup() def get_count_label(self): score = len(self.grid.words) label = VGroup( Integer(len(self.possibilities), edge_to_fix=UR), Text("Pos,"), DecimalNumber(self.get_current_entropy(), edge_to_fix=UR, color=self.entropy_color), Text("Bits", color=self.entropy_color), ) label.arrange( RIGHT, buff=MED_SMALL_BUFF, aligned_edge=UP, ) label.scale(0.6) label.next_to(self.grid[score], LEFT) return label def reveal_pattern(self, pattern=None, animate=True): is_valid_guess = self.is_valid_guess() if is_valid_guess: self.isolate_guessed_row() did_fill = super().reveal_pattern(pattern, animate) if not did_fill: return False if self.presenter_mode: while self.wait_to_proceed: self.update_frame(1 / self.camera.frame_rate) self.wait_to_proceed = True if is_valid_guess and not self.has_won(): self.show_possible_words() self.wait() self.show_guess_values() if self.has_won(): self.play( FadeOut(self.guess_value_grid, RIGHT), FadeOut(self.guess_value_grid_titles, RIGHT), ) def show_pattern(self, pattern, *args, **kwargs): guess = self.pending_word_as_string() new_possibilities = get_possible_words( guess, pattern, self.possibilities ) for word_mob, word, bar in zip(self.shown_words, self.shown_words.words, self.prob_bars): if word not in new_possibilities and word != "...": word_mob.set_fill(RED, 0.5) bar.set_opacity(0.2) self.show_pattern_information(guess, pattern, new_possibilities) super().show_pattern(pattern, *args, **kwargs) def show_pattern_information(self, guess, pattern, new_possibilities): # Put bits label next to pattern weights = get_weights(self.possibilities, self.priors) prob = sum( weight for word, weight in zip(self.possibilities, weights) if word in new_possibilities ) info = -math.log2(prob) ref = self.count_label[2:] info_label = VGroup( DecimalNumber(info), Text("Bits") ) info_label.set_color(RED) info_label.arrange(RIGHT) info_label.match_height(ref) info_label.next_to(self.get_curr_row(), RIGHT, buff=MED_SMALL_BUFF) info_label.match_y(ref) self.info_labels.add(info_label) def isolate_guessed_row(self): guess = self.pending_word_as_string() rows = self.guess_value_grid row_words = [row[0].text for row in rows] if guess in row_words: row = rows[row_words.index(guess)] rows.set_opacity(0.2) row[:-1].set_fill(YELLOW, 1) else: new_row = self.get_guess_value_row( self.guess_value_grid_lines[0], guess, ) rows.shift(DOWN) rows.add(new_row) def get_shown_words(self, font_size=24): return self.get_grid_of_words( self.possibilities, n_rows=20 - 2 * len(self.grid.words), n_cols=1 ) def get_probability_bars(self, shown_words, max_width=1.0): mobs = shown_words words = shown_words.words probs = [self.priors.get(w, 0) for w in words] # Unnormalized height = mobs[0].get_height() * 0.7 bars = VGroup(*( Rectangle( width=prob * max_width, height=height, fill_color=self.prior_color, fill_opacity=0.7, stroke_width=0.5 * (prob > 0), stroke_color=self.prior_color ) for prob in probs )) for bar, mob in zip(bars, mobs): bar.next_to(mob, RIGHT, SMALL_BUFF) bar.align_to(bars[0], LEFT) # if not self.show_prior: # bars.set_opacity(0) return bars def show_possible_words(self): shown_words = self.get_shown_words() count_label = self.get_count_label() shown_words.next_to(count_label[:2], DOWN, buff=0.35) prob_bars = self.get_probability_bars(shown_words) if len(self.grid.words) > 0: # Set up label transition prev_count_label = self.count_label count_label.shift( (prev_count_label[1].get_right() - count_label[1].get_right())[0] * RIGHT ) num_rate_func = squish_rate_func(rush_into, 0.3, 1) def update_moving_count_label(label, alpha): for i in (0, 2): label[i].set_value(interpolate( prev_count_label[i].get_value(), count_label[i].get_value(), num_rate_func(alpha), )) label.set_y(interpolate( prev_count_label.get_y(), count_label.get_y(), alpha )) return label label_transition = UpdateFromAlphaFunc( prev_count_label.copy(), update_moving_count_label, remover=True ) # Set up word transition prev_words = self.shown_words for shown_word, s_word in zip(shown_words, shown_words.words): shown_word.save_state() if s_word in prev_words.words: index = prev_words.words.index(s_word) shown_word.move_to(prev_words[index]) prev_words[index].set_opacity(0) self.prob_bars[index].set_opacity(0) elif "..." in prev_words.words: shown_word.move_to(prev_words[prev_words.words.index("...")]) shown_word.set_opacity(0) else: shown_word.set_opacity(0) prev_words.generate_target() for i, word in enumerate(prev_words.words): if word not in shown_words.words: fader = prev_words.target[i] fader.set_opacity(0) fader.shift(LEFT) # Set up bar transitions for bar, s_word, word in zip(prob_bars, shown_words, shown_words.words): bar.save_state() if word not in prev_words.words: bar.set_opacity(0) bar.match_y(s_word) bar.align_to(bar.saved_state, LEFT) # Carry out animations self.play( FadeOut(self.prob_bars, run_time=0.25), FadeOut(self.guess_value_grid, RIGHT), label_transition, MoveToTarget(prev_words, run_time=0.5), LaggedStartMap(Restore, shown_words, run_time=1), LaggedStartMap(Restore, prob_bars, run_time=1), run_time=1, ) self.add(count_label) self.remove(prev_words) shown_words.set_opacity(1) self.add(count_label) self.add(shown_words) self.add(prob_bars) self.count_label = count_label self.shown_words = shown_words self.prob_bars = prob_bars def show_guess_values(self): self.guess_value_grid = self.get_guess_value_grid() self.play(ShowIncreasingSubsets(self.guess_value_grid)) def get_guess_value_grid(self, font_size=36): if self.pre_computed_first_guesses and len(self.grid.words) == 0: guesses = self.pre_computed_first_guesses top_indices = np.arange(len(guesses)) else: guesses = self.all_words expected_scores = get_expected_scores( guesses, self.possibilities, self.priors, look_two_ahead=self.look_two_ahead ) top_indices = np.argsort(expected_scores)[:self.n_top_picks] guess_values_array = get_guess_values_array( guesses, self.possibilities, self.priors, look_two_ahead=self.look_two_ahead, ) top_words = np.array(guesses)[top_indices] top_guess_value_parts = guess_values_array[:, top_indices] lines = self.get_guess_value_grid_lines() guess_value_grid = VGroup(*( self.get_guess_value_row(line, word, *values) for line, word, values in zip( lines, top_words, top_guess_value_parts.T ) )) for value, row in zip(guess_values_array.sum(0)[top_indices], guess_value_grid): if value == 0: row.set_opacity(0) guess_value_grid.set_stroke(background=True) return guess_value_grid def get_guess_value_row(self, line, word, entropy=None, entropy2=None, probability=None, font_size=36): titles = self.guess_value_grid_titles row = VGroup() # Word word_mob = Text(str(word), font="Consolas", font_size=font_size) index = np.argmin([c.get_height() for c in word_mob]) aligner = word_mob[index] word_mob.shift(line.get_center() - aligner.get_bottom() + 0.5 * SMALL_BUFF * UP) word_mob.match_x(titles[0]) row.add(word_mob) # Entropy if entropy is None: weights = get_weights(self.possibilities, self.priors) entropy = get_entropies([word], self.possibilities, weights)[0] dec_kw = dict(num_decimal_places=2, font_size=font_size) row.add(DecimalNumber(entropy, color=self.entropy_color, **dec_kw)) # Second entropy if self.look_two_ahead: if entropy2 is None: entropy2 = get_average_second_step_entropies( [word], self.all_words, self.possibilities, self.priors ) row.add(DecimalNumber(entropy2, color=self.entropy_color, **dec_kw)) # Prior if self.show_prior: if probability is None: if word in self.possibilities: weights = get_weights(self.possibilities, self.priors) probability = weights[self.possibilities.index(word)] else: probability = 0 dec_kw['num_decimal_places'] = 5 # Dividing out by the weight given to prob in scores row.add(DecimalNumber(probability, color=self.prior_color, **dec_kw)) for mob, title in zip(row, titles): if mob is not word_mob: mob.match_y(aligner, DOWN) mob.match_x(title) row.add(line) return row def get_guess_value_grid_lines(self): titles = self.guess_value_grid_titles line = Line().match_width(titles) line.set_stroke(GREY_C, 1) lines = line.get_grid(self.n_top_picks, 1, buff=0.5) lines.next_to(titles, DOWN, buff=0.75) return lines def get_column_of_numbers(self, values, row_refs, col_ref, num_decimal_places=2, font_size=36): mobs = VGroup(*( DecimalNumber( value, num_decimal_places=num_decimal_places, font_size=font_size ) for value in values )) for row_ref, mob in zip(row_refs, mobs): mob.match_x(col_ref) mob.match_y(row_ref) return mobs def on_key_press(self, symbol, modifiers): if chr(symbol) == " ": self.wait_to_proceed = False super().on_key_press(symbol, modifiers) class WordleDistributions(WordleScene): grid_center = [-4.5, -0.5, 0] grid_height = 5 bar_style = dict( fill_color=TEAL_D, fill_opacity=0.8, stroke_color=WHITE, stroke_width=0.1, ) show_fraction_in_p_label = True def get_axes(self, x_max=3**5 / 2, y_max=0.1, width=7.5, height=6): axes = Axes( (0, x_max), (0, y_max, y_max / 5), height=height, width=width, x_axis_config={ "tick_size": 0, } ) axes.next_to(self.grid, RIGHT, LARGE_BUFF, aligned_edge=DOWN) # y_label = OldTex("p(\\text{Pattern})", font_size=24) # y_label.next_to(axes.y_axis.get_top(), UR, buff=SMALL_BUFF) # axes.y_axis.add(y_label) axes.y_axis.add_numbers(num_decimal_places=2) x_label = Text("Pattern", font_size=24) x_label.next_to(axes.x_axis.get_right(), DR, MED_SMALL_BUFF) x_label.shift_onto_screen() axes.x_axis.add(x_label) self.axes = axes return axes def get_total_words_label(self, font_size=36): label = VGroup( Integer(len(self.all_words), font_size=font_size, edge_to_fix=UR), Text("Total words", font_size=font_size) ) label.arrange(RIGHT, aligned_edge=UP) label.match_x(self.grid) label.to_edge(UP, buff=MED_SMALL_BUFF) return label def get_dynamic_match_label(self, font_size=36): label = VGroup( Integer(len(self.possibilities), font_size=font_size, edge_to_fix=UR), Text("Possible matches", font_size=font_size) ) label.arrange(RIGHT, aligned_edge=DOWN) label.set_max_width(self.grid.get_width()) label.next_to(self.grid, UP) def update_label(label): word = self.pending_word_as_string() if self.grid.pending_pattern is None or not self.is_valid_guess(): label.set_opacity(0) else: buckets = get_word_buckets(word, self.possibilities) bucket_size = len(buckets[self.grid.pending_pattern]) label[0].set_value(bucket_size) label[0].next_to(label[1], LEFT, submobject_to_align=label[0][-1]) label.set_opacity(1) label.add_updater(update_label) return label def get_bars(self, axes, values): x_unit = axes.x_axis.unit_size y_unit = axes.y_axis.unit_size bars = Rectangle(width=x_unit, **self.bar_style).replicate(3**5) for x, bar, value in zip(it.count(), bars, values): bar.set_height(value * y_unit, stretch=True) bar.move_to(axes.c2p(x, 0), DL) return bars def get_distribution_bars(self, axes, guess): distribution = get_pattern_distributions( [guess], self.possibilities, get_weights(self.possibilities, self.priors) )[0] buckets = get_word_buckets(guess, self.possibilities) pattern_indices = np.argsort(distribution)[::-1] bars = self.get_bars(axes, distribution[pattern_indices]) bars.patterns = pattern_indices for i, bar in enumerate(bars): bar.prob = distribution[pattern_indices[i]] bar.count = len(buckets[pattern_indices[i]]) return bars def get_bar_indicator(self, bars, pattern_index): pattern_index_tracker = ValueTracker(pattern_index) def get_pattern_index(): return int(pattern_index_tracker.get_value()) def get_pattern(): return bars.patterns[get_pattern_index()] tri = ArrowTip(angle=PI / 2) tri.set_height(0.1) tri.add_updater(lambda m: m.next_to(bars[get_pattern_index()], DOWN, buff=0)) row = self.get_curr_row() row_copy = row.copy() row_copy.scale(0.25) row_copy.add_updater(lambda m: m.next_to(tri, DOWN, SMALL_BUFF)) bars.add_updater(lambda m: m.set_opacity(0.35)) bars.add_updater(lambda m: m[get_pattern_index()].set_opacity(1)) self.grid.add_updater(lambda m: self.show_pattern(get_pattern())) self.add(self.grid) row_copy.add_updater(lambda m: m.match_style(row).set_stroke(width=0.1)) self.mouse_drag_point.move_to(tri) pattern_index_tracker.add_updater(lambda m: m.set_value( clip(self.axes.x_axis.p2n(self.mouse_drag_point.get_center()), 0, 3**5) )) indicator = Group(tri, row_copy) def get_bar(): value = pattern_index_tracker.get_value() index = int(clip(value, 0, 3**5 - 1)) return bars[index] return indicator, pattern_index_tracker, get_bar def get_dynamic_bar_label(self, tex, font_size=36): row_copy = self.get_curr_row().copy() row_copy.scale(0.25) ndp = len(tex[-1].split(".")[1]) dec = DecimalNumber(0, num_decimal_places=ndp, font_size=font_size) result = VGroup(*Tex(*tex, font_size=font_size)) row_copy.replace(result[1], dim_to_match=0) dec.replace(result[-1]) result.replace_submobject(1, row_copy) result.remove(result[-1]) result.add(dec) result.add_updater(lambda m: m[1].match_style(self.get_curr_row()).set_stroke(WHITE, 0.1)) return result def get_p_label(self, get_bar, max_y=1): poss_string = "{:,}".format(len(self.possibilities)).replace(",", "{,}") strs = ["p\\left(", "00000", "\\right)", "="] if self.show_fraction_in_p_label: strs.extend(["{" + poss_string, "\\over ", poss_string + "}", "=", ]) strs.append("0.0000") p_label = self.get_dynamic_bar_label(strs) if self.show_fraction_in_p_label: num = Integer(edge_to_fix=DOWN, font_size=36) num.move_to(p_label[4], DOWN) p_label.replace_submobject(4, num) def update_label(label): label[4].set_value(int(get_bar().count)) label[-1].set_value(get_bar().prob) label.next_to(get_bar(), UR, SMALL_BUFF) label.set_y(min(max_y, label.get_y())) label.shift_onto_screen(buff=1.0) p_label.add_updater(update_label) return p_label def get_information_label(self, p_label, get_bar): info_label = self.get_dynamic_bar_label( ( "I\\left(", "00000", "\\right)", "=", "\\log_2\\left(1 / p)", "=", "0.00" ), ) info_label.add_updater(lambda m: m[-1].set_value(-safe_log2(get_bar().prob))) info_label.add_updater(lambda m: m.next_to(p_label, UP, aligned_edge=LEFT)) info_label.add_updater(lambda m: m.shift_onto_screen()) return info_label def get_entropy_label(self, font_size=36): guess = self.pending_word_as_string() if self.is_valid_guess(): entropy = get_entropies( [guess], self.possibilities, get_weights(self.possibilities, self.priors) )[0] else: entropy = 0 lhs = OldTex( "E[I] = \\sum_x ", "p(x) \\cdot \\log_2(1 / p(x))", "=", tex_to_color_map={"I": BLUE}, font_size=font_size, ) value = DecimalNumber(entropy, font_size=font_size) value.next_to(lhs[-1], RIGHT) result = VGroup(lhs, value) result.move_to(self.axes, UR) result.to_edge(UP) return result def get_grid_of_matches(self, n_rows=20, n_cols=9): if self.grid.pending_pattern is not None: buckets = get_word_buckets( self.pending_word_as_string(), self.possibilities ) words = buckets[self.grid.pending_pattern] else: words = self.possibilities word_mobs = self.get_grid_of_words(words, n_rows, n_cols) word_mobs.move_to(midpoint(self.grid.get_right(), RIGHT_SIDE)) return word_mobs # Animations def add_distribution(self, axes): pass class ExternalPatternEntry(WordleSceneWithAnalysis): # uniform_prior = True # wordle_based_prior = True def setup(self): self.pending_pattern = [] super().setup() def get_pattern(self, guess): if len(self.pending_pattern) == 5: return pattern_from_string(self.pending_pattern) return None def reveal_pattern(self, *args, **kwargs): super().reveal_pattern(*args, **kwargs) self.pending_pattern = [] # Interactive parts def on_key_press(self, symbol, modifiers): char = chr(symbol) if '0' <= char <= '2' and len(self.pending_pattern) < 5: square = self.get_curr_row()[len(self.pending_pattern)] square.set_fill(self.color_map[int(char)], 1) self.pending_pattern.append(char) super().on_key_press(symbol, modifiers) class TitleCardScene(WordleScene): grid_height = 7 words = ["three", "blues", "wonts"] secret_word = "brown" reveal_run_time = 1 reveal_lag_ratio = 0.2 def construct(self): for guess in self.words: for letter in guess: self.add_letter(letter) self.wait(0.05 + random.random() * 0.15) self.reveal_pattern() self.wait(0.25) self.wait() def is_valid_guess(self): # Everyone's a winner! return True def refresh_possibilities(self, guess, pattern): pass # Scenes class LessonTitleCard(Scene): def construct(self): title = VGroup( Text("Lesson today:", font_size=40), Text("Information theory", color=TEAL), ) title.arrange(DOWN) title.scale(1.5) title.center() title[1].add( Underline(title[1], buff=-0.05).set_stroke(GREY, 2) ) self.add(title[0]) self.play(Write(title[1], run_time=1)) self.wait() self.play(title.animate.scale(1 / 1.5).to_edge(UP)) self.wait() class DrawPhone(Scene): def construct(self): morty = Mortimer().flip() morty.center().to_edge(DOWN) phone = SVGMobject("wordle-phone") phone.set_height(5) phone.next_to(morty.get_corner(UR), RIGHT) phone.shift(UP) phone.set_fill(opacity=0) phone.set_stroke(WHITE, 0) bubble = ThoughtBubble(height=4, width=4, direction=RIGHT) bubble.next_to(morty, UL, buff=0) bubble.add_content(WordleScene.patterns_to_squares( list(map(pattern_from_string, ["00102", "00110", "22222"])) )) bubble.content.scale(0.7) self.add(morty) self.add(phone) self.play( LaggedStart( morty.change("thinking", phone), ShowCreation(bubble), FadeIn(bubble.content, lag_ratio=0.1) ), Write(phone, run_time=3, lag_ratio=0.01), ) self.play( Blink(morty), FadeOut(phone), ) self.wait() class AskWhatWorldeIs(TeacherStudentsScene): def construct(self): self.student_says( "What is Wordle?", index=0, target_mode="raise_left_hand", added_anims=[ self.teacher.change("tease") ] ) self.play_student_changes( "raise_left_hand", "hesitant", "happy", look_at=self.students[0].bubble, ) self.wait(3) class IntroduceGame(WordleScene): secret_word = "brown" grid_center = 3.5 * LEFT def construct(self): # Secret grid = self.grid row_copy = self.get_curr_row().copy() secret = VGroup( Text("Secret word"), Vector(0.5 * DOWN), row_copy, ) secret[2].match_width(secret[0]) secret.arrange(DOWN, buff=MED_SMALL_BUFF) secret.next_to(grid, RIGHT, buff=2.0, aligned_edge=UP) word_list = random.sample(get_word_list(short=True), 100) word_list.append("?????") words = VGroup(*(Text(word, font="Consolas") for word in word_list)) words.set_height(row_copy.get_height() * 0.7) words[-1].set_color(RED) for word in words: for char, square in zip(word, row_copy): char.move_to(square) self.wait() self.wait() self.play( Write(secret[0]), ShowCreation(secret[1]), TransformFromCopy(grid[0], secret[2]) ) self.play( ShowSubmobjectsOneByOne(words, run_time=10, rate_func=linear), ) self.wait() self.row_copy = row_copy self.q_marks = words[-1] # Guesses numbers = VGroup(*(Integer(i) for i in range(1, 7))) for number, row in zip(numbers, grid): number.next_to(row, LEFT) self.play(FadeIn(numbers, lag_ratio=0.1)) guesses = ["three", "blues", "one", "onnne", "wonky", "brown"] if not self.presenter_mode: for guess in guesses: self.add_word(guess) self.reveal_pattern() else: self.wait(note=f"Type {guesses}") # Show word lists all_words = get_word_list() answers = get_word_list(short=True) titles = VGroup( VGroup(Text("Allowed guesses"), Integer(len(all_words))), VGroup(Text("Possible answers"), Integer(len(answers))), ) for title in titles: title.arrange(DOWN) titles.scale(0.8) titles.arrange(RIGHT, buff=1.5, aligned_edge=UP) titles[1][1].match_y(titles[0][1]) titles.to_corner(UR) titles.to_edge(RIGHT, buff=MED_LARGE_BUFF) word_columns = VGroup( self.get_grid_of_words(all_words, 20, 5), self.get_grid_of_words(answers, 20, 1), ) word_columns[1].set_color(GREEN) for column, title in zip(word_columns, titles): column.next_to(title, DOWN, MED_LARGE_BUFF) grid.add(numbers) self.play( FadeOut(secret), FadeOut(self.q_marks), grid.animate.scale(0.7, about_edge=LEFT), Write(titles[0][0], run_time=1), ) self.play( CountInFrom(titles[0][1], 0), ShowIncreasingSubsets(word_columns[0]), ) self.wait() self.play( FadeIn(titles[1][0]), CountInFrom(titles[1][1], 0), ShowIncreasingSubsets(word_columns[1]), ) self.wait() # Try not to use wordle_words frame = self.camera.frame answer_rect = SurroundingRectangle(VGroup(titles[1], word_columns[1])) answer_rect.set_stroke(TEAL, 3) avoid = OldTexText("Let's try to avoid\\\\using this") avoid.next_to(answer_rect, RIGHT) morty = Mortimer(height=2) morty.next_to(avoid, DOWN, MED_LARGE_BUFF) morty.change("hesitant", answer_rect) morty.save_state() morty.change("plain").set_opacity(0) self.play( frame.animate.match_x(word_columns, LEFT).shift(LEFT), ShowCreation(answer_rect), run_time=2, ) self.play( Write(avoid), Restore(morty), ) self.wait() # Common but not in wordle list priors = get_frequency_based_priors() not_in_answers = set(all_words).difference(answers) sorted_by_freq = list(sorted(not_in_answers, key=lambda w: priors[w])) n = 15 most_common = self.get_grid_of_words(sorted_by_freq[-n:], n, 1) most_common.set_color(BLUE) most_common.move_to(morty.get_corner(UR), DOWN).shift(MED_SMALL_BUFF * UP) non_s_most_common = self.get_grid_of_words( list(filter(lambda w: w[-1] != 's', sorted_by_freq))[-n:], n, 1 ) non_s_most_common.match_style(most_common) non_s_most_common.replace(most_common) label = Text("Not in wordle list", font_size=36) label.next_to(most_common, UP) self.play( FadeOut(avoid, DOWN), morty.change("raise_LEFT_hand", most_common), ShowIncreasingSubsets(most_common), ) self.play(FadeIn(label)) self.play(Blink(morty)) self.wait() self.play( morty.change("pondering", most_common), LaggedStartMap(FadeOut, most_common, shift=RIGHT), LaggedStartMap(FadeIn, non_s_most_common, shift=RIGHT), ) self.wait() def show_pattern(self, *args, **kwargs): guess = self.pending_word_as_string() letters = self.grid.pending_word.copy() for letter, q_mark in zip(letters, self.q_marks): letter.replace(q_mark, dim_to_match=1) added_anims = [] if guess == self.secret_word: added_anims.append(LaggedStart( *( square.animate.set_fill(GREEN, 1) for square in self.row_copy ), lag_ratio=0.7, run_time=2 )) added_anims.append(LaggedStart( *( Transform(q_mark, letter) for q_mark, letter in zip(self.q_marks, letters) ), lag_ratio=0.7, run_time=2 )) super().show_pattern(*args, added_anims=added_anims, **kwargs) class InitialDemo(ExternalPatternEntry): secret_word = "elder" pre_computed_first_guesses = [ "crane", "slane", "slate", "salet", "trace", "reast", "crate", "toile", "torse", "carse", "carle", "trone", "carte", "roast", ] # wordle_based_prior = True class ShowTonsOfWords(Scene): def construct(self): words = get_word_list() n_rows = 18 n_cols = 15 N = n_rows * n_cols grids = VGroup(*( WordleScene.get_grid_of_words(words[N * k:N * (k + 1)], n_rows, n_cols) for k in range(5) )) grids.set_width(FRAME_WIDTH - 3) grids.arrange(DOWN, buff=0.8 * SMALL_BUFF) grids.to_edge(UP) self.add(grids) frame = self.camera.frame self.play(frame.animate.move_to(grids, DOWN), run_time=15) class FinalPerformanceFrame(VideoWrapper): title = "Final performance" animate_boundary = False class FirstThoughtsTitleCard(TitleCardScene): n_letters = 5 words = ["first", "naive", "ideas"] secret_word = "start" class ChoosingBasedOnLetterFrequencies(IntroduceGame): def construct(self): # Reconfigure grid to be flat grid = self.grid grid.set_submobjects([VGroup(*it.chain(*grid))]) grid.add(grid.pending_word) self.add(grid) # Data on right letters_and_frequencies = [ ("E", 13), ("T", 9.1), ("A", 8.2), ("O", 7.5), ("I", 7), ("N", 6.7), ("S", 6.3), ("H", 6.1), ("R", 6), ("D", 4.3), ("L", 4), ("U", 2.8), ("C", 2.8), ("M", 2.5), ("W", 2.4), ("F", 2.2), ("G", 2.0), ("Y", 2.0), ] freq_data = VGroup(*( VGroup( Text(letter, font="Consolas"), Rectangle( height=0.25, width=0.2 * freq, stroke_width=0, fill_color=(BLUE if letter in "AEIOUY" else GREY_B), fill_opacity=1, ), DecimalNumber(freq, num_decimal_places=1, font_size=24, unit="\\%") ).arrange(RIGHT) for letter, freq in letters_and_frequencies )) freq_data.arrange(DOWN, aligned_edge=LEFT) freq_data.set_height(FRAME_HEIGHT - 1) freq_data.to_edge(RIGHT, buff=LARGE_BUFF) self.freq_data = freq_data for row, lf in zip(freq_data, letters_and_frequencies): letter = lf[0] row.letter = letter row.rect = SurroundingRectangle(row, buff=SMALL_BUFF) row.rect.set_stroke(YELLOW, 0) row.add(row.rect) freq_data.add_updater(lambda m: m) self.add(freq_data) def add_letter(self, letter): super().add_letter(letter) self.update_freq_data_highlights() def delete_letter(self): super().delete_letter() self.update_freq_data_highlights() def update_freq_data_highlights(self): word = self.pending_word_as_string() for row in self.freq_data: if row.letter.lower() in word.lower(): row.set_opacity(1) row.rect.set_fill(opacity=0) row.rect.set_stroke(width=2) else: row.set_opacity(0.5) row.rect.set_fill(opacity=0) row.rect.set_stroke(width=0) class ExampleGridColors(WordleScene): grid_center = ChoosingBasedOnLetterFrequencies.grid_center secret_word = "baker" def construct(self): self.wait(3) grid = self.grid for guess in ["other", "nails"]: self.add_word(guess, 0) self.reveal_pattern() self.wait() for color in [BLACK, self.color_map[0]]: grid.generate_target() grid.target[:2].set_fill(color, 1), self.play( MoveToTarget(grid), lag_ratio=0.5, run_time=2 ) self.wait() self.embed() class PreviewGamePlay(WordleSceneWithAnalysis): n_games = 10 pre_computed_first_guesses = [ "tares", "lares", "rates", "rales", "tears", "tales", "salet", "teras", "arles", "nares", "soare", "saner", "reals" ] def construct(self): self.show_guess_values() self.initial_guess_value_grid = self.guess_value_grid for x in range(self.n_games): self.clear() self.setup() self.secret_word = random.choice(get_word_list(short=True)) self.guess_value_grid = self.initial_guess_value_grid self.add(self.guess_value_grid) while not self.has_won(): guess = self.guess_value_grid[0][0].text self.add_word(guess) self.wait(0.5) self.reveal_pattern() class UlteriorMotiveWrapper(VideoWrapper): title = "Ulterior motive: Lesson on entropy" class IntroduceDistribution(WordleDistributions): secret_word = "brown" uniform_prior = True n_word_rows = 20 n_bars_to_analyze = 3 def construct(self): # Total labels total_label = self.get_total_words_label() self.add(total_label) # Show an example guess guess = "weary" match_label = self.get_dynamic_match_label() word_grid = self.get_grid_of_matches(n_rows=self.n_word_rows) self.wait() self.wait() self.play(ShowIncreasingSubsets(word_grid, run_time=3)) self.wait(note=f"Write {guess}, (but don't submit)") if not self.presenter_mode or self.skip_animations: self.add_word(guess) # Show several possible patterns, with corresponding matches pattern_strs = ["20100", "01000"] prob_label = VGroup() for i, pattern_str in enumerate(pattern_strs): pattern = pattern_from_string(pattern_str) self.remove(match_label) self.show_pattern(pattern, animate=True) self.play(FadeOut(word_grid), FadeOut(prob_label)) word_grid = self.get_grid_of_matches(n_rows=self.n_word_rows) self.add(match_label) match_label.update() self.play( CountInFrom(match_label[0], 0), ShowIncreasingSubsets(word_grid, run_time=2) ) self.wait(note=f"Pattern {i} / {len(pattern_strs)}") num = match_label[0].get_value() denom = total_label[0].get_value() prob_label = self.get_dynamic_bar_label(( "p\\left(", "0000", "\\right)", "=", "{" + "{:,}".format(num).replace(",", "{,}"), "\\over ", "{:,}".format(denom).replace(",", "{,}") + "}", "=", "0.0000", )) prob_label[-1].set_value(num / denom) prob_label.next_to(word_grid, UP) prob_label.clear_updaters() self.play( LaggedStart( FadeTransform(match_label[0].copy().clear_updaters(), prob_label[4], remover=True), FadeTransform(total_label[0].copy().clear_updaters(), prob_label[6], remover=True), lag_ratio=0.5, ), FadeIn(VGroup(*prob_label[:4], prob_label[5], prob_label[7:])), ) self.add(prob_label) self.wait() # Show distribution axes = self.get_axes(y_max=0.15) bars = self.get_distribution_bars(axes, guess) self.play( FadeOut(word_grid), FadeOut(prob_label), ) self.play(LaggedStart( Write(axes), ShowIncreasingSubsets(bars), lag_ratio=0.5 )) self.add(bars) self.wait() index = 20 bar_indicator, x_tracker, get_bar = self.get_bar_indicator(bars, index) p_label = self.get_p_label(get_bar) self.add(bar_indicator, x_tracker) self.add(p_label) self.add(match_label) for x in range(self.n_bars_to_analyze): self.wait(note=f"Play around with probability {x} / {self.n_bars_to_analyze}") word_grid = self.get_grid_of_matches(n_rows=12, n_cols=5) word_grid.next_to(p_label, UP, LARGE_BUFF) self.play(ShowIncreasingSubsets(word_grid)) self.wait() self.remove(word_grid) # Describe aim for expected information want = Text("What we want:") standin = OldTex( "E[\\text{Information}] = \\sum_{x} p(x) \\cdot (\\text{Something})", tex_to_color_map={ "\\text{Something}": GREY_B, "\\text{Information}": BLUE, }, font_size=36, ) group = VGroup(want, standin) group.arrange(DOWN, buff=MED_LARGE_BUFF) group.to_corner(UR) self.play(FadeIn(want)) self.play(Write(standin)) self.wait(note="Discuss adding up over all patterns") # Define information info_label = self.get_information_label(p_label, get_bar) il_copy = info_label.copy().clear_updaters() self.play(FadeIn(il_copy, UP, remover=True)) self.add(info_label) self.wait(note="Give intuitions on values of I") # Define entropy entropy_definition = self.get_entropy_label() brace = Brace(entropy_definition, DOWN, buff=SMALL_BUFF) ent_label = OldTexText("Entropy, $H$") ent_label.set_color(BLUE) ent_label.next_to(brace, DOWN, SMALL_BUFF) self.play( FadeIn(entropy_definition, UP), FadeOut(standin, UP), FadeOut(want, UP), ) self.wait(note="Drag tracker through full distributinon") self.wait() self.play(x_tracker.animate.set_value(10), run_time=3) self.play( GrowFromCenter(brace), Write(ent_label) ) self.wait() # Show an alternate word self.remove(bar_indicator, x_tracker, p_label, info_label, bars, match_label) entropy_definition[-1].set_opacity(0) self.grid.clear_updaters() self.grid.add_updater(lambda m: m) self.get_curr_row().set_fill(BLACK, 0) self.grid.pending_pattern = None self.wait(note="Delete word, write \"saner\", but don't enter!") if not self.presenter_mode or self.skip_animations: for x in range(5): self.delete_letter() self.add_word('saner') guess = self.pending_word_as_string() bars = self.get_distribution_bars(axes, guess) self.play(ShowIncreasingSubsets(bars, run_time=3)) self.wait() trackers = self.add_trackers(bars, index=20) self.wait(note="Play around more with distribiution") self.recalculate_entropy(entropy_definition, guess, trackers[0]) self.wait() # Examples of good entropy self.remove(*trackers) bars.set_opacity(0.7) self.grid.clear_updaters() self.grid.add_updater(lambda m: m) self.grid.pending_word.set_submobjects([]) self.add_word("?????") self.get_curr_row().set_fill(BLACK, 0) eqs = VGroup( OldTex("E[I] = \\log_2\\left({1 \\over 1 / 3^5}\\right) = \\log_2(3^5) \\approx 7.92"), OldTex("E[I] = \\log_2\\left({1 \\over 1 / 16}\\right) = \\log_2(16) = 4.00"), OldTex("E[I] = \\log_2\\left({1 \\over 1 / 64}\\right) = \\log_2(64) = 6.00"), ) eqs.scale(0.7) for eq in eqs: eq.next_to(ent_label, DOWN, LARGE_BUFF) prev_values = [bar.prob for bar in bars] last_eq = VGroup() ent_rhs = entropy_definition[-1] for eq, x in zip(eqs, [3**5, 16, 64]): values = [1 / x] * x + [0] * (3**5 - x) self.set_bars_to_values(bars, values, ent_rhs, added_anims=[FadeOut(last_eq)]) self.wait() self.play(FadeIn(eq, UP)) last_eq = eq self.wait() self.grid.pending_word.set_submobjects([]) self.add_word(guess, wait_time_per_letter=0) self.set_bars_to_values(bars, prev_values, ent_rhs, added_anims=[FadeOut(last_eq)]) self.wait() # Show the second guess true_pattern = self.get_pattern(guess) self.show_pattern(true_pattern, animate=True) trackers[0].set_value(list(bars.patterns).index(true_pattern)) match_label.update() self.play(FadeIn(match_label)) self.wait() self.play( ApplyMethod( match_label[0].copy().move_to, total_label[0], UR, remover=True, ), FadeOut(total_label[0], UP) ) total_label[0].set_value(match_label[0].get_value()) self.add(total_label) self.wait() faders = [axes, bars, match_label] for fader in faders: fader.clear_updaters() self.play( LaggedStart(*map(FadeOut, faders)), FadeOut(entropy_definition[-1]), ) self.grid.clear_updaters() self.reveal_pattern(animate=False) next_guess = "wordy" self.wait(note=f"Type in \"{next_guess}\"") if not self.presenter_mode or self.skip_animations: self.add_word(next_guess) # Show new distribution guess = self.pending_word_as_string() axes = self.get_axes(y_max=1, x_max=50) bars = self.get_distribution_bars(axes, guess) self.play( FadeIn(axes), FadeIn(bars, lag_ratio=0.1, run_time=2) ) self.wait() self.remove(match_label) trackers = self.add_trackers(bars) self.wait(note="Play around with distribution") trackers[0].clear_updaters() self.play(trackers[0].animate.set_value(10), run_time=3) self.play(trackers[0].animate.set_value(0), run_time=5) self.recalculate_entropy(entropy_definition, guess) # Other second guesses self.grid.clear_updaters() self.get_curr_row().set_fill(BLACK, 0) self.pending_pattern = None entropy_definition[1].set_opacity(0) self.remove(bars, *trackers) if not self.presenter_mode or self.skip_animations: words = get_word_list() for guess in random.sample(words, 15): for x in range(5): self.delete_letter() self.add_word(guess, wait_time_per_letter=0) bars = self.get_distribution_bars(axes, guess) self.add(bars) self.play(FadeIn(bars, lag_ratio=0.1, run_time=2)) self.recalculate_entropy(entropy_definition, guess) self.wait() self.remove(bars) else: guess = "print" self.wait(note=f"Write \"{guess}\"") trackers = self.add_trackers(bars) self.wait(note="Play around with distribution") def set_bars_to_values(self, bars, values, ent_rhs, run_time=3, added_anims=[]): y_unit = self.axes.y_axis.unit_size bars.generate_target() bar_template = bars[0].copy() entropy = entropy_of_distributions(np.array(values)) for bar, value in zip(bars.target, values): target = bar_template.copy() target.set_height( y_unit * value, stretch=True, about_edge=DOWN ) target.move_to(bar, DOWN) bar.become(target) self.play( MoveToTarget(bars, run_time=run_time), ChangeDecimalToValue(ent_rhs, entropy, run_time=run_time), *added_anims ) def recalculate_entropy(self, entropy_definition, guess, x_tracker=None): dec = entropy_definition[-1] dec.set_value( get_entropies( [guess], self.possibilities, get_weights(self.possibilities, self.priors) )[0] ) dec.set_opacity(1) dec.next_to(entropy_definition[-2][-1]) anims = [CountInFrom(dec, 0)] run_time = 1 if x_tracker is not None: x_tracker.suspend_updating() anims.append(UpdateFromAlphaFunc( x_tracker, lambda m, a: m.set_value(a * 200), run_time=5, )) run_time = 3 self.play(*anims, run_time=run_time) self.wait() def add_trackers(self, bars, index=1): bar_indicator, x_tracker, get_bar = self.get_bar_indicator(bars, index) p_label = self.get_p_label(get_bar, max_y=1) info_label = self.get_information_label(p_label, get_bar) match_label = self.get_dynamic_match_label() trackers = [x_tracker, bar_indicator, p_label, info_label, match_label] self.add(*trackers) return trackers class ButTheyreNotEquallyLikely(Scene): def construct(self): randy = Randolph() morty = Mortimer() pis = VGroup(randy, morty) pis.arrange(RIGHT, buff=2) pis.to_edge(DOWN) randy.make_eye_contact(morty) self.play( PiCreatureSays( randy, OldTexText("But they're \\emph{not}\\\\equally likely!"), target_mode="angry", ), morty.change("guilty", randy.eyes), ) self.play(Blink(randy)) self.wait() self.play( PiCreatureSays( morty, OldTexText("To warm up, let's\\\\assume they are."), target_mode="speaking", ), RemovePiCreatureBubble(randy), ) self.play(Blink(morty)) self.wait() class KeyIdea(Scene): def construct(self): title = Text("Key idea", font_size=72) title.to_edge(UP, LARGE_BUFF) title.add(Underline(title, buff=-SMALL_BUFF, stroke_width=0.5).scale(1.5)) title.set_color(YELLOW) idea = OldTexText("Informative", " $\\Leftrightarrow$", " Unlikely", font_size=72) self.add(title) idea[0].save_state() idea[0].center() self.play(FadeIn(idea[0])) self.wait() self.play( Restore(idea[0]), FadeIn(idea[1], RIGHT), FadeIn(idea[2], 2 * RIGHT) ) self.play(FlashAround(idea, run_time=2)) self.wait() class ExpectedMatchesInsert(Scene): def construct(self): tex = OldTex( "\\sum_{x} p(x) \\big(\\text{\\# Matches}\\big)", tex_to_color_map={"\\text{\\# Matches}": GREEN} ) cross = Cross(tex).scale(1.25) self.play(Write(tex)) self.wait() self.play(ShowCreation(cross)) self.wait() class InformationTheoryTitleCard(TitleCardScene): n_letters = 6 words = ["inform", "ation-", "theory", "basics"] class DescribeBit(TeacherStudentsScene): def construct(self): words = OldTexText( "Standard unit of\\\\information: The bit", tex_to_color_map={"The bit": YELLOW} ) words.next_to(self.teacher.get_corner(UL), UP, MED_LARGE_BUFF) words.to_edge(RIGHT) self.play( self.teacher.change("raise_left_hand"), FadeIn(words, UP) ) self.play_student_changes( "happy", "pondering", "thinking", look_at=words ) self.wait(4) formula = OldTex("I = -\\log_2(p)", tex_to_color_map={"I": YELLOW}) formula.next_to(self.teacher.get_corner(UL), UP) self.play( words.animate.to_edge(UP), FadeIn(formula, UP), self.teacher.change("raise_right_hand", formula), self.students[0].change("erm", formula), self.students[1].change("confused", formula), self.students[2].change("pondering", formula), ) self.wait(5) class DefineInformation(Scene): def construct(self): # Spaces pre_space = Square(side_length=3) pre_space.set_stroke(WHITE, 2) pre_space.set_fill(BLUE, 0.7) post_space = self.get_post_space(pre_space, 1) arrow = Vector(2 * RIGHT) group = VGroup(pre_space, arrow, post_space) group.arrange(RIGHT) # Labels kw = dict(font_size=36) pre_label = Text("Space of possibilities", **kw) pre_label.next_to(pre_space, UP, SMALL_BUFF) obs_label = Text("Observation", **kw) obs_label.next_to(arrow, UP) post_labels = self.get_post_space_labels(post_space, **kw) # 1 bit (has an s) self.add(pre_space) self.add(pre_label) self.wait() self.wait() self.play( ShowCreation(arrow), FadeIn(obs_label, lag_ratio=0.1), FadeTransform(pre_space.copy().set_fill(opacity=0), post_space), FadeIn(post_labels[1], 3 * RIGHT), ) self.wait() self.play(Write(post_labels[0], run_time=1)) self.wait() # Show all words n_rows = 25 n_cols = 8 all_words = get_word_list() words_sample = random.sample(all_words, n_rows * n_cols) word_grid = WordleScene.get_grid_of_words(words_sample, n_rows, n_cols) word_grid.replace(pre_space, dim_to_match=1) word_grid.scale(0.95) word_grid.shuffle() for word in word_grid: word.save_state() word_grid.scale(2) word_grid.set_opacity(0) self.play(LaggedStartMap(Restore, word_grid, lag_ratio=0.02, run_time=2)) self.wait() word_grid.save_state() word_grid.generate_target() for word in word_grid.target: if 's' not in word.text: word.set_opacity(0.1) has_s = OldTexText("Has an `s'", font_size=24) has_s.next_to(arrow, DOWN) self.play( MoveToTarget(word_grid), FadeIn(has_s, 0.5 * DOWN), ) self.wait() # 2 bits (has a t) frame = self.camera.frame mini_group1 = self.get_mini_group(pre_space, arrow, post_space, post_labels) mini_group1.target.to_edge(UP, buff=0.25) post_space2 = self.get_post_space(pre_space, 2).move_to(post_space) post_labels2 = self.get_post_space_labels(post_space2, **kw) has_t = OldTexText("Has a `t'", font_size=24) has_t.next_to(arrow, DOWN, SMALL_BUFF) self.play( MoveToTarget(mini_group1), FadeOut(has_s), Restore(word_grid), FadeOut(post_space), FadeOut(post_labels), frame.animate.move_to(2 * RIGHT) ) self.play( FadeTransform(pre_space.copy(), post_space2), FadeIn(post_labels2, shift=3 * RIGHT) ) self.wait() word_grid.generate_target() for word in word_grid.target: if 't' not in word.text: word.set_opacity(0.1) self.play( FadeIn(has_t, 0.5 * DOWN), MoveToTarget(word_grid), ) self.wait() self.remove(has_t) word_grid.restore() # 3 through 5 bits last_posts = VGroup(post_space2, post_labels2) mini_groups = VGroup(mini_group1) for n in range(3, 7): new_mini = self.get_mini_group(pre_space, arrow, *last_posts) new_mini.target.next_to(mini_groups, DOWN, buff=0.5) new_post_space = self.get_post_space(pre_space, n) new_post_space.move_to(post_space) new_post_labels = self.get_post_space_labels(new_post_space, **kw) self.play(LaggedStart( MoveToTarget(new_mini), AnimationGroup( FadeOut(last_posts), FadeIn(new_post_space), FadeIn(new_post_labels), ), lag_ratio=0.5 )) self.wait() mini_groups.add(new_mini) last_posts = VGroup(new_post_space, new_post_labels) # Show formula group = VGroup(pre_space, pre_label, word_grid, arrow, obs_label, *last_posts) kw = dict(tex_to_color_map={"I": YELLOW}) formulas = VGroup( OldTex("\\left( \\frac{1}{2} \\right)^I = p", **kw), OldTex("2^I = \\frac{1}{p}", **kw), OldTex("I = \\log_2\\left(\\frac{1}{p}\\right)", **kw), OldTex("I = -\\log_2(p)", **kw) ) formulas[:3].arrange(RIGHT, buff=LARGE_BUFF) formulas[:3].to_edge(UP) formulas[1:3].match_y(formulas[0][-1][0]) formulas[3].next_to(formulas[2], DOWN, aligned_edge=LEFT) formulas[0].save_state() formulas[0].move_to(formulas[1]) self.play( FadeIn(formulas[0]), group.animate.to_edge(DOWN, buff=MED_SMALL_BUFF) ) self.wait() self.play(Restore(formulas[0])) for i in (0, 1, 2): self.play(TransformMatchingShapes(formulas[i].copy(), formulas[i + 1])) self.wait() rhs_rect = SurroundingRectangle(formulas[3]) rhs_rect.set_stroke(YELLOW, 2) self.play(ShowCreation(rhs_rect)) self.wait() # Ask why? randy = Randolph("confused", height=1.5) randy.next_to(formulas[2], DL, MED_LARGE_BUFF) randy.look_at(rhs_rect) randy.save_state() randy.change("plain") randy.set_opacity(0) self.play(Restore(randy)) self.play(Blink(randy)) self.wait() self.play(randy.change("maybe")) self.play(Blink(randy)) self.wait() # Readibility expr = OldTex( "20 \\text{ bits} \\Leftrightarrow p \\approx 0.00000095", tex_to_color_map={"\\text{bits}": YELLOW} ) expr.next_to(group, UP, buff=0.75) self.play( FadeOut(randy), FadeOut(formulas[3]), FadeOut(rhs_rect), Write(expr), ) self.wait() # Additive group = group[:-2] self.play( FadeOut(expr), FadeOut(last_posts), group.animate.scale(0.7, about_edge=DL), FadeOut(mini_groups, RIGHT), frame.animate.move_to(RIGHT), ) ps1 = self.get_post_space(pre_space, 2) ps2 = self.get_post_space(pre_space, 5) ps2.set_stroke(width=1) ps2.add(ps1.copy().fade(0.5)) arrow2 = arrow.copy() ps1.next_to(arrow, RIGHT) arrow2.next_to(ps1, RIGHT) ps2.next_to(arrow2, RIGHT) ps1.label = self.get_post_space_labels(ps1, font_size=24) ps2.label = self.get_post_space_labels( self.get_post_space(pre_space, 3).replace(ps2), font_size=24 ) self.play( FadeTransform(pre_space.copy().set_opacity(0), ps1), FadeIn(ps1.label, 2 * RIGHT), ) self.wait() self.play( FadeTransform(ps1.copy().set_opacity(0), ps2), FadeIn(ps2.label, 2 * RIGHT), ShowCreation(arrow2), ) self.wait() brace = Brace(VGroup(ps1.label, ps2.label), UP) b_label = brace.get_text("5 bits").set_color(YELLOW) self.play( GrowFromCenter(brace), FadeIn(b_label, 0.2 * UP), ) self.wait() def get_post_space(self, pre_space, n_bits): n_rows = 2**((n_bits // 2)) n_cols = 2**((n_bits // 2) + n_bits % 2) result = pre_space.get_grid(n_rows, n_cols, buff=0) result.replace(pre_space, stretch=True) result[:-1].set_fill(opacity=0) return result def get_post_space_labels(self, post_space, **kw): n_bits = int(math.log2(len(post_space))) top_label = OldTexText("Information = ", f"${n_bits}$ bits", **kw) if n_bits == 1: top_label[-1][-1].set_opacity(0) top_label.next_to(post_space, UP, buff=0.15) top_label.set_color(YELLOW) bottom_label = OldTexText(f"$p = {{1 \\over {2**n_bits}}}$", **kw) bottom_label.next_to(post_space, DOWN, SMALL_BUFF) return VGroup(top_label, bottom_label) def get_mini_group(self, pre_space, arrow, post_space, post_labels): mini_group = VGroup(pre_space, arrow, post_space, post_labels[0]).copy() mini_group.generate_target() mini_group.target.scale(0.25) mini_group.target[-1][0].set_opacity(0) mini_group.target[-1][1].scale(3, about_edge=DOWN) mini_group.target[-1][1].match_x(mini_group.target[2]) mini_group.target.next_to(post_space, RIGHT, buff=2.0) mini_group[::2].set_fill(opacity=0) mini_group.target[::2].set_stroke(width=1) return mini_group class AskForFormulaForI(Scene): def construct(self): tex = OldTex( "I = ???", tex_to_color_map={"I": YELLOW}, font_size=72, ) tex.to_edge(UP) self.play(Write(tex)) self.wait() class MinusLogExpression(Scene): def construct(self): tex = OldTex( "I = -\\log_2(p)", tex_to_color_map={"I": YELLOW}, font_size=60, ) self.play(FadeIn(tex, DOWN)) self.wait() class ShowPatternInformationExamples(WordleDistributions): def construct(self): grid = self.grid guess = "wordy" self.add_word(guess) axes = self.get_axes() bars = self.get_distribution_bars(axes, guess) index = 20 bar_indicator, x_tracker, get_bar = self.get_bar_indicator(bars, index) p_label = self.get_p_label(get_bar) I_label = self.get_information_label(p_label, get_bar) I_label.scale(1.75) I_label.add_updater(lambda m: m.next_to(grid, UR, buff=LARGE_BUFF).shift(0.5 * DOWN)) self.add(I_label) randy = Randolph(height=2.0) randy.flip() randy.to_corner(DR) self.play(PiCreatureSays( randy, OldTexText("I thought this\\\\was a word game"), bubble_config={"width": 4, "height": 3}, target_mode="pleading" )) x_tracker.clear_updaters() x_tracker.set_value(0) self.play( x_tracker.animate.set_value(120), run_time=20, rate_func=linear, ) self.wait() class TwentyBitOverlay(Scene): def construct(self): eq = OldTex("20 \\text{ bits} \\Leftrightarrow 0.00000095") eq.scale(1.5) self.play(Write(eq)) self.wait() class AddingBitsObservationOverlay(Scene): def construct(self): mystery = Square(side_length=0.5).get_grid(1, 5, buff=SMALL_BUFF) mystery.set_stroke(WHITE, 1) for box in mystery: char = Text("?", font="Consolas") char.set_height(0.7 * box.get_height()) char.move_to(box) box.add(char) # Delete... phase1_strs = [list("?????") for x in range(5)] phase2_strs = [list("s????") for x in range(4)] for i, s in enumerate(phase1_strs): s[i] = "t" for i, s in enumerate(phase2_strs): s[i + 1] = "t" kw = dict( font="Consolas", t2c={"t": RED, "s": YELLOW}, ) phase1 = VGroup(*(Text("".join(s), **kw) for s in phase1_strs)) phase2 = VGroup(*(Text("".join(s), **kw) for s in phase2_strs)) for phase in [phase1, phase2]: phase.arrange(DOWN, buff=SMALL_BUFF) phases = VGroup(mystery, phase1, phase2) phases.arrange(RIGHT, buff=2.0) phases.to_edge(UP) # Arrange observations mystery.set_x(-4).to_edge(UP, buff=LARGE_BUFF) arrows = Arrow(LEFT, RIGHT).set_width(3).replicate(2) arrows.arrange(RIGHT, buff=MED_LARGE_BUFF) arrows.next_to(mystery, RIGHT, buff=MED_LARGE_BUFF) obss = VGroup( OldTexText("Has a `t'"), OldTexText("Starts with `s'"), ) obss.scale(0.85) bits_labels = VGroup( Text("2 bits"), Text("3 more bits"), ) bits_labels.scale(0.75) for obs, bl, arrow in zip(obss, bits_labels, arrows): obs.next_to(arrow, UP) bl.next_to(arrow, DOWN) bl.set_color(YELLOW) self.add(mystery) for arrow, bl, obs in zip(arrows, bits_labels, obss): self.play( ShowCreation(arrow), Write(obs), run_time=1 ) self.play(FadeIn(bl, 0.25 * DOWN)) self.wait() long_arrow = Arrow(arrows[0].get_start(), arrows[1].get_end(), buff=0) full_bits_label = Text("5 bits") full_bits_label.match_style(bits_labels[0]) full_bits_label.next_to(long_arrow, DOWN) self.play(bits_labels.animate.to_edge(UP, buff=SMALL_BUFF)) self.play( FadeTransform(arrows[0], long_arrow), FadeTransform(arrows[1], long_arrow), Write(full_bits_label, run_time=1), ) self.wait() class ExpectedInformationLabel(Scene): def construct(self): eq = OldTex( "E[\\text{Information}] = ", "\\sum_x p(x) \\cdot \\text{Information}(x)", tex_to_color_map={ "\\text{Information}": YELLOW, }, font_size=60 ) eq.to_edge(UP) self.play(Write(eq)) self.wait() class LookTwoAheadWrapper(VideoWrapper): title = "Later..." class AskAboutPhysicsRelation(TeacherStudentsScene): def construct(self): physics = self.get_physics_entropy_image() physics.next_to(self.students[2], UL) physics.to_edge(UP) self.student_says( OldTexText("What does this have\\\\to do with thermodynamics?"), target_mode="raise_right_hand", index=2, bubble_config=dict(width=5, height=3, direction=LEFT), ) self.play(self.teacher.change("tease")) self.play( self.students[0].change("pondering", physics), self.students[1].change("pondering", physics), self.students[2].change("raise_left_hand", physics), Write(physics), ) self.wait(3) self.embed() def get_physics_entropy_image(self): dots = Dot().get_grid(14, 10) dots.set_height(3) n = len(dots) dots[:n // 2].set_color(RED) dots[n // 2:].set_color(BLUE) dots_copy = dots.deepcopy() dots_copy.set_color(RED) VGroup(*random.sample(list(dots_copy), n // 2)).set_color(BLUE) pair = VGroup(dots, dots_copy) pair.arrange(RIGHT, buff=LARGE_BUFF) rects = VGroup(*map(SurroundingRectangle, pair)) rects.set_stroke(WHITE, 1) labels = VGroup( Text("Low entropy"), Text("High entropy"), ) labels.scale(0.75) for label, rect in zip(labels, rects): label.next_to(rect, UP) return VGroup(labels, rects, pair) class ContrastWearyAndSlate(WordleScene): def construct(self): grid = self.grid grid.set_height(4) grid.move_to(FRAME_WIDTH * LEFT / 4) self.add_word("weary", wait_time_per_letter=0) grid1 = grid.deepcopy() self.add(grid1) for x in range(5): self.delete_letter() grid.move_to(FRAME_WIDTH * RIGHT / 4) self.add_word("slate", wait_time_per_letter=0) grid2 = grid grids = VGroup(grid1, grid2) grids.to_edge(DOWN) # Entropy EI_label = OldTex( "E[I]", "= ", "\\sum_{x} p(x) \\log_2\\big(1 / p(x) \\big)", tex_to_color_map={"I": BLUE}, font_size=36, ) EI_label.to_edge(UP) EI_rect = SurroundingRectangle(EI_label) EI_rect.set_stroke(YELLOW, 2) values = VGroup( DecimalNumber(4.90, unit="\\text{ bits}"), DecimalNumber(5.87, unit="\\text{ bits}"), ) arrows = VGroup() for value, grid in zip(values, grids): value[4:].shift(SMALL_BUFF * RIGHT) value.next_to(grid, UP) arrows.add(Arrow(EI_rect, value)) self.add(EI_label) self.add(EI_rect) for arrow, value in zip(arrows, values): self.play( ShowCreation(arrow), CountInFrom(value) ) self.wait() class VonNeumannPhrase(Scene): text = "You should call \n it entropy!" def construct(self): label = Text(self.text) label.set_backstroke(width=8) for word in self.text.split(): self.add(label.get_part_by_text(word)) self.wait(0.1) self.wait() class VonNeumannPhrase2(VonNeumannPhrase): text = "Nobody knows what \n entropy really is." class MaximumInsert(Scene): def construct(self): text = OldTexText("Maximum possible\\\\", "expected information") arrow = Arrow(text.get_top(), text.get_top() + UR) arrow.shift(RIGHT) VGroup(text, arrow).set_color(YELLOW) self.play( Write(text), ShowCreation(arrow), run_time=1 ) self.wait() class ShowEntropyCalculations(IntroduceDistribution): grid_height = 3.5 grid_center = [-5.0, -1.0, 0] CONFIG = {"random_seed": 0} n_words = 100 def construct(self): # Axes grid = self.grid kw = dict(x_max=150, width=8.5, height=6.5) axes = self.get_axes(y_max=0.2, **kw) axes.to_edge(RIGHT, buff=0.1) axes.to_edge(UP, buff=0.5) y_label = OldTex("p", font_size=24) y_label.next_to(axes.y_axis.n2p(0.2), RIGHT) axes.y_axis.add(y_label) self.add(axes) # old_axes = self.get_axes(y_max=0.4, **kw) # old_axes.next_to(axes, DOWN, buff=0.8) # y_label = OldTex("p \\cdot \\log_2(1/p)", font_size=24) # y_label.next_to(old_axes.y_axis.n2p(0.4), RIGHT, MED_SMALL_BUFF) # old_axes.y_axis.add(y_label) # self.add(old_axes) # Formula ent_formula = self.get_entropy_label() ent_formula.scale(1.2) ent_formula.move_to(axes, UR) ent_formula.shift(DOWN) ent_formula.shift_onto_screen() ent_rhs = ent_formula[1] self.add(ent_formula) n = 3**5 # Bang on through words = list(random.sample(self.all_words, self.n_words)) words = ["maths", "weary", "other", "tares", "kayak"] + words for word in words: low_bars = self.get_distribution_bars(axes, word) self.add(low_bars) dist = np.array([bar.prob for bar in low_bars]) ent_summands = -np.log2(dist, where=dist > 1e-10) * dist # high_bars = self.get_bars(old_axes, ent_summands) # high_bars.add_updater(lambda m: m.match_style(low_bars)) # self.add(high_bars) self.add_word(word, wait_time_per_letter=0) trackers = self.add_trackers(low_bars, index=0) x_tracker, bar_indicator, p_label, info_label, match_label = trackers p_label.add_updater(lambda m: m.move_to(axes, DL).shift([2, 1, 0])) self.remove(info_label) self.remove(match_label) # Highlight answer arrow = OldTex("\\rightarrow") pw = grid.pending_word.copy() pw.generate_target() pw.arrange(RIGHT, buff=0.05) rhs = ent_rhs.copy() rhs.set_value(sum(ent_summands)) group = VGroup(pw, arrow, rhs) group.set_color(BLUE) group.arrange(RIGHT) group.match_width(grid) group.next_to(grid, UP, LARGE_BUFF) self.add(group) # Show calculation x_tracker.suspend_updating() n = list(dist).index(0) + 1 self.play( UpdateFromAlphaFunc( x_tracker, lambda m, a: m.set_value(int(a * (n - 1))), ), UpdateFromAlphaFunc( ent_rhs, lambda m, a: m.set_value(sum(ent_summands[:int(a * n)])) ), rate_func=linear, run_time=4 * n / 3**5, ) self.wait() # x_tracker.resume_updating() # self.embed() self.remove(group) # Clear self.remove(*trackers, low_bars, pw, arrow, rhs) ent_rhs.set_value(0) grid.pending_word.set_submobjects([]) grid.clear_updaters() grid.add_updater(lambda m: m) self.get_curr_row().set_fill(BLACK, 0) class WrapperForEntropyCalculation(VideoWrapper): title = "Search for maximum entropy" class AltWrapperForEntropyCalculation(VideoWrapper): title = "Refined entropy calculation" animate_boundary = False class UniformPriorExample(WordleSceneWithAnalysis): uniform_prior = True show_prior = False weight_to_prob = 0 # TODO pre_computed_first_guesses = [ "tares", "lares", "rales", "rates", "teras", "nares", "soare", "tales", "reais", "tears", "arles", "tores", "salet", ] class MentionUsingWordFrequencies(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("Next step: Integrate\\\\word frequency data"), added_anims=[self.change_students("hooray", "happy", "tease")] ) self.wait() self.play(self.students[1].change("pondering")) self.wait(2) class V2TitleCard(TitleCardScene): n_letters = 6 words = ["how-to", "prefer", "common", "words"] secret_word = "priors" class HowThePriorWorks(Scene): def construct(self): # Prepare columns all_words = get_word_list() freq_map = get_word_frequencies() sorted_words = list(sorted(all_words, key=lambda w: -freq_map[w])) col1, col2 = cols = [ WordleScene.get_grid_of_words( word_list, 25, 1, dots_index=-12 ) for word_list in (random.sample(all_words, 100), sorted_words) ] for col in cols: col.set_height(6) col.set_x(-1) col.to_edge(DOWN, buff=MED_SMALL_BUFF) bars1, bars2 = [ self.get_freq_bars(col, freq_map, max_width=width, exp=exp) for col, width, exp in zip(cols, (1, 2), (0.3, 1)) ] group1 = VGroup(col1, bars1) group2 = VGroup(col2, bars2) col1_title = VGroup( Text("Relative frequencies of all words"), Text("From the Google Books English n-gram public dataset", font_size=24, color=GREY_B), ) col1_title.arrange(DOWN) col1_title.set_height(1) col1_title.next_to(col1, UP, MED_LARGE_BUFF) # Introduce frequencies for bar in bars1: bar.save_state() bar.stretch(0, 0, about_edge=LEFT) bar.set_stroke(width=0) self.wait() self.add(col1) self.play( LaggedStartMap(Restore, bars1), FadeIn(col1_title, 0.5 * UP) ) self.wait() arrow = Vector(2 * RIGHT, stroke_width=5) arrow.set_x(0).match_y(col1) arrow_label = Text("Sort", font_size=36) arrow_label.next_to(arrow, UP, SMALL_BUFF) self.play( ShowCreation(arrow), Write(arrow_label), group1.animate.next_to(arrow, LEFT) ) group2.next_to(arrow, RIGHT, buff=LARGE_BUFF) self.play(LaggedStart(*( FadeInFromPoint(VGroup(word, bar), col1.get_center()) for word, bar in zip(col2, bars2) ), lag_ratio=0.1, run_time=3)) self.wait() # Word play numbers = VGroup( *(Integer(i + 1) for i in range(13)) ) numbers.match_height(col2[0]) for number, word in zip(numbers, col2): number.next_to(word, LEFT, SMALL_BUFF, aligned_edge=UP) number.word = word number.add_updater(lambda m: m.match_style(m.word)) rect = SurroundingRectangle(col2[:13], buff=0.05) rect.set_stroke(YELLOW, 2) self.play(ShowCreation(rect)) self.wait() self.play( rect.animate.replace(col2[7], stretch=True).set_opacity(0), col2[7].animate.set_color(YELLOW), ShowIncreasingSubsets(numbers), run_time=0.5 ) self.wait() self.remove(rect) for i in [0, 1, 2, 8, 7, 6, 3, 4, (9, 10, 11, 12)]: col2.set_color(GREY_A) for j in listify(i): col2[j].set_color(YELLOW) self.wait(0.5) self.play(col2.animate.set_color(GREY_A)) # Don't care about relative frequencies comp_words = ["which", "braid"] which_group, braid_group = comp = VGroup(*( VGroup( Text(word, font="Consolas"), Vector(RIGHT), DecimalNumber(freq_map[word], num_decimal_places=6) ).arrange(RIGHT) for word in comp_words )) comp.arrange(DOWN, buff=2.0) comp.to_edge(LEFT) percentages = DecimalNumber(99.9, num_decimal_places=1, unit="\\%").replicate(2) rhss = VGroup() for per, group in zip(percentages, comp): rhs = group[2] rhss.add(rhs) per.move_to(rhs, LEFT) rhs.generate_target() rhs.target.scale(0.8) rhs.target.set_color(GREY_B) rhs.target.next_to(per, DOWN, aligned_edge=LEFT) self.play( FadeOut(arrow), FadeOut(arrow_label), FadeOut(group1), FadeTransform(col2[0].copy(), which_group[0]), ) self.play( ShowCreation(which_group[1]), CountInFrom(which_group[2], 0), ) self.wait() self.play(FadeTransform(which_group[:2].copy(), braid_group[:2])) self.play(CountInFrom(braid_group[2], 0, run_time=0.5)) self.wait() self.play( FadeIn(percentages, 0.75 * DOWN), *map(MoveToTarget, rhss), ) self.wait() # Sigmoid axes = Axes((-10, 10), (0, 2, 0.25), width=12, height=6) axes.y_axis.add_numbers(np.arange(0.25, 2.25, 0.25), num_decimal_places=2, font_size=18) axes.center() col3 = WordleScene.get_grid_of_words(sorted_words, 25, 4, dots_index=-50) col3.arrange(DOWN, buff=SMALL_BUFF) col3.generate_target() col3.target.rotate(-90 * DEGREES) col3.target.match_width(axes.x_axis) col3.target.next_to(axes.x_axis, DOWN, buff=0) col2_words = [w.text for w in col2] col3.match_width(col2) for word in col3: if word.text in col2_words: word.move_to(col2[col2_words.index(word.text)]) else: word.rotate(-90 * DEGREES) word.move_to(col2[col2_words.index('...')]) word.scale(0) word.set_opacity(0) self.remove(col2), self.play(LaggedStart( FadeOut(VGroup(comp, percentages), 2 * LEFT), FadeOut(numbers), FadeOut(bars2), FadeOut(col1_title, UP), MoveToTarget(col3), Write(axes), FadeOut(col2[col2_words.index("...")]), run_time=5, )) self.wait() graph = axes.get_graph(sigmoid) graph.set_stroke(BLUE, 3) graph_label = OldTex("\\sigma(x) = {1 \\over 1 + e^{-x} }") graph_label.next_to(graph.get_end(), UL) self.play(ShowCreation(graph)) self.play(Write(graph_label)) self.wait() # Lines to graph lines = Line().replicate(len(col3)) lines.set_stroke(BLUE_B, 1.0) def update_lines(lines): for line, word in zip(lines, col3): line.put_start_and_end_on( word.get_top(), axes.input_to_graph_point(axes.x_axis.p2n(word.get_center()), graph), ) lines.add_updater(update_lines) self.play(ShowCreation(lines, lag_ratio=0.05, run_time=5)) self.wait() self.play(col3.animate.scale(2.0, about_edge=UP), run_time=3) self.play(col3.animate.scale(0.25, about_edge=UP), run_time=3) self.play(col3.animate.scale(2.0, about_edge=UP), run_time=3) self.wait() for vect in [RIGHT, 2 * LEFT, RIGHT]: self.play(col3.animate.shift(vect), run_time=2) lines.clear_updaters() self.wait() # Show window of words n_shown = 15 col4 = WordleScene.get_grid_of_words( sorted_words[3000:3000 + n_shown], 20, 1 ) dots = Text("...", font="Consolas", font_size=24).rotate(90 * DEGREES) col4.add_to_back(dots.copy().next_to(col4, UP)) col4.add(dots.copy().next_to(col4, DOWN)) col4.set_height(6) col4.to_corner(UL) col4.shift(RIGHT) numbers = VGroup(*(Integer(n) for n in range(3000, 3000 + n_shown))) numbers.set_height(col4[1].get_height()) for number, word in zip(numbers, col4[1:]): number.next_to(word, LEFT, MED_SMALL_BUFF, aligned_edge=UP) number.match_style(word) number.align_to(numbers[0], LEFT) word.add(number) self.play(ShowIncreasingSubsets(col4)) self.wait() def get_freq_bars(self, words, freq_map, max_width=2, exp=1): freqs = [freq_map.get(w.text, 0)**exp for w in words] # Smoothed out a bit max_freq = max(freqs) bars = VGroup() height = np.mean([w.get_height() for w in words]) * 0.8 for word, freq in zip(words, freqs): bar = Rectangle( height=height, width=max_width * freq / max_freq, stroke_color=WHITE, stroke_width=1, fill_color=BLUE, fill_opacity=1, ) bar.next_to(word, RIGHT, SMALL_BUFF) if word.text not in freq_map: bar.set_opacity(0) bars.add(bar) return bars class ShowWordLikelihoods(Scene): title = "How likely is each word\\\\to be an answer?" n_shown = 20 def construct(self): all_words = get_word_list() n = self.n_shown words = random.sample(all_words, n) word_mobs = WordleScene.get_grid_of_words(words, 2, n // 2) word_mobs[n // 2:].next_to(word_mobs[:n // 2], DOWN, buff=2.0) word_mobs.set_width(FRAME_WIDTH - 2) word_mobs.to_edge(DOWN) self.add(word_mobs) title = OldTexText(self.title) title.to_edge(UP) self.add(title) freq_prior = get_frequency_based_priors() true_prior = get_true_wordle_prior() bars = VGroup() decs = VGroup() for word in word_mobs: fp = freq_prior[word.text] tp = true_prior[word.text] p = (0.7 * tp + 0.3 * fp) bar = Rectangle(0.5, 1.5 * p) bar.set_stroke(WHITE, 1) bar.set_fill(BLUE, 1) bar.next_to(word, UP, SMALL_BUFF) dec = DecimalNumber(100 * p, unit="\\%") dec.scale(0.5) dec.bar = bar dec.add_updater(lambda m: m.next_to(m.bar, UP, SMALL_BUFF)) dec.next_to(bar, UP) bar.save_state() bar.stretch(0, 1, about_edge=DOWN) bar.set_opacity(0) decs.add(dec) bars.add(bar) self.play( LaggedStartMap(Restore, bars, lag_ratio=0.01), LaggedStartMap(CountInFrom, decs, lag_ratio=0.01), run_time=4 ) self.wait() self.bars = bars self.decs = decs self.word_mobs = word_mobs class SidewaysWordProbabilities(Scene): CONFIG = {"random_seed": 5} def construct(self): # Blatant copy-paste-and-modify from scene above... all_words = get_word_list() n = 15 words = random.sample(all_words, n) word_mobs = WordleScene.get_grid_of_words(words, 15, 1) word_mobs.arrange(DOWN, buff=MED_SMALL_BUFF) word_mobs.set_height(FRAME_HEIGHT - 1) word_mobs.to_edge(LEFT) self.add(word_mobs) freq_prior = get_frequency_based_priors() true_prior = get_true_wordle_prior() bars = VGroup() decs = VGroup() for word in word_mobs: fp = freq_prior[word.text] tp = true_prior[word.text] p = (0.7 * tp + 0.3 * fp) bar = Rectangle(1.5 * p, 0.2) bar.set_stroke(WHITE, 1) bar.set_fill(BLUE, 1) bar.next_to(word, RIGHT, MED_SMALL_BUFF) dec = DecimalNumber(100 * p, unit="\\%", num_decimal_places=0) dec.scale(0.5) dec.bar = bar dec.add_updater(lambda m: m.next_to(m.bar, RIGHT, SMALL_BUFF)) bar.save_state() bar.stretch(0, 0, about_edge=LEFT) bar.set_opacity(0) decs.add(dec) bars.add(bar) self.play( LaggedStartMap(Restore, bars, lag_ratio=0.01), LaggedStartMap(CountInFrom, decs, lag_ratio=0.01), run_time=4 ) self.wait() class DistributionOverWord(ShowWordLikelihoods): CONFIG = {"random_seed": 2} class LookThroughWindowsOfWords(Scene): def construct(self): # Copied from previous scene priors = get_frequency_based_priors() sorted_words = sorted(get_word_list(), key=lambda w: -priors[w]) base = 2880 group_size = 20 n_groups = 3 col4 = VGroup(*( WordleScene.get_grid_of_words( sorted_words[base + n * group_size:base + (n + 1) * group_size], group_size, 1 ) for n in range(n_groups) )) col4.arrange(DOWN, buff=0.1) col4 = VGroup(*it.chain(*col4)) col4.center().to_edge(UP) numbers = VGroup(*(Integer(n) for n in range(base, base + n_groups * group_size))) numbers.set_height(col4[1].get_height()) for number, word in zip(numbers, col4[1:]): number.next_to(word, LEFT, MED_SMALL_BUFF, aligned_edge=UP) number.match_style(word) number.align_to(numbers[0], LEFT) number.align_to(word[np.argmin([c.get_height() for c in word])], DOWN) word.add(number) self.add(col4) frame = self.camera.frame self.play(frame.animate.align_to(col4, DOWN), run_time=20) class EntropyOfWordDistributionExample(WordleScene): grid_height = 4 grid_center = 4.5 * LEFT secret_word = "graph" wordle_based_prior = True def construct(self): # Try first two guesses grid = self.grid guesses = ["other", "nails"] if not self.presenter_mode or self.skip_animations: self.add_word("other") self.reveal_pattern() self.add_word("nails") self.reveal_pattern() else: self.wait() self.wait("Enter \"{}\" then \"{}\"".format(*guesses)) # Add match label match_label = VGroup(Integer(4, edge_to_fix=RIGHT), Text("Matches")) match_label.scale(0.75) match_label.arrange(RIGHT, buff=MED_SMALL_BUFF) match_label.next_to(grid, UP) self.add(match_label) # Show words s_words = get_word_list(short=True) col1 = self.get_grid_of_words( sorted(list(set(self.possibilities).intersection(s_words))), 4, 1 ) col1.scale(1.5) col1.next_to(grid, RIGHT, buff=1) bars1 = VGroup(*( self.get_prob_bar(word, 0.25) for word in col1 )) for bar in bars1: bar.save_state() bar.stretch(0, 0, about_edge=LEFT) bar.set_opacity(0) self.play( ShowIncreasingSubsets(col1), CountInFrom(match_label[0], 0), ) self.wait() self.play(LaggedStartMap(Restore, bars1)) self.wait() # Ask about entropy brace = Brace(bars1, RIGHT) question = Text("What is the\nentropy?", font_size=36) question.next_to(brace, RIGHT) formula = OldTex( "H &=", "\\sum_x p(x) \\cdot", "\\log_2\\big(1 / p(x) \\big)\\\\", font_size=36, ) formula.next_to(brace, RIGHT, submobject_to_align=formula[0]) info_box = SurroundingRectangle(formula[2], buff=SMALL_BUFF) info_box.set_stroke(TEAL, 2) info_label = Text("Information", font_size=36) info_label.next_to(info_box, UP) info_label.match_color(info_box) info_value = OldTex("\\log_2(4)", "=", "2", font_size=36) info_value[1].rotate(PI / 2) info_value.arrange(DOWN, SMALL_BUFF) info_value.next_to(info_box, DOWN) alt_lhs = formula[0].copy().next_to(info_value[-1], LEFT) self.play( GrowFromCenter(brace), Write(question), ) self.wait() self.play( FadeIn(formula, lag_ratio=0.1), question.animate.shift(2 * UP) ) self.wait() self.play( ShowCreation(info_box), Write(info_label) ) self.wait() self.play(FadeIn(info_value[0])) self.wait() self.play(Write(info_value[1:])) self.wait() self.play(TransformFromCopy(formula[0], alt_lhs)) self.wait() # Introduce remaining words col2 = self.get_grid_of_words( sorted(self.possibilities), 16, 1 ) col2.match_width(col1) col2.move_to(col1, LEFT) col2.save_state() col1_words = [w.text for w in col1] for word in col2: if word.text in col1_words: word.move_to(col1[col1_words.index(word.text)]) else: word.move_to(col1) word.set_opacity(0) pre_bars2, bars2 = [ VGroup(*( self.get_prob_bar( word, 0.246 * self.priors[word.text] + 0.001, num_decimal_places=3, ) for word in group )) for group in (col2, col2.saved_state) ] new_brace = Brace(bars2, RIGHT) self.play( FadeTransform(col1, col2), FadeTransform(bars1, pre_bars2), LaggedStart(*map(FadeOut, [alt_lhs, info_value, info_label, info_box])) ) self.play( ChangeDecimalToValue(match_label[0], 16, run_time=1), Restore(col2, run_time=2), ReplacementTransform(pre_bars2, bars2, run_time=2), Transform(brace, new_brace), ) self.wait() # Pass the time by entering the various words shuffled_col2 = list(col2) random.shuffle(shuffled_col2) for word in shuffled_col2: if word.text in [w.text for w in col1]: continue word.set_color(YELLOW) for letter in word.text: self.add_letter(letter) self.wait(random.random() * 0.2) self.wait(0.5) for x in range(5): self.delete_letter() self.wait(0.1) word.set_color(WHITE) shuffled_col2 = list(col2) random.shuffle(shuffled_col2) for word in shuffled_col2: if word.text not in [w.text for w in col1]: continue rect = SurroundingRectangle(word) rect.set_color(GREEN) self.add(rect) word.set_color(GREEN) for letter in word.text: self.add_letter(letter) self.wait(random.random() * 0.2) self.wait(0.5) for x in range(5): self.delete_letter() self.wait(0.1) word.set_color(WHITE) self.remove(rect) # Proposed answer rhs1 = OldTex("= \\log_2(16) = 4?", font_size=36) rhs1.next_to(formula[1], DOWN, aligned_edge=LEFT) cross = Cross(rhs1).set_stroke(RED, 6) rhs2 = OldTex( "= &4 \\big(0.247 \\cdot \\log_2(1/0.247)\\big) \\\\", "+ &12 \\big(0.001 \\cdot \\log_2(1/0.001)\\big)\\\\ ", "= &2.11", font_size=30, ) rhs2.next_to(rhs1, DOWN, aligned_edge=LEFT) self.play(Write(rhs1)) self.wait() self.play(ShowCreation(cross)) self.wait() self.play( Write(rhs2), run_time=3 ) self.wait() rect = SurroundingRectangle(rhs2[-1]) self.play(ShowCreation(rect)) self.wait() def get_prob_bar(self, word, prob, num_decimal_places=2, height=0.15, width_mult=8.0): bar = Rectangle( height=height, width=width_mult * prob, stroke_color=WHITE, stroke_width=1, fill_color=BLUE, ) bar.next_to(word, RIGHT, MED_SMALL_BUFF) label = DecimalNumber(prob, font_size=24, num_decimal_places=num_decimal_places) label.next_to(bar, RIGHT, SMALL_BUFF) bar.add(label) bar.label = label bar.set_opacity(word[0].get_fill_opacity()) return bar def seek_good_examples(self): words = get_word_list() swords = get_word_list(short=True) for answer in swords: poss = list(words) for guess in ["other", "nails"]: poss = get_possible_words( guess, get_pattern(guess, answer), poss, ) n = len(set(poss).intersection(swords)) m = len(poss) if n == 4 and m in (16, 32, 64): print(answer, n, len(poss)) class WhatMakesWordleNice(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("This is what makes wordle\\\\such a nice example"), added_anims=[self.change_students( "pondering", "thinking", "erm", look_at=ORIGIN, )] ) self.wait(5) class TwoInterpretationsWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) screens = ScreenRectangle().get_grid(1, 2, buff=MED_LARGE_BUFF) screens.set_fill(BLACK, 1) screens.set_stroke(WHITE, 1) screens.set_width(FRAME_WIDTH - 1) screens.move_to(DOWN) title = Text("Two applications of entropy", font_size=60) title.to_edge(UP) screen_titles = VGroup( Text("Expected information from guess"), Text("Remaining uncertainty"), ) screen_titles.scale(0.8) for screen, word in zip(screens, screen_titles): word.next_to(screen, UP) screen_titles[0].set_color(BLUE) screen_titles[1].set_color(TEAL) self.add(title) self.add(screens) self.wait() for word in screen_titles: self.play(Write(word, run_time=1)) self.wait() class IntroduceDistributionFreqPrior(IntroduceDistribution): n_word_rows = 1 uniform_prior = False show_fraction_in_p_label = False class FreqPriorExample(WordleSceneWithAnalysis): pre_computed_first_guesses = [ "tares", "lares", "rates", "rales", "tears", "tales", "salet", "teras", "arles", "nares", "soare", "saner", "reals" ] class ConstrastResultsWrapper(Scene): def construct(self): self.add(FullScreenRectangle()) screens = Rectangle(4, 3).replicate(2) screens.arrange(RIGHT, buff=SMALL_BUFF) screens.set_width(FRAME_WIDTH - 1) screens.set_stroke(WHITE, 1) screens.set_fill(BLACK, 1) screens.move_to(DOWN) self.add(screens) class WordlePriorExample(WordleSceneWithAnalysis): secret_word = "thump" wordle_based_prior = True pre_computed_first_guesses = [ "soare", "raise", "roate", "raile", "reast", "slate", "crate", "irate", "trace", "salet", "arise", "orate", "stare" ] class HowToCombineEntropyAndProbability(FreqPriorExample): secret_word = "words" def construct(self): super().construct() # Put in first three guesses = ["favor", "ideal", "scores"] if not self.presenter_mode or self.skip_animations: for guess in guesses: self.add_word(guess) self.reveal_pattern() else: self.wait(note=f"Enter{guesses}, discuss") # Fade lower grid rows = self.guess_value_grid self.wait() self.play(rows[:2].animate.set_opacity(0.3)) self.wait() self.play( rows[:2].animate.set_opacity(1), rows[2:].animate.set_opacity(0.3), ) self.wait() self.play( rows[1].animate.set_opacity(0.3), rows[2].animate.set_opacity(1), rows[3:].animate.set_opacity(0.3), ) self.wait() # Expected score es_eq = OldTex( "E[\\text{Score}] = 0.58 \\cdot {4} +", "(1 - 0.58)", " \\cdot \\big({4} + f(1.44 - 1.27)\\big)", tex_to_color_map={ "\\text{Score}": YELLOW, "{4}": YELLOW, "0.58": self.prior_color, "1.44": self.entropy_color, "1.27": self.entropy_color, "=": WHITE, } ) es_eq.next_to(self.grid, DOWN, LARGE_BUFF) es_eq.to_edge(RIGHT) left_part = es_eq[:11] left_part.save_state() left_part.align_to(self.grid, LEFT) q_marks = OldTex("???") q_marks.next_to(es_eq.get_part_by_tex("="), RIGHT) if not self.presenter_mode or self.skip_animations: self.add_word("words") else: self.wait(note="Enter \"words\"") self.wait() self.play( Write(es_eq[:4]), FadeIn(q_marks) ) self.wait() self.play(FlashAround(rows[0][2], run_time=3)) self.play( FadeTransform(rows[0][2].copy(), es_eq.get_part_by_tex("0.58")), FadeIn(es_eq.slice_by_tex("\\cdot", "(1 -")), q_marks.animate.next_to(es_eq[:8], RIGHT, aligned_edge=UP) ) self.remove(es_eq) self.add(es_eq[:8]) self.wait() self.play( FadeIn(es_eq[8:11]), q_marks.animate.next_to(es_eq[10], RIGHT), FadeOut(rows[3:]) ) self.wait() self.play( Restore(left_part), FadeTransform(q_marks, es_eq[11:]) ) self.wait() class FirstThoughtsOnCombination(Scene): def construct(self): morty = Mortimer(height=2) morty.flip() morty.to_corner(DL) example = VGroup( Text("dorms", font="Consolas"), DecimalNumber(1.08, color=TEAL), DecimalNumber(0.31, color=BLUE), ) word, n1, n2 = example example.arrange(RIGHT, buff=1.5) example[0].shift(0.5 * RIGHT) example.to_corner(UR) example.shift(DOWN) example_titles = VGroup( OldTex("E[\\text{Info.}]", color=TEAL), OldTex("p(\\text{word})", color=BLUE), ) for title, ex in zip(example_titles, example[1:]): title.next_to(ex, UP, MED_LARGE_BUFF) title.add(Underline(title, buff=-0.05).set_stroke(GREY, 1)) self.add(example_titles) self.add(example) self.add(morty) self.play(PiCreatureBubbleIntroduction( morty, OldTexText("How should I measure\\\\guess quality?", font_size=36), look_at=example, target_mode="pondering", bubble_type=ThoughtBubble, bubble_config={"width": 4, "height": 3}, )) self.play(Blink(morty)) self.wait() attempt = example.copy() attempt.generate_target() arrow = OldTex("\\rightarrow") plus = OldTex("+") group = VGroup( attempt.target[0], arrow, attempt.target[1], plus, attempt.target[2], ) group.arrange(RIGHT, buff=0.2) group.next_to(example, DOWN, buff=2) self.play( MoveToTarget(attempt), morty.change("shruggie", attempt), FadeIn(arrow), FadeIn(plus), ) self.wait() self.play(Blink(morty)) cross = Cross(group) cross.insert_n_curves(100) better_words = OldTexText("We can do\\\\better!") better_words.next_to(cross, DOWN) better_words.set_color(RED) self.play(ShowCreation(cross)) self.play( Write(better_words, run_time=1), morty.change("pondering", cross), ) self.play(Blink(morty)) self.wait() self.embed() class EntropyToScoreData(Scene): def construct(self): # Axes axes = Axes( (0, 13), (0, 6), height=6, width=10, ) axes.x_axis.add_numbers() axes.y_axis.add_numbers() x_label = Text("Entropy", font_size=24) x_label.next_to(axes.x_axis, UR, SMALL_BUFF) x_label.shift_onto_screen() y_label = Text("Score", font_size=24) y_label.next_to(axes.y_axis, UR) y_label.shift_onto_screen() axes.add(x_label, y_label) self.add(axes) self.wait() self.wait() # Data with open(ENT_SCORE_PAIRS_FILE) as fp: data = np.array(json.load(fp)) dots = DotCloud([ axes.c2p(*pair) for pair in data ]) dots.set_radius(0.05) dots.set_color(BLUE) dots.set_opacity(0.02) dots.add_updater(lambda m: m) self.play(ShowCreation(dots, run_time=3)) self.wait() # Window window = FullScreenRectangle().replicate(2) window.arrange(RIGHT, buff=3 * dots.radius) window.set_fill(BLACK, 0.7) window.set_x(axes.c2p(8.65, 0)[0]) self.add(dots, window, axes) self.wait() for x in (0, 1, 2): self.play( window.animate.set_x(axes.c2p(x, 0)[0]) ) self.wait() self.play(FadeOut(window)) self.wait() # Buckets bucket_size = 0.25 buckets = dict() bucket_xs = np.arange(0, axes.x_range[1], bucket_size) bars = VGroup() for x in bucket_xs: indices = (x < data[:, 0]) & (data[:, 0] <= x + bucket_size) buckets[x] = data[indices, 1] y = data[indices, 1].mean() if not indices.any(): continue bar = Rectangle( width=axes.x_axis.unit_size * bucket_size, height=axes.y_axis.unit_size * y ) bar.set_stroke(WHITE, 1) bar.move_to(axes.c2p(x, 0), DL) bar.set_fill(TEAL, 0.5) bars.add(bar) self.play(FadeIn(bars, lag_ratio=0.1, run_time=2)) self.wait() bars.save_state() self.play( bars[:4].animate.fade(0.7), bars[5:].animate.fade(0.7), ) self.wait() self.play(Restore(bars)) self.play( bars[:16].animate.fade(0.7), bars[17:].animate.fade(0.7), ) self.wait() self.play(Restore(bars)) # Model curve = axes.get_graph( lambda x: 1 + 0.56 * math.log(x + 1) + 0.08 * x, ) curve.set_stroke(YELLOW, 2) self.play(ShowCreation(curve, run_time=2)) self.wait() class LookTwoStepsAhead(WordleSceneWithAnalysis): look_two_ahead = True wordle_based_prior = True pre_computed_first_guesses = [ "slate", "salet", "slane", "reast", "trace", "carse", "crate", "torse", "carle", "carte", "toile", "crane", "least", "saint", "crine", "roast", ] class HowLookTwoAheadWorks(Scene): prob_color = BLUE_D entropy_color = TEAL first_guess = "tares" n_shown_trials = 240 transition_time = 1 def get_priors(self): return get_frequency_based_priors() def construct(self): # Setup all_words = get_word_list() possibilities = get_word_list() priors = self.get_priors() # Show first guess guess1 = self.get_word_mob(self.first_guess) guess1.to_edge(LEFT) pattern_array1 = self.get_pattern_array(guess1, possibilities, priors) prob_bars1 = self.get_prob_bars(pattern_array1.pattern_mobs) self.add(guess1) self.play( ShowCreation( pattern_array1.connecting_lines, lag_ratio=0.1 ), LaggedStartMap( FadeIn, pattern_array1.pattern_mobs, shift=0.2 * RIGHT, lag_ratio=0.1, ), run_time=2, ) self.play(Write(pattern_array1.dot_parts)) self.wait() for bar in prob_bars1: bar.save_state() bar.stretch(0, 0, about_edge=LEFT) bar.set_opacity(0) self.play(LaggedStartMap(Restore, prob_bars1)) self.wait() # Reminder on entropy H_eq = OldTex( "E[I] = \\sum_{x} p(x) \\cdot \\log_2\\big((1 / p(x)\\big)", font_size=36 ) H_eq.next_to(prob_bars1, RIGHT) info_labels = VGroup(*( self.get_info_label(bar) for bar in prob_bars1 )) self.play(Write(H_eq)) self.wait() self.play(FadeIn(info_labels[0], lag_ratio=0.1)) self.wait() self.play( LaggedStartMap(FadeIn, info_labels[1:], lag_ratio=0.5), H_eq.animate.scale(0.7).to_edge(DOWN), run_time=2, ) self.wait() H_label = self.get_entropy_label(guess1, pattern_array1.distribution) self.play(FadeTransform(H_eq, H_label)) self.wait() self.play(LaggedStartMap(FadeOut, info_labels), run_time=1) # Show example second guess word_buckets = get_word_buckets(guess1.text, possibilities) arrows = VGroup() second_guesses = VGroup() second_ents = VGroup() for i, bar in enumerate(prob_bars1): pattern = pattern_array1.pattern_mobs[i].pattern bucket = word_buckets[pattern] optimal_word = optimal_guess(all_words, bucket, priors) shown_words = random.sample(all_words, self.n_shown_trials) shown_words.append(optimal_word) for j, shown_word in enumerate(shown_words): guess2 = self.get_word_mob(shown_word) guess2.set_width(0.7) guess2.match_y(bar) guess2.set_x(0, LEFT) arrow = Arrow(bar.label, guess2, stroke_width=3, buff=SMALL_BUFF) pattern_array2 = self.get_pattern_array(guess2, bucket, priors, n_shown=25) prob_bars2 = self.get_prob_bars(pattern_array2.pattern_mobs, width_scalar=5) h2_label = self.get_entropy_label(guess2, pattern_array2.distribution) group = VGroup( arrow, guess2, h2_label, pattern_array2, prob_bars2, ) self.add(group, second_ents) self.wait(1 / self.camera.frame_rate, ignore_presenter_mode=True) if i in (0, 1) and j == 0: self.wait(self.transition_time) self.remove(group) self.add(*group, second_ents) self.wait() # Consolidate arrow, guess2, h2_label, pattern_array2, prob_bars2 = group for line in pattern_array2.connecting_lines: line.reverse_points() h2_label.generate_target() h2_label.target.scale(0.8) h2_label.target.next_to(guess2, RIGHT) guess2.set_color(YELLOW) self.add(pattern_array2.connecting_lines, second_ents) self.play( MoveToTarget(h2_label), Uncreate(pattern_array2.connecting_lines, lag_ratio=0.01), LaggedStartMap(FadeOut, pattern_array2.pattern_mobs), LaggedStartMap(FadeOut, pattern_array2.dot_parts), LaggedStartMap(FadeOut, prob_bars2, scale=0.25), run_time=self.transition_time ) arrows.add(arrow) second_guesses.add(guess2) second_ents.add(h2_label) # Show weighted sum brace = Brace(VGroup(second_ents, pattern_array1), RIGHT) label = brace.get_text("Compute a\nweighted average", buff=MED_SMALL_BUFF) sum_parts = VGroup() for bar, h_label in zip(prob_bars1, second_ents): d0 = DecimalNumber(bar.prob, num_decimal_places=3) d1 = h_label[1].copy() d0.match_height(d1) group = VGroup(d0, OldTex("\\cdot", font_size=24), d1) group.generate_target() group.target.arrange(RIGHT, buff=SMALL_BUFF) group.target.next_to(brace, RIGHT) group.target.match_y(bar) sum_parts.add(group) for part in group[:2]: part.move_to(bar.label) part.set_opacity(0) self.play( GrowFromCenter(brace), Write(label) ) self.wait() self.play( LaggedStartMap(MoveToTarget, sum_parts, run_time=2), label.animate.scale(0.7).to_edge(DOWN), ) self.wait() def get_word_mob(self, word): return Text(word, font="Consolas", font_size=36) def get_pattern_array(self, word, possibilities, priors, n_shown=15): weights = get_weights(possibilities, priors) dist = get_pattern_distributions([word.text], possibilities, weights)[0] indices = np.argsort(dist)[::-1] patterns = np.arange(3**5)[indices] patterns = patterns[:n_shown] # Only show non-zero possibilities top_parts = VGroup(*(self.get_pattern_mob(p) for p in patterns[:n_shown])) dot_parts = OldTex("\\vdots\\\\", "\\le 3^5 \\text{ patterns}\\\\", "\\vdots") for prob, row in zip(dist[indices][:n_shown], top_parts): row.prob = prob stack = VGroup(*top_parts, *dot_parts) dot_parts.match_width(stack[0]) stack.arrange(DOWN, buff=SMALL_BUFF) stack.set_max_height(FRAME_HEIGHT - 1) stack.next_to(word, RIGHT, buff=1.5) # stack.set_y(0) stack.shift_onto_screen(buff=MED_LARGE_BUFF) pattern_mobs = top_parts connecting_lines = VGroup(*( self.get_connecting_line(word, row) for row in pattern_mobs )) result = VGroup(pattern_mobs, dot_parts, connecting_lines) result.pattern_mobs = pattern_mobs result.dot_parts = dot_parts result.connecting_lines = connecting_lines result.distribution = dist return result def get_pattern_mob(self, pattern, width=1.5): result = Square().replicate(5) result.arrange(RIGHT, buff=SMALL_BUFF) result.set_stroke(WHITE, width=0.5) for square, n in zip(result, pattern_to_int_list(pattern)): square.set_fill(WordleScene.color_map[n], 1) result.set_width(width) result.pattern = pattern return result def get_connecting_line(self, mob1, mob2): diff = mob2.get_left()[0] - mob1.get_right()[0] return CubicBezier( mob1.get_right() + SMALL_BUFF * RIGHT, mob1.get_right() + RIGHT * diff / 2, mob2.get_left() + LEFT * diff / 2, mob2.get_left() + SMALL_BUFF * LEFT, stroke_color=WHITE, stroke_width=1, ) def get_prob_bars(self, pattern_mobs, width_scalar=10): result = VGroup() for pattern_mob in pattern_mobs: bar = Rectangle( width=width_scalar * pattern_mob.prob, height=pattern_mob.get_height(), fill_color=self.prob_color, fill_opacity=1, stroke_width=0.5, stroke_color=WHITE, ) bar.next_to(pattern_mob, RIGHT, buff=SMALL_BUFF) label = DecimalNumber(100 * pattern_mob.prob, num_decimal_places=1, unit="\\%") # label = DecimalNumber(pattern_mob.prob, num_decimal_places=3) label.set_height(bar.get_height() * 0.6) label.next_to(bar, RIGHT, SMALL_BUFF) bar.label = label bar.add(label) bar.prob = pattern_mob.prob result.add(bar) return result def get_entropy_label(self, word_mob, distribution): ent2 = entropy_of_distributions(distribution) kw = dict(font_size=24) h_label = VGroup(OldTex(f"E[I] = ", **kw), DecimalNumber(ent2, **kw)) h_label.set_color(self.entropy_color) h_label.arrange(RIGHT, buff=SMALL_BUFF, aligned_edge=UP) h_label.move_to(word_mob) h_label.shift(0.5 * DOWN) h_label.set_backstroke(width=8) return h_label def get_info_label(self, bar): result = VGroup( # DecimalNumber(bar.prob, num_decimal_places=3), OldTex("\\log_2\\big( 1 / "), DecimalNumber(bar.prob, num_decimal_places=3), OldTex("\\big) = "), # DecimalNumber(-bar.prob * math.log2(bar.prob), num_decimal_places=3) DecimalNumber(-math.log2(bar.prob), num_decimal_places=3) ) result.arrange(RIGHT, buff=SMALL_BUFF) result.set_height(bar.get_height()) result.match_y(bar) result.set_x(0, LEFT) arrow = Arrow(bar.label.get_right(), result, stroke_width=2, buff=SMALL_BUFF) result.add_to_back(arrow) return result class BestDoubleEntropies(Scene): def construct(self): pass # Facts on theoretical possibilities: # Best two-step entropy is slane: 5.7702 + 4.2435 = 10.014 # Given the start, with log2(2315) = 11.177 bits of entropy, # this means an average uncertainty after two guesses of 1.163. # This is akin to being down to 2.239 words # In that case, there's a 1/2.239 = 0.4466 chance of getting it in 3 # Otherwise, 0.5534 chance of requiring at least 4 # # Assuming best case scenarios, that out of the 2315 answers, you get: # - 1 in 1 # - 273 in 2 with your encoded second guesses # - Of the remaining 2041, you get 0.4466 * 2041 = 912 in 3 # - Of the remaining 1,129, all are in 4 # Average: (1 + 2 * 273 + 3 * 912 + 4 * 1129) / 2315 = 3.368 # # But actually, number of 2's is (at most) 150, so we could update to: # Average: (1 + 2 * 150 + 3 * 967 + 4 * 1197) / 2315 = 3.451 # More general formula # p3 = 1 / 2**(np.log2(2315) - 10.014) # (1 + 2 * n + 3 * p3 * (2315 - n - 1) + 4 * (1 - p3) * (2315 - n - 1)) / 2315 # # Analyzing crane games, it looks like indeed, the average uncertainty # at the third step is 1.2229, just slightly higher than the 1.163 above. # In fact, for 'crane' the average shoudl be 11.177 - 9.9685 = 1.208 # # game_data = json.load(open("/Users/grant/Dropbox/3Blue1Brown/data/wordle/crane_with_wordle_prior.json")) # games = game_data["game_results"] # reductions = [g['reductions'] for g in games] # step3_state = [red[1] if len(red) > 1 else 1 for red in reductions] # step3_bits = [math.log2(x) for x in step3_state] # np.mean(step3_bits) # Out: 1.2229 class TripleComparisonFrame(Scene): def construct(self): self.add(FullScreenRectangle()) squares = Square().replicate(3) squares.stretch(0.9, 0) squares.arrange(RIGHT, buff=0.1) squares.set_width(FRAME_WIDTH - 0.5) squares.set_stroke(WHITE, 2) squares.set_fill(BLACK, 1) squares.to_edge(DOWN, buff=1.5) self.add(squares) titles = VGroup( OldTexText("V1: Just maximize\\\\entropy"), OldTexText("V2: Incorporate word\\\\frequency data"), OldTexText("V3: Use true wordle list\\\\(plus 1 or 2 other tricks)"), ) titles.scale(0.75) for title, square in zip(titles, squares): title.next_to(square, UP) self.add(titles) self.embed() class InformationLimit(WordleScene): def construct(self): # Setup grid = self.grid grid.set_height(4) title = Text("Is there a fundamental limit?") title.to_edge(UP, buff=MED_SMALL_BUFF) line = Line(LEFT, RIGHT) line.set_width(12) line.set_stroke(WHITE, 1) line.next_to(title, DOWN, buff=SMALL_BUFF) self.add(title, line) # Show wordle list kw = dict(font_size=36) left_title = Text("2,315 words, equally likely", **kw) left_title.next_to(line, DOWN, buff=0.75) left_title.to_edge(LEFT) words = get_word_list(short=True) word_mobs = self.get_grid_of_words(words, 18, 1, dots_index=-7) word_mobs.set_height(5.5) word_mobs.next_to(left_title, DOWN, aligned_edge=LEFT) brace = Brace(word_mobs, RIGHT) brace_label = VGroup( OldTex("\\log_2(2{,}315)", "=", "11.17 \\text{ bits}", **kw), Text("of uncertainty", **kw) ) brace_label[0][1].rotate(PI / 2) brace_label[0].arrange(DOWN, buff=MED_SMALL_BUFF) brace_label.arrange(DOWN, aligned_edge=LEFT) brace_label.set_color(TEAL) brace_label[0][:2].set_color(WHITE) brace_label.next_to(brace, RIGHT, SMALL_BUFF) group = VGroup(word_mobs, left_title, brace_label) grid.next_to(group, RIGHT) self.play( Write(left_title), FadeIn(word_mobs, lag_ratio=0.1, run_time=3), ) self.wait() self.play( GrowFromCenter(brace), FadeIn(brace_label, 0.25 * RIGHT) ) self.wait() # Brute for search all_words = get_word_list() sample = random.sample(all_words, 180) for word in sorted(sample): self.add_word(word, wait_time_per_letter=0) self.reveal_pattern(animate=False) self.add_word(random.choice(all_words), wait_time_per_letter=0) self.reveal_pattern(animate=False) self.wait(1 / 30) grid.words.set_submobjects([]) grid.pending_word.set_submobjects([]) grid.set_fill(BLACK, 0) self.add_word("slane", wait_time_per_letter=0) # Two step entropy s_title = OldTexText( "Maximum expected information\\\\", "after first two guesses:", **kw ) s_title.match_y(left_title) s_title.to_edge(RIGHT) arrows = VGroup(*( Arrow( grid[i].get_right(), grid[i + 1].get_right(), buff=0, path_arc=-(PI + 0.1), width_to_tip_len=0.005 ) for i in (0, 1) )) for arrow in arrows: arrow.shift(0.1 * RIGHT) arrows.space_out_submobjects(1.2) EI_labels = VGroup( OldTex("E[I_1] = 5.77", **kw), OldTex("E[I_2] = 4.24", **kw), ) EI_labels.set_color(BLUE) for label, arrow in zip(EI_labels, arrows): label.next_to(arrow, RIGHT, buff=SMALL_BUFF) EI2_arrow = Vector(DR) EI2_arrow.next_to(EI_labels[1].get_bottom(), DR, buff=SMALL_BUFF) total_brace = Brace(EI_labels, RIGHT) total_label = OldTexText("10.01 bits", **kw) total_label.set_color(BLUE) total_label.next_to(total_brace, RIGHT) self.play( Write(s_title), ShowCreation(arrows), ) self.play(LaggedStart(*( FadeIn(EI_label, 0.25 * RIGHT) for EI_label in EI_labels )), lag_ratio=0.5) self.play( GrowFromCenter(total_brace), FadeIn(total_label), ) self.wait() self.play(FadeIn(EI2_arrow)) self.play(FadeOut(EI2_arrow)) self.wait() # Highlight third spot row3 = grid[2].copy() row3.set_stroke(RED, 3) self.play( grid.animate.fade(0.75), FadeIn(row3), ) self.wait() # Best case words best_case_words = Text( "Best case scenario:\n" "Down to ~1.16 bits of\n" "uncertainty, on average", **kw ) best_case_words.get_part_by_text("~").match_y( best_case_words.get_part_by_text("1.16") ) best_case_words.next_to(grid[2], DR, MED_LARGE_BUFF) self.play(Write(best_case_words)) self.wait() class EndScreen(PatreonEndScreen): CONFIG = { "scroll_time": 30, } # Distribution animations class ShowScoreDistribution(Scene): data_file = "crane_with_wordle_prior.json" axes_config = dict( x_range=(0, 9), y_range=(0, 1, 0.1), width=8, height=6, ) weighted_sample = False bar_count_font_size = 30 def construct(self): axes = self.get_axes() self.add(axes) with open(os.path.join(DATA_DIR, "simulation_results", self.data_file)) as fp: game_data = json.load(fp) games = game_data["game_results"] scores = [game["score"] for game in games] bars = self.get_bars(axes, scores[:0]) mean_label = VGroup( Text("Average score: "), DecimalNumber(np.mean(scores), num_decimal_places=3) ) mean_label.arrange(RIGHT, aligned_edge=UP) mean_label.move_to(axes, UP) self.add(mean_label) grid = WordleScene.patterns_to_squares(6 * [0]) grid.set_fill(BLACK, 0) grid.set_width(axes.get_width() / 4) grid.move_to(axes, RIGHT) grid.shift(0.5 * DOWN) grid.words = VGroup() grid.add(grid.words) self.add(grid) score_label = VGroup( Text("Score: "), Integer(0, edge_to_fix=LEFT), ) score_label.scale(0.75) score_label.arrange(RIGHT, aligned_edge=DOWN) score_label.next_to(grid, UP, aligned_edge=LEFT) self.add(score_label) answer_label = VGroup( Text("Answer: "), Text(games[0]["answer"], font="Consolas") ) answer_label.match_height(score_label) answer_label.arrange(RIGHT) answer_label.next_to(score_label, UP, aligned_edge=LEFT) self.add(answer_label) def a2n(alpha): return integer_interpolate(0, len(scores), alpha)[0] def update_bars(bars, alpha): bars.set_submobjects(self.get_bars(axes, scores[:a2n(alpha) + 1])) def update_mean_label(label, alpha): label[1].set_value(np.mean(scores[:a2n(alpha) + 1])) def update_grid(grid, alpha): game = games[a2n(alpha)] patterns = game["patterns"] patterns.append(3**5 - 1) grid.set_fill(BLACK, 0) for pattern, row in zip(patterns, grid): for square, key in zip(row, pattern_to_int_list(pattern)): square.set_fill(WordleScene.color_map[key], 1) try: grid.words.set_submobjects([ Text(guess.upper(), font="Consolas") for guess in (*game["guesses"], game["answer"]) ]) except Exception: return for word, row in zip(grid.words, grid): word.set_height(row.get_height() * 0.6) for char, square in zip(word, row): char.move_to(square) def update_score_label(score_label, alpha): score = games[a2n(alpha)]["score"] score_label[1].set_value(score) def update_answer_label(answer_label, alpha): answer = games[a2n(alpha)]["answer"] new_text = Text(answer, font="Consolas") new_text.scale(0.75) new_text.move_to(answer_label[1], LEFT) low_y = new_text[np.argmin([c.get_height() for c in new_text])].get_bottom()[1] new_text.shift((answer_label[0].get_bottom()[1] - low_y) * UP) answer_label.replace_submobject(1, new_text) return answer_label self.play( UpdateFromAlphaFunc(bars, update_bars), UpdateFromAlphaFunc(mean_label, update_mean_label), UpdateFromAlphaFunc(grid, update_grid), UpdateFromAlphaFunc(score_label, update_score_label), UpdateFromAlphaFunc(answer_label, update_answer_label), run_time=20, rate_func=linear, ) update_bars(bars, 1) self.wait() self.remove(grid, score_label, answer_label) def get_axes(self): axes = Axes(**self.axes_config) x_axis, y_axis = axes.x_axis, axes.y_axis y_axis.add_numbers(num_decimal_places=1) x_axis.add_numbers() x_axis.numbers.shift(x_axis.unit_size * LEFT / 2) x_label = Text("Score", font_size=24) x_label.next_to(x_axis.get_end(), RIGHT) x_axis.add(x_label) return axes def get_bars(self, axes, scores): scores = np.array(scores) buckets = np.array([ (scores == n + 1).sum() for n in np.arange(*axes.x_range) ]) props = buckets / buckets.sum() bars = VGroup(*( self.get_bar(axes, n + 1, prop) for n, prop in enumerate(props) )) colors = color_gradient([BLUE, YELLOW, RED], 8) for bar, color in zip(bars, colors): bar.set_fill(color, 1) bars.set_stroke(WHITE, 1) for bar, count in zip(bars, buckets): bar.add(self.get_bar_count(bar, count)) return VGroup(bars) def get_bar(self, axes, score, proportion): bar = Rectangle( width=axes.x_axis.unit_size, height=axes.y_axis.unit_size * proportion, ) bar.set_fill(BLUE, 1) bar.set_stroke(WHITE, 1) bar.move_to(axes.c2p(score, 0), DR) return bar def get_bar_count(self, bar, count): result = Integer(count, font_size=self.bar_count_font_size) result.set_max_width(bar.get_width() * 0.8) result.next_to(bar, UP, SMALL_BUFF) if count == 0: result.set_opacity(0) return result class SimulatedGamesUniformPriorDist(ShowScoreDistribution): data_file = "tares_with_uniform_prior.json" class SimulatedGamesFreqBasedPriorDist(ShowScoreDistribution): data_file = "tares_with_freq_prior.json" class SimulatedGamesWordleBasedPriorDist(ShowScoreDistribution): data_file = "soare_with_wordle_prior.json" class SimulatedGamesWordleBasedPriorCraneStartDist(ShowScoreDistribution): data_file = "crane_with_wordle_prior.json" class SimulatedGamesCraneHardModeDist(ShowScoreDistribution): data_file = "crane_hard_mode.json" class SimulatedGamesWordleBasedPriorExcludeSeenWordsDist(ShowScoreDistribution): data_file = "crane_with_wordle_prior_exclude_seen.json" class SimulatedGamesFreqBasedPriorExcludeSeenWordsDist(ShowScoreDistribution): data_file = "tares_with_freq_prior_exclude_seen.json" class ThinV1Stats(SimulatedGamesUniformPriorDist): axes_config = dict( x_range=(0, 8), y_range=(0, 1, 0.1), width=5, height=6, ) bar_count_font_size = 24 class ThinV2Stats(SimulatedGamesFreqBasedPriorDist): axes_config = ThinV1Stats.axes_config bar_count_font_size = 24 class ThinV3Stats(SimulatedGamesWordleBasedPriorCraneStartDist): axes_config = ThinV1Stats.axes_config bar_count_font_size = 24 class GenericWrapper(VideoWrapper): pass # Thumbnail class Thumbnail(Scene): def construct(self): # Grid answer = "aging" guesses = ["crane", "tousy", answer] patterns = [get_pattern(guess, answer) for guess in guesses] rows = WordleScene.patterns_to_squares( patterns, color_map=[GREY_D, YELLOW, GREEN_E] ) rows.set_stroke(width=0) rows.set_width(0.5 * FRAME_WIDTH) rows.to_edge(DOWN, buff=1.0) rows.set_gloss(0.4) self.add(rows) # Words in grid (probbaly don't include) words = VGroup() for guess, row in zip(guesses, rows): word = Text(guess.upper(), font="Consolas") word.set_height(0.6 * row.get_height()) for char, square in zip(word, row): char.move_to(square) words.add(word) # self.add(words) # Title title = Text( "Best opener: CRANE", font_size=100, font="Consolas", t2c={"crane": GREEN} ) title.to_edge(UP, buff=0.75) self.add(title) self.rows = rows self.title = title
from manim_imports_ext import * from tqdm import tqdm as ProgressDisplay from scipy.stats import entropy MISS = np.uint8(0) MISPLACED = np.uint8(1) EXACT = np.uint8(2) DATA_DIR = os.path.join( os.path.dirname(os.path.realpath(__file__)), "data", ) SHORT_WORD_LIST_FILE = os.path.join(DATA_DIR, "possible_words.txt") LONG_WORD_LIST_FILE = os.path.join(DATA_DIR, "allowed_words.txt") WORD_FREQ_FILE = os.path.join(DATA_DIR, "wordle_words_freqs_full.txt") WORD_FREQ_MAP_FILE = os.path.join(DATA_DIR, "freq_map.json") SECOND_GUESS_MAP_FILE = os.path.join(DATA_DIR, "second_guess_map.json") PATTERN_MATRIX_FILE = os.path.join(DATA_DIR, "pattern_matrix.npy") ENT_SCORE_PAIRS_FILE = os.path.join(DATA_DIR, "ent_score_pairs.json") # To store the large grid of patterns at run time PATTERN_GRID_DATA = dict() def safe_log2(x): return math.log2(x) if x > 0 else 0 # Reading from files def get_word_list(short=False): result = [] file = SHORT_WORD_LIST_FILE if short else LONG_WORD_LIST_FILE with open(file) as fp: result.extend([word.strip() for word in fp.readlines()]) return result def get_word_frequencies(regenerate=False): if os.path.exists(WORD_FREQ_MAP_FILE) or regenerate: with open(WORD_FREQ_MAP_FILE) as fp: result = json.load(fp) return result # Otherwise, regenerate freq_map = dict() with open(WORD_FREQ_FILE) as fp: for line in fp.readlines(): pieces = line.split(' ') word = pieces[0] freqs = [ float(piece.strip()) for piece in pieces[1:] ] freq_map[word] = np.mean(freqs[-5:]) with open(WORD_FREQ_MAP_FILE, 'w') as fp: json.dump(freq_map, fp) return freq_map def get_frequency_based_priors(n_common=3000, width_under_sigmoid=10): """ We know that that list of wordle answers was curated by some human based on whether they're sufficiently common. This function aims to associate each word with the likelihood that it would actually be selected for the final answer. Sort the words by frequency, then apply a sigmoid along it. """ freq_map = get_word_frequencies() words = np.array(list(freq_map.keys())) freqs = np.array([freq_map[w] for w in words]) arg_sort = freqs.argsort() sorted_words = words[arg_sort] # We want to imagine taking this sorted list, and putting it on a number # line so that it's length is 10, situating it so that the n_common most common # words are positive, then applying a sigmoid x_width = width_under_sigmoid c = x_width * (-0.5 + n_common / len(words)) xs = np.linspace(c - x_width / 2, c + x_width / 2, len(words)) priors = dict() for word, x in zip(sorted_words, xs): priors[word] = sigmoid(x) return priors def get_true_wordle_prior(): words = get_word_list() short_words = get_word_list(short=True) return dict( (w, int(w in short_words)) for w in words ) # Generating color patterns between strings, etc. def words_to_int_arrays(words): return np.array([[ord(c)for c in w] for w in words], dtype=np.uint8) def generate_pattern_matrix(words1, words2): """ A pattern for two words represents the wordle-similarity pattern (grey -> 0, yellow -> 1, green -> 2) but as an integer between 0 and 3^5. Reading this integer in ternary gives the associated pattern. This function computes the pairwise patterns between two lists of words, returning the result as a grid of hash values. Since this can be time-consuming, many operations that can be are vectorized (perhaps at the expense of easier readibility), and the the result is saved to file so that this only needs to be evaluated once, and all remaining pattern matching is a lookup. """ # Number of letters/words nl = len(words1[0]) nw1 = len(words1) # Number of words nw2 = len(words2) # Number of words # Convert word lists to integer arrays word_arr1, word_arr2 = map(words_to_int_arrays, (words1, words2)) # equality_grid keeps track of all equalities between all pairs # of letters in words. Specifically, equality_grid[a, b, i, j] # is true when words[i][a] == words[b][j] equality_grid = np.zeros((nw1, nw2, nl, nl), dtype=bool) for i, j in it.product(range(nl), range(nl)): equality_grid[:, :, i, j] = np.equal.outer(word_arr1[:, i], word_arr2[:, j]) # full_pattern_matrix[a, b] should represent the 5-color pattern # for guess a and answer b, with 0 -> grey, 1 -> yellow, 2 -> green full_pattern_matrix = np.zeros((nw1, nw2, nl), dtype=np.uint8) # Green pass for i in range(nl): matches = equality_grid[:, :, i, i].flatten() # matches[a, b] is true when words[a][i] = words[b][i] full_pattern_matrix[:, :, i].flat[matches] = EXACT for k in range(nl): # If it's a match, mark all elements associated with # that letter, both from the guess and answer, as covered. # That way, it won't trigger the yellow pass. equality_grid[:, :, k, i].flat[matches] = False equality_grid[:, :, i, k].flat[matches] = False # Yellow pass for i, j in it.product(range(nl), range(nl)): matches = equality_grid[:, :, i, j].flatten() full_pattern_matrix[:, :, i].flat[matches] = MISPLACED for k in range(nl): # Similar to above, we want to mark this letter # as taken care of, both for answer and guess equality_grid[:, :, k, j].flat[matches] = False equality_grid[:, :, i, k].flat[matches] = False # Rather than representing a color pattern as a lists of integers, # store it as a single integer, whose ternary representations corresponds # to that list of integers. pattern_matrix = np.dot( full_pattern_matrix, (3**np.arange(nl)).astype(np.uint8) ) return pattern_matrix def generate_full_pattern_matrix(): words = get_word_list() pattern_matrix = generate_pattern_matrix(words, words) # Save to file np.save(PATTERN_MATRIX_FILE, pattern_matrix) return pattern_matrix def get_pattern_matrix(words1, words2): if not PATTERN_GRID_DATA: if not os.path.exists(PATTERN_MATRIX_FILE): log.info("\n".join([ "Generating pattern matrix. This takes a minute, but", "the result will be saved to file so that it only", "needs to be computed once.", ])) generate_full_pattern_matrix() PATTERN_GRID_DATA['grid'] = np.load(PATTERN_MATRIX_FILE) PATTERN_GRID_DATA['words_to_index'] = dict(zip( get_word_list(), it.count() )) full_grid = PATTERN_GRID_DATA['grid'] words_to_index = PATTERN_GRID_DATA['words_to_index'] indices1 = [words_to_index[w] for w in words1] indices2 = [words_to_index[w] for w in words2] return full_grid[np.ix_(indices1, indices2)] def get_pattern(guess, answer): if PATTERN_GRID_DATA: saved_words = PATTERN_GRID_DATA['words_to_index'] if guess in saved_words and answer in saved_words: return get_pattern_matrix([guess], [answer])[0, 0] return generate_pattern_matrix([guess], [answer])[0, 0] def pattern_from_string(pattern_string): return sum((3**i) * int(c) for i, c in enumerate(pattern_string)) def pattern_to_int_list(pattern): result = [] curr = pattern for x in range(5): result.append(curr % 3) curr = curr // 3 return result def pattern_to_string(pattern): d = {MISS: "⬛", MISPLACED: "🟨", EXACT: "🟩"} return "".join(d[x] for x in pattern_to_int_list(pattern)) def patterns_to_string(patterns): return "\n".join(map(pattern_to_string, patterns)) def get_possible_words(guess, pattern, word_list): all_patterns = get_pattern_matrix([guess], word_list).flatten() return list(np.array(word_list)[all_patterns == pattern]) def get_word_buckets(guess, possible_words): buckets = [[] for x in range(3**5)] hashes = get_pattern_matrix([guess], possible_words).flatten() for index, word in zip(hashes, possible_words): buckets[index].append(word) return buckets # Functions associated with entropy calculation def get_weights(words, priors): frequencies = np.array([priors[word] for word in words]) total = frequencies.sum() if total == 0: return np.zeros(frequencies.shape) return frequencies / total def get_pattern_distributions(allowed_words, possible_words, weights): """ For each possible guess in allowed_words, this finds the probability distribution across all of the 3^5 wordle patterns you could see, assuming the possible answers are in possible_words with associated probabilities in weights. It considers the pattern hash grid between the two lists of words, and uses that to bucket together words from possible_words which would produce the same pattern, adding together their corresponding probabilities. """ pattern_matrix = get_pattern_matrix(allowed_words, possible_words) n = len(allowed_words) distributions = np.zeros((n, 3**5)) n_range = np.arange(n) for j, prob in enumerate(weights): distributions[n_range, pattern_matrix[:, j]] += prob return distributions def entropy_of_distributions(distributions, atol=1e-12): axis = len(distributions.shape) - 1 return entropy(distributions, base=2, axis=axis) def get_entropies(allowed_words, possible_words, weights): if weights.sum() == 0: return np.zeros(len(allowed_words)) distributions = get_pattern_distributions(allowed_words, possible_words, weights) return entropy_of_distributions(distributions) def max_bucket_size(guess, possible_words, weights): dist = get_pattern_distributions([guess], possible_words, weights) return dist.max() def words_to_max_buckets(possible_words, weights): return dict( (word, max_bucket_size(word, possible_words, weights)) for word in ProgressDisplay(possible_words) ) words_and_maxes = list(w2m.items()) words_and_maxes.sort(key=lambda t: t[1]) words_and_maxes[:-20:-1] def get_bucket_sizes(allowed_words, possible_words): """ Returns a (len(allowed_words), 243) shape array reprenting the size of word buckets associated with each guess in allowed_words """ weights = np.ones(len(possible_words)) return get_pattern_distributions(allowed_words, possible_words, weights) def get_bucket_counts(allowed_words, possible_words): """ Returns the number of separate buckets that each guess in allowed_words would separate possible_words into """ bucket_sizes = get_bucket_sizes(allowed_words, possible_words) return (bucket_sizes > 0).sum(1) # Functions to analyze second guesses def get_average_second_step_entropies(first_guesses, allowed_second_guesses, possible_words, priors): result = [] weights = get_weights(possible_words, priors) if weights.sum() == 0: return np.zeros(len(first_guesses)) distributions = get_pattern_distributions(first_guesses, possible_words, weights) for first_guess, dist in ProgressDisplay(list(zip(first_guesses, distributions)), leave=False, desc="Searching 2nd step entropies"): word_buckets = get_word_buckets(first_guess, possible_words) # List of maximum entropies you could achieve in # the second step for each pattern you might see # after this setp ents2 = np.array([ get_entropies( allowed_words=allowed_second_guesses, possible_words=bucket, weights=get_weights(bucket, priors) ).max() for bucket in word_buckets ]) # Multiply each such maximal entropy by the corresponding # probability of falling into that bucket result.append(np.dot(ents2, dist)) return np.array(result) # Solvers def get_guess_values_array(allowed_words, possible_words, priors, look_two_ahead=False): weights = get_weights(possible_words, priors) ents1 = get_entropies(allowed_words, possible_words, weights) probs = np.array([ 0 if word not in possible_words else weights[possible_words.index(word)] for word in allowed_words ]) if look_two_ahead: # Look two steps out, but restricted to where second guess is # amoung the remaining possible words ents2 = np.zeros(ents1.shape) top_indices = np.argsort(ents1)[-250:] ents2[top_indices] = get_average_second_step_entropies( first_guesses=np.array(allowed_words)[top_indices], allowed_second_guesses=allowed_words, possible_words=possible_words, priors=priors ) return np.array([ents1, ents2, probs]) else: return np.array([ents1, probs]) def entropy_to_expected_score(ent): """ Based on a regression associating entropies with typical scores from that point forward in simulated games, this function returns what the expected number of guesses required will be in a game where there's a given amount of entropy in the remaining possibilities. """ # Assuming you can definitely get it in the next guess, # this is the expected score min_score = 2**(-ent) + 2 * (1 - 2**(-ent)) # To account for the likely uncertainty after the next guess, # and knowing that entropy of 11.5 bits seems to have average # score of 3.5, we add a line to account # we add a line which connects (0, 0) to (3.5, 11.5) return min_score + 1.5 * ent / 11.5 def get_expected_scores(allowed_words, possible_words, priors, look_two_ahead=False, n_top_candidates_for_two_step=25, ): # Currenty entropy of distribution weights = get_weights(possible_words, priors) H0 = entropy_of_distributions(weights) H1s = get_entropies(allowed_words, possible_words, weights) word_to_weight = dict(zip(possible_words, weights)) probs = np.array([word_to_weight.get(w, 0) for w in allowed_words]) # If this guess is the true answer, score is 1. Otherwise, it's 1 plus # the expected number of guesses it will take after getting the corresponding # amount of information. expected_scores = probs + (1 - probs) * (1 + entropy_to_expected_score(H0 - H1s)) if not look_two_ahead: return expected_scores # For the top candidates, refine the score by looking two steps out # This is currently quite slow, and could be optimized to be faster. # But why? sorted_indices = np.argsort(expected_scores) allowed_second_guesses = get_word_list() expected_scores += 1 # Push up the rest for i in ProgressDisplay(sorted_indices[:n_top_candidates_for_two_step], leave=False): guess = allowed_words[i] H1 = H1s[i] dist = get_pattern_distributions([guess], possible_words, weights)[0] buckets = get_word_buckets(guess, possible_words) second_guesses = [ optimal_guess(allowed_second_guesses, bucket, priors, look_two_ahead=False) for bucket in buckets ] H2s = [ get_entropies([guess2], bucket, get_weights(bucket, priors))[0] for guess2, bucket in zip(second_guesses, buckets) ] prob = word_to_weight.get(guess, 0) expected_scores[i] = sum(( # 1 times Probability guess1 is correct 1 * prob, # 2 times probability guess2 is correct 2 * (1 - prob) * sum( p * word_to_weight.get(g2, 0) for p, g2 in zip(dist, second_guesses) ), # 2 plus expected score two steps from now (1 - prob) * (2 + sum( p * (1 - word_to_weight.get(g2, 0)) * entropy_to_expected_score(H0 - H1 - H2) for p, g2, H2 in zip(dist, second_guesses, H2s) )) )) return expected_scores def get_score_lower_bounds(allowed_words, possible_words): """ Assuming a uniform distribution on how likely each element of possible_words is, this gives the a lower boudn on the possible score for each word in allowed_words """ bucket_counts = get_bucket_counts(allowed_words, possible_words) N = len(possible_words) # Probabilities of getting it in 1 p1s = np.array([w in possible_words for w in allowed_words]) / N # Probabilities of getting it in 2 p2s = bucket_counts / N - p1s # Otherwise, assume it's gotten in 3 (which is optimistics) p3s = 1 - bucket_counts / N return p1s + 2 * p2s + 3 * p3s def optimal_guess(allowed_words, possible_words, priors, look_two_ahead=False, optimize_for_uniform_distribution=False, purely_maximize_information=False, ): if purely_maximize_information: if len(possible_words) == 1: return possible_words[0] weights = get_weights(possible_words, priors) ents = get_entropies(allowed_words, possible_words, weights) return allowed_words[np.argmax(ents)] # Just experimenting here... if optimize_for_uniform_distribution: expected_scores = get_score_lower_bounds( allowed_words, possible_words ) else: expected_scores = get_expected_scores( allowed_words, possible_words, priors, look_two_ahead=look_two_ahead ) return allowed_words[np.argmin(expected_scores)] def brute_force_optimal_guess(all_words, possible_words, priors, n_top_picks=10, display_progress=False): if len(possible_words) == 0: # Doesn't matter what to return in this case, so just default to first word in list. return all_words[0] # For the suggestions with the top expected scores, just # actually play the game out from this point to see what # their actual scores are, and minimize. expected_scores = get_score_lower_bounds(all_words, possible_words) top_choices = [all_words[i] for i in np.argsort(expected_scores)[:n_top_picks]] true_average_scores = [] if display_progress: iterable = ProgressDisplay( top_choices, desc=f"Possibilities: {len(possible_words)}", leave=False ) else: iterable = top_choices for next_guess in iterable: scores = [] for answer in possible_words: score = 1 possibilities = list(possible_words) guess = next_guess while guess != answer: possibilities = get_possible_words( guess, get_pattern(guess, answer), possibilities, ) # Make recursive? If so, we'd want to keep track of # the next_guess map and pass it down in the recursive # subcalls guess = optimal_guess( all_words, possibilities, priors, optimize_for_uniform_distribution=True ) score += 1 scores.append(score) true_average_scores.append(np.mean(scores)) return top_choices[np.argmin(true_average_scores)] # Run simulated wordle games def get_two_step_score_lower_bound(first_guess, allowed_words, possible_words): """ Useful to prove what the minimum possible average score could be for a given initial guess """ N = len(possible_words) buckets = get_word_buckets(first_guess, possible_words) min_score = 0 for bucket in buckets: if len(bucket) == 0: continue lower_bounds = get_score_lower_bounds(allowed_words, bucket) min_score += (len(bucket) / N) * lower_bounds.min() p = (1 / len(possible_words)) * (first_guess in possible_words) return p + (1 - p) * (1 + min_score) def find_top_scorers(n_top_candidates=100, quiet=True, file_ext="", **kwargs): # Run find_best_two_step_entropy first file = os.path.join(get_directories()["data"], "wordle", "best_double_entropies.json") with open(file) as fp: double_ents = json.load(fp) answers = get_word_list(short=True) priors = get_true_wordle_prior() guess_to_score = {} guess_to_dist = {} for row in ProgressDisplay(double_ents[:n_top_candidates]): first_guess = row[0] result, decision_map = simulate_games( first_guess, priors=priors, optimize_for_uniform_distribution=True, quiet=quiet, **kwargs, ) average = result["average_score"] total = int(np.round(average * len(answers))) guess_to_score[first_guess] = total guess_to_dist[first_guess] = result["score_distribution"] top_scorers = sorted(list(guess_to_score.keys()), key=lambda w: guess_to_score[w]) result = [[w, guess_to_score[w], guess_to_dist[w]] for w in top_scorers] file = os.path.join( get_directories()["data"], "wordle", "best_scores" + file_ext + ".json", ) with open(file, 'w') as fp: json.dump(result, fp) return result def find_best_two_step_entropy(): words = get_word_list() answers = get_word_list(short=True) priors = get_true_wordle_prior() ents = get_entropies(words, answers, get_weights(answers, priors)) sorted_indices = np.argsort(ents) top_candidates = np.array(words)[sorted_indices[:-250:-1]] top_ents = ents[sorted_indices[:-250:-1]] ent_file = os.path.join(get_directories()["data"], "wordle", "best_entropies.json") with open(ent_file, 'w') as fp: json.dump([[tc, te] for tc, te in zip(top_candidates, top_ents)], fp) ents2 = get_average_second_step_entropies( top_candidates, words, answers, priors, ) total_ents = top_ents + ents2 sorted_indices2 = np.argsort(total_ents) double_ents = [ [top_candidates[i], top_ents[i], ents2[i]] for i in sorted_indices2[::-1] ] ent2_file = os.path.join(get_directories()["data"], "wordle", "best_double_entropies.json") with open(ent2_file, 'w') as fp: json.dump(double_ents, fp) return double_ents def find_smallest_second_guess_buckets(n_top_picks=100): all_words = get_word_list() possibilities = get_word_list(short=True) priors = get_true_wordle_prior() weights = get_weights(possibilities, priors) dists = get_pattern_distributions(all_words, possibilities, weights) sorted_indices = np.argsort((dists**2).sum(1)) top_indices = sorted_indices[:n_top_picks] top_picks = np.array(all_words)[top_indices] top_dists = dists[top_indices] # Figure out the average number of matching words there will # be after two steps of game play avg_ts_buckets = [] for first_guess, dist in ProgressDisplay(list(zip(top_picks, top_dists))): buckets = get_word_buckets(first_guess, possibilities) avg_ts_bucket = 0 for p, bucket in zip(dist, buckets): weights = get_weights(bucket, priors) sub_dists = get_pattern_distributions(all_words, bucket, weights) min_ts_bucket = len(bucket) * (sub_dists**2).sum(1).min() avg_ts_bucket += p * min_ts_bucket avg_ts_buckets.append(avg_ts_bucket) result = [] for j in np.argsort(avg_ts_buckets): i = top_indices[j] result.append(( # Word all_words[i], # Average bucket size after first guess len(possibilities) * (dists[i]**2).sum(), # Average bucket size after second, with optimal # play. avg_ts_buckets[j], )) return result def get_optimal_second_guess_map(first_guess, n_top_picks=10, regenerate=False): with open(SECOND_GUESS_MAP_FILE) as fp: all_sgms = json.load(fp) if first_guess in all_sgms and not regenerate: return all_sgms[first_guess] log.info("\n".join([ f"Generating optimal second guess map for {first_guess}.", "This involves brute forcing many simulations", "so can take a little while." ])) sgm = [""] * 3**5 all_words = get_word_list() wordle_answers = get_word_list(short=True) priors = get_true_wordle_prior() buckets = get_word_buckets(first_guess, wordle_answers) for pattern, bucket in ProgressDisplay(list(enumerate(buckets)), leave=False): sgm[pattern] = brute_force_optimal_guess( all_words, bucket, priors, n_top_picks=n_top_picks, display_progress=True ) # Save to file with open(SECOND_GUESS_MAP_FILE) as fp: all_sgms = json.load(fp) all_sgms[first_guess] = sgm with open(SECOND_GUESS_MAP_FILE, 'w') as fp: json.dump(all_sgms, fp) return sgm def gather_entropy_to_score_data(first_guess="crane", priors=None): words = get_word_list() answers = get_word_list(short=True) if priors is None: priors = get_true_wordle_prior() # List of entropy/score pairs ent_score_pairs = [] for answer in ProgressDisplay(answers): score = 1 possibilities = list(filter(lambda w: priors[w] > 0, words)) guess = first_guess guesses = [] entropies = [] while True: guesses.append(guess) weights = get_weights(possibilities, priors) entropies.append(entropy_of_distributions(weights)) if guess == answer: break possibilities = get_possible_words( guess, get_pattern(guess, answer), possibilities ) guess = optimal_guess(words, possibilities, priors) score += 1 for sc, ent in zip(it.count(1), reversed(entropies)): ent_score_pairs.append((ent, sc)) with open(ENT_SCORE_PAIRS_FILE, 'w') as fp: json.dump(ent_score_pairs, fp) return ent_score_pairs def simulate_games(first_guess=None, priors=None, look_two_ahead=False, optimize_for_uniform_distribution=False, second_guess_map=None, exclude_seen_words=False, test_set=None, shuffle=False, hard_mode=False, purely_maximize_information=False, brute_force_optimize=False, brute_force_depth=10, results_file=None, next_guess_map_file=None, quiet=False, ): all_words = get_word_list(short=False) short_word_list = get_word_list(short=True) if first_guess is None: first_guess = optimal_guess( all_words, all_words, priors, **choice_config ) if priors is None: priors = get_frequency_based_priors() if test_set is None: test_set = short_word_list if shuffle: random.shuffle(test_set) seen = set() # Function for choosing the next guess, with a dict to cache # and reuse results that are seen multiple times in the sim next_guess_map = {} def get_next_guess(guesses, patterns, possibilities): phash = "".join( str(g) + "".join(map(str, pattern_to_int_list(p))) for g, p in zip(guesses, patterns) ) if second_guess_map is not None and len(patterns) == 1: next_guess_map[phash] = second_guess_map[patterns[0]] if phash not in next_guess_map: choices = all_words if hard_mode: for guess, pattern in zip(guesses, patterns): choices = get_possible_words(guess, pattern, choices) if brute_force_optimize: next_guess_map[phash] = brute_force_optimal_guess( choices, possibilities, priors, n_top_picks=brute_force_depth, ) else: next_guess_map[phash] = optimal_guess( choices, possibilities, priors, look_two_ahead=look_two_ahead, purely_maximize_information=purely_maximize_information, optimize_for_uniform_distribution=optimize_for_uniform_distribution, ) return next_guess_map[phash] # Go through each answer in the test set, play the game, # and keep track of the stats. scores = np.zeros(0, dtype=int) game_results = [] for answer in ProgressDisplay(test_set, leave=False, desc=" Trying all wordle answers"): guesses = [] patterns = [] possibility_counts = [] possibilities = list(filter(lambda w: priors[w] > 0, all_words)) if exclude_seen_words: possibilities = list(filter(lambda w: w not in seen, possibilities)) score = 1 guess = first_guess while guess != answer: pattern = get_pattern(guess, answer) guesses.append(guess) patterns.append(pattern) possibilities = get_possible_words(guess, pattern, possibilities) possibility_counts.append(len(possibilities)) score += 1 guess = get_next_guess(guesses, patterns, possibilities) # Accumulate stats scores = np.append(scores, [score]) score_dist = [ int((scores == i).sum()) for i in range(1, scores.max() + 1) ] total_guesses = scores.sum() average = scores.mean() seen.add(answer) game_results.append(dict( score=int(score), answer=answer, guesses=guesses, patterns=list(map(int, patterns)), reductions=possibility_counts, )) # Print outcome if not quiet: message = "\n".join([ "", f"Score: {score}", f"Answer: {answer}", f"Guesses: {guesses}", f"Reductions: {possibility_counts}", *patterns_to_string((*patterns, 3**5 - 1)).split("\n"), *" " * (6 - len(patterns)), f"Distribution: {score_dist}", f"Total guesses: {total_guesses}", f"Average: {average}", *" " * 2, ]) if answer is not test_set[0]: # Move cursor back up to the top of the message n = len(message.split("\n")) + 1 print(("\033[F\033[K") * n) else: print("\r\033[K\n") print(message) final_result = dict( score_distribution=score_dist, total_guesses=int(total_guesses), average_score=float(scores.mean()), game_results=game_results, ) # Save results for obj, file in [(final_result, results_file), (next_guess_map, next_guess_map_file)]: if file: path = os.path.join(DATA_DIR, "simulation_results", file) with open(path, 'w') as fp: json.dump(obj, fp) return final_result, next_guess_map if __name__ == "__main__": first_guess = "salet" results, decision_map = simulate_games( first_guess=first_guess, priors=get_true_wordle_prior(), optimize_for_uniform_distribution=True, # shuffle=True, # brute_force_optimize=True, # hard_mode=True, )
from manim_imports_ext import * from _2022.wordle.scenes import * class HeresTheThing(TeacherStudentsScene): def construct(self): thumbnail = ImageMobject(os.path.join( self.file_writer.output_directory, self.file_writer.get_default_module_directory(), os.pardir, "images", "Thumbnail", )) thumbnail = Group( SurroundingRectangle(thumbnail, buff=0, stroke_color=WHITE, stroke_width=2), thumbnail ) thumbnail.set_height(3) thumbnail.move_to(self.hold_up_spot, DOWN) self.play( self.teacher.change("raise_right_hand"), FadeIn(thumbnail, UP), ) self.play_student_changes( "raise_left_hand", "pondering", "erm", look_at=self.teacher.eyes, ) self.wait() self.teacher_says( OldTexText("Right, here's\\\\the thing...", font_size=40), target_mode="hesitant", bubble_config=dict(width=3.5, height=2.5), run_time=1, added_anims=[ self.change_students("dance_3", "frustrated", "sassy"), thumbnail.animate.to_corner(UL), ] ) self.look_at(thumbnail) cross = Cross(Text("CRANE")) cross.insert_n_curves(20) cross.move_to(thumbnail, UR) cross.shift([-0.25, -0.22, 0]) self.play(ShowCreation(cross)) self.wait(3) class WriteTheTitle(Scene): def construct(self): title = Text("Solving Wordle using\ninformation theory", font_size=60) title.get_part_by_text('information theory').set_color(BLUE) self.play(Write(title)) self.wait() class Confessions(Scene): def construct(self): titles = VGroup(*( Text(f"Confession {n}", font_size=60) for n in range(1, 4) )) titles.arrange(DOWN, buff=2, aligned_edge=LEFT) titles.center() for title in titles: title.save_state() title.generate_target() phrases = VGroup( OldTexText("Bug in the code", font_size=48), OldTexText("About the opening scene...", font_size=48), OldTexText("Maybe don't use entropy?", font_size=48), ) self.play(LaggedStart(*( FadeIn(title, RIGHT) for title in titles ), lag_ratio=0.3)) self.wait() last_phrase = VMobject() for title, phrase in zip(titles, phrases): others = VGroup(*( t for t in titles if t is not title )) others_target = VGroup(*(t.target for t in others)) for t in others_target: t.set_height(0.2) t.set_opacity(0.5) others_target.arrange(DOWN, buff=0.75) others_target.to_edge(LEFT) phrase.set_color(BLUE) phrase.to_edge(UP, buff=1.5) self.play( FadeOut(last_phrase), title.animate.restore().set_height(0.5).center().to_edge(UP), *map(MoveToTarget, others), ) self.play(FadeIn(phrase)) self.wait(2) last_phrase = phrase class WhatWasTheBug(TeacherStudentsScene): def construct(self): self.student_says("What as the bug?") self.play( self.change_students("raise_left_hand", "pondering", "raise_right_hand"), self.teacher.change("tired") ) self.wait(3) class HowWordleColoringWorks(WordleScene): def construct(self): # Rows guess_row = self.grid[0].copy() answer_row = self.grid[0].copy() rows = VGroup(guess_row, answer_row) rows.arrange(DOWN, buff=LARGE_BUFF) words = VGroup() for row in rows: row.word = VGroup() self.add(row.word) words.add(row.word) self.add(rows) self.remove(self.grid) # Add labels guess_label = OldTexText("Guess $\\rightarrow$") answer_label = OldTexText("Answer $\\rightarrow$") labels = VGroup(guess_label, answer_label) for label, row in zip(labels, rows): label.next_to(row, LEFT, buff=MED_LARGE_BUFF) def get_box_to_box_path(box1, box2): p1 = box1.get_bottom() p2 = box2.get_top() v = 0.3 * get_norm(p2 - p1) * DOWN return CubicBezier(p1, p1 + v, p2 - v, p2) def get_grey_label(i): result = VGroup( Vector(0.5 * UP), OldTexText("No 2nd `E'"), ) result.arrange(UP, SMALL_BUFF) result.next_to(guess_row[i], UP, SMALL_BUFF) result.set_color(GREY_B) return result def generate_group_target(group): target = group.copy() target.scale(0.3) for sm in target.get_family(): if sm.get_stroke_width() > 0: sm.set_stroke(width=1.5) return target # And answer, yellow grey guess = "speed" answer = "abide" self.play(Write(guess_label), run_time=1) self.write_word_in_row(guess, guess_row) self.wait() answer_row.generate_target() answer_row.target.set_stroke(GREEN, 3) self.play( Write(answer_row.target, remover=True), Write(answer_label), run_time=1 ) answer_row.match_style(answer_row.target) self.write_word_in_row(answer, answer_row,) self.wait() colors = self.get_colors(get_pattern(guess, answer)) self.animate_color_change(guess_row, guess_row.word, colors) self.wait() # Explain two e's path = get_box_to_box_path(guess_row[2], answer_row[4]) gl = get_grey_label(3) self.play(ShowCreation(path)) self.play(Write(gl)) self.wait() group1 = VGroup( guess_row.copy(), answer_row.copy(), guess_row.word.copy(), answer_row.word.copy(), path, gl, ) answer_row.word.set_submobjects([]) vect = 1.5 * DOWN self.play( Transform(group1, generate_group_target(group1).to_corner(UL)), labels.animate.shift(vect), rows.animate.set_fill(BLACK, 0).shift(vect), guess_row.word.animate.shift(vect), ) # General transition def change_answer(answer): self.write_word_in_row(answer, answer_row) colors = self.get_colors(get_pattern(guess, answer)) self.animate_color_change(guess_row, guess_row.word, colors) self.wait() # Two yellows change_answer("erase") path1 = get_box_to_box_path(guess_row[2], answer_row[0]) path2 = get_box_to_box_path(guess_row[3], answer_row[4]) self.play(ShowCreation(path1)) self.play(ShowCreation(path2)) self.wait() group2 = VGroup( *rows.copy(), *words.copy(), path1, path2, ) answer_row.word.set_submobjects([]) group2.target = generate_group_target(group2) group2.target.next_to(group1, RIGHT, buff=LARGE_BUFF, aligned_edge=DOWN) self.play( guess_row.animate.set_fill(BLACK, 0), MoveToTarget(group2), ) # Green grey change_answer("steal") path = get_box_to_box_path(guess_row[2], answer_row[2]) gl = get_grey_label(3) self.play(ShowCreation(path)) self.play(Write(gl)) self.wait() group3 = VGroup( *rows.copy(), *words.copy(), path, gl, ) answer_row.word.set_submobjects([]) group3.target = generate_group_target(group3) group3.target.next_to(group2, RIGHT, buff=LARGE_BUFF, aligned_edge=DOWN) self.play( guess_row.animate.set_fill(BLACK, 0), MoveToTarget(group3) ) # Green yellow change_answer("crepe") path1 = get_box_to_box_path(guess_row[2], answer_row[2]) path2 = get_box_to_box_path(guess_row[3], answer_row[4]) self.play(ShowCreation(path1)) self.play(ShowCreation(path2)) self.wait() group4 = VGroup(*rows, *words, path1, path2) # Organize all groups groups = VGroup(group1, group2, group3, group4) groups.generate_target() groups.target[-1].become(generate_group_target(group4)) groups.target.arrange(RIGHT, buff=LARGE_BUFF, aligned_edge=DOWN) groups.target.set_width(FRAME_WIDTH - 1) groups.target.to_edge(UP) self.play( MoveToTarget(groups, run_time=2), FadeOut(labels) ) # Compare to bug low_groups = groups.deepcopy() low_groups.to_edge(DOWN, buff=LARGE_BUFF) paths = VGroup() for lg in low_groups: # Remove grey labels lg.remove(lg[-1]) # Make fourth square grey lg[0][3].set_fill(WordleScene.color_map[1]) new_path = get_box_to_box_path(lg[0][3], VectorizedPoint(lg[-1].get_end())) new_path.set_stroke(width=1.5) lg.add(new_path) paths.add(*lg[-2:]) paths.set_opacity(0) bug_box = SurroundingRectangle(low_groups, buff=0.25) bug_box.set_stroke(RED, 3) bug_label = Text("Buggy behavior") bug_label.next_to(bug_box, UP) bug_label.set_color(RED) self.play( FadeTransform(groups.copy(), low_groups), FadeIn(bug_box), Write(bug_label), ) paths.set_stroke(opacity=1) self.play(LaggedStartMap(ShowCreation, paths, lag_ratio=0.5, run_time=3)) self.wait() def animate_color_change(self, row, word, colors): super().animate_color_change(row, word, colors) self.add(word) def write_word_in_row(self, word, row, added_anims=[]): word_mob = VGroup(*( self.get_letter_in_square(letter, square) for letter, square in zip(word, row) )) self.play( ShowIncreasingSubsets(word_mob, run_time=0.5), *added_anims, ) self.remove(word_mob) row.word.set_submobjects(list(word_mob)) def delete_word_from_row(self, row, added_anims=[]): self.play(FadeOut(row.word, lag_ratio=0.2), *added_anims) row.word.set_submobjects([]) self.add(row.word) class MatrixOfPatterns(Scene): n_shown_words = 50 def construct(self): words = get_word_list(short=True) words = random.sample(words, self.n_shown_words) words.sort() word_mobs = VGroup(*(Text(word, font="Consolas", font_size=30) for word in words)) top_row = word_mobs.copy().arrange(RIGHT, buff=0.35) left_col = word_mobs.copy().arrange(DOWN, buff=0.35) top_row.to_corner(UL).shift(1.25 * RIGHT) left_col.to_corner(UL).shift(0.5 * DOWN) h_line = Line(LEFT, RIGHT).match_width(top_row).scale(1.2) v_line = Line(UP, DOWN).match_height(left_col).scale(1.2) h_line.next_to(top_row, DOWN, SMALL_BUFF) v_line.next_to(left_col, RIGHT) lines = VGroup(h_line, v_line) lines.set_stroke(GREY, 1) pattern_mobs = VGroup() for n in range(2 * self.n_shown_words): for k in range(n + 1): if n - k > len(words) - 1 or k > len(words) - 1: continue w1 = left_col[n - k] w2 = top_row[k] pattern = get_pattern(w1.text, w2.text) pm = WordleScene.patterns_to_squares([pattern])[0] pm.set_stroke(WHITE, 0.5) pm.match_width(w1) pm.match_y(w1) pm.match_x(w2, UP) pattern_mobs.add(pm) frame = self.camera.frame self.add(top_row, left_col) self.add(h_line, v_line) self.play( ApplyMethod( frame.set_height, 25, dict(about_edge=UL), rate_func=squish_rate_func(smooth, 0.1, 1), ), ShowIncreasingSubsets(pattern_mobs), run_time=20, ) self.wait() class SaletBruteForceDistribution(ShowScoreDistribution): data_file = "salet_brute_force.json" class CraneBruteForceDistribution(ShowScoreDistribution): data_file = "crane_brute_force.json" class CrateBruteForceDistribution(ShowScoreDistribution): data_file = "crate_brute_force.json" class TraceBruteForceDistribution(ShowScoreDistribution): data_file = "trace_brute_force.json" class LeastDistribution(ShowScoreDistribution): data_file = "least_results.json" class SlateDistribution(ShowScoreDistribution): data_file = "slate_results.json" class WearyDistribution(ShowScoreDistribution): data_file = "weary_results.json" class AdieuDistribution(ShowScoreDistribution): data_file = "adieu_results.json" class AudioDistribution(ShowScoreDistribution): data_file = "audio_results.json" class LastVideoWrapper(VideoWrapper): title = "Last video" class SneakAttackInformationTheory(Scene): def construct(self): randy = Randolph() randy.to_edge(DOWN) phone = ImageMobject("wordle-phone") phone.set_height(4) phone.next_to(randy, RIGHT) phone.shift(UP) phone_outline = SVGMobject("wordle-phone") phone_outline.set_fill(opacity=0) phone_outline.set_stroke(width=0) phone_outline.replace(phone).scale(0.8) self.play( randy.change("thinking", phone), FadeIn(phone), Write(phone_outline, stroke_width=1, run_time=2), ) self.play(Blink(randy)) self.wait() # surprise words = VGroup( Text("Surprise!"), Text("Information theory!"), ) words.scale(1.25) words.arrange(DOWN) words.to_corner(UL) ent_formula = OldTex("H = \\sum_{x} -p(x)\\log_2\\big(p(x)\\right)") ent_formula.set_color(TEAL) ent_formula.next_to(words, DOWN, LARGE_BUFF) self.play( FadeIn(words[0], scale=2), randy.change("horrified", words), run_time=0.5 ) self.play( FadeIn(words[1], scale=2), run_time=0.5, ) self.play(Blink(randy)) self.play( Write(ent_formula), randy.change("erm", ent_formula), ) self.play(Blink(randy)) self.wait(2) self.play(Blink(randy)) self.wait(2) class HowAreYouFindingTheBest(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("What exactly is this\\\\``final analysis''?"), index=0, ) self.play( self.students[1].change("pondering"), self.students[2].change("raise_left_hand"), self.teacher.change("happy") ) self.wait(2) self.teacher_says(OldTexText("I'm glad\\\\you asked!"), target_mode="hooray") self.wait(3) class SaletDistThin(SaletBruteForceDistribution): axes_config = dict( x_range=(0, 6), y_range=(0, 1, 0.1), width=4.5, height=6, ) bar_count_font_size = 24 class CrateDistThin(SaletDistThin): data_file = "crate_brute_force.json" class TraceDistThin(SaletDistThin): data_file = "trace_brute_force.json" class FromEstimatedProbabilityOfInclusionToExact(DistributionOverWord): def construct(self): super().construct() bars = self.bars decs = self.decs word_mobs = self.word_mobs true_answers = get_word_list(short=True) anims = [] height = 1.5 for bar, dec, word_mob in zip(bars, decs, word_mobs): value = float(word_mob.text in true_answers) anims.extend([ bar.animate.set_height(value * height, stretch=True, about_edge=DOWN), ChangeDecimalToValue(dec, 100 * value), ]) self.play(*anims, run_time=2) self.wait() self.embed() class SearchThroughFirstGuessDistributions(HowLookTwoAheadWorks): def construct(self): # Setup all_words = get_word_list() possibilities = get_word_list() priors = self.get_priors() template = self.get_word_mob("soare").to_edge(LEFT) # Show first guess sample = random.sample(all_words, 300) for word in sample: guess = self.get_word_mob(word) guess.move_to(template, RIGHT) pattern_array = self.get_pattern_array(guess, possibilities, priors) prob_bars = self.get_prob_bars(pattern_array.pattern_mobs) EI_label = self.get_entropy_label(guess, pattern_array.distribution) self.add(guess) self.add(pattern_array) self.add(prob_bars) self.add(EI_label) self.wait(0.05) self.clear() class TwoStepLookAheadWithSlane(HowLookTwoAheadWorks): first_guess = "slane" n_shown_trials = 120 transition_time = 0.01 def get_priors(self): return get_true_wordle_prior() class TwoStepLookAheadWithSoare(TwoStepLookAheadWithSlane): first_guess = "soare" class TwoStepLookAheadWithCrane(TwoStepLookAheadWithSlane): first_guess = "crane" class TwoStepLookAheadWithSalet(TwoStepLookAheadWithSlane): first_guess = "salet" class SaletSecondGuessMap(HowLookTwoAheadWorks): first_guess = "salet" def construct(self): path = os.path.join(get_directories()['data'], 'wordle', 'salet_with_brute_force_guess_map.json') with open(path) as fp: self.guess_map = json.load(fp) self.all_words = get_word_list() possibilities = get_word_list(short=True) priors = self.priors = self.get_priors() guess1 = self.get_word_mob(self.first_guess) guess1.to_edge(LEFT) pattern_array1 = self.get_pattern_array(guess1, possibilities, priors) arrows, guess2s = self.get_next_guess_group(guess1.text, pattern_array1, possibilities) self.add(guess1) self.add(pattern_array1) self.play( LaggedStartMap(ShowCreation, arrows, lag_ratio=0.5), LaggedStartMap(FadeIn, guess2s, lambda m: (m, RIGHT), lag_ratio=0.5), run_time=2, ) self.wait() for pm, guess2 in zip(pattern_array1.pattern_mobs, guess2s): bucket = get_possible_words(guess1.text, pm.pattern, possibilities) pattern_array2 = self.get_pattern_array(guess2, bucket, priors) ng_group = self.get_next_guess_group( guess2.text, pattern_array2, bucket, prefix=guess1.text + "".join(map(str, pattern_to_int_list(pm.pattern))), ) self.add(pattern_array2, ng_group) self.wait(0.5) self.remove(pattern_array2, ng_group) def get_next_guess_group(self, guess, pattern_array, possibilities, prefix=""): arrows = VGroup() guesses = VGroup() for pm in pattern_array.pattern_mobs: ps = "".join(map(str, pattern_to_int_list(pm.pattern))) key = prefix + guess + ps if key in self.guess_map: next_guess = self.guess_map[key] else: next_guess = optimal_guess( self.all_words, get_possible_words(guess, pm.pattern, possibilities), self.priors, optimize_for_uniform_distribution=True ) next_guess_mob = self.get_word_mob(next_guess) next_guess_mob.scale(0.8) arrow = Vector(0.5 * RIGHT, stroke_width=3) arrow.next_to(pm, RIGHT, buff=SMALL_BUFF) next_guess_mob.next_to(arrow, RIGHT, buff=SMALL_BUFF) arrows.add(arrow) guesses.add(next_guess_mob) return VGroup(arrows, guesses) class RankingUpdates(Scene): def construct(self): # Titles kw = dict(tex_to_color_map={"$E[I]$": TEAL}, font_size=30) titles = VGroup( OldTexText("Highest $E[I]$\\\\(one step)", **kw), OldTexText("Highest $E[I]$\\\\(two steps)", **kw), OldTexText("Lowest average\\\\scores", **kw), ) for x, title in zip(range(-1, 2), titles): title.set_x(x * FRAME_WIDTH / 3) title.to_edge(UP, buff=MED_SMALL_BUFF) titles.to_edge(UP) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.set_stroke(GREY_B, 1) h_line.next_to(titles, DOWN) h_line.set_x(0) v_lines = VGroup(*( Line(UP, DOWN).set_height(FRAME_HEIGHT).set_x(x * FRAME_WIDTH / 6) for x in (-1, 1) )) v_lines.match_style(h_line) self.add(h_line) self.add(v_lines) # Lists n_shown = 15 def get_column(rows, title, row_height=0.2, buff=0.2): for row in rows: row.move_to(ORIGIN, LEFT) rows.set_height(row_height) for i, row in enumerate(rows): row.shift(i * (row_height + buff) * DOWN) rows.next_to(h_line, DOWN) numbers = VGroup() for i, row in zip(it.count(1), rows): num = Integer(i, unit=".") num.match_height(row) num.next_to(row, LEFT) numbers.add(num) result = VGroup(numbers, rows) result.match_x(title) result.rows = rows result.numbers = numbers return result # One step with open(os.path.join(get_directories()["data"], "wordle", "best_entropies.json")) as fp: rows1 = VGroup() for word, ent in json.load(fp)[:n_shown]: row = VGroup( Text(word, font="Consolas"), OldTex("\\rightarrow"), DecimalNumber(ent, color=TEAL), ) row.arrange(RIGHT) rows1.add(row) # Two step with open(os.path.join(get_directories()["data"], "wordle", "best_double_entropies.json")) as fp: rows2 = VGroup() for word, ent1, ent2 in json.load(fp)[:n_shown]: row = VGroup( Text(word, font="Consolas"), OldTex("\\rightarrow"), DecimalNumber(ent1, color=TEAL), OldTex("+"), DecimalNumber(ent2, color=TEAL), OldTex("="), DecimalNumber(ent1 + ent2, color=TEAL), ) row.arrange(RIGHT) rows2.add(row) # Score answers = get_word_list(short=True) with open(os.path.join(get_directories()["data"], "wordle", "best_scores_with_entropy_method.json")) as fp: rows3 = VGroup() for word, score, dist in json.load(fp)[:n_shown]: row = VGroup( Text(word, font="Consolas"), OldTex("\\rightarrow"), DecimalNumber(score / len(answers), num_decimal_places=3, color=BLUE), ) row.arrange(RIGHT) rows3.add(row) all_rows = [rows1, rows2, rows3] col1, col2, col3 = cols = [ get_column(rows, title) for rows, title in zip(all_rows, titles) ] for row in col2.rows: row[-2:].align_to(col2.rows[0][-2:], LEFT) # Animations self.add(titles[0]) self.play(FadeIn(col1, lag_ratio=0.1, run_time=2)) self.wait() last_col = col1 for title, col in zip(titles[1:], cols[1:]): pre_words = VGroup(*(r[0] for r in last_col.rows)) words = VGroup(*(r[0] for r in col.rows)) mover_anims = [] fade_anims = [] for word in words: has_pre = False for pre_word in pre_words: if word.text == pre_word.text: has_pre = True mover_anims.append(TransformFromCopy(pre_word, word)) if not has_pre: fade_anims.append(FadeInFromPoint(word, last_col.get_bottom())) for row in col.rows: fade_anims.append(FadeIn(row[1:])) self.play( FadeIn(title), FadeIn(col.numbers, lag_ratio=0.1), LaggedStart(*mover_anims, run_time=2, lag_ratio=0.2), ) self.play(LaggedStart(*fade_anims)) self.add(col) self.wait() last_col = col class WeCanDoBetter(Scene): def construct(self): morty = Mortimer() morty.to_corner(DR) self.play(PiCreatureSays( morty, OldTexText("We can do\\\\better!"), bubble_config=dict(width=3.5, height=2.5, fill_opacity=0.95), )) for x in range(2): self.play(Blink(morty)) self.wait(2) class WhydYouHaveToRuinIt(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("Why'd you have to\\\\ruin Wordle!"), target_mode="pleading", added_anims=[self.teacher.change("guilty")] ) self.play_student_changes("sassy", "angry", "pleading") self.wait(3) self.teacher_says( OldTexText("But ``salet'' is probably\\\\not the best for us"), added_anims=[self.change_students("confused", "sassy", "hesitant")] ) self.wait(3) class ForgetTheBestWord(Scene): def construct(self): self.add(FullScreenRectangle()) randy = Randolph() randy.to_corner(DL) text = OldTexText("Wait, was it ``slane'',\\\\``salet'' or ``soare''?") self.play(PiCreatureBubbleIntroduction( randy, text, bubble_type=ThoughtBubble, target_mode="confused", )) self.play(Blink(randy)) self.wait() randy.bubble.add(text) self.play( FadeOut(randy.bubble, scale=0.25, shift=2 * DL), randy.change("erm") ) self.wait() self.play(randy.change("thinking", UR)) for x in range(2): self.play(Blink(randy)) self.wait(2) class Thumbnail2(Thumbnail): def construct(self): super().construct() title = self.title self.rows.to_edge(DOWN, buff=MED_SMALL_BUFF) crane = title.get_part_by_text("CRANE") strike = Line( crane.get_corner(DL), crane.get_corner(UR), ) strike.set_stroke(RED, 15) strike.scale(1.2) strike.insert_n_curves(100) strike.set_stroke(width=(2, 15, 15, 2)) self.add(strike) oops = Text("Here's the thing...", font="Consolas", font_size=90) oops.set_color(RED) oops.next_to(title, DR, buff=MED_LARGE_BUFF) oops.shift_onto_screen() self.add(oops) class EndScreen2(EndScreen): pass
from manim_imports_ext import * import sympy PRIME_COLOR = YELLOW def get_primes(max_n=100): pass def get_prime_colors(): pass # Scenes class Intro(InteractiveScene): def construct(self): pass class ShowPrimeDensity(InteractiveScene): def construct(self): # Setup frame = self.camera.frame x_max = 150 numberline = NumberLine((0, x_max), width=0.7 * x_max) numberline.to_edge(LEFT) numberline.add_numbers() def get_number_animation(n): if sympy.isprime(n): return self.get_prime_animation(numberline, n) else: return Animation(Mobject(), remover=True) self.add(numberline) # Show the first 100 primes all_prime_animations = [] soft_smooth = bezier([0, 0, 1, 1]) for n in range(x_max): if sympy.isprime(n): t = smooth() all_prime_animations.append(self.get_prime_animation( numberline, n, run_time=11, time_span=(t, t + 1) )) frame.generate_target() frame.target.move_to(numberline.n2p(100)) frame.target.scale(2) self.play( LaggedStart(*all_prime_animations, lag_ratio=0.25), MoveToTarget( frame, rate_func=smooth, time_span=(2, 10), ), run_time=10, ) # Zoom out to 1 million # Zoom out to 1 trillion # Mention logarithm rule # Ask about log rule def get_prime_animation(self, numberline, prime, **kwargs): numberline.get_unit_size() point = numberline.n2p(prime) dot = GlowDot(point, color=PRIME_COLOR) dot.set_glow_factor(0) dot.set_radius(0.5) dot.set_opacity(0) dot.generate_target() dot.target.set_glow_factor(2) dot.target.set_opacity(1) dot.target.set_radius(DEFAULT_GLOW_DOT_RADIUS) arrow = Vector(DOWN, color=PRIME_COLOR) arrow.move_to(point, DOWN) return AnimationGroup( ShowCreation(arrow), MoveToTarget(dot, rate_func=rush_into), numberline.numbers[prime].animate.set_color(PRIME_COLOR), **kwargs ) class ShowLogarithmicWeighting(InteractiveScene): def construct(self): pass
from manim_imports_ext import * EQUATOR_STYLE = dict(stroke_color=TEAL, stroke_width=2) def get_sphere_slices(radius=1.0, n_slices=20): delta_theta = TAU / n_slices north_slices = Group(*( ParametricSurface( uv_func=lambda u, v: [ radius * math.sin(v) * math.cos(u), radius * math.sin(v) * math.sin(u), radius * math.cos(v), ], u_range=[theta, theta + delta_theta], v_range=[0, PI / 2], resolution=(4, 25), ) for theta in np.arange(0, TAU, delta_theta) )) north_slices.set_x(0) color_slices(north_slices) equator = Circle(**EQUATOR_STYLE) equator.insert_n_curves(100) equator.match_width(north_slices) equator.move_to(ORIGIN) equator.apply_depth_test() return Group(north_slices, get_south_slices(north_slices, dim=2), equator) def get_flattened_slices(radius=1.0, n_slices=20, straightened=True): slc = ParametricSurface( # lambda u, v: [u * v, 1 - v, 0], lambda u, v: [u * math.sin(v * PI / 2), 1 - v, 0], u_range=[-1, 1], v_range=[0, 1], resolution=(4, 25), ) slc.set_width(TAU / n_slices, stretch=True) slc.set_height(radius * PI / 2) north_slices = slc.get_grid(1, n_slices, buff=0) north_slices.move_to(ORIGIN, DOWN) color_slices(north_slices) equator = Line( north_slices.get_corner(DL), north_slices.get_corner(DR), **EQUATOR_STYLE, ) return Group(north_slices, get_south_slices(north_slices, dim=1), equator) def color_slices(slices, colors=(BLUE_D, BLUE_E)): for slc, color in zip(slices, it.cycle([BLUE_D, BLUE_E])): slc.set_color(color) return slices def get_south_slices(north_slices, dim): ss = north_slices.copy().stretch(-1, dim, about_point=ORIGIN) for slc in ss: slc.reverse_points() return ss # Scenes class PreviewThreeExamples(InteractiveScene): def construct(self): # Setup self.add(FullScreenRectangle()) rects = Rectangle(3.5, 4.5).replicate(3) rects.set_stroke(WHITE, 2) rects.set_fill(BLACK, 1) rects.arrange(RIGHT, buff=0.75) rects.to_edge(DOWN, buff=0.25) # Titles titles = VGroup( OldTexText("S.A. = $\\pi^2 R^2$"), OldTex("\\pi = 4").scale(1.5), Text("All triangles\nare isosceles"), ) titles.set_width(rects[0].get_width()) for title, rect in zip(titles, rects): title.next_to(rect, UP) self.play( LaggedStartMap(DrawBorderThenFill, rects, lag_ratio=0.3), LaggedStartMap(FadeIn, titles, shift=0.25 * UP, lag_ratio=0.3), ) self.wait() # Increasing subtlety arrow = Arrow(LEFT, RIGHT, stroke_width=10) arrow.set_width(FRAME_WIDTH - 1) arrow.next_to(titles, UP) arrow.set_stroke(opacity=(0.5, 0.9, 1)) words = Text("Increasingly subtle", font_size=72, color=YELLOW) words.next_to(arrow, UP) VGroup(arrow, words).to_edge(UP) arrow.set_x(0) arrow.set_color(YELLOW) self.play( ShowCreation(arrow), FadeIn(words, lag_ratio=0.1), ) self.wait() class Intro(TeacherStudentsScene): CONFIG = {"background_color": BLACK} def construct(self): morty = self.teacher ss = self.students self.play(morty.change("raise_right_hand")) self.play_student_changes( "pondering", "angry", "confused", look_at=self.screen ) self.wait() self.play(ss[0].change("worried", self.screen)) self.wait() self.play(ss[1].change("pondering", self.screen)) self.wait(3) class SimpleSphereQuestion(InteractiveScene): def construct(self): # Intro statement text = OldTexText("A ``proof'' of a formula for\\\\the surface area of a sphere") text.set_stroke(WHITE, 0) rect = Rectangle(width=TAU, height=TAU / 4) rect.set_stroke(width=0) rect.set_fill(GREY_E, 1) rect.set_width(FRAME_WIDTH) self.add(rect) morty = Mortimer(height=1.5) randy = Randolph(height=1.5) morty.next_to(text, RIGHT) randy.next_to(text, LEFT) VGroup(morty, randy).align_to(rect, DOWN).shift(0.1 * UP) self.add(morty, randy) self.play( Write(text), morty.change("raise_right_hand", text), randy.change("thinking", text) ) self.play(Blink(morty)) self.wait() class SphereExample(InteractiveScene): radius = 2.0 n_slices = 20 slice_stroke_width = 1.0 # show_true_slices = False show_true_slices = True def construct(self): # Setup frame = self.camera.frame frame.set_focal_distance(100) light = self.camera.light_source light.move_to([-10, 2, 5]) # Create the sphere img_path = "/Users/grant/Dropbox/3Blue1Brown/videos/2022/visual_proofs/lies/images/SimpleSphereQuestion.png" radius = 2.5 sphere = TexturedSurface(Sphere(radius=radius), img_path) sphere.set_opacity(1.0) sphere.rotate(91 * DEGREES, OUT).rotate(80 * DEGREES, LEFT) mesh = SurfaceMesh(sphere) mesh.set_stroke(BLUE_B, 1, 0.5) banner = TexturedSurface(Surface(resolution=sphere.resolution), img_path) banner.set_width(FRAME_WIDTH) banner.set_height(FRAME_WIDTH / 4, stretch=True) banner.center() banner.set_gloss(0) banner.set_reflectiveness(0) banner.set_shadow(0) self.add(banner) self.play(ReplacementTransform(banner, sphere, run_time=2)) self.play(Write(mesh, run_time=1)) self.wait() # Slice sphere slices = get_sphere_slices(n_slices=self.n_slices) slices.rotate(90 * DEGREES, OUT).rotate(80 * DEGREES, LEFT) slices.scale(radius) slice_highlights = slices[0][len(slices[0]) // 4:3 * len(slices[0]) // 4].copy().set_color(YELLOW) slice_highlights.scale(1.01, about_point=ORIGIN) flat_slices = get_flattened_slices(n_slices=self.n_slices) flat_slices.to_edge(RIGHT, buff=1.0) self.play( FadeIn(slices), FadeOut(sphere, lag_ratio=0, scale=0.95), FadeOut(mesh, lag_ratio=0, scale=0.95), ) self.play(LaggedStart(*( FadeIn(sh, rate_func=there_and_back) for sh in slice_highlights ), lag_ratio=0.35, run_time=1.5)) self.remove(slice_highlights) self.wait() # Unfold sphere self.play(slices.animate.scale(1 / radius).to_corner(UL).shift(IN)) pre_slices = slices.copy() self.add(pre_slices, slices) for slcs in pre_slices: for slc in slcs: slc.set_color(interpolate_color(slc.get_color(), BLACK, 0.0)) flat_slices[2].shift(0.01 * OUT) self.play( Transform(slices[0], flat_slices[0]), Transform(slices[2], flat_slices[2]), run_time=2, ) self.wait() self.play( Transform( slices[1], flat_slices[1], run_time=2, ), ) self.wait() # Show width line slc = flat_slices[0][0] v_tracker = ValueTracker(0) width_line = Line(LEFT, RIGHT) width_line.set_stroke(RED, 3) def update_width_line(width_line, slc=slc, v_tracker=v_tracker): v = v_tracker.get_value() width_line.set_width(1.2 * slc.get_width() * math.sin(v) + 1e-2) width_line.move_to(interpolate(slc.get_top(), slc.get_bottom(), v)) width_line.add_updater(update_width_line) self.add(width_line) self.play(v_tracker.animate.set_value(1), run_time=3) self.play(v_tracker.animate.set_value(0), run_time=3) self.remove(width_line) # Interlink tri_template = Triangle(start_angle=90 * DEGREES) tri_template.set_width(2).set_height(1, stretch=True) tri_template.move_to(ORIGIN, DOWN) if self.show_true_slices: tri_template = VMobject() dtheta = TAU / self.n_slices curve = ParametricCurve(lambda phi: [-math.sin(phi) * dtheta / 2, PI / 2 - phi, 0], t_range=(0, PI / 2)) curve2 = curve.copy().stretch(-1, 0, about_point=ORIGIN) curve2.reverse_points() tri_template.append_vectorized_mobject(curve) tri_template.add_line_to(curve2.get_start()) tri_template.append_vectorized_mobject(curve2) vslices = VGroup(*( VGroup(*( tri_template.copy().rotate(rot).replace(slc, stretch=True) for slc in hemi )) for rot, hemi in zip([0, PI], slices) )) for hemi, vhemi in zip(slices, vslices): for slc, vslc in zip(hemi, vhemi): vslc.set_fill(slc.get_color(), 1) vslc.set_stroke(WHITE, 0) slices[2].deactivate_depth_test() vslices.add(slices[2].copy()) vslices[1].move_to(vslices[0][0].get_top(), UL) vslices[1].set_stroke(WHITE, self.slice_stroke_width) vslices.center() self.play(FadeTransformPieces(slices, vslices)) self.wait() if self.show_true_slices: self.play(vslices.animate.set_opacity(0.5)) # Show equator circ_label = Text("Circumference") circ_label.next_to(vslices[2], DOWN) circ_formula = OldTex("2\\pi R") circ_formula.next_to(vslices[2], DOWN) circ_formula.set_stroke(WHITE, 0) equator = pre_slices[2] vslices[2].set_stroke() self.play( Write(circ_label), VShowPassingFlash( vslices[2].copy().set_stroke(YELLOW, 5).insert_n_curves(20), time_width=1.5, run_time=1.5, ), vslices[2].animate.set_color(YELLOW), ) self.play(equator.animate.shift(1.5 * DOWN).set_color(YELLOW)) self.wait() self.play(equator.animate.shift(1.5 * UP)) self.wait() self.play( Write(circ_formula), circ_label.animate.next_to(circ_formula, DOWN) ) self.wait() # Arc height edge = Line(vslices.get_corner(DL), vslices[0][0].get_top()) edge.set_stroke(PINK, 2) q_marks = OldTex("???") q_marks.next_to(edge.get_center(), LEFT, SMALL_BUFF) arc = Arc(0, 90 * DEGREES) arc.match_style(edge) arc.set_height(pre_slices.get_height() / 2) arc.rotate(-10 * DEGREES, LEFT) arc.shift(pre_slices[0][0].get_points()[0] - arc.get_end()) arc_form = OldTex("{\\pi \\over 2} R") arc_form.scale(0.5) arc_form.next_to(arc.pfp(0.5), RIGHT) arc_form2 = arc_form.copy() arc_form2.scale(1.5) arc_form2.move_to(q_marks, RIGHT) self.play( ShowCreation(edge), Write(q_marks), ) self.play(WiggleOutThenIn(edge, run_time=1)) self.wait() self.play(TransformFromCopy(edge, arc)) self.play(Write(arc_form)) self.wait() self.play( TransformFromCopy(arc_form, arc_form2), FadeOut(q_marks, DOWN) ) self.wait() # Area arc_tex = "{\\pi \\over 2} R" circ_tex = "2\\pi R" eq_parts = ["\\text{Area}", "=", arc_tex, "\\times", circ_tex, "=", "\\pi^2 R^2"] equation = Tex(" ".join(eq_parts), isolate=eq_parts) equation.center().to_edge(UP, buff=LARGE_BUFF) rect = SurroundingRectangle(equation.select_parts(eq_parts[-1])) rect.set_stroke(YELLOW, 2) self.play( Write(equation.select_parts("\\text{Area}")), Write(equation.select_parts("=")[0]), Write(equation.select_parts("\\times")), TransformFromCopy(arc_form2, equation.select_parts(arc_tex)), TransformFromCopy(circ_formula, equation.select_parts(circ_tex)), ) self.wait() self.play( Write(equation.select_parts("=")[1]), Write(equation.select_parts("\\pi^2 R^2")), ) self.play(ShowCreation(rect)) self.wait() class SphereExample50(SphereExample): n_slices = 50 slice_stroke_width = 0.5 class SphereExample100(SphereExample): n_slices = 100 slice_stroke_width = 0.1 class CallOutSphereExampleAsWrong(InteractiveScene): def construct(self): pass class SomethingSomethingLimits(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("Something,\nsomething\nlimits!", mode="shruggie"), self.change_students("hesitant", "angry", "erm") ) self.wait() class PiEqualsFourOverlay(InteractiveScene): def construct(self): words = OldTexText("Fine, as long as\\\\$\\pi = 4$") words.scale(2) words.set_color(RED) self.play(Write(words, stroke_color=WHITE)) self.wait() class Proof2Slide(InteractiveScene): def construct(self): # Setup self.add(FullScreenRectangle()) title = OldTexText("``Proof'' \\#2", font_size=60) title.to_edge(UP) subtitle = OldTex("\\pi = 4", font_size=60) subtitle.next_to(title, DOWN) subtitle.set_color(RED) self.add(title, subtitle) # Number line t_tracker = ValueTracker(0) get_t = t_tracker.get_value radius = 1.25 circle = Circle(radius=radius) circle.to_edge(DOWN) circle.set_fill(BLUE_E, 1) circle.set_stroke(width=0) circle.rotate(-TAU / 4) nl = NumberLine((0, 4), width=4 * circle.get_width()) nl.add_numbers() nl.move_to(2 * DOWN) v_lines = VGroup(*( DashedLine(ORIGIN, circle.get_height() * UP).move_to(nl.n2p(x), DOWN) for x in range(5) )) v_lines.set_stroke(GREY_B, 1) circum = circle.copy() circum.set_fill(opacity=0) circum.set_stroke(YELLOW, 2) def update_circum(circum): line = Line(nl.n2p(0), nl.n2p(get_t() * 4)) arc = Arc(start_angle=-TAU / 4, angle=TAU * (1 - get_t()), radius=radius) arc.shift(circle.get_bottom() - arc.get_start()) circum.set_points(np.vstack([line.get_points(), arc.get_points()])) return circum circum.add_updater(update_circum) radial_line = Line(circle.get_bottom(), circle.get_center(), stroke_width=1) radial_line.add_updater(lambda m: m.set_angle(TAU * (0.75 - get_t())).shift(circle.get_center() - m.get_start())) circle.move_to(nl.n2p(0.5), DOWN) self.add(nl, circle, radial_line, circum) self.play(LaggedStartMap(ShowCreation, v_lines, run_time=1)) # Roll self.play(circle.animate.set_x(nl.n2p(0)[0])) self.play( circle.animate.set_x(nl.n2p(4)[0]), t_tracker.animate.set_value(1), rate_func=linear, run_time=4, ) self.wait() class CircleExample(InteractiveScene): n_slices = 20 sector_stroke_width = 1.0 def construct(self): radius = 2.0 # Slice up circle circle = Circle(radius=radius) circle.set_stroke(WHITE, 1) circle.set_fill(BLUE_E, 1) question = Text("Area?") question.next_to(circle, UP) sectors = self.get_sectors(circle, n_slices=self.n_slices) self.play( DrawBorderThenFill(circle), Write(question, stroke_color=WHITE) ) self.wait() self.play(Write(sectors)) self.remove(circle) # Lay out sectors laid_sectors = sectors.copy() N = len(sectors) dtheta = TAU / N angles = np.arange(0, TAU, dtheta) for sector, angle in zip(laid_sectors, angles): sector.rotate(-90 * DEGREES - angle - dtheta / 2) laid_sectors.arrange(RIGHT, buff=0, aligned_edge=DOWN) laid_sectors.move_to(1.5 * DOWN) self.play( sectors.animate.scale(0.7).to_corner(UL), question.animate.to_corner(UR), ) self.play(TransformFromCopy(sectors, laid_sectors, run_time=2)) self.wait() # Interslice lh, rh = laid_sectors[:N // 2], laid_sectors[N // 2:] lh.generate_target() rh.generate_target() rh.target.rotate(PI) rh.target.move_to(lh[0].get_top(), UL) VGroup(lh.target, rh.target).set_x(0) rh.target.shift(UP) lh.target.shift(DOWN) self.play( MoveToTarget(lh, run_time=1.5), MoveToTarget(rh, run_time=1.5, path_arc=PI), ) self.play( lh.animate.shift(UP), rh.animate.shift(DOWN), ) self.wait() self.play(*( LaggedStart(*( VShowPassingFlash(piece, time_width=2) for piece in group.copy().set_fill(opacity=0).set_stroke(RED, 5) ), lag_ratio=0.02, run_time=4) for group in [laid_sectors, sectors] )) # Side lengths ulp = lh[0].get_top() width_line = Line(ulp, rh.get_corner(UR)) width_line.set_stroke(YELLOW, 3) width_form = OldTex("\\pi R") width_form.next_to(width_line, UP) semi_circ = Arc(angle=PI) semi_circ.set_stroke(YELLOW, 3) semi_circ.replace(sectors) semi_circ.move_to(sectors, UP) height_line = Line(lh.get_corner(DL), ulp) height_line.set_stroke(PINK, 3) height_form = OldTex("R") height_form.next_to(height_line, LEFT) radial_line = Line(sectors.get_center(), sectors.get_right()) radial_line.match_style(height_line) pre_R_label = OldTex("R").next_to(radial_line, UP, SMALL_BUFF) self.play(ShowCreation(width_line)) self.play(TransformFromCopy(width_line, semi_circ, path_arc=-PI / 2, run_time=2)) self.wait() self.play(Write(width_form, stroke_color=WHITE)) self.wait() self.play(ShowCreation(height_line)) self.play(TransformFromCopy(height_line, radial_line)) self.play(Write(pre_R_label)) self.play(ReplacementTransform(pre_R_label, height_form)) self.wait() # Area rhs = OldTex("=\\pi R^2") question.generate_target() question.target.match_y(sectors).match_x(lh) question.target[-1].scale(0, about_edge=LEFT) rhs.next_to(question.target, RIGHT) rect = SurroundingRectangle(VGroup(question.target, rhs)) rect.set_stroke(YELLOW, 2) self.play(MoveToTarget(question)) self.play( TransformMatchingShapes(VGroup(height_form, width_form).copy(), rhs) ) self.wait() self.play(ShowCreation(rect)) def get_sectors(self, circle, n_slices=20, fill_colors=[BLUE_D, BLUE_E]): angle = TAU / n_slices sectors = VGroup(*( Sector(angle=angle, start_angle=i * angle, fill_color=color, fill_opacity=1) for i, color in zip(range(n_slices), it.cycle(fill_colors)) )) sectors.set_stroke(WHITE, self.sector_stroke_width) sectors.replace(circle, stretch=True) return sectors class CircleExample50(CircleExample): n_slices = 50 sector_stroke_width = 0.5 class CircleExample100(CircleExample): n_slices = 100 sector_stroke_width = 0.2 class SideBySide(InteractiveScene): def construct(self): pass class SphereSectorAnalysis(Scene): n_slices = 20 def construct(self): # Setup radius = 2.0 frame = self.camera.frame frame.reorient(10, 60) axes = ThreeDAxes() axes.insert_n_curves(20) axes.set_stroke(GREY_B, 1) axes.apply_depth_test() sphere = Sphere(radius=radius) mesh = SurfaceMesh(sphere, resolution=(self.n_slices + 1, 3)) mesh.set_stroke(BLUE_E, 1) slices = get_sphere_slices(radius=radius, n_slices=self.n_slices) slices[2].scale(1.007) slices.rotate(-90 * DEGREES, OUT) self.add(axes) self.add(slices, mesh) self.play( ShowCreation(slices, lag_ratio=0.05), frame.animate.reorient(-10, 70), run_time=2, ) self.add(slices, mesh) self.wait() # Isolate one slice self.play( slices[0][1:].animate.set_opacity(0.1), slices[1].animate.set_opacity(0.1), ) self.wait() # Preview varying width dtheta = TAU / self.n_slices phi_tracker = ValueTracker(45 * DEGREES) get_phi = phi_tracker.get_value def get_width_line(): return ParametricCurve( lambda t: radius * np.array([ math.sin(t) * math.sin(get_phi()), -math.cos(t) * math.sin(get_phi()), math.cos(get_phi()), ]), t_range=(0, dtheta), stroke_color=RED, stroke_width=2, ) width_line = get_width_line() width_label = Text("Width", color=RED) width_label.rotate(90 * DEGREES, RIGHT) width_label.set_stroke(BLACK, 1, background=True) width_label.add_updater(lambda m: m.next_to(width_line, OUT, buff=SMALL_BUFF).set_width(1.5 * width_line.get_width() + 1e-2)) self.play(ShowCreation(width_line), Write(width_label)) self.wait() width_line.add_updater(lambda m: m.match_points(get_width_line())) for angle in 0, PI / 2, 0: self.play(phi_tracker.animate.set_value(angle), run_time=2) self.play(FadeOut(width_label)) self.wait() # Reorient slices.generate_target() mesh.generate_target() for mob in slices, mesh: for submob in mob.target.family_members_with_points(): if submob.get_x() < -0.1: submob.set_opacity(0) self.add(slices, width_line) self.play( frame.animate.reorient(-65, 65), MoveToTarget(slices), MoveToTarget(mesh), slices[2].animate.set_stroke(width=0), run_time=2, ) frame.add_updater(lambda f, dt: f.increment_theta(0.01 * dt)) # Show phi angle def get_sphere_point(): return radius * (math.cos(get_phi()) * OUT + math.sin(get_phi()) * DOWN) def get_radial_line(): return Line( ORIGIN, get_sphere_point(), stroke_color=YELLOW, stroke_width=2, ) phi_label = OldTex("\\phi", font_size=30) def get_angle_label(): arc = Arc(start_angle=90 * DEGREES, angle=-get_phi(), radius=0.5, n_components=8) arc.set_stroke(WHITE, 2) arc.set_fill(opacity=0) label = phi_label.copy() label.next_to(arc.pfp(0.5), UP, buff=SMALL_BUFF) result = VGroup(arc, label) result.rotate(90 * DEGREES, RIGHT, about_point=ORIGIN) result.rotate(90 * DEGREES, IN, about_point=ORIGIN) return result def get_lat_line_radius(): point = get_sphere_point() return Line(point[2] * OUT, point, stroke_color=PINK, stroke_width=2) def get_lat_line(): result = Circle(radius=radius * math.sin(get_phi())) result.set_stroke(RED, 1, opacity=0.5) result.set_z(get_sphere_point()[2]) return result radial_line = get_radial_line() radial_line.add_updater(lambda m: m.match_points(get_radial_line())) angle_label = get_angle_label() angle_label[0].add_updater(lambda m: m.match_points(get_angle_label()[0]).set_stroke(WHITE, 2).set_fill(opacity=0)) angle_label[1].add_updater(lambda m: m.move_to(get_angle_label()[1])) lat_line_radius = get_lat_line_radius() lat_line_radius.add_updater(lambda m: m.match_points(get_lat_line_radius())) lat_line_label = OldTex("R\\sin(\\phi)", font_size=24) lat_line_label.rotate(90 * DEGREES, RIGHT).rotate(90 * DEGREES, IN) lat_line_label.next_to(lat_line_radius, OUT, SMALL_BUFF) self.play(ShowCreation(radial_line)) self.play( phi_tracker.animate.set_value(30 * DEGREES), UpdateFromAlphaFunc(angle_label, lambda m, a: m.update().set_opacity(a)), ) self.wait() self.play( phi_tracker.animate.set_value(75 * DEGREES), run_time=3, ) self.play(phi_tracker.animate.set_value(45 * DEGREES), run_time=2) self.wait() lat_line_label.add_updater(lambda m: m.next_to(lat_line_radius, OUT, SMALL_BUFF)) self.play( ShowCreation(lat_line_radius), Write(lat_line_label) ) self.wait() lat_line = get_lat_line() lat_line.add_updater(lambda m: m.match_points(get_lat_line())) self.play(ShowCreation(lat_line)) self.wait() # Show delta theta brace = Brace(Line(ORIGIN, radius * dtheta * RIGHT), UP, buff=SMALL_BUFF) delta_theta = OldTex("\\Delta \\theta", font_size=36) delta_theta.next_to(brace, UP, buff=SMALL_BUFF) dt_label = VGroup(brace, delta_theta) dt_label.rotate(90 * DEGREES, RIGHT) dt_label.next_to(radius * DOWN, OUT, buff=0) dt_label.rotate(0.5 * dtheta, OUT, about_point=ORIGIN) self.play(Write(dt_label), frame.animate.set_theta(-30 * DEGREES)) self.wait() # Exact formula formula1 = OldTex("2\\pi", " R \\sin(\\phi)", "\\cdot", "{\\Delta \\theta", " \\over 2\\pi}") formula2 = OldTex("R \\sin(\\phi)", "\\cdot", "\\Delta \\theta") for formula in formula1, formula2: formula.to_corner(UR) formula.fix_in_frame() self.play(Write(formula1)) self.wait() self.play( FadeTransform(formula1[1], formula2[0]), FadeTransform(formula1[2], formula2[1]), FadeTransform(formula1[3], formula2[2]), FadeOut(formula1[0]), FadeOut(formula1[4:]), ) self.wait() # Graph axes = Axes( (0, PI, PI / 4), (0, 1, 1 / 2), height=1, width=PI, ) axes.y_axis.add(Text("Wedge width", font_size=24, color=RED).next_to(axes.c2p(0, 1), LEFT)) axes.x_axis.add(OldTex("\\pi / 2", font_size=24).next_to(axes.c2p(PI / 2, 0), DOWN)) axes.x_axis.add(OldTex("\\pi", font_size=24).next_to(axes.c2p(PI, 0), DOWN)) axes.x_axis.add(OldTex("\\phi", font_size=24).next_to(axes.c2p(PI, 0), UR, buff=SMALL_BUFF)) axes.to_corner(UL) axes.fix_in_frame() graph = axes.get_graph(lambda x: math.sin(x), x_range=[0, PI / 2]) graph.set_stroke(RED, 2) graph.fix_in_frame() dot = Dot() dot.scale(0.25) dot.fix_in_frame() self.play(FadeIn(axes), frame.animate.set_theta(-50 * DEGREES)) self.wait() self.play(phi_tracker.animate.set_value(0)) self.wait() graph_copy = graph.copy() self.play( phi_tracker.animate.set_value(90 * DEGREES), ShowCreation(graph), UpdateFromAlphaFunc(dot, lambda d, a: d.move_to(graph_copy.pfp(a))), run_time=6, ) self.wait() self.play( phi_tracker.animate.set_value(45 * DEGREES), UpdateFromAlphaFunc(dot, lambda d, a: d.move_to(graph.pfp(1 - 0.5 * a))), run_time=3, ) self.wait() class FalseVsTrueSurfaceAreaOverlay(InteractiveScene): def construct(self): false_answer = VGroup( Text("False answer", color=RED), OldTex("\\pi^2 R^2"), ) true_answer = VGroup( Text("True answer", color=GREEN), OldTex("4\\pi R^2"), ) answers = VGroup(false_answer, true_answer) for answer in answers: answer.arrange(DOWN, buff=MED_LARGE_BUFF) answers.arrange(RIGHT, buff=LARGE_BUFF, aligned_edge=UP) self.play(FadeIn(false_answer)) self.play(FadeIn(true_answer)) self.wait() class FakeAreaManipulation(InteractiveScene): CONFIG = { "unit": 0.5 } def construct(self): # Setup unit = self.unit group1, group2 = groups = self.get_diagrams() for group in groups: group.set_width(10 * unit, stretch=True) group.set_height(12 * unit, stretch=True) group.move_to(3 * DOWN, DOWN) group[2].append_points(3 * [group[2].get_left() + LEFT]) group[3].append_points(3 * [group[3].get_right() + RIGHT]) grid = NumberPlane( x_range=(-30, 30), y_range=(-30, 30), faded_line_ratio=0, ) grid.set_stroke(width=1) grid.scale(unit) grid.shift(3 * DOWN - grid.c2p(0, 0)) vertex_dots = VGroup( Dot(group1.get_top()), Dot(group1.get_corner(DR)), Dot(group1.get_corner(DL)), ) self.add(grid) self.add(*group1) self.add(vertex_dots) self.disable_interaction(grid, vertex_dots) targets = [group1.copy(), group2.copy()] self.wait(note="Manually manipulate") # Animate swap kw = { "lag_ratio": 0.1, "run_time": 2, "rate_func": bezier([0, 0, 1, 1]), } path_arc_factors = [-1, 1, 0, 0, -1, 1] for target in targets: self.play(group1.animate.space_out_submobjects(1.2)) self.play(*[ Transform( sm1, sm2, path_arc=path_arc_factors[i] * 60 * DEGREES, **kw ) for i, sm1, sm2 in zip(it.count(), group1, target) ]) self.wait(2) # Zoom lines = VGroup( Line(grid.c2p(0, 12), grid.c2p(-5, 0)), Line(grid.c2p(0, 12), grid.c2p(5, 0)), ) lines.set_stroke(YELLOW, 2) self.disable_interaction(lines) frame = self.camera.frame frame.save_state() self.play(ShowCreation(lines, lag_ratio=0)) self.play( frame.animate.scale(0.15).move_to(group1[0].get_corner(UR)), run_time=4, ) self.wait(3) self.play(frame.animate.restore(), run_time=2) # Another switch self.wait(note="Hold for next swap") self.play(*( Transform(sm1, sm2, **kw) for sm1, sm2 in zip(group1, targets[0]) )) self.wait() # Another zooming self.play( frame.animate.scale(0.15).move_to(group1[4].get_corner(UR)), run_time=4, ) self.wait(2) self.play(frame.animate.restore(), run_time=2) # Show slopes tris = VGroup(group1[0], group1[4]) lil_lines = VGroup(*(Line(tri.get_corner(DL), tri.get_corner(UR)) for tri in tris)) lil_lines[0].set_stroke(PINK, 3) lil_lines[1].set_stroke(WHITE, 3) slope_labels = VGroup( OldTexText("Slope =", " $5 / 2$"), OldTexText("Slope =", " $7 / 3$"), ) for line, label in zip(lil_lines, slope_labels): label.next_to(line.pfp(0.5), UL, buff=0.7) arrow = Arrow(label.get_bottom(), line.pfp(0.5)) label.add(arrow) self.play( FadeOut(lines[0]), ShowCreation(lil_lines), ) for line, label in zip(lil_lines, slope_labels): p1, p2 = line.get_start_and_end() corner = [p2[0], p1[1], 0] x_line = Line(p1, corner).set_stroke(line.get_color(), 2) y_line = Line(corner, p2).set_stroke(line.get_color(), 2) self.play( FadeIn(label[:2]), ShowCreation(label[2]), ) self.play( TransformFromCopy(line, y_line), FlashAround(label[1][0]), ) self.play( TransformFromCopy(line, x_line), FlashAround(label[1][2]), ) self.wait() def get_diagrams(self): unit = self.unit tri1 = Polygon(2 * LEFT, ORIGIN, 5 * UP) tri2 = tri1.copy() tri2.flip() tri2.next_to(tri1, RIGHT, buff=0) tris = VGroup(tri1, tri2) tris.scale(unit) tris.move_to(3 * UP, UP) tris.set_stroke(width=0) tris.set_fill(BLUE_D) tris[1].set_color(BLUE_C) ell = Polygon( ORIGIN, 4 * RIGHT, 4 * RIGHT + 2 * UP, 2 * RIGHT + 2 * UP, 2 * RIGHT + 5 * UP, 5 * UP, ) ell.scale(unit) ells = VGroup(ell, ell.copy().rotate(PI).shift(2 * unit * UP)) ells.next_to(tris, DOWN, buff=0) ells.set_stroke(width=0) ells.set_fill(GREY) ells[1].set_fill(GREY_BROWN) big_tri = Polygon(ORIGIN, 3 * LEFT, 7 * UP) big_tri.set_stroke(width=0) big_tri.scale(unit) big_tri.move_to(ells.get_corner(DL), DR) big_tris = VGroup(big_tri, big_tri.copy().rotate(PI, UP, about_point=ORIGIN)) big_tris[0].set_fill(RED_E, 1) big_tris[1].set_fill(RED_C, 1) full_group = VGroup(*tris, *ells, *big_tris) full_group.set_height(5, about_edge=UP) alt_group = full_group.copy() alt_group[0].move_to(alt_group, DL) alt_group[1].move_to(alt_group, DR) alt_group[4].move_to(alt_group[0].get_corner(UR), DL) alt_group[5].move_to(alt_group[1].get_corner(UL), DR) alt_group[2].rotate(90 * DEGREES) alt_group[2].move_to(alt_group[1].get_corner(DL), DR) alt_group[2].rotate(-90 * DEGREES) alt_group[2].move_to(alt_group[0].get_corner(DR), DL) alt_group[3].move_to(alt_group[1].get_corner(DL), DR) full_group.set_opacity(0.75) alt_group.set_opacity(0.75) return full_group, alt_group class ContrastSphericalGeometry(InteractiveScene): def construct(self): # Titles titles = VGroup( Text("Spherical geometry"), Text("Euclidean geometry"), ) for title, v in zip(titles, [LEFT, RIGHT]): title.move_to(FRAME_WIDTH * v / 4) title.to_edge(UP) v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line.set_stroke(WHITE, 1) self.add(v_line, titles) # Setup sphere sphere = TexturedSurface(Sphere(radius=1.5), "EarthTextureMap", "NightEarthTextureMap") mesh = SurfaceMesh(sphere) mesh.set_stroke(GREY_C, 1, opacity=0.5) sphere_group = Group(sphere, mesh) sphere_group.rotate(80 * DEGREES, LEFT) sphere_group.rotate(-3 * DEGREES, OUT) sphere_axis = mesh[0].get_end() - sphere.get_center() sphere_group.move_to(FRAME_WIDTH * LEFT / 4) sphere_group.to_edge(DOWN, buff=0.75) self.add(sphere_group) # Flat shapes shapes = VGroup( Polygon(RIGHT, UP, DL).set_fill(BLACK, 1), Square().set_fill(BLUE_C, 1), Circle().set_fill(BLUE_E, 1), RegularPolygon(5).set_fill(GREY_BROWN, 1) ) shapes.set_stroke(WHITE, 2) for shape in shapes: shape.set_height(1) shapes.arrange_in_grid() shapes.match_x(titles[1]) shapes.to_edge(DOWN) pre_tri = shapes[0].copy() pre_tri.scale(2.5) pre_tri.move_to(shapes).align_to(sphere, DOWN) pre_tri_arcs, pre_tri_angle_labels = self.get_flat_angle_labels(pre_tri) shift_line, new_arcs, new_labels = self.get_aligned_angle_labels( pre_tri, pre_tri_arcs, pre_tri_angle_labels ) # Setup spherical triangle t2c = { "\\alpha": BLUE_B, "\\beta": BLUE_C, "\\gamma": BLUE_D, } kw = dict(tex_to_color_map=t2c) sph_tri = VGroup( VMobject().pointwise_become_partial(mesh[16], 0.5, 1.0), VMobject().pointwise_become_partial(mesh[19], 0.5, 1.0).reverse_points(), VMobject().pointwise_become_partial(mesh[26], 16 / 20, 19 / 20).reverse_points(), ) sph_tri.set_stroke(BLUE, 3) sph_tri_angle_labels = Tex("\\alpha\\beta\\gamma", font_size=30, **kw) sph_tri_angle_labels.set_backstroke() for label, curve in zip(sph_tri_angle_labels, sph_tri): label.curve = curve label.add_updater(lambda l: l.move_to(l.curve.get_end())) label.add_updater(lambda l: l.shift(0.2 * normalize(sph_tri.get_center() - l.curve.get_end()))) sph_tri.deactivate_depth_test() # Equations angle_equations = VGroup( Tex("\\alpha + \\beta + \\gamma > 180^\\circ", **kw), Tex("\\alpha + \\beta + \\gamma = 180^\\circ", **kw), ) for eq, title in zip(angle_equations, titles): eq.next_to(title, DOWN, buff=1.5) # Write triangles sph_tri_angle_labels.suspend_updating() self.play( LaggedStartMap(Write, VGroup( pre_tri, pre_tri_arcs, pre_tri_angle_labels, sph_tri, sph_tri_angle_labels, )), *(FadeIn(eq, 0.25 * DOWN) for eq in angle_equations) ) sph_tri_angle_labels.resume_updating() sphere_group.add(sph_tri, sph_tri_angle_labels) sph_tri.deactivate_depth_test() self.add(sphere_group) self.play() # Justify euclidean case self.play( FadeIn(shift_line, shift=shift_line.shift_vect), Rotate(sphere_group, -30 * DEGREES, axis=sphere_axis, run_time=2) ) for i in (0, 1): self.play( TransformFromCopy(pre_tri_arcs[i + 1], new_arcs[i]), TransformFromCopy(pre_tri_angle_labels[i + 1], new_labels[i]), ) self.wait() pre_tri_group = VGroup( pre_tri, pre_tri_arcs, pre_tri_angle_labels, shift_line, new_arcs, new_labels ) # Write area formulas area_formulas = VGroup( Tex("\\text{Area}(\\Delta) = (\\alpha + \\beta + \\gamma - \\pi) R^2", **kw), Tex("\\text{Area}(\\Delta) = \\frac{1}{2} bh") ) for title, formula in zip(titles, area_formulas): formula.move_to(title).shift(1.5 * DOWN) self.play( FadeIn(area_formulas, 0.5 * DOWN), angle_equations.animate.shift(0.75 * DOWN) ) # Mention Gaussian Curvature curvature_words = VGroup( OldTexText("Gaussian curvature > 0", color=GREEN_B), OldTexText("Gaussian curvature = 0", color=YELLOW), ) for words, eq in zip(curvature_words, angle_equations): words.next_to(eq, DOWN, MED_LARGE_BUFF) self.play( FadeIn(curvature_words, 0.7 * DOWN), sphere_group.animate.scale(0.7, about_edge=DOWN), pre_tri_group.animate.scale(0.7, about_edge=DOWN), ) self.wait() # Try unraveling sphere unwrapped = TexturedSurface(Surface(), "EarthTextureMap", "NightEarthTextureMap") unwrapped.set_height(2) unwrapped.set_width(TAU, stretch=True) unwrapped.set_width(FRAME_WIDTH / 2 - 1) unwrapped.next_to(titles[1], DOWN, LARGE_BUFF) loss_words = Text("Some geometric information\nmust be lost") loss_words.set_color(RED) loss_words.set_max_width(unwrapped.get_width()) loss_words.next_to(unwrapped, DOWN, MED_LARGE_BUFF) self.play( LaggedStart(*( FadeOut(mob, RIGHT) for mob in [area_formulas[1], angle_equations[1], curvature_words[1], pre_tri_group] )), TransformFromCopy(sphere, unwrapped, run_time=2) ) self.play(Write(loss_words)) self.wait(2) def get_flat_angle_labels(self, tri): arcs = VGroup() for v1, v2, v3 in adjacent_n_tuples(tri.get_vertices(), 3): a1 = angle_of_vector(v2 - v1) a2 = angle_of_vector(v3 - v2) arc = Arc( start_angle=a2, angle=PI - (a2 - a1) % PI, radius=0.2 ) arc.shift(v2) arcs.add(arc) labels = Tex("\\alpha \\beta \\gamma", font_size=30) for label, arc in zip(labels, arcs): vect = normalize(arc.pfp(0.5) - midpoint(arc.get_start(), arc.get_end())) label.move_to(arc.pfp(0.5)) label.shift(0.25 * vect) result = VGroup(arcs, labels) for group in result: group.set_submobject_colors_by_gradient(BLUE_B, BLUE_C, BLUE_D) return result def get_aligned_angle_labels(self, tri, arcs, labels): verts = tri.get_vertices() line = Line(verts[0], verts[2]) line.set_stroke(GREY_B, 2) vect1 = verts[1] - verts[2] vect2 = verts[1] - verts[0] line.shift_vect = (vect1 + vect2) / 2 line.shift(line.shift_vect) new_arcs = arcs[1:3].copy() new_labels = labels[1:3].copy() VGroup(new_arcs[0], new_labels[0]).rotate(PI, about_point=midpoint(verts[1], verts[2])) VGroup(new_arcs[1], new_labels[1]).rotate(PI, about_point=midpoint(verts[1], verts[0])) for label in new_labels: label.rotate(PI) return VGroup(line, new_arcs, new_labels) class GiveItAGo(TeacherStudentsScene): def construct(self): morty = self.teacher ss = self.students self.play( morty.says("Can you see\nwhat's happening?"), ss[0].change("pondering", self.screen), ss[1].change("angry", self.screen), ss[2].change("confused", self.screen), ) self.wait() self.play(ss[1].change("maybe")) self.play(morty.change("tease"), ss[0].change("thinking")) self.wait(4) class SquareCircleExample(InteractiveScene): def construct(self): # Setup radius = 2.0 circle = Circle(radius=radius, n_components=32) rich_circle = Circle(radius=radius, n_components=2**14) circle.set_fill(BLUE_E, 1) circle.set_stroke(WHITE, 1) approx_curves = [ self.get_square_approx(rich_circle, 4 * 2**n) for n in range(10) ] square = approx_curves[0].copy() self.add(circle) # Ask about circumference radial_line = Line(ORIGIN, circle.get_right()) radial_line.set_stroke(WHITE, 1) radius_label = OldTex("1") radius_label.next_to(radial_line, UP, SMALL_BUFF) circum = circle.copy() circum.set_stroke(YELLOW, 3).set_fill(opacity=0) question = Text("What is the circumference?") question.next_to(circle, UP, MED_LARGE_BUFF) unwrapped_circum = Line(LEFT, RIGHT) unwrapped_circum.set_width(PI * circle.get_width()) unwrapped_circum.match_style(circum) unwrapped_circum.next_to(circle, UP) diameter = Line(circle.get_left(), circle.get_right()) diameter.set_stroke(RED, 2) self.play( ShowCreation(radial_line), Write(radius_label, stroke_color=WHITE) ) self.wait() self.play( Write(question), ShowCreation(circum) ) self.wait() self.play( question.animate.to_edge(UP), Transform(circum, unwrapped_circum), ) self.play(ShowCreation(diameter)) self.wait() self.play(*map(FadeOut, [question, circum, diameter])) # Show perimeter length points = [square.get_edge_center(np.round(vect)) for vect in compass_directions(8)] new_radii = VGroup(*( Line(p1, p2).match_style(radial_line) for p1, p2 in adjacent_pairs(points) )) new_radii.save_state() new_radii.space_out_submobjects(1.1) perimeter_label = OldTexText("Perimeter = $8$") perimeter_label.to_edge(UP) self.play(ShowCreation(square), run_time=3) self.play(square.animate.scale(1.2), rate_func=there_and_back) self.wait() self.play( TransformFromCopy(VGroup(radial_line), new_radii, lag_ratio=0.2, run_time=2), FadeIn(perimeter_label), ) self.wait() self.play(new_radii.animate.restore()) self.play(FadeOut(new_radii)) self.wait() # Finer approximations for i, curve in enumerate(approx_curves[1:]): curve.set_color(YELLOW) self.play( square.animate.set_stroke(width=1), TransformFromCopy(square, curve) ) self.wait() if i == 0: dots = GlowDot().replicate(2) dots.set_color(BLUE) sc = square.copy().insert_n_curves(200) cc = curve.copy().insert_n_curves(200) self.play(VGroup(square, curve).animate.set_stroke(opacity=0.2)) self.play( MoveAlongPath(dots[0], square), MoveAlongPath(dots[1], curve), ShowCreation(sc), ShowCreation(cc), rate_func=linear, run_time=6, ) self.play(FadeOut(dots), FadeOut(sc), FadeOut(cc), VGroup(square, curve).animate.set_stroke(opacity=1)) if i == 1: curve.set_stroke(width=5) print(self.num_plays) self.play(FadeOut(square), curve.animate.set_color(RED)) square = curve # Zoom in frame = self.camera.frame self.wait(note="Prepare for zoom") self.play(frame.animate.set_height(0.05).move_to(circle.pfp(1 / 8)), run_time=4) self.wait() self.play(frame.animate.to_default_state(), run_time=3) # Define parametric curve frame = self.camera.frame t_tracker = ValueTracker(0) get_t = t_tracker.get_value dot = GlowDot() t_axis = UnitInterval() t_axis.set_width(6) t_axis.next_to(circle, RIGHT, buff=1.5) t_axis.add_numbers() t_indicator = Triangle(start_angle=-90 * DEGREES) t_indicator.set_height(0.1) t_indicator.set_fill(RED, 1) t_indicator.set_stroke(WHITE, 0) t_label = VGroup(OldTex("t = "), DecimalNumber()) t_label.arrange(RIGHT) t_label.next_to(t_axis, UP, buff=LARGE_BUFF) VGroup(t_axis, t_label).to_edge(UP) globals().update(locals()) t_label[1].add_updater(lambda d: d.set_value(get_t())) dot.add_updater(lambda d: d.move_to(square.pfp(get_t()))) t_indicator.add_updater(lambda m: m.move_to(t_axis.n2p(get_t()), DOWN)) c_labels = VGroup(*(OldTex(f"c_{n}(t)") for n in range(len(approx_curves)))) c_labels.add(OldTex("c_\\infty (t)")) for label in c_labels: label.scale(0.75) label.add_updater(lambda m: m.next_to(dot, UR, buff=-SMALL_BUFF)) self.play( Transform(square, approx_curves[0]), frame.animate.move_to(4 * RIGHT), FadeIn(dot), FadeIn(t_label), Write(c_labels[0]), Write(t_axis), Write(t_indicator), run_time=1 ) square.match_points(approx_curves[0]) self.wait() self.play(t_tracker.animate.set_value(1), run_time=7) self.wait() t_tracker.set_value(0) self.play( Transform(square, approx_curves[1]), FadeTransform(c_labels[0], c_labels[1]), ) self.play(t_tracker.animate.set_value(1), run_time=7) self.wait() t_tracker.set_value(0) # Show limits self.play(t_tracker.animate.set_value(0.2), run_time=3) dot_shadows = VGroup() self.add(dot_shadows) for i in range(2, len(approx_curves)): dot_shadow = Dot(radius=0.01, color=YELLOW, opacity=0.5) dot_shadow.move_to(dot) dot_shadows.add(dot_shadow) self.play( Transform(square, approx_curves[i]), FadeTransform(c_labels[i - 1], c_labels[i]), run_time=0.5, ) self.wait(0.5) # Write limits lim_tex_ex = Tex("\\lim_{n \\to \\infty} c_{n}(" + "{:.1f}".format(get_t()) + ")") lim_tex = OldTex("c_\\infty(t)", ":=", "\\lim_{n \\to \\infty} c_{n}(t)") for lt in lim_tex_ex, lim_tex: lt.next_to(t_axis, DOWN, aligned_edge=LEFT, buff=2.0) lim_arrow = Arrow(lim_tex_ex.get_corner(UL), dot.get_center(), buff=0.1, stroke_width=2, color=YELLOW) self.play(Write(lim_tex_ex)) self.play(ShowCreation(lim_arrow)) self.wait() self.play( FadeTransform(lim_tex_ex, lim_tex[2]), Write(lim_tex[:2]), ) self.wait() self.play(FadeOut(dot_shadows), FadeOut(lim_arrow), FadeTransform(c_labels[9], c_labels[-1])) self.play(t_tracker.animate.set_value(0), run_time=2) self.play(t_tracker.animate.set_value(1), run_time=8) self.wait() # This is a circle text = Text("This is, precisely, a circle", t2s={"precisely": ITALIC}) text.next_to(lim_tex, DOWN, LARGE_BUFF, aligned_edge=LEFT) arrow = Arrow(text, lim_tex[0]) VGroup(text, arrow).set_color(GREEN) self.play(Write(text), ShowCreation(arrow)) self.wait() self.play(FadeOut(text), FadeOut(arrow), lim_tex.animate.shift(UP)) # Mismatched limits t2c = { "\\lim_{n \\to \\infty}": YELLOW, "\\text{len}": RED, "c_n(t)": WHITE, "\\Big(": WHITE, "\\Big)": WHITE, } lim_len = Tex("\\lim_{n \\to \\infty}\\Big(\\text{len}\\big(c_n(t)\\big) \\Big) = 8", tex_to_color_map=t2c) len_lim = Tex("\\text{len} \\Big( \\lim_{n \\to \\infty} c_n(t) \\Big) = 2\\pi", tex_to_color_map=t2c) lims = VGroup(lim_len, len_lim) lim_len.next_to(lim_tex, DOWN, LARGE_BUFF, aligned_edge=LEFT) top_group = VGroup(t_axis, t_indicator, t_label) self.play(Write(lim_len)) self.wait() self.play( VGroup(lim_tex, lim_len).animate.next_to(frame.get_corner(UR), DL, MED_LARGE_BUFF), FadeOut(top_group, 2 * UR), ) len_lim.next_to(lim_len, DOWN, buff=2.0, aligned_edge=LEFT) not_eq = OldTex("\\ne", font_size=96) not_eq.rotate(90 * DEGREES) not_eq.move_to(VGroup(len_lim, lim_len)) not_eq.match_x(len_lim) self.play(*( TransformFromCopy(lim_len.select_parts(tex), len_lim.select_parts(tex)) for tex in t2c.keys() )) self.play(Write(not_eq)) self.wait() self.play(Write(len_lim[3:])) self.wait() # Commentary morty = Mortimer() def get_square_approx(self, circle, n_samples): radius = circle.radius points = [ radius * np.array([math.cos(a), math.sin(a), 0]) for a in np.linspace(0, TAU, n_samples + 1) ] result = VMobject() result.start_new_path(points[0]) for p1, p2 in zip(points, points[1:]): corners = np.array([ [p2[0], p1[1], 0], [p1[0], p2[1], 0] ]) corner = corners[np.argmax(np.apply_along_axis(np.linalg.norm, 1, corners))] result.add_line_to(corner) result.add_line_to(p2) result.set_stroke(RED, 2) return result class ObviouslyWrong(TeacherStudentsScene): def construct(self): morty = self.teacher ss = self.students self.play(LaggedStart( ss[2].says("Obviously those\nperimeters aren't\nthe circle...", mode="sassy", look_at=self.screen, bubble_direction=LEFT), ss[0].change("erm", self.screen), ss[1].change("angry", self.screen), morty.change("guilty") )) self.wait(5) class UpshotOfLimitExample(InteractiveScene): def construct(self): # Title title = Text("The takeaway", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) underline = Underline(title, buff=-0.05) underline.scale(1.2) underline.insert_n_curves(20) underline.set_stroke(WHITE, (1, 3, 3, 1)) subtitle = Text( "What's true of a sequence may not be true of the limit", t2c={"sequence": BLUE, "limit": YELLOW}, ) subtitle.set_max_width(FRAME_WIDTH - 1) subtitle.next_to(title, DOWN, buff=MED_LARGE_BUFF) self.add(title, underline, subtitle) # Various limits n = 4 numbers = VGroup( OldTex("1.4"), OldTex("1.41"), OldTex("1.414"), OldTex("1.4142"), OldTex("\\sqrt{2}") ) numbers.scale(1.25) properties = VGroup( *Text("Rational", font_size=30).replicate(n), Text("Irrational", font_size=30) ) folder = "/Users/grant/Dropbox/3Blue1Brown/videos/2022/visual_proofs/lies/images/" rational_example = VGroup(numbers, properties) circle_example = Group( Group(*( ImageMobject(os.path.join(folder, "SquareApprox" + end)).set_width(1.25) for end in ["1", "2", "3", "4", "Inf"] )), VGroup( *TexText("Len = 8").replicate(n), OldTexText("Len = $2\\pi$") ) ) fourier_example = Group( Group(*( ImageMobject(os.path.join(folder, "Fourier" + end)).set_width(1.25) for end in ["1", "2", "3", "4", "Inf"] )), VGroup( *TexText("Continuous").replicate(n), OldTexText("Discontinuous") ) ) examples = Group(rational_example, circle_example, fourier_example) for objs, descs in examples: arrow = OldTex("\\cdots \\, \\rightarrow", font_size=72) group = Group(*objs[:n], arrow, objs[n]) for x, mob in enumerate(group): mob.move_to(2.75 * x * RIGHT) group.set_x(0) for desc, obj in zip(descs, objs): desc.set_max_width(1.25 * obj.get_width()) desc.next_to(obj, DOWN) descs[:n].set_color(BLUE) descs[n].set_color(YELLOW) objs.insert_submobject(n, arrow) examples.arrange(DOWN, buff=LARGE_BUFF) examples.set_height(5.0) examples.to_edge(DOWN) for i in range(3): objs, descs = examples[i] self.play( LaggedStartMap(FadeIn, objs, lag_ratio=0.5, scale=2), LaggedStartMap(FadeIn, descs, lag_ratio=0.5, scale=2), run_time=2 ) class WhyWeNeedProofs(TeacherStudentsScene): def construct(self): phrases = VGroup( Text("Looks can be deceiving"), Text("We need rigor!"), Text("We need proofs!"), ) phrases.move_to(self.hold_up_spot, DOWN) for phrase in phrases: phrase.shift_onto_screen() phrase.align_to(phrases[0], LEFT) image = ImageMobject("Euclid").set_height(3) rect = SurroundingRectangle(image, buff=0) rect.set_stroke(WHITE, 2) name = Text("Euclid") name.next_to(image, DOWN, ) euclid = Group(image, rect, name) euclid.to_corner(UL) morty = self.teacher ss = self.students # Show phrases self.play( morty.change("raise_right_hand"), FadeIn(phrases[0], UP), ss[0].change("happy"), ss[1].change("tease"), ss[2].change("happy"), ) self.wait() self.play( morty.change("hooray"), phrases[0].animate.shift(UP), FadeIn(phrases[1], UP), ) self.play( phrases[0].animate.shift(UP), phrases[1].animate.shift(UP), FadeIn(phrases[2], UP), ) self.wait() self.play( morty.change("tease"), FadeIn(euclid, lag_ratio=0.3), self.change_students("pondering", "pondering", "thinking", look_at=euclid) ) self.wait(4) class Proof3Slide(InteractiveScene): def construct(self): self.add(FullScreenRectangle()) title = OldTexText("``Proof'' \\#3", font_size=60) subtitle = Text("All triangles are isosceles", font_size=60, color=BLUE) title.to_edge(UP) subtitle.next_to(title, DOWN) self.add(title, subtitle) # Triangle tri = Triangle() tri.set_fill(BLUE_E) tri.set_stroke(WHITE, 1) tri.stretch(2, 1) tri.to_corner(DL, buff=LARGE_BUFF).shift(RIGHT) A, B, C = tri.get_top(), tri.get_corner(DL), tri.get_corner(DR) AB = Line(A, B, color=YELLOW) AC = Line(A, C, color=TEAL) eq = OldTex("\\overline{AB}", " = ", "\\overline{AC}") eq.next_to(tri, UP) eq[0].match_color(AB) eq[2].match_color(AC) self.add(tri) self.play(ShowCreation(AB), Write(eq[0])) self.play( TransformFromCopy(AB, AC), FadeTransform(eq[0].copy(), eq[2]), Write(eq[1]), ) self.wait() class SpeakingOfLimits(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("Speaking of\nlimits..."), self.change_students("happy", "tease", "thinking"), ) self.wait(4) class IntegralExample(InteractiveScene): def construct(self): # Setup axes = Axes((-1, 4), (-1, 10), width=12, height=6) graph = axes.get_graph(lambda x: x**2) graph.set_stroke(TEAL, 2) all_rects = VGroup(*( axes.get_riemann_rectangles(graph, (0, 3), dx).set_stroke(BLACK, np.round(4 * dx, 1), background=False) for dx in [2**(-n) for n in range(2, 8)] )) rects = all_rects[0] last_rects = all_rects[-1].copy() last_rects.set_stroke(width=0) self.add(axes) self.play(ShowCreation(graph)) self.play(FadeIn(last_rects, lag_ratio=0.1)) self.wait() self.play(FadeIn(rects, lag_ratio=0.1), FadeOut(last_rects)) self.wait() self.play(LaggedStart(*( ApplyMethod(rect.set_color, YELLOW, rate_func=there_and_back) for rect in rects ), lag_ratio=0.5, run_time=4)) # Iterations for new_rects in all_rects[1:]: self.play(Transform(rects, new_rects)) self.wait(0.5) # Zoom frame = self.camera.frame self.play(frame.animate.move_to(graph.pfp(0.5)).set_height(0.1), run_time=3) self.wait() self.play(frame.animate.to_default_state(), run_time=3) self.wait() class IntegralError(InteractiveScene): def construct(self): # (Coped from above) axes = Axes((-1, 4), (-1, 10), width=12, height=6) graph = axes.get_graph(lambda x: x**2) graph.set_stroke(TEAL, 2) all_rects = VGroup(*( axes.get_riemann_rectangles(graph, (0, 3), dx).set_stroke(BLACK, np.round(4 * dx, 1), background=False) for dx in [2**(-n) for n in range(2, 9)] )) rects = all_rects[0] last_rects = all_rects[-1].copy() last_rects.set_stroke(width=0) self.add(axes, graph) self.add(rects) # Mention error error = last_rects.copy() error.set_fill(RED, 1) error_label = Text("Error", font_size=72, color=RED) error_label.move_to(rects, UP).shift(UP) error_arrows = VGroup(*( Arrow(error_label, rect.get_top() + 0.2 * UP, stroke_width=2, tip_width_ratio=8) for rect in rects )) error_arrows.set_color(RED) self.add(error, rects) self.play( FadeIn(error, lag_ratio=0.5, run_time=2), Write(error_label, stroke_color=RED), LaggedStart(*( ShowCreation(arrow) for arrow in error_arrows ), lag_ratio=0.2, run_time=3) ) self.wait() # Error boxes all_error_boxes = VGroup() for rg in all_rects: boxes = VGroup() for rect in rg: box = Rectangle(stroke_width=0, fill_opacity=0.5, fill_color=RED) box.replace(Line( axes.i2gp(axes.x_axis.p2n(rect.get_left()), graph), axes.i2gp(axes.x_axis.p2n(rect.get_right()), graph), ), stretch=True) boxes.add(box) all_error_boxes.add(boxes) self.play( FadeIn(all_error_boxes[0], lag_ratio=0.1), error.animate.set_opacity(0.25), FadeOut(error_arrows), ) for rg, ebg in zip(all_rects, all_error_boxes): for rect, box in zip(rg, ebg): rect.add(box) self.remove(all_error_boxes) self.add(rects) # Inequality error_label.generate_target() error_label.target.scale(0.7) sum_squares = Tex("< \\sum \\Delta", isolate="\\Delta") rhs = VGroup(OldTex("="), DecimalNumber(num_decimal_places=4)) rhs.arrange(RIGHT) rhs[1].set_value(0.3417) group = VGroup(error_label.target, sum_squares, rhs) group.arrange(RIGHT) group.to_edge(UP) pre_box_sym = rects[-1].submobjects[0] box_sym = pre_box_sym.copy() box_sym.replace(sum_squares[2], dim_to_match=1) sum_squares.replace_submobject(2, box_sym) self.play( MoveToTarget(error_label), Write(sum_squares[:2]), TransformFromCopy(pre_box_sym, box_sym) ) self.add(rhs) self.play( CountInFrom(rhs[1], 0), LaggedStart(*( VFadeInThenOut(r.copy().set_fill(opacity=1), buff=0, color=RED) for r in all_error_boxes[0] ), lag_ratio=0.2), run_time=2 ) self.wait() # Iterations for new_rects in all_rects[1:]: self.play( Transform(rects, new_rects), ChangeDecimalToValue(rhs[1], rhs[1].get_value() / 4), run_time=3, ) self.wait(0.5) class IntegralExampleWithErrorBoxes(IntegralExample): show_error_boxes = True class DefiningTheLengthOfACurve(InteractiveScene): def construct(self): pass class FalseEuclidProofAnnotation(InteractiveScene): def construct(self): # path = "/Users/grant/Dropbox/3Blue1Brown/videos/2022/visual_proofs/lies/images/FalseEuclidProof.jpg" # self.add(ImageMobject(path).set_width(FRAME_WIDTH)) # Points A = np.array([-1.94444444, 1.44444444, 0.]) B = np.array([-4.44444444, -0.02777778, 0.]) C = np.array([-1.09722222, -0.48611111, 0.]) D = np.array([-2.63888889, -0.27777778, 0.]) E = np.array([-1.56944444, 0.55555556, 0.]) F = np.array([-3.01388889, 0.83555556, 0.]) P = np.array([-2.58333333, 0.122222, 0.]) # dots = Group(*(GlowDot(point, color=RED) for point in [A, B, C, D, E, F, P])) AFP = Polygon(A, F, P) AEP = Polygon(A, E, P) BPD = Polygon(B, P, D) CPD = Polygon(C, P, D) BFP = Polygon(B, F, P) CEP = Polygon(C, E, P) tris = VGroup(AFP, AEP, BPD, CPD, BFP, CEP) tris.set_stroke(BLACK, 1) tris[:2].set_fill(BLUE) tris[2:4].set_fill(GREEN) tris[4:].set_fill(RED) tris.set_fill(opacity=0.8) # Final sum AF = Line(A, F) FB = Line(F, B) AB = Line(A, B) AE = Line(A, E) EC = Line(E, C) AC = Line(A, C) lines = VGroup(AF, FB, AB, AE, EC, AC) for line in lines: brace = Brace(Line(ORIGIN, line.get_length() * RIGHT), UP) brace.next_to(ORIGIN, UP, buff=0.1) angle = line.get_angle() angle = (angle + PI / 2) % PI - PI / 2 brace.rotate(angle, about_point=ORIGIN) brace.shift(line.get_center()) brace.set_fill(BLACK, 1) line.brace = brace self.play(GrowFromCenter(AF.brace), run_time=1) self.play(GrowFromCenter(FB.brace), run_time=1) self.wait() self.play( Transform(AF.brace, AB.brace, path_arc=45 * DEGREES), Transform(FB.brace, AB.brace, path_arc=45 * DEGREES), ) self.wait() self.play(GrowFromCenter(AE.brace), run_time=1) self.play(GrowFromCenter(EC.brace), run_time=1) self.wait() self.play( Transform(AE.brace, AC.brace, path_arc=45 * DEGREES), Transform(EC.brace, AC.brace, path_arc=45 * DEGREES), ) self.wait() return # Lines for final triangles BP = Line(B, P) CP = Line(C, P) PF = Line(P, F) PE = Line(P, E) BF = Line(B, F) CE = Line(C, E) VGroup(BP, CP).set_stroke(BLUE_E, 5) VGroup(PF, PE).set_stroke(TEAL, 5) VGroup(BF, CE).set_stroke(RED, 5) self.play(*map(ShowCreation, [BP, CP])) self.play(*map(ShowCreation, [PF, PE])) self.wait() self.play( TransformFromCopy(PF, BF, path_arc=90 * DEGREES), TransformFromCopy(PE, CE, path_arc=-90 * DEGREES), ) self.wait() # Compare AB to BC AB = Line(A, B).set_stroke(RED, 3) AC = Line(A, C).set_stroke(BLUE, 3) self.play(ShowCreation(AB)) self.play(ShowCreation(AC)) self.wait() self.add(AB.copy(), AC.copy()) self.play( AB.animate.set_angle(-90 * DEGREES).next_to(A, RIGHT, aligned_edge=UP, buff=2), AC.animate.set_angle(-90 * DEGREES).next_to(A, RIGHT, aligned_edge=UP, buff=2.5), ) self.wait() self.play(FadeOut(AB), FadeOut(AC)) # Bisector labels perp = Text("Perpendicular\nbisector", font_size=30, color=BLACK, stroke_width=0) perp.next_to(F, UL, buff=0.5) perp.set_color(BLUE_E) perp_arrow = Arrow(perp, midpoint(D, P), buff=0.1, stroke_width=2) perp_arrow.match_color(perp) ang_b = Text("Angle\nbisector", font_size=30, color=BLACK, stroke_width=0) ang_b.next_to(F, UL, buff=0.5) ang_b.set_color(RED_E) ang_b_arrow = Arrow(ang_b, midpoint(A, P), buff=0.1, stroke_width=2) ang_b_arrow.match_color(ang_b) self.play(Write(perp), ShowCreation(perp_arrow), run_time=1) self.wait() self.play(FadeOut(perp), FadeOut(perp_arrow)) self.wait() self.play(Write(ang_b), ShowCreation(ang_b_arrow), run_time=1) self.wait() self.play(FadeOut(ang_b), FadeOut(ang_b_arrow)) self.wait() # Similar triangles for pair in [(AFP, AEP), (BPD, CPD), (BFP, CEP)]: self.play(DrawBorderThenFill(pair[0])) self.play(TransformFromCopy(pair[0], pair[1])) self.wait() self.play(LaggedStartMap(FadeOut, VGroup(*pair))) self.wait() class FalseEuclidFollowup(InteractiveScene): def construct(self): # All triangles are equilateral tri1 = Polygon(3 * UP, DL, RIGHT) tri2 = Polygon(3 * UP, LEFT, RIGHT) tri3 = tri2.copy().set_height(math.sqrt(3) * tri2.get_width() / 2, stretch=True, about_edge=DOWN) tris = VGroup(tri1, tri2, tri3) tris.set_fill(BLUE_D, 1) tris.set_stroke(WHITE, 2) tris.scale(1.5) tris.to_edge(DOWN, buff=1.0) tri = tri1 def get_side(i, j, tri=tri): return Line(tri.get_vertices()[i], tri.get_vertices()[j]).set_stroke(YELLOW, 4) labels = Text("ABC") for letter, vert in zip(labels, tri.get_vertices()): letter.next_to(vert, normalize(vert - tri.get_center_of_mass()), SMALL_BUFF) equation = Tex("\\overline{AB} = \\overline{AC}") equation2 = Tex("\\overline{AB} = \\overline{AC} = \\overline{BC}") equation.next_to(labels, LEFT, aligned_edge=UP) equation2.move_to(equation).to_edge(LEFT) words = Text("All triangles are\nisosceles") words.next_to(equation, DOWN, LARGE_BUFF) VGroup(equation, words).to_edge(LEFT) iso = words.select_parts("isosceles") iso_cross = Cross(iso) equi = Text("equilateral") equi.move_to(iso, UP) equi.set_color(YELLOW) self.add(tri, labels) self.wait() self.play( FadeIn(equation), FadeIn(words), ShowCreationThenDestruction(get_side(0, 1), run_time=2), ShowCreationThenDestruction(get_side(0, 2), run_time=2), ) self.play(Transform(tri, tri2), labels[1].animate.shift(1.5 * UP)) self.wait() self.play(CyclicReplace(*labels)) self.play( ShowCreationThenDestruction(get_side(1, 0), run_time=2), ShowCreationThenDestruction(get_side(1, 2), run_time=2), ShowCreation(iso_cross) ) cross_group = VGroup(iso, iso_cross) self.play( cross_group.animate.shift(DOWN), FadeIn(equi, 0.5 * DOWN), Transform(tri, tri3), labels[2].animate.next_to(tri3, UP, SMALL_BUFF) ) self.play( Transform(equation, equation2[:len(equation)]), FadeIn(equation2[len(equation):], RIGHT), ) self.wait() words = VGroup(words.select_parts("All triangles are"), equi) # Three possibilities possibilities = VGroup( Text("1. This is true"), OldTexText("2. Euclid's axioms $\\Rightarrow$ falsehoods")[0], Text("3. This proof has a flaw"), ) possibilities.arrange(DOWN, buff=1.0, aligned_edge=LEFT) possibilities.to_edge(RIGHT, buff=LARGE_BUFF) poss_title = Text("Possibilities", font_size=60) poss_title.next_to(possibilities, UP, buff=1.5, aligned_edge=LEFT) poss_title.add(Underline(poss_title)) tri.add(labels) self.play( FadeOut(cross_group, DL), tri.animate.match_width(words).next_to(words, DOWN, LARGE_BUFF), LaggedStart(*( FadeIn(poss[:2], shift=LEFT) for poss in possibilities )), Write(poss_title) ) self.wait() for poss in possibilities: self.play(Write(poss[2:], stroke_color=WHITE)) self.wait() class TryToFindFault(TeacherStudentsScene): def construct(self): # Setup morty = self.teacher ss = self.students points = compass_directions(5, start_vect=UP) star = Polygon(*(points[i] for i in [0, 2, 4, 1, 3])) star.set_fill(YELLOW, 1) star.set_stroke(width=0) star.set_gloss(1) star.set_height(0.5) stars = star.replicate(3) stars.arrange(RIGHT) stars.move_to(self.hold_up_spot, DOWN) stars.insert_n_curves(10) stars.refresh_triangulation() self.play( morty.says("I dare you to\nfind a fault", mode="tease"), ) self.play_student_changes("pondering", "pondering", "sassy") self.wait() self.play( morty.debubble(mode="raise_right_hand"), self.change_students("thinking", "happy", "tease"), Write(stars) ) self.wait(3) class SideSumTruthiness(InteractiveScene): def construct(self): # Lines A, E, C = Dot().replicate(3) A.move_to(2 * UL) C.move_to(DR) VGroup(A, C).to_corner(DR, buff=1.5) alpha_tracker = ValueTracker(0.75) E.add_updater(lambda m: m.move_to(interpolate( A.get_center(), C.get_center(), alpha_tracker.get_value() ))) AE = Line().set_stroke(RED, 3, opacity=0.75) EC = Line().set_stroke(BLUE, 3, opacity=0.75) AE.add_updater(lambda l: l.put_start_and_end_on(A.get_center(), E.get_center())) EC.add_updater(lambda l: l.put_start_and_end_on(E.get_center(), C.get_center())) labels = Text("AEC") labels[0].next_to(A, UP, SMALL_BUFF) labels[1].add_updater(lambda m: m.next_to(E, DL, SMALL_BUFF)) labels[2].next_to(C, RIGHT, SMALL_BUFF) self.add(AE, EC, A, E, C, *labels) # Equation eq = OldTex("\\overline{AE} + \\overline{EC} = \\overline{AC}", font_size=60) eq.to_corner(UR) labels = VGroup( VGroup(Text("True"), Checkmark()), VGroup(Text("False"), Exmark()), ) labels.scale(60 / 48) for label in labels: label[0].match_color(label[1]) label.arrange(RIGHT, buff=MED_LARGE_BUFF) label.next_to(eq, DOWN, MED_LARGE_BUFF) labels[0].add_updater(lambda m: m.set_opacity(1 if 0 < alpha_tracker.get_value() < 1 else 0)) labels[1].add_updater(lambda m: m.set_opacity(0 if 0 < alpha_tracker.get_value() < 1 else 1)) self.add(eq) self.add(labels) # Move around for alpha in [0.3, 0.7, 0.5, 0.7, 0.3, -0.3, 0.7, 1.4, 1.2, 0.5]: self.play(alpha_tracker.animate.set_value(alpha), run_time=2) self.wait() class PythagoreanProofSketch(InteractiveScene): def construct(self): # First orientation tri = Polygon(ORIGIN, UP, 2 * RIGHT) tri.set_stroke(WHITE, 1) tri.set_fill(BLUE_E, 1) verts = tri.get_vertices() tris = VGroup(tri, tri.copy().rotate(PI, about_point=midpoint(*verts[1:]))) tris.add(*tris.copy().rotate(PI, axis=UL, about_point=tris.get_corner(DL))) tris[2:4].flip(UP) big_square = SurroundingRectangle(tris, buff=0) big_square.set_stroke(WHITE, 2) VGroup(tris, big_square).center().set_height(5) A, B = tri.get_height(), tri.get_width() a_square = Square(A) a_square.move_to(big_square, UL) a_square.set_fill(RED_C, 0.75) b_square = Square(B) b_square.move_to(big_square, DR) b_square.set_fill(RED_D, 0.75) a_square_label = Tex("a^2").move_to(a_square) b_square_label = Tex("b^2").move_to(b_square) # Pre triangle pre_tri = tris[0].copy() pre_tri.scale(1.5) pre_tri.shift(-pre_tri.get_center_of_mass()) side_labels = Tex("abc") side_labels[0].next_to(pre_tri, LEFT) side_labels[1].next_to(pre_tri, DOWN) side_labels[2].next_to(pre_tri.get_center(), UR) self.add(pre_tri) self.add(side_labels) # Equation equation = Tex("a^2 + b^2 = c^2", isolate=["a^2", "+", "b^2", "=", "c^2"]) equation.next_to(big_square, UP).to_edge(UP) # A^2 and B^2 scale_factor = tris[0].get_height() / pre_tri.get_height() shift_vect = tris[0].get_center() - pre_tri.get_center() self.play( ReplacementTransform(pre_tri, tris[0]), side_labels.animate.scale(scale_factor, about_point=pre_tri.get_center()).shift(shift_vect) ) self.add(tris[1], side_labels) self.play(LaggedStart( TransformFromCopy(tris[0], tris[1], path_arc=PI), TransformFromCopy(tris[0], tris[2]), TransformFromCopy(tris[0], tris[3]), FadeIn(big_square), Animation(side_labels), lag_ratio=0.3 )) self.play( FadeIn(a_square), FadeTransform(side_labels[0], a_square_label), FadeIn(b_square), FadeTransform(side_labels[1], b_square_label), ) self.play( FadeOut(a_square), FadeOut(b_square), TransformFromCopy(a_square_label, equation.select_parts("a^2")), TransformFromCopy(b_square_label, equation.select_parts("b^2")), Write(equation.select_parts("+")), ) self.wait() # Second orientation tris.save_state() tris2 = tris.copy() tris2[0].rotate(PI / 2, OUT, about_point=tris2[0].get_corner(DR)) tris2[3].rotate(-PI / 2).move_to(big_square, DL) tris2[2].move_to(big_square, UL) c_square = Square(math.sqrt(A**2 + B**2)) c_square.rotate(math.atan(B / A)) c_square.move_to(big_square) c_square.set_fill(RED_D, 0.7) c_square_label = Tex("c^2").move_to(c_square) self.play(LaggedStart( FadeOut(a_square_label), FadeOut(b_square_label), *(Transform(tris[i], tris2[i]) for i in (0, 2, 3)), lag_ratio=0.5 )) self.wait() self.play( FadeIn(c_square), FadeIn(c_square_label), ) self.play( FadeTransform(c_square_label.copy(), equation.select_parts("c^2")), Write(equation.select_parts("=")), c_square.animate.set_fill(opacity=0.5) ) self.wait() self.play(FadeOut(c_square)) # Final gif self.play( Transform(tris, tris.saved_state, lag_ratio=0.2, run_time=3, path_arc=45 * DEGREES), FadeOut(c_square_label), FadeIn(a_square_label, time_span=(1.5, 2.5)), FadeIn(b_square_label, time_span=(2, 3)), ) self.wait() self.play( Transform(tris, tris2, lag_ratio=0.2, run_time=3, path_arc=45 * DEGREES), FadeIn(c_square_label, time_span=(2, 3)), FadeOut(a_square_label, time_span=(0, 1)), FadeOut(b_square_label, time_span=(0.5, 1.5)), ) self.wait() class LastSideBySide(InteractiveScene): def construct(self): self.add(FullScreenRectangle()) squares = Square().replicate(2) squares.set_stroke(WHITE, 2) squares.set_fill(BLACK, 2) squares.set_height(5) squares.set_width(6, stretch=True) for square, vect in zip(squares, [LEFT, RIGHT]): square.move_to(FRAME_WIDTH * vect / 4) squares.to_edge(DOWN, buff=0.7) self.add(squares) titles = VGroup( OldTexText("Given examples\\\\like this..."), OldTexText("What's needed to\\\\make this rigorous?"), ) for title, square in zip(titles, squares): title.next_to(square, UP, buff=MED_LARGE_BUFF) self.play(Write(titles[0])) self.wait() self.play(Write(titles[1])) self.wait() class ByTheWay(InteractiveScene): def construct(self): self.play(Write(Text("By the way..."))) self.wait() class EndScreen(PatreonEndScreen): CONFIG = { "thanks_words": "Special thanks to the following patrons", }
from manim_imports_ext import * from _2022.piano.fourier_animations import DecomposeAudioSegment from _2019.diffyq.part2.fourier_series import FourierCirclesScene class DecomposeRoar_SlowFPS(DecomposeAudioSegment): audio_file = "/Users/grant/Dropbox/3Blue1Brown/videos/2022/infinity/Roar.wav" graph_point = 0.428 zoom_rect_dims = (0.2, 6.0) def construct(self): self.add_full_waveform(run_time=2.5) self.zoom_in_on_segment( self.axes, self.graph, self.graph_point, self.zoom_rect_dims, run_time=3, ) self.prepare_for_3d() self.show_all_waves() def show_all_waves(self): t_axes = self.axes graph = self.graph # Take the fourier transform t_max = t_axes.x_range[1] ts, values = t_axes.p2c(graph.get_points()[::6]) signal = values[(ts > 0) * (ts < t_max)] signal_fft = np.fft.fft(signal) signal_fft /= len(signal) signal_fft_abs = np.abs(signal_fft) signal_fft_phase = np.log(signal_fft).imag # Prepare the graph max_freq = signal.size / t_max f_axes = Axes( (0, max_freq / 2, max_freq / len(signal) / 2), (0, 1, 1 / 8), height=t_axes.get_depth(), width=150, ) f_axes.rotate(PI / 2, RIGHT) f_axes.rotate(PI / 2, OUT) f_axes.shift(t_axes.get_origin() - f_axes.get_origin()) freqs = np.fft.fftfreq(signal.size, 1 / max_freq) % max_freq # Express the most dominant signals as sine waves sine_waves = VGroup() amps = [] for index in range(1, 50): freq = freqs[index] amp = signal_fft_abs[index] phase = signal_fft_phase[index] wave = t_axes.get_graph( lambda t: 2 * amp * np.cos(TAU * freq * (t + phase)), x_range=(0, t_max), ) wave.match_y(f_axes.c2p(freq, 0)) # wave.set_stroke(opacity=0.75) wave.set_stroke(opacity=1.0) wave.amp = amp wave.freq = freq wave.phase = phase amps.append(amp) sine_waves.add(wave) sine_waves.set_submobject_colors_by_gradient(YELLOW, GREEN, RED, ORANGE) sine_waves.set_stroke(width=3) # Break down frame = self.camera.frame frame.generate_target() frame.target.reorient(67, 71) frame.target.set_height(10.5) frame.target.move_to([2.6, 6.15, 0.79]) self.play( FadeIn(f_axes), MoveToTarget(frame), LaggedStart( *( ReplacementTransform( graph.copy().set_opacity(0), wave ) for wave in sine_waves ), lag_ratio=1 / len(sine_waves), ), run_time=4 ) self.wait(3) class CombineWavesToImage_SlowFPS(FourierCirclesScene): CONFIG = { "drawing_height": 6.0, "n_shown_waves": 5, "n_vectors": 500, # "n_vectors": 50, "slow_factor": 0.1, "max_circle_stroke_width": 2.0, "parametric_function_step_size": 0.001, # "parametric_function_step_size": 0.01, "drawn_path_color": YELLOW, "remove_background_waves": False, "drawing_file": "/Users/grant/Dropbox/3Blue1Brown/videos/2022/infinity/monster-holding-piece-sign-3.svg", } def construct(self): self.generate_coefs() self.show_sine_waves() self.piece_together_circles() def generate_coefs(self): drawing = self.get_drawing() coefs = self.get_coefficients_of_path(drawing) vectors = self.get_rotating_vectors(coefficients=coefs) circles = self.get_circles(vectors) self.style_vectors(vectors) self.style_circles(circles) self.path = drawing self.coefs = coefs self.vectors = vectors self.circles = circles def show_sine_waves(self): # Initialized copycat vectors and circles s = slice(1, 1 + self.n_shown_waves) shown_vectors = self.vectors[s].copy().clear_updaters() shown_circles = self.circles[s].copy().clear_updaters() scale_factor = 1.0 / 3.0 for vect, circ in zip(shown_vectors, shown_circles): vect.scale(scale_factor) circ.scale(scale_factor) vect.center_point = VectorizedPoint() vect.center_func = vect.center_point.get_center circ.center_func = vect.center_point.get_center vect.add_updater(lambda v: v.set_angle( np.log(v.coefficient).imag + self.get_vector_time() * v.freq * TAU )) vect.add_updater(lambda v: v.shift(v.center_func() - v.get_start())) circ.add_updater(lambda c: c.move_to(c.center_func())) shown_circles.set_stroke(width=2) shown_vectors.set_stroke(width=2) graphs = VGroup() # Add axes max_y = int(np.ceil(max(v.get_length() for v in shown_vectors))) all_axes = VGroup(*( Axes( x_range=(0, 8 * PI, PI), y_range=(-max_y, max_y), height=1.0, width=18, ) for n in range(self.n_shown_waves) )) all_axes.arrange(DOWN, buff=1.0) dots = OldTex("\\vdots", font_size=100) dots.next_to(all_axes, DOWN, buff=0.5) dots.match_x(all_axes[0].get_origin()) dots.set_fill(WHITE) frame = self.camera.frame group = Group(all_axes, dots) group.move_to(0.5 * UP) group.set_height(7) frame.set_height(group.get_height() + 1) frame.move_to(group) frame.shift(0.5 * LEFT) # Add graphs colors = color_gradient([RED, YELLOW], self.n_shown_waves) v2g_lines = VGroup() for vect, axes, color in zip(shown_vectors, all_axes, colors): vect.center_point.next_to(axes, LEFT, buff=0.75) axes.amp = vect.get_length() / axes.y_axis.get_unit_size() axes.vect = vect axes.color = color axes.graph = always_redraw( lambda a=axes: a.get_graph( lambda x: a.amp * math.sin(a.vect.freq * x + a.vect.get_angle()), stroke_width=2, stroke_color=a.color ) ) graphs.add(axes.graph) line = Line() line.set_stroke(WHITE, 1.0) line.vect = vect line.graph = axes.graph line.add_updater(lambda l: l.put_start_and_end_on( l.vect.get_end(), l.graph.get_start() )) v2g_lines.add(line) # Animate the addition of all these? self.wait(1) for mobs in zip(all_axes, graphs, shown_vectors, shown_circles, v2g_lines): self.add(*mobs) self.wait(0.25) self.add(dots) self.all_axes = all_axes self.shown_vectors = shown_vectors self.shown_circles = shown_circles self.graphs = graphs self.v2g_lines = v2g_lines self.dots = dots def piece_together_circles(self): # Setup path and labels true_path = self.path fade_region = self.get_fade_region(true_path) rt = 5 # sf = self.get_slow_factor() # future_vt = self.get_vector_time() + sf * rt label = VGroup(Integer(100, edge_to_fix=DR), Text("terms")) label.arrange(RIGHT, buff=0.15) label.next_to(true_path, UP, buff=0.85) label[0].set_value(self.n_shown_waves) # Animate entry terms = self.get_terms(self.n_shown_waves) self.play( FadeIn(fade_region, lag_ratio=0.1), LaggedStart(*( TransformFromCopy(v1, v2) for v1, v2 in zip(self.shown_vectors, self.vectors[1:]) ), lag_ratio=0.1), LaggedStart(*( TransformFromCopy(c1, c2) for c1, c2 in zip(self.shown_circles, self.circles[1:]) ), lag_ratio=0.1), FadeIn(label), Write(terms), run_time=rt, ) # Set up drawn paths drawn_path = self.get_drawn_path(self.vectors[:self.n_shown_waves + 1]) dot = self.add_draw_dot(self.vectors[:self.n_shown_waves + 1]) self.add(drawn_path, terms, dot) anims = [ UpdateFromAlphaFunc(drawn_path, lambda m, a: m.set_stroke(interpolate_color(BLACK, YELLOW, a))), UpdateFromAlphaFunc(dot, lambda m, a: m.set_opacity(a)), ] if self.remove_background_waves: self.play( fade_region.animate.set_height(2 * FRAME_WIDTH).set_opacity(0.05), *anims, run_time=2 ) self.remove( self.all_axes, self.graphs, self.shown_vectors, self.shown_circles, self.v2g_lines, self.dots, fade_region, ) else: self.play(*anims, run_time=2) # Now add on new vectors one at a time drawn_paths = dict() all_terms = dict() drawing_group = VGroup( drawn_path, terms, label, VGroup(), # Vectors VGroup(), # Circles ) def update_drawing_group(group, alpha): n, _ = integer_interpolate(self.n_shown_waves, self.n_vectors, alpha) if n not in drawn_paths: drawn_paths[n] = self.get_drawn_path(self.vectors[:n]) if n not in all_terms: all_terms[n] = self.get_terms(n) group.replace_submobject(0, drawn_paths[n]) group.replace_submobject(1, all_terms[n]) group[2][0].set_value(n) group[3].set_submobjects(self.vectors[:n]) group[4].set_submobjects(self.circles[:n]) self.style_vectors(group[3]) self.style_circles(group[4]) if n > 25: group[4].set_stroke(opacity=(1.0 / (n - 25))**0.2) group.update() return group self.remove(self.vectors, self.circles, drawn_path, terms, dot) self.add_draw_dot(drawing_group[3]) self.play(UpdateFromAlphaFunc( drawing_group, update_drawing_group, run_time=15, rate_func=lambda a: a**2, )) inf = OldTex("\\infty") inf.match_height(label[0]) inf.move_to(label[0], RIGHT) inf.set_fill(WHITE) drawn_path = drawing_group[0] # self.add_path_fader(true_path, fade_rate=1) true_path.set_stroke(width=1.0) self.add(drawn_path, true_path, self.circles, self.vectors) self.play( UpdateFromAlphaFunc(drawn_path, lambda m, a: m.set_stroke(interpolate_color(YELLOW, BLACK, a))), VFadeIn(true_path), ChangeDecimalToValue(label[0], 1000), VFadeOut(label[0]), FadeIn(inf), run_time=3, ) self.remove(drawn_path) self.wait(12) ## def get_drawing(self): svg = SVGMobject(self.drawing_file) drawing = svg[1] drawing.set_height(self.drawing_height) drawing.set_stroke(self.drawn_path_color, 2) return drawing def get_peace_sign(self): theta = 40 * DEGREES arc1 = Arc(270 * DEGREES, -theta, n_components=1) arc2 = Arc(270 * DEGREES + theta, -(theta + PI), n_components=7) circ = Circle(start_angle=90 * DEGREES, n_components=12) parts = [ circ, Line(UP, ORIGIN), Line(ORIGIN, DOWN), arc1, Line(arc1.get_end(), ORIGIN), Line(ORIGIN, arc2.get_start()), arc2, ] path = VMobject() for part in parts: path.append_points(part.get_points()) return path def style_vectors(self, vectors): for k, vector in enumerate(vectors): vector.set_stroke(width=2.5 / (1 + k / 10), opacity=1) return vectors def style_circles(self, circles): mcsw = self.max_circle_stroke_width circles.set_stroke(Color('green')) for k, circle in zip(it.count(0), circles): circle.set_stroke(width=mcsw / (1 + k / 4), opacity=1) return circles def get_fade_region(self, path): dot = GlowDot() dot.set_radius(1.0 * path.get_width()) dot.set_glow_factor(0.2) dot.set_color(BLACK, 0.95) return dot def get_drawn_path(self, vectors): nv = len(vectors) if nv == 0: return VGroup() fade_rate = 10 * np.exp(0.01 * (5 - nv)) + 1.0 path = super().get_drawn_path(vectors, stroke_width=4, fade_rate=fade_rate) path.set_stroke(self.drawn_path_color) return path def get_terms(self, n_terms, max_terms=100, max_width=12): ks = list(range(-int(np.floor(n_terms / 2)), int(np.ceil(n_terms / 2)))) ks.sort(key=abs) ks = ks[:max_terms] ks.sort() font_size = max(180 / n_terms, 5) terms = VGroup() for k in ks: terms.add(Tex("c_{k} e^{k \\cdot 2 \\pi i \\cdot t} +".replace("k", str(k)))) if n_terms <= max_terms: terms[-1][-1].set_opacity(0) else: terms.add_to_back(Tex("\\cdots + ")) terms.add(Tex("\\cdots")) terms.arrange(RIGHT, SMALL_BUFF) terms.scale(font_size / 48) terms.set_max_width(max_width) terms.next_to(self.path, UP, SMALL_BUFF) max_light_terms = 15 if n_terms > max_light_terms: terms.set_fill(opacity=max_light_terms / (n_terms - max_light_terms)) terms.set_stroke(width=0) return terms def add_draw_dot(self, vectors): dot = GlowDot() dot.add_updater(lambda d: d.move_to( vectors[-1].get_end() if len(vectors) > 0 else ORIGIN )) self.add(dot) return dot
from manim_imports_ext import * from _2022.quintic.roots_and_coefs import * class CubicFormula(RootCoefScene): coefs = [1, -1, 0, 1] coef_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": GREY, "stroke_width": 1.0, } } root_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": BLUE_E, "stroke_width": 1.0, } } sqrt_plane_config = { "x_range": (-1.0, 1.0), "y_range": (-1.0, 1.0), "background_line_style": { "stroke_color": GREY_B, "stroke_width": 1.0, }, "height": 3.0, "width": 3.0, } crt_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": BLUE_E, "stroke_width": 1.0, }, "height": 3.0, "width": 3.0, } cf_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": BLUE_E, "stroke_width": 1.0, }, "height": 3.0, "width": 3.0, } plane_height = 3.0 plane_buff = 1.0 planes_center = 1.6 * UP lower_planes_height = 2.75 lower_planes_buff = 2.0 sqrt_dot_color = GREEN crt_dot_colors = (RED, BLUE) cf_dot_color = YELLOW def add_planes(self): super().add_planes() self.root_plane_label.next_to(self.root_plane, -self.plane_arrangement) self.coef_plane_label.next_to(self.coef_plane, self.plane_arrangement) self.add_lower_planes() def add_lower_planes(self): sqrt_plane = ComplexPlane(**self.sqrt_plane_config) crt_plane = ComplexPlane(**self.crt_plane_config) cf_plane = ComplexPlane(**self.cf_plane_config) planes = VGroup(sqrt_plane, crt_plane, cf_plane) for plane in planes: plane.add_coordinate_labels(font_size=16) planes.set_height(self.lower_planes_height) planes.arrange(RIGHT, buff=self.lower_planes_buff) planes.to_edge(DOWN, buff=SMALL_BUFF) kw = dict( font_size=24, tex_to_color_map={ "\\delta_1": GREEN, "\\delta_2": GREEN, }, background_stroke_width=3, background_stroke_color=3, ) sqrt_label = OldTex( "\\delta_1, \\delta_2 = \\sqrt{ \\frac{q^2}{4} + \\frac{p^3}{27}}", **kw ) sqrt_label.set_backstroke() sqrt_label.next_to(sqrt_plane, UP, SMALL_BUFF) crt_labels = VGroup( OldTex("\\cdot", "= \\sqrt[3]{-\\frac{q}{2} + \\delta_1}", **kw), OldTex("\\cdot", "= \\sqrt[3]{-\\frac{q}{2} + \\delta_2}", **kw), ) for label, color in zip(crt_labels, self.crt_dot_colors): label[0].scale(4, about_edge=RIGHT) label[0].set_color(color) label.set_backstroke() crt_labels.arrange(RIGHT, buff=MED_LARGE_BUFF) crt_labels.next_to(crt_plane, UP, SMALL_BUFF) cf_label = OldTex( "\\sqrt[3]{ -\\frac{q}{2} + \\delta_1 } +", "\\sqrt[3]{ -\\frac{q}{2} + \\delta_2 }", # **kw # TODO, What the hell is going on here... font_size=24, ) cf_label.set_backstroke() cf_label.next_to(cf_plane, UP, SMALL_BUFF) self.add(planes) self.add(sqrt_label) self.add(crt_labels) self.add(cf_label) self.sqrt_plane = sqrt_plane self.crt_plane = crt_plane self.cf_plane = cf_plane self.sqrt_label = sqrt_label self.crt_labels = crt_labels self.cf_label = cf_label def get_coef_poly(self): return OldTex( "x^3 + {0}x^2 + {p}x + {q}", tex_to_color_map={ "{0}": self.coef_color, "{p}": self.coef_color, "{q}": self.coef_color, } ) def add_c_labels(self): self.c_dot_labels = self.add_dot_labels( VGroup(*map(Tex, ["q", "p", "0"])), self.coef_dots ) def get_c_symbols(self, coef_poly): return VGroup(*( coef_poly.get_part_by_tex(tex) for tex in ["q", "p", "0"] )) # def add_dots(self): super().add_dots() self.add_sqrt_dots() self.add_crt_dots() self.add_cf_dots() def add_sqrt_dots(self): sqrt_dots = Dot(**self.dot_style).replicate(2) sqrt_dots.set_color(self.sqrt_dot_color) def update_sqrt_dots(dots): q, p, zero, one = self.get_coefs() disc = (q**2 / 4) + (p**3 / 27) roots = get_nth_roots(disc, 2) optimal_transport(dots, map(self.sqrt_plane.n2p, roots)) return dots sqrt_dots.add_updater(update_sqrt_dots) self.sqrt_dots = sqrt_dots self.add(sqrt_dots) self.add(self.get_tracers(sqrt_dots)) # Labels self.delta_labels = self.add_dot_labels( VGroup(OldTex("\\delta_1"), OldTex("\\delta_2")), sqrt_dots ) def get_deltas(self): return list(map(self.sqrt_plane.p2n, (d.get_center() for d in self.sqrt_dots))) def add_crt_dots(self): crt_dots = Dot(**self.dot_style).replicate(3).replicate(2) for dots, color in zip(crt_dots, self.crt_dot_colors): dots.set_color(color) def update_crt_dots(dot_triples): q, p, zero, one = self.get_coefs() deltas = self.get_deltas() for delta, triple in zip(deltas, dot_triples): roots = get_nth_roots(-q / 2 + delta, 3) optimal_transport(triple, map(self.crt_plane.n2p, roots)) return dot_triples crt_dots.add_updater(update_crt_dots) self.add(crt_dots) self.add(*(self.get_tracers(triple) for triple in crt_dots)) self.crt_dots = crt_dots def get_cube_root_values(self): return [ [ self.crt_plane.p2n(d.get_center()) for d in triple ] for triple in self.crt_dots ] def add_crt_lines(self): crt_lines = VGroup(*( Line(stroke_color=color, stroke_width=1).replicate(3) for color in self.crt_dot_colors )) def update_crt_lines(crt_lines): cube_root_values = self.get_cube_root_values() origin = self.crt_plane.n2p(0) for lines, triple in zip(crt_lines, cube_root_values): for line, value in zip(lines, triple): line.put_start_and_end_on(origin, self.crt_plane.n2p(value)) crt_lines.add_updater(update_crt_lines) self.add(crt_lines) self.crt_lines = crt_lines def add_cf_dots(self): cf_dots = Dot(**self.dot_style).replicate(9) cf_dots.set_fill(self.root_color, opacity=0.5) def update_cf_dots(dots): cube_root_values = self.get_cube_root_values() for dot, (z1, z2) in zip(dots, it.product(*cube_root_values)): dot.move_to(self.cf_plane.n2p(z1 + z2)) return dots cf_dots.add_updater(update_cf_dots) alt_root_dots = GlowDot() alt_root_dots.add_updater(lambda m: m.set_points( list(map(self.cf_plane.n2p, self.get_roots())) )) self.cf_dots = cf_dots self.alt_root_dots = alt_root_dots self.add(cf_dots) self.add(self.get_tracers(cf_dots, stroke_width=0.5)) self.add(alt_root_dots) def add_cf_lines(self): cf_lines = VGroup( Line(stroke_color=self.crt_dot_colors[0]).replicate(9), Line(stroke_color=self.crt_dot_colors[1]).replicate(3), ) cf_lines.set_stroke(width=1) def update_cf_lines(cf_lines): cube_root_values = self.get_cube_root_values() for z1, line in zip(cube_root_values[1], cf_lines[1]): line.put_start_and_end_on( self.cf_plane.n2p(0), self.cf_plane.n2p(z1), ) for line, (z1, z2) in zip(cf_lines[0], it.product(*cube_root_values)): line.put_start_and_end_on( self.cf_plane.n2p(z2), self.cf_plane.n2p(z1 + z2), ) cf_lines.add_updater(update_cf_lines) self.cf_lines = cf_lines self.add(cf_lines) class CubicFormulaTest(CubicFormula): def construct(self): pass # self.embed()
from manim_imports_ext import * # Helpers def roots_to_coefficients(roots): n = len(list(roots)) return [ ((-1)**(n - k)) * sum( np.prod(tup) for tup in it.combinations(roots, n - k) ) for k in range(n) ] + [1] def poly(x, coefs): return sum(coefs[k] * x**k for k in range(len(coefs))) def dpoly(x, coefs): return sum(k * coefs[k] * x**(k - 1) for k in range(1, len(coefs))) def find_root(func, dfunc, seed=complex(1, 1), tol=1e-8, max_steps=100): # Use newton's method last_seed = np.inf for n in range(max_steps): if abs(seed - last_seed) < tol: break last_seed = seed seed = seed - func(seed) / dfunc(seed) return seed def coefficients_to_roots(coefs): if len(coefs) == 0: return [] elif coefs[-1] == 0: return coefficients_to_roots(coefs[:-1]) roots = [] # Find a root, divide out by (x - root), repeat for i in range(len(coefs) - 1): root = find_root( lambda x: poly(x, coefs), lambda x: dpoly(x, coefs), ) roots.append(root) new_reversed_coefs, rem = np.polydiv(coefs[::-1], [1, -root]) coefs = new_reversed_coefs[::-1] return roots def get_nth_roots(z, n): base_root = z**(1 / n) return [ base_root * np.exp(complex(0, k * TAU / n)) for k in range(n) ] def sort_to_minimize_distances(unordered_points, reference_points): """ Sort the initial list of points in R^n so that the sum of the distances between corresponding points in both lists is smallest """ ordered_points = [] unused_points = list(unordered_points) for ref_point in reference_points: distances = [get_norm(ref_point - up) for up in unused_points] index = np.argmin(distances) ordered_points.append(unused_points.pop(index)) return ordered_points def optimal_transport(dots, target_points): """ Move the dots to the target points such that each dot moves a minimal distance """ points = sort_to_minimize_distances(target_points, [d.get_center() for d in dots]) for dot, point in zip(dots, points): dot.move_to(point) return dots def x_power_tex(power, base="x"): if power == 0: return "" elif power == 1: return base else: return f"{base}^{{{power}}}" def poly_tex(coefs, prefix="P(x) = ", coef_color=RED_B): n = len(coefs) - 1 coefs = [f"{{{coef}}}" for coef in coefs] terms = [prefix, x_power_tex(n)] for k in range(n - 1, -1, -1): coef = coefs[k] if not coef[1] == "-": terms.append("+") terms.append(str(coef)) terms.append(x_power_tex(k)) t2c = dict([(coef, coef_color) for coef in coefs]) return OldTex(*terms, tex_to_color_map=t2c) def factored_poly_tex(roots, prefix="P(x) = ", root_colors=[YELLOW, YELLOW]): roots = list(roots) root_colors = color_gradient(root_colors, len(roots)) root_texs = [str(r) for r in roots] parts = [] if prefix: parts.append(prefix) for root_tex in root_texs: parts.extend(["(", "x", "-", root_tex, ")"]) t2c = dict(( (rt, root_color) for rt, root_color in zip(root_texs, root_colors) )) return OldTex(*parts, tex_to_color_map=t2c) def sym_poly_tex_args(roots, k, abbreviate=False): result = [] subsets = list(it.combinations(roots, k)) if k in [1, len(roots)]: abbreviate = False if abbreviate: subsets = [*subsets[:2], subsets[-1]] for subset in subsets: if abbreviate and subset is subsets[-1]: result.append(" \\cdots ") result.append("+") for r in subset: result.append(str(r)) result.append(" \\cdot ") result.pop() result.append("+") result.pop() return result def expanded_poly_tex(roots, vertical=True, root_colors=[YELLOW, YELLOW], abbreviate=False): roots = list(roots) root_colors = color_gradient(root_colors, len(roots)) n = len(roots) kw = dict( tex_to_color_map=dict(( (str(r), root_color) for r, root_color in zip(roots, root_colors) )), arg_separator=" " ) result = VGroup() result.add(OldTex(f"x^{{{n}}}")) for k in range(1, n + 1): sym_poly = sym_poly_tex_args( roots, k, abbreviate=abbreviate ) line = OldTex( "+" if k % 2 == 0 else "-", "\\big(", *sym_poly, "\\big)", x_power_tex(n - k), **kw, ) result.add(line) for line in result: line[-1].set_color(WHITE) if vertical: result.arrange(DOWN, aligned_edge=LEFT) else: result.arrange(RIGHT, buff=SMALL_BUFF) result[0].shift(result[0].get_height() * UP / 4) return result def get_symmetric_system(lhss, roots=None, root_colors=[YELLOW, YELLOW], lhs_color=RED_B, abbreviate=False, signed=False, ): lhss = [f"{{{lhs}}}" for lhs in lhss] if roots is None: roots = [f"r_{{{i}}}" for i in range(len(lhss))] root_colors = color_gradient(root_colors, len(roots)) t2c = dict([ (root, root_color) for root, root_color in zip(roots, root_colors) ]) t2c.update(dict([ (str(lhs), lhs_color) for lhs in lhss ])) kw = dict(tex_to_color_map=t2c) equations = VGroup(*( OldTex( lhs, "=", "-(" if neg else "", *sym_poly_tex_args(roots, k, abbreviate=abbreviate), ")" if neg else "", **kw ) for k, lhs in zip(it.count(1), lhss) for neg in [signed and k % 2 == 1] )) equations.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) for eq in equations: eq.shift((equations[0][1].get_x() - eq[1].get_x()) * RIGHT) return equations def get_quadratic_formula(lhs="", **tex_config): return Tex( lhs + "{-{b} \\pm \\sqrt{ {b}^2 - 4{a}{c} } \\over 2{a} }", **tex_config ) def get_full_cubic_formula(lhs="", **tex_config): # Thanks to Mathologer and MathPix here... return OldTex(lhs + """ &\\sqrt[3]{\\left(-{ {b}^{3} \\over 27 {a}^{3}}+{ {b} {c} \\over 6 {a}^{2}} -{ {d} \\over 2 {a} }\\right)-\\sqrt{\\left(-{ {b}^{3} \\over 27 {a}^{3}} +{ {b} {c} \\over 6 {a}^{2}}-{ {d} \\over 2 {a}}\\right)^{2} +\\left({ {c} \\over 3 {a} }-{ {b}^{2} \\over 9 {a}^{2}}\\right)^{3}}} \\\\ +&\\sqrt[3]{\\left(-{ {b}^{3} \\over 27 {a}^{3}}+{ {b} {c} \\over 6 {a}^{2}} -{ {d} \\over 2 {a} }\\right)+\\sqrt{\\left(-{ {b}^{3} \\over 27 {a}^{3}} +{ {b} {c} \\over 6 {a}^{2}}-{ {d} \\over 2 {a}}\\right)^{2} +\\left({ {c} \\over 3 {a} }-{ {b}^{2} \\over 9 {a}^{2} }\\right)^{3}}} \\\\ -&{ {b} \\over 3 {a} } """, **tex_config) def get_cubic_formula(lhs="", **tex_config): return Tex( lhs + """ \\sqrt[3]{-{q \\over 2}-\\sqrt{\\left({q \\over 2}\\right)^{2}+\\left({p \\over 3}\\right)^{3}}} +\\sqrt[3]{-{q \\over 2}+\\sqrt{\\left({q \\over 2}\\right)^{2}+\\left({p \\over 3}\\right)^{3}}} """, **tex_config ) def get_quartic_formula(lhs="", **tex_config): pass # General scene types class RootCoefScene(Scene): coefs = [3, 2, 1, 0, -1, 1] root_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": BLUE_E, } } coef_plane_config = { "x_range": (-4, 4), "y_range": (-4, 4), "background_line_style": { "stroke_color": GREY, } } plane_height = 5.5 plane_buff = 1.5 planes_center = ORIGIN plane_arrangement = LEFT cycle_run_time = 5 root_color = YELLOW coef_color = RED_B dot_style = { "radius": 0.05, "stroke_color": BLACK, "stroke_width": 3, "stroke_behind": True, } include_tracers = True include_labels = True label_font_size = 30 coord_label_font_size = 18 continuous_roots = True show_equals = True def setup(self): self.lock_coef_imag = False self.lock_coef_norm = False self.add_planes() self.add_dots() self.active_dot_aura = Group() self.add(self.active_dot_aura) self.prepare_cycle_interaction() if self.include_tracers: self.add_all_tracers() if self.include_labels: self.add_r_labels() self.add_c_labels() def add_planes(self): # Planes planes = VGroup( ComplexPlane(**self.root_plane_config), ComplexPlane(**self.coef_plane_config), ) for plane in planes: plane.set_height(self.plane_height) planes.arrange(self.plane_arrangement, buff=self.plane_buff) planes.move_to(self.planes_center) for plane in planes: plane.add_coordinate_labels(font_size=self.coord_label_font_size) plane.coordinate_labels.set_opacity(0.8) root_plane, coef_plane = planes # Lower labels root_plane_label = Text("Roots") coef_plane_label = Text("Coefficients") root_plane_label.next_to(root_plane, DOWN) coef_plane_label.next_to(coef_plane, DOWN) # Upper labels root_poly = self.get_root_poly() self.get_r_symbols(root_poly).set_color(self.root_color) root_poly.next_to(root_plane, UP) root_poly.set_max_width(root_plane.get_width()) coef_poly = self.get_coef_poly() self.get_c_symbols(coef_poly).set_color(self.coef_color) coef_poly.set_max_width(coef_plane.get_width()) coef_poly.next_to(coef_plane, UP) coef_poly.match_y(root_poly) self.add(planes) self.add(root_plane_label, coef_plane_label) self.add(root_poly, coef_poly) if self.show_equals: equals = OldTex("=") equals.move_to(midpoint(root_poly.get_right(), coef_poly.get_left())) self.add(equals) self.poly_equal_sign = equals self.root_plane = root_plane self.coef_plane = coef_plane self.root_plane_label = root_plane_label self.coef_plane_label = coef_plane_label self.root_poly = root_poly self.coef_poly = coef_poly def get_degree(self): return len(self.coefs) - 1 def get_coef_poly(self): degree = self.get_degree() return OldTex( f"x^{degree}", *( f" + c_{n} x^{n}" for n in range(degree - 1, 1, -1) ), " + c_{1} x", " + c_{0}", ) def get_root_poly(self): return OldTex(*( f"(x - r_{i})" for i in range(self.get_degree()) )) def add_dots(self): self.root_dots = VGroup() self.coef_dots = VGroup() roots = coefficients_to_roots(self.coefs) self.add_root_dots(roots) self.add_coef_dots(self.coefs) # def get_all_dots(self): return (*self.root_dots, *self.coef_dots) def get_r_symbols(self, root_poly): return VGroup(*(part[3:5] for part in root_poly)) def get_c_symbols(self, coef_poly): return VGroup(*(part[1:3] for part in coef_poly[:0:-1])) def get_random_root(self): return complex( interpolate(*self.root_plane.x_range[:2], random.random()), interpolate(*self.root_plane.y_range[:2], random.random()), ) def get_random_roots(self): return [self.get_random_root() for x in range(self.degree)] def get_roots_of_unity(self): return [np.exp(complex(0, TAU * n / self.degree)) for n in range(self.degree)] def set_roots(self, roots): self.root_dots.set_submobjects( Dot( self.root_plane.n2p(root), color=self.root_color, **self.dot_style, ) for root in roots ) def set_coefs(self, coefs): self.coef_dots.set_submobjects( Dot( self.coef_plane.n2p(coef), color=self.coef_color, **self.dot_style, ) for coef in coefs[:-1] # Exclude highest term ) def add_root_dots(self, roots=None): if roots is None: roots = self.get_roots_of_unity() self.set_roots(roots) self.add(self.root_dots) def add_coef_dots(self, coefs=None): if coefs is None: coefs = [0] * self.degree + [1] self.set_coefs(coefs) self.add(self.coef_dots) def get_roots(self): return [ self.root_plane.p2n(root_dot.get_center()) for root_dot in self.root_dots ] def get_coefs(self): return [ self.coef_plane.p2n(coef_dot.get_center()) for coef_dot in self.coef_dots ] + [1.0] def tie_coefs_to_roots(self, clear_updaters=True): if clear_updaters: self.root_dots.clear_updaters() self.coef_dots.clear_updaters() self.coef_dots.add_updater(self.update_coef_dots_by_roots) self.add(self.coef_dots) self.add(*self.root_dots) def update_coef_dots_by_roots(self, coef_dots): coefs = roots_to_coefficients(self.get_roots()) for dot, coef in zip(coef_dots, coefs): dot.move_to(self.coef_plane.n2p(coef)) return coef_dots def tie_roots_to_coefs(self, clear_updaters=True): if clear_updaters: self.root_dots.clear_updaters() self.coef_dots.clear_updaters() self.root_dots.add_updater(self.update_root_dots_by_coefs) self.add(self.root_dots) self.add(*self.coef_dots) def update_root_dots_by_coefs(self, root_dots): new_roots = coefficients_to_roots(self.get_coefs()) new_root_points = map(self.root_plane.n2p, new_roots) if self.continuous_roots: optimal_transport(root_dots, new_root_points) else: for dot, point in zip(root_dots, new_root_points): dot.move_to(point) return root_dots def get_tracers(self, dots, time_traced=2.0, **kwargs): tracers = VGroup() for dot in dots: dot.tracer = TracingTail( dot, stroke_color=dot.get_fill_color(), time_traced=time_traced, **kwargs ) tracers.add(dot.tracer) return tracers def add_all_tracers(self, **kwargs): self.tracers = self.get_tracers(self.get_all_dots()) self.add(self.tracers) def get_tracking_lines(self, dots, syms, stroke_width=1, stroke_opacity=0.5): lines = VGroup(*( Line( stroke_color=root.get_fill_color(), stroke_width=stroke_width, stroke_opacity=stroke_opacity, ) for root in dots )) def update_lines(lines): for sym, dot, line in zip(syms, dots, lines): line.put_start_and_end_on( sym.get_bottom(), dot.get_center() ) lines.add_updater(update_lines) return lines def add_root_lines(self, **kwargs): self.root_lines = self.get_tracking_lines( self.root_dots, self.get_r_symbols(self.root_poly), **kwargs ) self.add(self.root_lines) def add_coef_lines(self, **kwargs): self.coef_lines = self.get_tracking_lines( self.coef_dots, self.get_c_symbols(self.coef_poly), **kwargs ) self.add(self.coef_lines) def add_dot_labels(self, labels, dots, buff=0.05): for label, dot in zip(labels, dots): label.scale(self.label_font_size / label.font_size) label.set_fill(dot.get_fill_color()) label.set_stroke(BLACK, 3, background=True) label.dot = dot label.add_updater(lambda m: m.next_to(m.dot, UR, buff=buff)) self.add(*labels) return labels def add_r_labels(self): self.r_dot_labels = self.add_dot_labels( VGroup(*( OldTex(f"r_{i}") for i in range(self.get_degree()) )), self.root_dots ) def add_c_labels(self): self.c_dot_labels = self.add_dot_labels( VGroup(*( OldTex(f"c_{i}") for i in range(self.get_degree()) )), self.coef_dots ) def add_value_label(self): pass # TODO # Animations def play(self, *anims, **kwargs): movers = list(it.chain(*(anim.mobject.get_family() for anim in anims))) roots_move = any(rd in movers for rd in self.root_dots) coefs_move = any(cd in movers for cd in self.coef_dots) if roots_move and not coefs_move: self.tie_coefs_to_roots() elif coefs_move and not roots_move: self.tie_roots_to_coefs() super().play(*anims, **kwargs) def get_root_swap_arrows(self, i, j, path_arc=90 * DEGREES, stroke_width=5, stroke_opacity=0.7, buff=0.3, **kwargs): di = self.root_dots[i].get_center() dj = self.root_dots[j].get_center() kwargs["path_arc"] = path_arc kwargs["stroke_width"] = stroke_width kwargs["stroke_opacity"] = stroke_opacity kwargs["buff"] = buff return VGroup( Arrow(di, dj, **kwargs), Arrow(dj, di, **kwargs), ) def swap_roots(self, *indices, run_time=2, wait_time=1, **kwargs): self.play(CyclicReplace( *( self.root_dots[i] for i in indices ), run_time=run_time, **kwargs )) self.wait(wait_time) def rotate_coefs(self, indicies, center_z=0, run_time=5, wait_time=1, **kwargs): self.play(*( Rotate( self.coef_dots[i], TAU, about_point=self.coef_plane.n2p(center_z), run_time=run_time, **kwargs ) for i in indicies )) self.wait(wait_time) def rotate_coef(self, i, **kwargs): self.rotate_coefs([i], **kwargs) # Interaction def add_dot_auroa(self, dot): glow_dot = GlowDot(color=WHITE) always(glow_dot.move_to, dot) self.active_dot_aura.add(glow_dot) def remove_dot_aura(self): if len(self.active_dot_aura) > 0: self.play(FadeOut(self.active_dot_aura), run_time=0.5) self.active_dot_aura.set_submobjects([]) self.add(self.active_dot_aura) def prepare_cycle_interaction(self): self.dots_awaiting_cycle = [] self.dot_awaiting_loop = None def handle_cycle_preparation(self, dot): if dot in self.root_dots and dot not in self.dots_awaiting_cycle: self.dots_awaiting_cycle.append(dot) if dot in self.coef_dots and dot is not self.dot_awaiting_loop: self.dot_awaiting_loop = dot self.add(dot) def carry_out_cycle(self): if self.dots_awaiting_cycle: self.tie_coefs_to_roots() self.play(CyclicReplace(*self.dots_awaiting_cycle, run_time=self.cycle_run_time)) self.remove_dot_aura() if self.dot_awaiting_loop is not None: self.tie_roots_to_coefs() self.play(Rotate( self.dot_awaiting_loop, angle=TAU, about_point=self.mouse_point.get_center().copy(), run_time=8 )) self.remove_dot_aura() self.prepare_cycle_interaction() def on_mouse_release(self, point, button, mods): super().on_mouse_release(point, button, mods) if self.root_dots.has_updaters or self.coef_dots.has_updaters: # End the interaction where a dot is tied to the mouse self.root_dots.clear_updaters() self.coef_dots.clear_updaters() self.remove_dot_aura() return dot = self.point_to_mobject(point, search_set=self.get_all_dots(), buff=0.1) if dot is None: return self.add_dot_auroa(dot) if self.window.is_key_pressed(ord("c")): self.handle_cycle_preparation(dot) return # Make sure other dots are updated accordingly if dot in self.root_dots: self.tie_coefs_to_roots() elif dot in self.coef_dots: self.tie_roots_to_coefs() # Have this dot track with the mouse dot.mouse_point_diff = dot.get_center() - self.mouse_point.get_center() dot.add_updater(lambda d: d.move_to(self.mouse_point.get_center() + d.mouse_point_diff)) if self.lock_coef_imag or self.window.is_key_pressed(ord("r")): # Fix the imaginary value dot.last_y = dot.get_y() dot.add_updater(lambda d: d.set_y(d.last_y)) elif (self.lock_coef_norm or self.window.is_key_pressed(ord("a"))) and dot in self.coef_dots: # Fix the norm dot.last_norm = get_norm(self.coef_plane.p2c(dot.get_center())) dot.add_updater(lambda d: d.move_to(self.coef_plane.c2p( *d.last_norm * normalize(self.coef_plane.p2c(d.get_center())) ))) def on_key_release(self, symbol, modifiers): super().on_key_release(symbol, modifiers) char = chr(symbol) if char == "c": self.carry_out_cycle() # def update_mobjects(self, dt): # Go in reverse order, since dots are often re-added # once they become interactive for mobject in reversed(self.mobjects): mobject.update(dt) class RadicalScene(RootCoefScene): n = 3 c = 1.5 root_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": BLUE_E, } } coef_plane_config = { "x_range": (-2, 2), "y_range": (-2, 2), "background_line_style": { "stroke_color": GREY, } } plane_height = 4.0 plane_buff = 3.0 planes_center = 1.5 * DOWN show_equals = False def setup(self): self.coefs = [-self.c, *[0] * (self.n - 1), 1] super().setup() self.remove(self.coef_plane_label) self.remove(self.root_plane_label) self.sync_roots(self.root_dots[0]) def get_radical_labels(self): left = self.coef_plane.get_right() right = self.root_plane.get_left() arrow_kw = dict( stroke_width=5, stroke_color=GREY_A, buff=0.5, ) r_arrow = Arrow(left, right, **arrow_kw).shift(UP) l_arrow = Arrow(right, left, **arrow_kw).shift(DOWN) r_label = OldTex(f"\\sqrt[{self.n}]{{c}}")[0] l_label = OldTex(f"r_i^{{{self.n}}}")[0] r_label[3].set_color(self.coef_color) l_label[-3::2].set_color(self.root_color) if self.n == 2: r_label[0].set_opacity(0) r_label.next_to(r_arrow, UP) l_label.next_to(l_arrow, UP) return VGroup( VGroup(r_arrow, l_arrow), VGroup(r_label, l_label), ) def get_angle_label(self, dot, plane, sym, get_theta): line = Line() line.set_stroke(dot.get_fill_color(), width=2) line.add_updater(lambda m: m.put_start_and_end_on( plane.get_origin(), dot.get_center() )) arc = always_redraw(lambda: ParametricCurve( lambda t: plane.n2p((0.25 + 0.01 * t) * np.exp(complex(0, t))), t_range=[0, get_theta() + 1e-5, 0.025], stroke_width=2, )) tex_mob = OldTex(sym, font_size=24) tex_mob.set_backstroke(width=8) def update_sym(tex_mob): tex_mob.set_opacity(min(1, 3 * get_theta())) point = arc.t_func(0.5 * get_theta()) origin = plane.get_origin() w = tex_mob.get_width() tex_mob.move_to(origin + (1.3 + 2 * w) * (point - origin)) return tex_mob tex_mob.add_updater(update_sym) return VGroup(line, arc, tex_mob) def get_c(self): return -self.get_coefs()[0] # Updates to RootCoefScene methods def get_coef_poly(self): degree = self.get_degree() return OldTex(f"x^{degree}", "-", "c") def get_c_symbols(self, coef_poly): return VGroup(coef_poly[-1]) def add_c_labels(self): self.c_dot_labels = self.add_dot_labels( VGroup(OldTex("c")), VGroup(self.coef_dots[0]), ) def get_coefs(self): c = self.coef_plane.p2n(self.coef_dots[0].get_center()) return [-c, *[0] * (self.n - 1), 1] def set_coefs(self, coefs): super().set_coefs(coefs) self.coef_dots[0].move_to(self.coef_plane.n2p(-coefs[0])) self.coef_dots[1:].set_opacity(0) def tie_coefs_to_roots(self, *args, **kwargs): super().tie_coefs_to_roots(*args, **kwargs) # Hack for dot in self.root_dots: dot.add_updater(lambda m: m) def update_coef_dots_by_roots(self, coef_dots): controlled_roots = [ d for d in self.root_dots if len(d.get_updaters()) > 1 ] root_dot = controlled_roots[0] if controlled_roots else self.root_dots[0] root = self.root_plane.p2n(root_dot.get_center()) coef_dots[0].move_to(self.coef_plane.n2p(root**self.n)) # Update all the root dots if controlled_roots: self.sync_roots(controlled_roots[0]) return coef_dots def sync_roots(self, anchor_root_dot): root = self.root_plane.p2n(anchor_root_dot.get_center()) anchor_index = self.root_dots.submobjects.index(anchor_root_dot) for i, dot in enumerate(self.root_dots): if i != anchor_index: zeta = np.exp(complex(0, (i - anchor_index) * TAU / self.n)) dot.move_to(self.root_plane.n2p(zeta * root)) class QuadraticFormula(RootCoefScene): coefs = [-1, 0, 1] coef_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": GREY_B, "stroke_width": 1.0, } } sqrt_plane_config = { "x_range": (-2.0, 2.0), "y_range": (-2.0, 2.0), "background_line_style": { "stroke_color": BLUE_D, "stroke_width": 1.0, } } plane_height = 3.5 plane_arrangement = RIGHT plane_buff = 1.0 planes_center = 2 * LEFT + DOWN def add_planes(self): super().add_planes() self.coef_plane_label.match_y(self.root_plane_label) self.add_sqrt_plane() def add_sqrt_plane(self): plane = ComplexPlane(**self.sqrt_plane_config) plane.next_to(self.coef_plane, self.plane_arrangement, self.plane_buff) plane.set_height(self.plane_height) plane.add_coordinate_labels(font_size=24) label = OldTex( "-{b \\over 2} \\pm \\sqrt{{b^2 \\over 4} - c}", font_size=30, )[0] for i in [1, 7, 12]: label[i].set_color(self.coef_color) label.next_to(plane, UP) self.sqrt_plane = plane self.sqrt_label = label self.add(plane) self.add(label) def add_dots(self): super().add_dots() dots = self.root_dots.copy().clear_updaters() dots.set_color(GREEN) def update_dots(dots): for dot, root in zip(dots, self.get_roots()): dot.move_to(self.sqrt_plane.n2p(root)) return dots dots.add_updater(update_dots) self.sqrt_dots = dots self.add(dots) self.add(self.get_tracers(dots)) def get_coef_poly(self): return OldTex( "x^2", "+ b x", "+ c" ) def add_c_labels(self): self.c_dot_labels = self.add_dot_labels( VGroup(OldTex("c"), OldTex("b")), self.coef_dots ) def get_c_symbols(self, coef_poly): return VGroup(*(part[1] for part in coef_poly[:0:-1])) # Analyze the cubic formula class Cubic(RootCoefScene): coefs = [1, 0, 1] def construct(self): pass class AmbientRootSwapping(RootCoefScene): n_swaps = 0 def construct(self): for x in range(self.n_swaps): k = random.randint(2, 5) indices = random.choice(list(it.combinations(range(5), k))) self.swap_roots(*indices) self.wait() self.embed()
from manim_imports_ext import * from _2022.quintic.roots_and_coefs import * # Introduction class IntroduceUnsolvability(Scene): def construct(self): pass class TableOfContents(Scene): def construct(self): pass # Preliminaries on polynomials class ConstructPolynomialWithGivenRoots(Scene): root_color = YELLOW def construct(self): # Add axes axes = self.add_axes() # Add challenge challenge = VGroup( Text("Can you construct a cubic polynomial"), OldTex( "P(x) = x^3 + c_2 x^2 + c_1 x + c_0", tex_to_color_map={ "c_2": RED_B, "c_1": RED_B, "c_0": RED_B, } ), OldTexText( "with roots at $x = 1$, $x = 2$, and $x = 4$?", tex_to_color_map={ "$x = 1$": self.root_color, "$x = 2$": self.root_color, "$x = 4$": self.root_color, } ) ) challenge.scale(0.7) challenge.arrange(DOWN, buff=MED_LARGE_BUFF) challenge.to_corner(UL) self.add(challenge) # Add graph roots = [1, 2, 4] coefs = roots_to_coefficients(roots) graph = axes.get_graph(lambda x: poly(x, coefs)) graph.set_color(BLUE) root_dots = Group(*(GlowDot(axes.c2p(x, 0)) for x in roots)) root_dots.set_color(self.root_color) x_terms = challenge[2].get_parts_by_tex("x = ") self.wait() self.play( LaggedStart(*( FadeTransform(x_term.copy(), dot) for x_term, dot in zip(x_terms, root_dots) ), lag_ratio=0.7, run_time=3) ) self.add(graph, root_dots) self.play(ShowCreation(graph, run_time=3, rate_func=linear)) self.wait() # Show factored solution factored = factored_poly_tex(roots) factored.match_height(challenge[1]) factored.next_to(challenge, DOWN, LARGE_BUFF) rects = VGroup(*( SurroundingRectangle( factored[i:i + 5], stroke_width=1, stroke_color=BLUE, buff=0.05 ) for i in range(1, 12, 5) )) arrows = VGroup(*( Vector(DOWN).next_to(dot, UP, buff=0) for dot in root_dots )) zeros_eqs = VGroup(*( OldTex( f"P({r}) = 0", font_size=24 ).next_to(rect, UP, SMALL_BUFF) for r, rect in zip(roots, rects) )) self.play(FadeIn(factored, DOWN)) self.wait() to_fade = VGroup() for rect, arrow, eq in zip(rects, arrows, zeros_eqs): self.play( ShowCreation(rect), FadeIn(eq), ShowCreation(arrow), FadeOut(to_fade) ) self.wait(2) to_fade = VGroup(rect, arrow, eq) self.play(FadeOut(to_fade)) # Expand solution x_terms = factored[2::5] root_terms = VGroup(*( VGroup(m1, m2) for m1, m2 in zip(factored[3::5], factored[4::5]) )) expanded = OldTex( "&x^3 ", "-1x^2", "-2x^2", "-4x^2 \\\\", "&+(-1)(-2)x", "+(-1)(-4)x", "+(-2)(-4)x\\\\", "&+(-1)(-2)(-4)", ) for i, part in enumerate(expanded): if i in [1, 2, 3]: part[:2].set_color(self.root_color) elif i in [4, 5, 6, 7]: part[2:4].set_color(self.root_color) part[6:8].set_color(self.root_color) if i == 7: part[10:12].set_color(self.root_color) expanded.scale(0.7) expanded.next_to(factored[1], DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) equals = factored[0][-1].copy() equals.match_y(expanded[0][0]) self.add(equals) expanded_iter = iter(expanded) for k in range(4): for tup in it.combinations(range(3), k): factored[1:].set_opacity(0.5) rects = VGroup() for i in range(3): mob = root_terms[i] if (i in tup) else x_terms[i] mob.set_opacity(1) rect = SurroundingRectangle(mob, buff=SMALL_BUFF) rect.set_min_height(0.45, about_edge=DOWN) rects.add(rect) rects.set_stroke(BLUE, 2) expanded_term = next(expanded_iter) expanded_rect = SurroundingRectangle( expanded_term, buff=SMALL_BUFF ) expanded_rect.match_style(rects) self.add(rects, expanded_rect) self.add(expanded_term) self.wait() self.remove(rects, expanded_rect) factored.set_opacity(1) self.add(expanded) self.wait() # Cleaner expansion cleaner_expanded = expanded_poly_tex(roots, vertical=False) cleaner_expanded.scale(0.7) cleaner_expanded.shift(expanded[0][0].get_center() - cleaner_expanded[0][0][0].get_center()) self.play( FadeTransform(expanded[0], cleaner_expanded[0]), TransformMatchingShapes( expanded[1:4], cleaner_expanded[1], ), expanded[4:].animate.next_to(cleaner_expanded[1], DOWN, aligned_edge=LEFT) ) self.wait() self.play( TransformMatchingShapes( expanded[4:7], cleaner_expanded[2], ) ) self.wait() self.play( TransformMatchingShapes( expanded[7], cleaner_expanded[3], ) ) back_rect = BackgroundRectangle(cleaner_expanded, buff=SMALL_BUFF) self.add(back_rect, cleaner_expanded) self.play(FadeIn(back_rect)) self.wait() # Evaluate answer = OldTex( "= x^3 -7x^2 + 14x -8", tex_to_color_map={ "-7": RED_B, "14": RED_B, "-8": RED_B, } ) answer.scale(0.7) answer.next_to(equals, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) self.play(FadeIn(answer, DOWN)) self.wait() # Note the symmetry randy = Randolph(height=1) randy.to_corner(DL, buff=MED_SMALL_BUFF) randy.change("tease") randy.save_state() randy.change("plain").set_opacity(0) bubble = SpeechBubble(width=3, height=1, stroke_width=2) bubble.move_to(randy.get_corner(UR), LEFT) bubble.shift(0.45 * UP + 0.1 * LEFT) bubble.add_content(Text("Note the symmetry!")) self.play(Restore(randy)) self.play(ShowCreation(bubble), Write(bubble.content)) self.play(Blink(randy)) self.wait() factored.save_state() cleaner_expanded.save_state() for alt_roots in [(2, 4, 1), (4, 2, 1), (1, 4, 2), (1, 2, 4)]: alt_factored = factored_poly_tex(alt_roots) alt_factored.replace(factored) alt_expanded = expanded_poly_tex(alt_roots, vertical=False) alt_expanded.replace(cleaner_expanded) globals().update(locals()) movers, targets = [ VGroup(*( group.get_parts_by_tex(str(root)) for root in alt_roots for group in groups )) for groups in [(factored, *cleaner_expanded), (alt_factored, *alt_expanded)] ] self.play( TransformMatchingShapes(movers, targets, path_arc=PI / 2, run_time=1.5), randy.animate.look_at(movers), ) self.remove(targets, factored, cleaner_expanded) factored.become(alt_factored) cleaner_expanded.become(alt_expanded) self.add(factored, cleaner_expanded) self.wait() factored.restore() cleaner_expanded.restore() self.play( FadeOut(randy), FadeOut(bubble), FadeOut(bubble.content), ) # Reverse question top_lhs = OldTex("P(x)").match_height(factored) top_lhs.next_to(answer, LEFT).align_to(factored, LEFT) top_lhs.set_opacity(0) coef_poly = VGroup(top_lhs, answer) coef_poly.generate_target() coef_poly.target.set_opacity(1).to_edge(UP) full_factored = VGroup(back_rect, factored, equals, cleaner_expanded) full_factored.generate_target() full_factored.target.next_to(coef_poly.target, DOWN, buff=0.75, aligned_edge=LEFT) full_factored.target.set_opacity(0.5) self.add(full_factored, coef_poly) self.play( FadeOut(challenge, UP), MoveToTarget(full_factored), MoveToTarget(coef_poly), ) new_challenge = Text("Find the roots!") new_challenge.add_background_rectangle(buff=0.1) arrow = Vector(LEFT) arrow.next_to(coef_poly, RIGHT) new_challenge.next_to(arrow, RIGHT) self.play( ShowCreation(arrow), FadeIn(new_challenge, 0.5 * RIGHT), ) self.wait() # Show general expansion rs = [f"r_{i}" for i in range(3)] gen_factored = factored_poly_tex(rs, root_colors=[YELLOW, GREEN]) gen_expanded = expanded_poly_tex(rs, vertical=False, root_colors=[YELLOW, GREEN]) for gen, old in (gen_factored, factored), (gen_expanded, cleaner_expanded): gen.match_height(old) gen.move_to(old, LEFT) self.play(FadeTransformPieces(factored, gen_factored)) self.wait() for i in range(1, 4): self.play( cleaner_expanded[0].animate.set_opacity(1), equals.animate.set_opacity(1), FadeTransformPieces(cleaner_expanded[i], gen_expanded[i]), cleaner_expanded[i + 1:].animate.next_to(gen_expanded[i], RIGHT, SMALL_BUFF) ) self.wait() self.remove(cleaner_expanded) self.add(gen_expanded) full_factored = VGroup(back_rect, gen_factored, equals, gen_expanded) # Show system of equations system = get_symmetric_system([7, 14, 8], root_colors=[YELLOW, GREEN]) system.next_to(full_factored, DOWN, LARGE_BUFF, aligned_edge=LEFT) coef_terms = answer[1::2] rhss = [term[2:-2] for term in gen_expanded[1:]] for coef, rhs, eq in zip(coef_terms, rhss, system): self.play( FadeTransform(coef.copy(), eq[0]), FadeIn(eq[1]), FadeTransform(rhs.copy(), eq[2:]), ) self.wait() cubic_example = VGroup(coef_poly, full_factored, system) # Show quintic q_roots = [-1, 1, 2, 4, 6] q_coefs = roots_to_coefficients(q_roots) q_poly = poly_tex(q_coefs) q_poly_factored = factored_poly_tex( [f"r_{i}" for i in range(5)], root_colors=[YELLOW, GREEN] ) VGroup(q_poly, q_poly_factored).scale(0.8) q_poly.to_corner(UL) q_poly_factored.next_to(q_poly, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) self.play( FadeOut(cubic_example, DOWN), FadeOut(VGroup(arrow, new_challenge), DOWN), FadeIn(q_poly, DOWN) ) y_scale_factor = 0.1 new_graph = axes.get_graph( lambda x: y_scale_factor * poly(x, q_coefs), x_range=(-1.2, 6.2) ) new_root_dots = Group(*( GlowDot(axes.c2p(x, 0)) for x in q_roots )) new_graph.match_style(graph) axes.save_state() graph.save_state() root_dots.save_state() self.play( Transform(graph, new_graph), Transform(root_dots, new_root_dots), ) self.wait() root_terms = q_poly_factored.get_parts_by_tex("r_") self.play( FadeIn(q_poly_factored, lag_ratio=0.1, run_time=2), LaggedStart(*( FadeTransform(dot.copy(), term, remover=True) for dot, term in zip(root_dots, root_terms) ), lag_ratio=0.5, run_time=3) ) self.wait() # Quintic system signed_coefs = [ (-1)**k * c for k, c in zip(it.count(1), q_coefs[-2::-1]) ] q_system, q_system_full = [ get_symmetric_system( signed_coefs, abbreviate=abbrev, root_colors=[YELLOW, GREEN], ) for abbrev in [True, False] ] for mob in q_system, q_system_full: mob.scale(0.8) mob.next_to(q_poly_factored, DOWN, LARGE_BUFF, aligned_edge=LEFT) root_tuple_groups = VGroup(*( VGroup(*( VGroup(*tup) for tup in it.combinations(root_terms, k) )) for k in range(1, 6) )) for equation, tuple_group in zip(q_system, root_tuple_groups): self.play(FadeIn(equation)) self.wait(0.25) rects_group = VGroup(*( VGroup(*( SurroundingRectangle(term).set_stroke(BLUE, 2) for term in tup )) for tup in tuple_group )) terms_column = VGroup(*( VGroup(*tup).copy().arrange(RIGHT, buff=SMALL_BUFF) for tup in tuple_group )) terms_column.arrange(DOWN) terms_column.move_to(4 * RIGHT).to_edge(UP) anims = [ ShowSubmobjectsOneByOne(rects_group, rate_func=linear), ShowIncreasingSubsets(terms_column, rate_func=linear, int_func=np.ceil), ] if equation is q_system[1]: anims.append( Group(axes, graph, root_dots).animate.scale( 0.5, about_point=axes.c2p(5, -3) ) ) self.play(*anims, run_time=0.25 * len(terms_column)) self.remove(rects_group) self.wait() self.play(FadeOut(terms_column)) self.wait() self.wait() frame = self.camera.frame frame.save_state() self.play( frame.animate.replace(q_system_full, dim_to_match=0).scale(1.1), FadeIn(q_system_full, lag_ratio=0.1), FadeOut(q_system), Group(axes, graph, root_dots).animate.shift(2 * DOWN), run_time=2, ) self.wait(2) # Back to cubic self.play( Restore(axes), Restore(graph), Restore(root_dots), FadeOut(q_system_full, 2 * DOWN), FadeOut(q_poly, 2 * DOWN), FadeOut(q_poly_factored, 2 * DOWN), FadeIn(cubic_example, 2 * DOWN), Restore(frame), run_time=2, ) self.wait() # Can you always factor? question = Text("Is this always possible?") question.add_background_rectangle(buff=0.1) question.next_to(gen_factored, RIGHT, buff=2) question.to_edge(UP, buff=MED_SMALL_BUFF) arrow = Arrow(question.get_left(), gen_factored.get_corner(UR)) self.play( FadeIn(question), ShowCreation(arrow), FlashAround(gen_factored, run_time=3) ) self.wait() self.play(FadeOut(question), FadeOut(arrow)) const_dec = DecimalNumber(8) top_const_dec = const_dec.copy() for dec, mob, vect in (const_dec, system[2][0], RIGHT), (top_const_dec, answer[-1][1], LEFT): dec.match_height(mob) dec.move_to(mob, vect) dec.set_color(RED) mob.set_opacity(0) self.add(dec) answer[-1][0].set_color(RED) top_const_dec.add_updater(lambda m: m.set_value(const_dec.get_value())) def get_coefs(): return [-const_dec.get_value(), 14, -7, 1] def get_roots(): return coefficients_to_roots(get_coefs()) def update_graph(graph): graph.become(axes.get_graph(lambda x: poly(x, get_coefs()))) graph.set_stroke(BLUE, 3) def update_root_dots(dots): roots = get_roots() for root, dot in zip(roots, dots): if abs(root.imag) > 1e-8: dot.set_opacity(0) else: dot.move_to(axes.c2p(root.real, 0)) dot.set_opacity(1) graph.add_updater(update_graph) self.remove(*root_dots, *new_root_dots) root_dots = root_dots[:3] root_dots.add_updater(update_root_dots) self.add(root_dots) example_constants = [5, 6, 9, 6.28] for const in example_constants: self.play( ChangeDecimalToValue(const_dec, const), run_time=3, ) self.wait() # Show complex plane plane = ComplexPlane( (-1, 6), (-3, 3) ) plane.replace(axes.x_axis.ticks, dim_to_match=0) plane.add_coordinate_labels(font_size=24) plane.save_state() plane.rotate(PI / 2, LEFT) plane.set_opacity(0) real_label = Text("Real numbers") real_label.next_to(root_dots, UP, SMALL_BUFF) complex_label = Text("Complex numbers") complex_label.set_backstroke() complex_label.next_to(plane.saved_state.get_corner(UR), DL, SMALL_BUFF) graph.clear_updaters() root_dots.clear_updaters() axes.generate_target(use_deepcopy=True) axes.target.y_axis.set_opacity(0) axes.target.x_axis.numbers.set_opacity(1) self.play( Uncreate(graph), Write(real_label), MoveToTarget(axes), ) self.wait(2) self.add(plane, root_dots, real_label) self.play( Restore(plane), FadeOut(axes.x_axis), FadeTransform(real_label, complex_label), run_time=2, ) self.wait(2) self.play( VGroup(coef_poly, top_const_dec).animate.next_to(plane, UP), gen_factored.animate.next_to(plane, UP, buff=1.2), FadeOut(equals), FadeOut(gen_expanded), frame.animate.shift(DOWN), run_time=2, ) self.wait() eq_zero = OldTex("= 0") eq_zero.scale(0.7) eq_zero.next_to(top_const_dec, RIGHT, SMALL_BUFF) eq_zero.shift(0.2 * LEFT) self.play( Write(eq_zero), VGroup(coef_poly, top_const_dec).animate.shift(0.2 * LEFT), ) self.wait() # Show constant tweaking again def update_complex_roots(root_dots): for root, dot in zip(get_roots(), root_dots): dot.move_to(plane.n2p(root)) root_dots.add_updater(update_complex_roots) self.play( FlashAround(const_dec), FlashAround(top_const_dec), run_time=2, ) self.play( ChangeDecimalToValue(const_dec, 4), run_time=3, ) self.wait() root_eqs = VGroup(*( VGroup(OldTex(f"r_{i} ", "="), DecimalNumber(root, num_decimal_places=3)).arrange(RIGHT) for i, root in enumerate(get_roots()) )) root_eqs.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) for eq in root_eqs: eq[0][0].set_color(YELLOW) root_eqs.next_to(system, UP) root_eqs.align_to(gen_factored, UP) self.play( FadeIn(root_eqs), VGroup(system, const_dec).animate.next_to(root_eqs, DOWN, LARGE_BUFF), ) self.wait(2) self.play(FadeOut(root_eqs)) example_constants = [4, 7, 9, 5] for const in example_constants: self.play( ChangeDecimalToValue(const_dec, const), run_time=3, ) self.wait() def add_axes(self): x_range = (-1, 6) y_range = (-3, 11) axes = Axes( x_range, y_range, axis_config=dict(include_tip=False, numbers_to_exclude=[]), widith=abs(op.sub(*x_range)), height=abs(op.sub(*y_range)), ) axes.set_height(FRAME_HEIGHT - 1) axes.to_edge(RIGHT) axes.x_axis.add_numbers(font_size=24) axes.x_axis.numbers[1].set_opacity(0) self.add(axes) return axes class FactsAboutRootsToCoefficients(RootCoefScene): coefs = [-5, 14, -7, 1] coef_plane_config = { "x_range": (-15.0, 15.0, 5.0), "y_range": (-10, 10, 5), "background_line_style": { "stroke_color": GREY, "stroke_width": 1.0, }, "height": 20, "width": 30, } root_plane_config = { "x_range": (-1.0, 6.0), "y_range": (-3.0, 3.0), "background_line_style": { "stroke_color": BLUE_E, "stroke_width": 1.0, } } plane_height = 3.5 planes_center = 1.5 * DOWN def construct(self): # Play with coefficients, confined to real axis self.wait() self.add_constant_decimals() self.add_graph() self.lock_coef_imag = True self.wait(note="Move around c0") self.lock_coef_imag = False self.decimal_poly.clear_updaters() self.play( FadeOut(self.decimal_poly, DOWN), FadeOut(self.graph_group, DOWN), ) # Show the goal self.add_system() self.add_solver_functions() # Why that's really weird self.play( self.coef_system.animate.set_opacity(0.2), self.root_system[1:].animate.set_opacity(0.2), ) self.wait(note="Show loops with c0") # Why something like this must be possible brace = Brace(self.coef_system, RIGHT) properties = VGroup( Text("Continuous"), Text("Symmetric"), ) properties.arrange(DOWN, buff=MED_LARGE_BUFF) properties.next_to(brace, RIGHT) self.play( GrowFromCenter(brace), self.root_system.animate.set_opacity(0), self.coef_system.animate.set_opacity(1), ) self.wait() for words in properties: self.play(Write(words, run_time=1)) self.wait() self.swap_root_symbols() self.wait(note="Physically swap roots") # What this implies about our functions brace.generate_target() brace.target.rotate(PI) brace.target.next_to(self.root_system, LEFT) left_group = VGroup(properties, self.coef_system) left_group.generate_target() left_group.target.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) left_group.target.set_height(1) left_group.target.to_corner(UL) left_group.target.set_opacity(0.5) self.play( MoveToTarget(brace, path_arc=PI / 2), MoveToTarget(left_group), self.root_system.animate.set_opacity(1) ) self.wait() restriction = VGroup( Text("Cannot(!) be both"), Text("Continuous and single-valued", t2c={ "Continuous": YELLOW, "single-valued": BLUE, }) ) restriction.scale(0.8) restriction.arrange(DOWN) restriction.next_to(brace, LEFT) self.play(FadeIn(restriction)) self.wait(note="Move c0, emphasize multiplicity of outputs") # Impossibility result words = Text("Cannot be built from ") symbols = OldTex( "+,\\,", "-,\\,", "\\times,\\,", "/,\\,", "\\text{exp}\\\\", "\\sin,\\,", "\\cos,\\,", "| \\cdot |,\\,", "\\dots", ) impossibility = VGroup(words, symbols) impossibility.arrange(RIGHT) impossibility.match_width(restriction) impossibility.next_to(restriction, DOWN, aligned_edge=RIGHT) impossible_rect = SurroundingRectangle(impossibility) impossible_rect.set_stroke(RED, 2) arrow = OldTex("\\Downarrow", font_size=36) arrow.next_to(impossible_rect, UP, SMALL_BUFF) restriction.generate_target() restriction.target.scale(1.0).next_to(arrow, UP, SMALL_BUFF) self.play( FadeIn(impossibility[0]), FadeIn(arrow), ShowCreation(impossible_rect), MoveToTarget(restriction), ) for symbol in symbols: self.wait(0.25) self.add(symbol) self.wait() # Show discontinuous example to_fade = VGroup( restriction[0], restriction[1].get_part_by_text("Continuous and"), arrow, impossibility, impossible_rect, ) to_fade.save_state() self.play(*(m.animate.fade(0.8) for m in to_fade)) root_tracers = VGroup(*(d.tracer for d in self.root_dots)) self.remove(root_tracers) self.continuous_roots = False self.root_dots[0].set_fill(BLUE) self.r_dot_labels[0].set_fill(BLUE) self.root_dots[1].set_fill(GREEN) self.r_dot_labels[1].set_fill(GREEN) self.wait(note="Show discontinuous behavior") self.add(self.get_tracers(self.root_dots)) self.wait(note="Turn tracers back on") self.continuous_roots = True # Represent as a multivalued function f_name = "\\text{cubic\\_solve}" t2c = dict([ (f"{sym}_{i}", color) for i in range(3) for sym, color in [ ("r", self.root_color), ("c", self.coef_color), ] ]) t2c[f_name] = GREY_A mvf = OldTex( f"{f_name}(c_0, c_1, c_2)\\\\", "=\\\\", "\\left\\{r_0, r_1, r_2\\right\\}", tex_to_color_map=t2c ) mvf.get_part_by_tex("=").rotate(PI / 2).match_x(mvf.slice_by_tex(None, "=")) mvf.slice_by_tex("left").match_x(mvf.get_part_by_tex("=")) mvf.move_to(self.root_system, LEFT) self.play( TransformMatchingShapes(self.root_system, mvf), restriction[1].get_part_by_text("single-valued").animate.fade(0.8), ) self.wait(note="Labeling is an artifact") self.play(FadeOut(self.r_dot_labels)) self.wait() def add_c_labels(self): super().add_c_labels() self.c_dot_labels[2].clear_updaters() self.c_dot_labels[2].add_updater( lambda l: l.next_to(l.dot, DL, buff=0) ) return self.c_dot_labels def add_constant_decimals(self): dummy = "+10.00" polynomial = OldTex( f"x^3 {dummy}x^2 {dummy}x {dummy}", isolate=[dummy], font_size=40, ) polynomial.next_to(self.coef_poly, UP, LARGE_BUFF) decimals = DecimalNumber(100, include_sign=True, edge_to_fix=LEFT).replicate(3) for dec, part in zip(decimals, polynomial.get_parts_by_tex(dummy)): dec.match_height(part) dec.move_to(part, LEFT) part.set_opacity(0) polynomial.add(dec) polynomial.decimals = decimals def update_poly(polynomial): for dec, coef in zip(polynomial.decimals, self.get_coefs()[-2::-1]): dec.set_value(coef.real) polynomial.decimals.set_fill(RED, 1) return polynomial update_poly(polynomial) VGroup(polynomial[0], decimals[0]).next_to( polynomial[2], LEFT, SMALL_BUFF, aligned_edge=DOWN ) self.play(FadeIn(polynomial, UP, suspend_updating=True)) polynomial.add_updater(update_poly) self.decimal_poly = polynomial def add_graph(self): self.decimal_poly axes = Axes( (0, 6), (-4, 10), axis_config=dict(tick_size=0.025), width=3, height=2, ) axes.set_height(2) axes.move_to(self.root_plane) axes.to_edge(UP, buff=SMALL_BUFF) graph = always_redraw( lambda: axes.get_graph( lambda x: poly(x, self.get_coefs()).real ).set_stroke(BLUE, 2) ) root_dots = GlowDot() root_dots.add_updater(lambda d: d.set_points([ axes.c2p(r.real, 0) for r in self.get_roots() if abs(r.imag) < 1e-5 ])) arrow = Arrow(self.decimal_poly.get_right(), axes) graph_group = Group(axes, graph, root_dots) self.play( ShowCreation(arrow), FadeIn(graph_group, shift=UR), ) graph_group.add(arrow) self.graph_group = graph_group def add_system(self): c_parts = self.get_c_symbols(self.coef_poly) system = get_symmetric_system( (f"c_{i}" for i in reversed(range(len(self.coef_dots)))), signed=True, ) system.scale(0.8) system.next_to(self.coef_poly, UP, LARGE_BUFF) system.align_to(self.coef_plane, LEFT) self.add(system) kw = dict(lag_ratio=0.8, run_time=2.5) self.play( LaggedStart(*( TransformFromCopy(c, line[0]) for c, line in zip(c_parts, system) ), **kw), LaggedStart(*( FadeIn(line[1:], lag_ratio=0.1) for line in system ), **kw) ) self.add(system) self.coef_system = system self.wait() def add_solver_functions(self): func_name = "\\text{cubic\\_solve}" t2c = dict(( (f"{sym}_{i}", color) for i in range(3) for sym, color in [ ("c", self.coef_color), ("r", self.root_color), (func_name, GREY_A), ] )) kw = dict(tex_to_color_map=t2c) lines = VGroup(*( OldTex(f"r_{i} = {func_name}_{i}(c_0, c_1, c_2)", **kw) for i in range(3) )) lines.scale(0.8) lines.arrange(DOWN, aligned_edge=LEFT) lines.match_y(self.coef_system) lines.align_to(self.root_plane, LEFT) kw = dict(lag_ratio=0.7, run_time=2) self.play( LaggedStart(*( TransformFromCopy(r, line[0]) for r, line in zip(self.get_r_symbols(self.root_poly), lines) ), **kw), LaggedStart(*( FadeIn(line[1:], lag_ratio=0.1) for line in lines ), **kw), ) self.add(lines) self.root_system = lines self.wait() def swap_root_symbols(self): system = self.coef_system cs = [f"c_{i}" for i in reversed(range(len(self.coef_dots)))] rs = [f"r_{{{i}}}" for i in range(len(self.root_dots))] for tup in [(1, 2, 0), (2, 0, 1), (0, 1, 2)]: rs = [f"r_{{{i}}}" for i in tup] alt_system = get_symmetric_system(cs, roots=rs, signed=True) alt_system.replace(system) self.play(*( TransformMatchingTex( l1, l2, path_arc=PI / 2, lag_ratio=0.01, run_time=2 ) for l1, l2 in zip(system, alt_system) )) self.remove(system) system = alt_system self.add(system) self.wait() self.coef_system = system class ComplicatedSingleValuedFunction(Scene): def construct(self): pass class SolvabilityChart(Scene): def construct(self): # Preliminary terms frame = self.camera.frame frame.set_height(10) words = self.get_words(frame) equations = self.get_equations(words) s_words = self.get_solvability_words(equations) gen_form_words = Text("General form") gen_form_words.match_x(equations, LEFT) gen_form_words.match_y(s_words, UP) lines = self.get_lines( rows=VGroup(s_words, *words), cols=VGroup(words, equations, *s_words), ) row_lines, col_lines = lines marks = self.get_marks(equations, s_words) # Shift colums marks[1].save_state() s_words[1].save_state() frame.save_state() frame.set_height(9, about_edge=DL) frame.shift(LEFT) VGroup(marks[1], s_words[1]).next_to(col_lines[1], RIGHT, MED_LARGE_BUFF) solvable_word = OldTexText("Can you solve\\\\for $x$?") solvable_word.move_to(s_words[1], DOWN) # Cover rects cover_rect = Rectangle() cover_rect.set_fill(BLACK, 1) cover_rect.set_stroke(BLACK, 0) cover_rect.replace(frame, stretch=True) cover_rect.add(VectorizedPoint(cover_rect.get_top() + 0.025 * UP)) cover_rect.move_to(row_lines[1], UL).shift(LEFT) right_cover_rect = cover_rect.copy() right_cover_rect.next_to(s_words[1], RIGHT, buff=MED_LARGE_BUFF) right_cover_rect.match_y(frame) self.add(words, equations, solvable_word) self.add(row_lines, col_lines[:2]) self.add(right_cover_rect, cover_rect) # Axes axes = self.get_axes(frame) coefs = np.array([1, 0.5, 0, 0, 0, 0]) coef_tracker = ValueTracker(coefs) get_coefs = coef_tracker.get_value graph = always_redraw(lambda: axes.get_graph( lambda x: poly(x, get_coefs()), stroke_color=BLUE, stroke_width=2, )) root_dots = GlowDot() root_dots.add_updater(lambda m: m.set_points([ axes.c2p(r.real, 0) for r in coefficients_to_roots(get_coefs()) if abs(r.imag) < 1e-5 and abs(r.real) < 5 ])) self.add(axes) # Linear equation tex_kw = dict(tex_to_color_map=self.get_tex_to_color_map()) lin_solution = OldTex("x = {-{b} \\over {a}}", **tex_kw) lin_solution.scale(1.2) lin_solution.next_to(equations[0], DOWN, buff=2.0) self.wait() self.play( ShowCreation(graph), FadeIn(root_dots, rate_func=squish_rate_func(smooth, 0.3, 0.4)), ) self.wait() self.play(TransformMatchingShapes( equations[0].copy(), lin_solution )) self.play(Write(marks[1][0])) self.wait() # Quadratic quadratic_formula = get_quadratic_formula(lhs="x = ", **tex_kw) quadratic_formula.next_to(equations[1], DOWN, buff=2.0) new_coefs = 0.2 * np.array([*roots_to_coefficients([-3, 2]), 0, 0, 0]) self.play( cover_rect.animate.move_to(row_lines[2], UL).shift(LEFT), FadeOut(lin_solution, DOWN), ) self.play(coef_tracker.animate.set_value(new_coefs)) self.wait() self.play(TransformMatchingShapes( equations[1].copy(), quadratic_formula, )) self.play(Write(marks[1][1])) self.wait() # Cubic key_to_color = dict([ (TransformMatchingShapes.get_mobject_key(OldTex(c)[0][0]), color) for c, color in self.get_tex_to_color_map().items() ]) full_cubic = get_full_cubic_formula(lhs="x = ") full_cubic.set_width(9) full_cubic.next_to(equations[2], DOWN, buff=1.0).shift(LEFT) for sm in full_cubic[0]: key = TransformMatchingShapes.get_mobject_key(sm) sm.set_color(key_to_color.get(key, WHITE)) new_coefs = 0.05 * np.array([*roots_to_coefficients([-4, -1, 3]), 0, 0]) self.play( cover_rect.animate.move_to(row_lines[3], UL).shift(LEFT), FadeOut(quadratic_formula, DOWN), ) self.play(coef_tracker.animate.set_value(new_coefs)) self.wait() self.play(TransformMatchingShapes( equations[2].copy(), full_cubic, run_time=2 )) self.wait() # Embed self.embed() def get_words(self, frame): words = VGroup(*map(Text, ( "Linear", "Quadratic", "Cubic", "Quartic", "Quintic", "Sextic", ))) words.add(OldTex("\\vdots")) words.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) words.next_to(frame.get_corner(DL), UR, buff=1.0) words.shift(0.5 * LEFT) words[-1].match_x(words[-2]) return words def get_equations(self, words): kw = dict(tex_to_color_map=self.get_tex_to_color_map()) equations = VGroup( OldTex("{a}x + {b} = 0", **kw), OldTex("{a}x^2 + {b}x + {c} = 0", **kw), OldTex("{a}x^3 + {b}x^2 + {c}x + {d} = 0", **kw), OldTex("{a}x^4 + \\cdots + {d}x + {e} = 0", **kw), OldTex("{a}x^5 + \\cdots + {e}x + {f} = 0", **kw), OldTex("{a}x^6 + \\cdots + {f}x + {g} = 0", **kw), OldTex("\\vdots", **kw), ) equations.arrange(DOWN, aligned_edge=LEFT) equations.next_to(words, RIGHT, LARGE_BUFF) for eq, word in zip(equations, words): dy = word[-1].get_bottom()[1] - eq[0][0].get_bottom()[1] eq.shift(dy * UP) equations[-1].match_y(words[-1]) equations[-1].match_x(equations[-2]) return equations def get_solvability_words(self, equations): operations = ["+", "-", "\\times", "/", "\\sqrt[n]{\\quad}"] arith, radicals = ( "$" + " ,\\, ".join(operations[s]) + "$" for s in (slice(None, -1), slice(None)) ) s_words = VGroup( OldTexText("Solvable", " using\\\\", arith), OldTexText("Solvable", " using\\\\", radicals), OldTexText("Solvable\\\\", "numerically"), ) s_words.arrange(RIGHT, buff=LARGE_BUFF, aligned_edge=UP) s_words.next_to(equations, UR, buff=MED_LARGE_BUFF) s_words.shift(MED_LARGE_BUFF * RIGHT) return s_words def get_lines(self, rows, cols, color=GREY_A, width=2): row_line = Line(cols.get_left(), cols.get_right()) row_lines = row_line.replicate(len(rows) - 1) for r1, r2, rl in zip(rows, rows[1:], row_lines): rl.match_y(midpoint(r1.get_bottom(), r2.get_top())) col_line = Line(rows.get_top(), rows.get_bottom()) col_lines = col_line.replicate(len(cols) - 1) for c1, c2, cl in zip(cols, cols[1:], col_lines): cl.match_x(midpoint(c1.get_right(), c2.get_left())) col_lines[0].match_height(Group(row_lines, Point(col_lines.get_bottom())), about_edge=DOWN) lines = VGroup(row_lines, col_lines) lines.set_stroke(color, width) return lines def get_marks(self, equations, solvability_words): pre_marks = [ "cxxxxxx", "ccccxxx", "ccccccc", ] marks = VGroup(*( VGroup(*( Checkmark() if pm == 'c' else Exmark() for pm in pm_list )) for pm_list in pre_marks )) for mark_group, s_word in zip(marks, solvability_words): mark_group.match_x(s_word) for mark, eq in zip(mark_group, equations): mark.match_y(eq) return marks def get_axes(self, frame): axes = Axes((-5, 5), (-5, 5), height=10, width=10) axes.set_width(4) axes.next_to(frame.get_corner(DR), UL) axes.add(OldTex("x", font_size=24).next_to(axes.x_axis.get_right(), DOWN, SMALL_BUFF)) axes.add(OldTex("y", font_size=24).next_to(axes.y_axis.get_top(), LEFT, SMALL_BUFF)) return axes def get_tex_to_color_map(self): chars = "abcdefg" colors = color_gradient([RED_B, RED_C, RED_D], len(chars)) return dict( (f"{{{char}}}", color) for char, color in zip(chars, colors) ) class StudySqrt(RadicalScene): n = 2 c = 2.0 def construct(self): # Show simple equation kw = dict(tex_to_color_map={"c": self.coef_color}) equations = VGroup( OldTex("x^2 - c = 0", **kw), OldTex("x =", "\\sqrt{c}", **kw), ) equations.arrange(DOWN, buff=MED_LARGE_BUFF) equations.to_edge(UP) self.wait() self.play(FadeIn(equations[0], UP)) self.wait() self.play( TransformMatchingShapes( equations[0].copy(), equations[1], path_arc=PI / 2, ) ) self.wait() sqrt_label = equations[1][1:].copy() # Add decimal labels, show square roots of real c c_label = VGroup( OldTex("c = ", tex_to_color_map={"c": self.coef_color}), DecimalNumber(self.c), ) c_label.arrange(RIGHT, aligned_edge=DOWN) c_label.next_to(self.coef_poly, UP, buff=1.5) c_label[1].add_updater(lambda d: d.set_value(self.get_c().real)) def update_root_dec(root_dec): c_real = self.get_c().real root_dec.unit = "" if c_real > 0 else "i" root_dec.set_value((-1)**root_dec.index * math.sqrt(abs(c_real))) r_labels = VGroup(*( VGroup(OldTex(f"r_{i}", "="), DecimalNumber(self.c, include_sign=True)) for i in range(2) )) for i, r_label in enumerate(r_labels): r_label.arrange(RIGHT) r_label[1].align_to(r_label[0][0][0], DOWN) r_label[0][0].set_color(self.root_color) r_label[1].index = i r_label[1].add_updater(update_root_dec) r_labels.arrange(DOWN, buff=0.75) r_labels.match_x(self.root_plane) r_labels.match_y(c_label) sqrt_arrow = Arrow(self.coef_plane, self.root_plane) sqrt_arrow.match_y(c_label) self.play( FadeIn(c_label), ShowCreation(sqrt_arrow), sqrt_label.animate.next_to(sqrt_arrow, UP), FadeOut(equations), ) self.play(FadeIn(r_labels)) self.lock_coef_imag = True self.wait(note="Move c along real line") self.lock_coef_imag = False # Focus just on one root root_dots = self.root_dots root_tracers = VGroup(*(d.tracer for d in root_dots)) root_labels = self.r_dot_labels self.play( r_labels[0].animate.match_y(c_label), FadeOut(r_labels[1], DOWN), root_dots[1].animate.set_opacity(0.5), root_dots[1].tracer.animate.set_stroke(opacity=0.5), root_labels[1].animate.set_opacity(0.5), ) self.wait() r_label = r_labels[0] # Vary the angle of c self.show_angle_variation(c_label, r_label, sqrt_arrow) self.play( sqrt_arrow.animate.set_width(1.75).match_y(self.root_plane), MaintainPositionRelativeTo(sqrt_label, sqrt_arrow) ) # Discontinuous square root option = VGroup( OldTexText("One option:", color=BLUE), OldTexText("\\\\Make", " $\\sqrt{\\quad}$", " single-valued, but discontinuous", font_size=36), ) option.arrange(DOWN, buff=0.5) option[1][1].align_to(option[1][0], DOWN) option.to_edge(UP, buff=MED_SMALL_BUFF) np_tex = Code("Python: numpy.sqrt(c)") np_tex.match_width(self.root_plane) np_tex.next_to(self.root_plane, UP) sqrt_dot = Dot(**self.dot_style) sqrt_dot.set_color(BLUE) sqrt_dot.add_updater(lambda d: d.move_to(self.root_plane.n2p(np.sqrt(self.get_c())))) sqrt_label = Code("sqrt(c)") sqrt_label.scale(0.75) sqrt_label.add_updater(lambda m: m.next_to(sqrt_dot, UR, buff=0)) self.play(FadeIn(option, UP)) self.wait() self.remove(root_tracers) self.play( self.root_dots.animate.set_opacity(0), FadeOut(self.root_poly), FadeOut(root_labels), FadeIn(np_tex), FadeIn(sqrt_dot), FadeIn(sqrt_label), ) self.wait(note="Show discontinuity") # Taylor series taylor_series = OldTex( "\\sqrt{x} \\approx", "1", "+ \\frac{1}{2}(x - 1)", "- \\frac{1}{8}(x - 1)^2", "+ \\frac{1}{16}(x - 1)^3", "- \\frac{5}{128}(x - 1)^4", "+ \\cdots", font_size=36, ) ts_title = Text("What about a Taylor series?") ts_title.set_color(GREEN) ts_group = VGroup(ts_title, taylor_series) ts_group.arrange(DOWN, buff=MED_LARGE_BUFF) ts_group.to_edge(UP, buff=MED_SMALL_BUFF) def f(x, n): return sum(( gen_choose(1 / 2, k) * (x - 1)**k for k in range(n) )) brace = Brace(taylor_series[1:-1], DOWN, buff=SMALL_BUFF) upper_f_label = brace.get_tex("f_4(x)", buff=SMALL_BUFF) upper_f_label.set_color(GREEN) f_dot = Dot(**self.dot_style) f_dot.set_color(GREEN) f_dot.add_updater(lambda d: d.move_to(self.root_plane.n2p(f(self.get_c(), 4)))) f_label = OldTex("f_4(x)", font_size=24, color=GREEN) f_label.add_updater(lambda m: m.next_to(f_dot, DL, buff=SMALL_BUFF)) self.play( FadeOut(np_tex), FadeIn(ts_group, UP), FadeOut(option, UP), ) self.wait() self.play( GrowFromCenter(brace), FadeIn(upper_f_label, 0.5 * DOWN), ) self.wait() self.play( TransformFromCopy(upper_f_label, f_label), GrowFromPoint(f_dot, upper_f_label.get_center()), ) self.wait() anims = [ brace.animate.become(Brace(taylor_series[1:], DOWN, buff=SMALL_BUFF)) ] for label in (upper_f_label, f_label): new_label = OldTex("f_{50}(x)") new_label.replace(label, 1) new_label.match_style(label) anims.append(Transform(label, new_label, suspend_updating=False)) self.play(*anims) f_dot.clear_updaters() f_dot.add_updater(lambda d: d.move_to(self.root_plane.n2p(f(self.get_c(), 50)))) self.wait() disc = Circle(radius=self.root_plane.x_axis.get_unit_size()) disc.move_to(self.root_plane.n2p(1)) disc.set_stroke(BLUE_B, 2) disc.set_fill(BLUE_B, 0.2) self.play(FadeIn(disc)) self.wait() # Back to normal ts_group.add(brace, upper_f_label) root_labels.set_opacity(1) self.play( FadeOut(ts_group, UP), *map(FadeOut, (disc, f_label, f_dot, sqrt_label, sqrt_dot)), FadeIn(root_labels), FadeIn(self.root_poly), root_dots.animate.set_opacity(1), ) self.add(root_tracers, *root_labels) self.wait() def show_angle_variation(self, c_label, r_label, arrow): angle_color = TEAL self.last_theta = 0 def get_theta(): angle = np.log(self.get_c()).imag diff = angle - self.last_theta diff = (diff + PI) % TAU - PI self.last_theta += diff return self.last_theta circle = Circle(radius=self.coef_plane.x_axis.get_unit_size()) circle.set_stroke(angle_color, 1) circle.move_to(self.coef_plane.get_origin()) left_exp_label, right_exp_label = ( self.get_exp_label( get_theta=func, color=angle_color ).move_to(label[-1], DL) for label, func in [ (c_label, get_theta), (r_label, lambda: get_theta() / self.n), ] ) below_arrow_tex = Tex( "e^{x} \\rightarrow e^{x /" + str(self.n) + "}", font_size=36, tex_to_color_map={"\\theta": angle_color}, ) below_arrow_tex.next_to(arrow, DOWN) angle_labels = VGroup( self.get_angle_label(self.coef_dots[0], self.coef_plane, "\\theta", get_theta), self.get_angle_label( self.root_dots[0], self.root_plane, f"\\theta / {self.n}", lambda: get_theta() / self.n, ), ) self.add(circle, self.coef_dots) self.lock_coef_norm = True self.tie_roots_to_coefs() self.play( FadeIn(circle), FadeIn(angle_labels), self.coef_dots[0].animate.move_to(self.coef_plane.n2p(1)), ) self.wait() self.play( FadeOut(c_label[-1], UP), FadeOut(r_label[-1], UP), FadeIn(left_exp_label, UP), FadeIn(right_exp_label, UP), ) self.wait(note="Rotate c a bit") self.play(Write(below_arrow_tex)) self.wait(note="Show full rotation, then two rotations") # Remove stuff self.play(LaggedStart(*map(FadeOut, ( circle, angle_labels, left_exp_label, right_exp_label, c_label[:-1], r_label[:-1], below_arrow_tex, )))) self.lock_coef_norm = False def get_exp_label(self, get_theta, color=GREEN): result = OldTex("e^{", "2\\pi i \\cdot", "0.00}") decimal = DecimalNumber() decimal.replace(result[2], dim_to_match=1) result.replace_submobject(2, decimal) result.add_updater(lambda m: m.assemble_family()) result.add_updater(lambda m: m[-1].set_color(color)) result.add_updater(lambda m: m[-1].set_value(get_theta() / TAU)) return result class CubeRootBehavior(StudySqrt): n = 3 c = 1.0 def construct(self): arrows, labels = self.get_radical_labels() self.add(arrows, labels) c_label = OldTex("c = ", "1.00", tex_to_color_map={"c": self.coef_color}) r_label = OldTex("r_0 = ", "1.00", tex_to_color_map={"r_0": self.root_color}) c_label.match_x(self.coef_plane) c_label.to_edge(UP, buff=1.0) r_label.match_x(self.root_plane) r_label.match_y(c_label) right_arrow_group = VGroup(arrows[0], labels[0]) right_arrow_group.save_state() self.wait() self.wait() self.play( right_arrow_group.animate.to_edge(UP), *map(FadeIn, (c_label, r_label)) ) self.show_angle_variation(c_label, r_label, right_arrow_group[0]) self.play(Restore(right_arrow_group)) def add_labeled_arrow(self): pass class FifthRootBehavior(CubeRootBehavior): n = 5 class SummarizeRootsToCyclesBehavior(Scene): def construct(self): pass
from manim_imports_ext import * class AmbientPermutations(Scene): def construct(self): # Test text = Text("abcde", font_size=72) text.arrange_to_fit_width(4.5) self.add(text) # Animate swaps n_swaps = 10 perms = list(it.permutations(range(len(text)))) for x in range(n_swaps): perm = random.choice(perms) letter_anims = [] arrow_anims = [] for i, letter in enumerate(text): target = text[perm[i]] letter_anims.append(letter.animate.move_to(target, DOWN).set_anim_args(path_arc=90 * DEGREES)) if i < perm[i]: arrow = Arrow(letter.get_bottom(), target.get_bottom(), path_arc=90 * DEGREES) elif i > perm[i]: arrow = Arrow(letter.get_top(), target.get_top(), path_arc=90 * DEGREES) else: arrow = VMobject() arrow.set_stroke(BLUE) arrow_anims.append(ShowCreationThenFadeOut(arrow, run_time=2)) self.play(LaggedStart(*arrow_anims, *letter_anims, lag_ratio=0.05)) text.sort() class WriteName(InteractiveScene): def construct(self): self.play(Write( Text("Évariste Galois", font_size=90).to_corner(UL), run_time=3 )) self.wait() class TimelineTransition(InteractiveScene): def construct(self): pass class OutpaintTransition(InteractiveScene): image_path = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2022/galois/artwork/chapter 1/wounded-by-pond/transition-to-hospital-2.png" def construct(self): image = ImageMobject(self.image_path) image.set_height(FRAME_HEIGHT) image.to_edge(LEFT, buff=0) self.add(image) # Pan self.play( image.animate.to_edge(RIGHT, buff=-1), run_time=8, rate_func=bezier([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1]) ) image.to_edge(RIGHT, buff=-1) class NightSkyOutpaintingTransition(InteractiveScene): image_path = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2022/galois/artwork/chapter 1/transition-to-night-sky/mural.png" def construct(self): # Add image image = ImageMobject(self.image_path) image.set_width(FRAME_WIDTH + 6) image.to_edge(DL, buff=0) image.shift(2 * DOWN + LEFT) self.add(image) # Pan image.generate_target() image.target.set_width(FRAME_WIDTH) image.target.center().to_edge(UP, buff=0) self.play( MoveToTarget(image), run_time=12, rate_func=bezier([0, 0, 0, 1, 1, 1]) ) self.wait() class LastWordsQuote(InteractiveScene): def construct(self): # French quote fr_quote = Text( """ Ne pleure pas, Alfred! J'ai besoin de tout mon courage pour mourir à vingt ans! """, alignment="LEFT", font="Better Grade", font_size=72 ) fr_quote.to_corner(UR) self.add(fr_quote) # Write english quote en_quote = Text( """ Do not cry, Alfred! I need all my courage to die at twenty years of age! """, alignment="LEFT", ) en_quote.match_width(fr_quote) en_quote.next_to(fr_quote, DOWN, buff=1) self.play(FadeIn(en_quote, lag_ratio=0.1, run_time=6)) self.wait() class InfamousCoquette(InteractiveScene): def construct(self): # Write quote quote = OldTexText( "``I die the victim of an infamous coquette and her two dupes.''", ) quote.to_edge(UP) quote.set_width(FRAME_WIDTH - 1) quote.set_stroke(BLACK, 0) quote.set_fill(BLACK) self.play(Write(quote, run_time=3)) self.wait() class NightBeforeQuote(InteractiveScene): def construct(self): # Write quote = OldTexText(""" ``You will publicly ask Jacobi\\\\ or Gauss to give their opinion\\\\ not on the truth but on the\\\\ importance of the theorems.'' """, alignment="")[0] quote.to_edge(RIGHT) self.play(FadeIn(quote, run_time=2, lag_ratio=0.025)) self.wait() self.play(quote[33:-2].animate.set_color(YELLOW).set_anim_args(lag_ratio=0.5, run_time=3)) self.wait(2) class CauchyFourierPoisson(InteractiveScene): def construct(self): # Test self.add(FullScreenRectangle(fill_color="#211F22", fill_opacity=1)) folder = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2022/galois/artwork/chapter 1/Portraits/" images = Group( ImageMobject(os.path.join(folder, "Cauchy-Portrait-Cutoff")), ImageMobject(os.path.join(folder, "Fourier-Portrait")), ImageMobject(os.path.join(folder, "Poisson-Portrait-Outpainted")), ) for image in images: image.set_width(4) images[0].set_width(3.5) images.arrange(RIGHT, aligned_edge=DOWN) images.set_width(FRAME_WIDTH - 1) images.to_edge(UP, buff=LARGE_BUFF) # Names names = VGroup( Text("Augustin Cauchy"), Text("Joseph Fourier"), Text("Siméon Poisson"), ) for name, image in zip(names, images): name.next_to(image, DOWN) name.set_fill(GREY_A) names[1:].shift(SMALL_BUFF * RIGHT) # Animations kw = dict(lag_ratio=0.5, run_time=3) self.play( LaggedStart(*(FadeIn(image, 0.5 * UP, scale=1.1) for image in images), **kw), LaggedStart(*(Write(name, rate_func=squish_rate_func(smooth, 0, 0.85)) for name in names), **kw), ) self.wait()
from manim_imports_ext import * ASSET_DIR = "/Users/grant/3Blue1Brown Dropbox/3Blue1Brown/videos/2022/galois/assets/" class FlowerSymmetries(InteractiveScene): flower_height = 6.3 def construct(self): # Add flower flower = ImageMobject(os.path.join(ASSET_DIR, "Flower")) flower.set_height(self.flower_height) self.add(flower) self.wait() # Several rotations angles = [45, 90, -45, 135, 180, -135] for angle in angles: arrow, label = self.get_arrow_and_label(flower, angle) self.play( Rotate(flower, angle * DEGREES), ShowCreation(arrow), FadeIn(label) ) self.wait() self.play(FadeOut(label), FadeOut(arrow)) # Show all rotations def get_vector_flower(self): flower_file = ImageMobject(os.path.join(ASSET_DIR, "Flower")) flower = SVGMobject(flower_file) flower.set_height(self.flower_height) flower.rotate(7 * DEGREES) flower.set_fill(GREY_A, 1) flower.set_gloss(1) flower.set_stroke(WHITE, 0) return flower def get_arrow_and_label(self, flower, degrees): radius = self.flower_height / 2 + MED_LARGE_BUFF arc = Arc( start_angle=0, angle=degrees * DEGREES - 3 * DEGREES, radius=radius, arc_center=flower.get_center(), stroke_width=5, color=BLUE, ) arc.add_tip() label = Integer(degrees, unit="^\\circ") label.match_color(arc) point = arc.pfp(min([0.5, abs(45 / degrees)])) label.next_to(point, normalize(point - flower.get_center())) return arc, label
import mpmath import sympy from manim_imports_ext import * def get_set_tex(values, max_shown=7, **kwargs): if len(values) > max_shown: value_mobs = [ *map(Integer, values[:max_shown - 2]), Tex("\\dots"), Integer(values[-1], group_with_commas=False), ] else: value_mobs = list(map(Integer, values)) commas = Tex(",").replicate(len(value_mobs) - 1) result = VGroup() result.add(Tex("\\{")) result.add(*it.chain(*zip(value_mobs, commas))) if len(value_mobs) > 0: result.add(value_mobs[-1].align_to(value_mobs[0], UP)) result.add(Tex("\\}")) result.arrange(RIGHT, buff=SMALL_BUFF) if len(values) > 0: commas.set_y(value_mobs[0].get_y(DOWN)) if len(values) > max_shown: result[-4].match_y(commas) result.values = values return result def get_part_by_value(set_tex, value): try: return next(sm for sm in set_tex if isinstance(sm, Integer) and sm.get_value() == value) except StopIteration: return VMobject().move_to(set_tex) def get_brackets(set_tex): return VGroup(set_tex[0], set_tex[-1]) def get_integer_parts(set_tex): result = VGroup(*( sm for sm in set_tex if isinstance(sm, Integer) )) if len(result) == 0: result.move_to(set_tex) return result def get_commas(set_tex): result = set_tex[2:-1:2] if len(result) == 0: result.move_to(set_tex) return result def set_tex_transform(set_tex1, set_tex2): bracket_anim = TransformFromCopy( get_brackets(set_tex1), get_brackets(set_tex2), ) matching_anims = [ TransformFromCopy( get_part_by_value(set_tex1, value), get_part_by_value(set_tex2, value), ) for value in filter( lambda v: v in set_tex2.values, set_tex1.values, ) ] mismatch_animations = [ FadeInFromPoint( get_part_by_value(set_tex2, value), set_tex1.get_center() ) for value in set(set_tex2.values).difference(set_tex1.values) ] anims = [bracket_anim, *matching_anims, *mismatch_animations] if len(set_tex2.values) > 1: commas = [] for st in set_tex1, set_tex2: if len(st.values) > 1: commas.append(st[2:-1:2]) else: commas.append(Tex(",").set_opacity(0).move_to(st, DOWN)) comma_animations = TransformFromCopy(*commas) anims.append(comma_animations) for part in set_tex2: if isinstance(part, Tex) and part.get_tex() == "\\dots": anims.append(FadeInFromPoint(part, set_tex1.get_bottom())) return AnimationGroup(*anims) def get_sum_wrapper(set_tex): wrapper = VGroup( OldTex("\\text{sum}\\big(\\big) = ")[0], Integer(sum(set_tex.values)) ) wrapper.set_height(1.25 * set_tex.get_height()) wrapper[0][:4].next_to(set_tex, LEFT, SMALL_BUFF) wrapper[0][4:].next_to(set_tex, RIGHT, SMALL_BUFF) wrapper[1].next_to(wrapper[0][-1], RIGHT, buff=0.2) return wrapper def get_sum_group(set_tex, sum_color=YELLOW): height = set_tex.get_height() buff = 0.75 * height arrow = Vector(height * RIGHT) arrow.next_to(set_tex, RIGHT, buff=buff) sum_value = Integer(sum(set_tex.values)) sum_value.set_color(sum_color) sum_value.set_height(0.66 * height) sum_value.next_to(arrow, RIGHT, buff=buff) return VGroup(arrow, sum_value) def get_sum_animation(set_tex, sum_group, path_arc=-10 * DEGREES): arrow, sum_value = sum_group return AnimationGroup( GrowArrow(arrow), FadeTransform( get_integer_parts(set_tex).copy(), sum_value, path_arc=path_arc, ), ) def get_subset_highlights(set_tex, subset, stroke_color=YELLOW, stroke_width=2): result = VGroup() for value in subset: if value not in set_tex.values: continue rect = SurroundingRectangle( set_tex.get_part_by_tex(str(value)), buff=0.05, stroke_color=stroke_color, stroke_width=stroke_width, ) rect.round_corners(radius=rect.get_width() / 4) result.add(rect) return result def get_subsets(full_set): return list(it.chain(*( it.combinations(full_set, k) for k in range(len(full_set) + 1) ))) def subset_to_int(subset): return sum(2**(v - 1) for v in subset) def subset_sum_generating_function(full_set): pass def get_question_title(): st = "$\\{1, 2, 3, 4, 5, \\dots, 2{,}000\\}$" question = OldTexText( f"Find the number of subsets of {st},\\\\" " the sum of whose elements is divisible by 5", isolate=[st] ) set_tex = get_set_tex(range(1, 2001)) set_tex.set_color(BLUE) set_tex.replace(question.get_part_by_tex(st)) question.replace_submobject(1, set_tex) question.to_edge(UP) return question def massive_int(num, n_cols=42, width=7): total = VGroup(*(Integer(int(digit)) for digit in str(num))) total.arrange_in_grid(h_buff=SMALL_BUFF, v_buff=1.5 * SMALL_BUFF, n_cols=n_cols) for n in range(len(total) - 3, -3, -3): comma = Tex(",") triplet = total[n:n + 3] triplet.arrange_to_fit_width( triplet.get_width() - 2 * comma.get_width(), about_edge=LEFT ) comma.move_to(triplet.get_corner(DR) + 1.5 * comma.get_width() * RIGHT) total.insert_submobject(n + 3, comma) total[-1].set_opacity(0) total.set_width(width) return total def von_mangoldt_str(n): factors = sympy.factorint(n) if len(factors) == 1: return f"\\ln({list(factors.keys())[0]})" else: return "0" # Scenes class PreviewFraming(TeacherStudentsScene): def construct(self): # Setup morty = self.teacher ss = self.students # top_text = Text("Question about whole numbers") # tt0 = top_text # tt1 = VMobject() top_text = Text("Today's puzzle (explained in a moment)") tt0 = top_text.select_part("Today's puzzle") tt1 = top_text.select_part("(explained in a moment)") top_text.to_edge(UP, buff=MED_SMALL_BUFF) tt1.set_fill(GREY_B) tt0.save_state() tt0.set_x(0) top_rect = Rectangle( width=0.75 * FRAME_WIDTH, height=0.125 * FRAME_WIDTH, ) top_rect.set_fill(BLACK, 1) top_rect.set_stroke(WHITE, 1) top_rect.next_to(top_text, DOWN) self.play( # FadeInFromPoint(top_rect, morty.get_corner(UR)), DrawBorderThenFill(top_rect), morty.change("raise_right_hand", top_rect), self.change_students( "erm", "thinking", "pondering", look_at=top_rect, ), Write(tt0) ) self.wait(2) self.play( tt0.animate.restore(), FadeIn(tt1, lag_ratio=0.1), self.change_students( "pondering", "hesitant", "sassy", look_at=top_rect, ), ) self.wait(4) # Spoiler spoiler_rect = ScreenRectangle() spoiler_rect.set_fill(BLACK, 1) spoiler_rect.set_stroke(WHITE, 1) spoiler_rect.set_height(4.5) spoiler_rect.to_corner(DL) spoiler_rect.align_to(top_rect, LEFT) spoiler_word = Text("Spoiler", color=RED, font_size=60) # spoiler_word = Text("Complex solution", color=BLUE) spoiler_word.next_to(spoiler_rect, RIGHT, buff=MED_LARGE_BUFF, aligned_edge=UP) spoiler_word.shift(SMALL_BUFF * DOWN) for pi in ss: pi.generate_target() pi.target.shift(2 * DOWN) pi.target.change("horrified", UP) pi.target.set_opacity(0) self.play( FadeIn(spoiler_rect, DOWN), LaggedStartMap(MoveToTarget, ss, run_time=1.5), morty.change("tease", ORIGIN), Write(spoiler_word), ) self.play(Blink(morty)) self.wait(3) self.play(morty.change("surprised", spoiler_rect)) self.play(Blink(morty)) self.wait(2) self.play(morty.change("hesitant", spoiler_rect)) self.wait() self.play(Blink(morty)) self.wait(3) class UnreasonableUsefulness(InteractiveScene): def construct(self): # Title pre_quote = Text( "The unreasonable effectiveness of\n" "mathematics in the natural sciences", t2c={"mathematics": BLUE, "the natural sciences": TEAL}, alignment="CENTER" ) quote = Text( "The unreasonable effectiveness of\n" "complex numbers in discrete math", t2c={"complex numbers": BLUE, "discrete math": TEAL}, alignment="CENTER" ) for text in pre_quote, quote: text.to_edge(UP) self.add(pre_quote) self.wait() self.remove(pre_quote) quote_anim = LaggedStart(*( FadeTransform(pre_quote.select_part(t0), quote.select_part(t1)) for t0, t1 in [ 2 * ["The unreasonable effectiveness of"], ["mathematics", "complex numbers"], 2 * ["in"], ["the natural sciences", "discrete math"], ] )) # Plane and numbers plane = ComplexPlane((-3, 3), (-3, 3)) plane.set_height(5.5) plane.to_corner(DL) plane.add_coordinate_labels(font_size=20) plane_title = Tex("\\mathds{C}") plane_title.next_to(plane.get_corner(UL), UR, SMALL_BUFF) n, m = 8, 12 numbers = VGroup(*(Integer(n) for n in range(1, n * m + 1))) numbers.arrange_in_grid(m, n, buff=MED_LARGE_BUFF) numbers.match_height(plane) numbers.match_y(plane).to_edge(RIGHT) arrow = Arrow(plane, numbers) self.play( Write(plane, run_time=1, lag_ratio=0.01, stroke_color=WHITE, stroke_width=1), Write(plane_title), quote_anim, ) self.play( GrowArrow(arrow), ShowIncreasingSubsets(numbers, run_time=5), ) self.wait() # Highlight primes prime_rects = VGroup() for num in numbers: num.generate_target() if sympy.isprime(num.get_value()): rect = SurroundingRectangle(num, buff=SMALL_BUFF) rect.round_corners() rect.set_stroke(TEAL, 1) prime_rects.add(rect) else: num.target.set_opacity(0.25) self.play( LaggedStartMap(MoveToTarget, numbers), ShowIncreasingSubsets(prime_rects), run_time=7, ) self.wait() # Show zeta zeta_def = Tex( "\\zeta(s) = \\sum_{n = 1}^\\infty {1 \\over n^s}", font_size=42, tex_to_color_map={"s": YELLOW} ) zeta_def.next_to(plane.c2p(-3, 3), DR) zeta_def_highlight = VHighlight( zeta_def, color_bounds=(BLACK, BLACK), max_stroke_addition=12, ) for a, layer in zip(np.linspace(1, 0.2, 5), zeta_def_highlight): layer.set_stroke(opacity=a) zeta_spiril = ParametricCurve( lambda t: plane.n2p(complex(mpmath.zeta(complex(0.5, t)))), t_range=(0, 42), ) zeta_spiril.set_stroke([YELLOW, YELLOW, RED], 2) self.play( ApplyMethod( plane.coordinate_labels[-2:].set_opacity, 0, time_span=(3, 4), ), FadeIn(zeta_def_highlight, time_span=(3, 4)), Write(zeta_def, time_span=(2, 4)), ShowCreation(zeta_spiril, rate_func=smooth, run_time=16), ) self.wait() class RiemannHypothesisMention(TeacherStudentsScene): def construct(self): self.teacher_says( "This is what the $1M\nRiemann Hypothesis\nis all about", bubble_config=dict(width=4, height=3), added_anims=[self.change_students( "erm", "happy", "thinking", look_at=self.screen, )] ) self.wait(3) self.play_student_changes("pondering", "pondering", "tease") self.wait(3) class ZetaVideoWrapper(VideoWrapper): title = "From a previous video: Visualizing the Riemann Zeta Function" class ToyVsRH(InteractiveScene): def construct(self): # Screens self.add(FullScreenRectangle().set_fill(GREY_E, 1)) screens = ScreenRectangle().replicate(2) screens.set_stroke(WHITE, 1) screens.set_fill(BLACK, 1) screens.set_height(3.5) screens[0].to_corner(UL, buff=SMALL_BUFF) screens[1].to_corner(DR, buff=SMALL_BUFF) titles = VGroup( Text("Our puzzle"), Text("Riemann Hypothesis"), ) for title, screen, vect in zip(titles, screens, [RIGHT, LEFT]): title.next_to(screen, vect, buff=MED_LARGE_BUFF) titles[0].shift(UP) titles[1].shift(DOWN) toy = Text("(toy problem)") toy.set_fill(GREY_B) toy.next_to(titles[0], RIGHT) self.add(screens) self.add(titles) # Distance arrow = CubicBezier( screens[0].get_right() + SMALL_BUFF * RIGHT, screens[0].get_right() + 5 * RIGHT, screens[1].get_left() + 5 * LEFT, screens[1].get_left() + MED_SMALL_BUFF * LEFT, ) arrow.add(ArrowTip().scale(0.5).move_to(arrow.get_end())) arrow.set_color(TEAL) arrow_label = Text("Long long\ndistance", font_size=36) arrow_label.next_to(arrow.pfp(0.25), RIGHT) arrow_label.set_color(TEAL) or_is_it = Text("or is it?", font_size=36) or_is_it.next_to(arrow_label, DOWN, MED_LARGE_BUFF) or_is_it.set_color(YELLOW) self.play(ShowCreation(arrow)) self.play(Write(arrow_label, run_time=1)) self.wait() self.play( FadeIn(toy, 0.5 * RIGHT) ) self.wait() self.play(FadeIn(or_is_it, 0.5 * DOWN)) self.wait() class AnswerGuess(InteractiveScene): def construct(self): # Count total title = get_question_title() count = VGroup(Text("Total subsets: "), Tex("2^{2{,}000}")) count[0].set_color(TEAL) count.arrange(RIGHT, buff=MED_SMALL_BUFF, aligned_edge=DOWN) count.scale(60 / 48) count.next_to(title, DOWN, LARGE_BUFF) self.add(title) self.wait() self.play(Write(count[0])) self.play( GrowFromCenter(count[1][0]), FadeTransform(title[1][-6:-1].copy(), count[1][1:]), ) self.wait() # Ask about why count_rect = SurroundingRectangle(count, buff=MED_SMALL_BUFF) count_rect.set_stroke(TEAL, 2) randy = Randolph(height=1.5) randy.flip() randy.next_to(count_rect, RIGHT, LARGE_BUFF).shift(0.5 * DOWN) randy.get_bubble(Text("Why?", font_size=24), direction=LEFT, height=1.0, width=1.0) self.play( ShowCreation(count_rect), VFadeIn(randy), randy.change("maybe", count_rect), Write(randy.bubble), Write(randy.bubble.content), ) self.play(Blink(randy)) self.wait() self.play(randy.change("thinking").look(DL)) self.play(Blink(randy)) randy.add(randy.bubble, randy.bubble.content) self.wait() self.play(*map(FadeOut, [randy, count_rect])) # Show total digits count.generate_target() count.target.to_edge(LEFT) eq = Tex("=") eq.next_to(count.target, RIGHT).match_y(count[1][0]) total = massive_int(2**2000) total.next_to(eq, RIGHT).align_to(count, UP) self.play(MoveToTarget(count), Write(eq)) self.play(ShowIncreasingSubsets(total, run_time=5)) self.wait() self.play( FadeOut(total, 0.1 * DOWN, lag_ratio=0.01), FadeOut(eq), ) # Guess 1 / 5 guess = VGroup(Text("Guess: "), Tex("\\approx \\frac{1}{5} \\cdot 2^{2{,}000}")) guess[0].set_color(YELLOW) guess.arrange(RIGHT) guess.next_to(count, RIGHT, buff=2.5) guess.match_y(count[0]) self.play(Write(guess[0])) self.play(TransformMatchingShapes(count[1].copy(), guess[1], path_arc=30 * DEGREES)) self.wait() # Simplify small_set = get_set_tex(range(1, 6)) small_set.to_edge(UP) simplify = Text("Simplify!") simplify.next_to(small_set, DOWN, MED_LARGE_BUFF) simplify.set_color(YELLOW) self.play( LaggedStartMap( FadeOut, VGroup(count, guess), lag_ratio=0.25, run_time=1, ) ) self.remove(title) self.play( FadeOut(title[0], scale=0.5), FadeOut(title[2], scale=0.5), set_tex_transform(title[1], small_set), FadeIn(simplify, scale=2) ) self.wait() # Ask questions kw = dict(t2c={ "construct": YELLOW, "organize": TEAL, }) questions = VGroup( Text("What are all\nthe subsets?", **kw), Text("How do you\norganize them?", **kw), Text("How do you\nconstruct them?", **kw), ) questions.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) questions.to_edge(LEFT).to_edge(DOWN, buff=LARGE_BUFF) self.play(FadeTransform(simplify, questions[0])) self.wait() self.play(Write(questions[1], run_time=1)) self.wait() self.play( TransformFromCopy( questions[1].get_part_by_text("How do you"), questions[2].get_part_by_text("How do you"), ), TransformFromCopy( questions[1][-5:], questions[2][-5:], ), FadeTransform( questions[1].get_part_by_text("organize").copy(), questions[2].get_part_by_text("construct"), ) ) self.wait() class GoThroughAllSubsets(InteractiveScene): n_searched = 2**6 rate = 1 def construct(self): full_set = get_set_tex(range(1, 2001), max_shown=25) full_set.set_width(0.9 * FRAME_WIDTH) full_set.center() full_set_elements = [sm for sm in full_set if isinstance(sm, Integer)] sum_mob = Integer(0) sum_mob.next_to(full_set, DOWN, buff=1.0) sum_lhs = Text("Sum = ") sum_lhs.next_to(sum_mob, LEFT) sum_label = VGroup(sum_lhs, sum_mob) sum_label.align_to(full_set, LEFT).shift(RIGHT) counter = VGroup( Text("Count so far: "), Integer(0, edge_to_fix=LEFT) ) counter.arrange(RIGHT) counter.next_to(sum_mob, RIGHT) counter.align_to(full_set, RIGHT).shift(LEFT) for elem in full_set_elements: elem.rect = SurroundingRectangle(elem, buff=0.05) elem.rect.set_stroke(BLUE, 2) elem.rect.round_corners() elem.line = Line(elem.rect.get_bottom(), sum_mob.get_top(), buff=0.2) elem.line.set_stroke(BLUE, 2) self.add(full_set) self.add(counter) self.add(sum_label) group = VGroup( VGroup(), # Rects VGroup(), # Lines sum_mob, counter[1], VGroup(), # Mark ) n_tracker = ValueTracker(0) all_counts = np.cumsum([ int(sum((int(bit) * n for n, bit in zip(it.count(1), reversed(bin(n)[2:])))) % 5 == 0) for n in range(self.n_searched) ]) def update_group(group): n = int(n_tracker.get_value()) rects, lines, sum_mob, count, mark = group bits = str(bin(n))[2:] elems = [] subset = [] for i, elem, bit in zip(it.count(1), full_set_elements, reversed(bits)): if bit == '1': elems.append(elem) subset.append(i) total = sum(subset) sum_mob.set_value(total) rects.set_submobjects([elem.rect for elem in elems]) lines.set_submobjects([elem.line for elem in elems]) if total % 5 == 0: count.set_value(all_counts[n]) count.set_color(GREEN) sum_mob.set_color(GREEN) check = Checkmark() check.next_to(sum_mob, RIGHT) mark.set_submobjects([check]) else: sum_mob.set_color(WHITE) mark.set_submobjects([]) self.add(group, n_tracker) self.play( n_tracker.animate.set_value(self.n_searched), UpdateFromFunc(group, update_group), run_time=self.n_searched / self.rate, rate_func=linear, ) class GoThroughAllSubsetsFast(GoThroughAllSubsets): n_searched = 2**13 rate = 120 class TwoThousandBinaryChoices(InteractiveScene): def construct(self): # Build parts full_set = get_set_tex(range(1, 2001), max_shown=25) full_set.set_width(0.9 * FRAME_WIDTH) full_set.center() self.add(full_set) elems = get_integer_parts(full_set) elem_rects = VGroup(*( SurroundingRectangle(elem, buff=0.05).round_corners() for elem in elems )) elem_rects.set_stroke(BLUE, 2) twos = VGroup(*( Integer(2).match_width(elems[1]).next_to(er, UP) for er in elem_rects )) dots = VGroup(*( Tex("\\cdot").move_to(midpoint(t1.get_right(), t2.get_left())) for t1, t2 in zip(twos, twos[1:]) )) dots.replace_submobject(-1, Tex("\\dots").move_to(dots[-1])) dots.add_to_back(VMobject()) choices = Text("choices").match_height(twos) VGroup(twos, dots, choices).set_color(TEAL) # Label choices words = Text("2,000 Binary choices") words.set_color(TEAL) words.next_to(full_set, DOWN, buff=MED_LARGE_BUFF) self.play( LaggedStartMap(ShowCreationThenFadeOut, elem_rects, lag_ratio=0.05), FadeIn(words, 0.5 * DOWN) ) self.wait() # Go through all choices self.add(choices) for rect, two, dot in zip(elem_rects, twos, dots): choices.next_to(two, RIGHT, buff=0.2) marks = VGroup(Checkmark(), Exmark()) marks.scale(0.5) marks.next_to(rect, DOWN, SMALL_BUFF) self.add(two, dot) include = random.random() < 0.5 if include: self.add(rect) marks.submobjects.reverse() self.play(ShowSubmobjectsOneByOne(marks.copy(), remover=True, run_time=0.5)) self.add(marks[-1]) self.wait(0.25) self.remove(choices) self.wait() class AskAboutGuess(InteractiveScene): def construct(self): # Number line virt_N = 64 line = NumberLine( (0, virt_N, 1), tick_size=0.02, longer_tick_multiple=4, numbers_with_elongated_ticks=range(0, virt_N + virt_N // 8, virt_N // 8), width=FRAME_WIDTH - 2 ) line.move_to(2.0 * DOWN) kw = dict(font_size=24) line_labels = VGroup( Tex("0", **kw), Tex("2^{1{,}998}", **kw), Tex("2^{1{,}999}", **kw), Tex("3 \\cdot 2^{1{,}998}", **kw), Tex("2^{2{,}000}", **kw), ) for n, label in zip(np.linspace(0, virt_N, 5), line_labels): label.next_to(line.n2p(n), DOWN, MED_SMALL_BUFF) self.add(line) self.add(line_labels) # Set label title = get_question_title() title.to_edge(UP) self.add(title) # set_tex = get_set_tex(range(1, 2001), max_shown=21) # set_tex.scale(0.75) # set_tex.to_edge(UP) # self.add(set_tex) # Arrow with labels right_arrow = Vector(DOWN, color=BLUE) right_arrow.next_to(line.n2p(virt_N), UP, buff=0) right_label = Text("Total number\nof subsets", font_size=36) right_label.next_to(right_arrow, UP) right_label.shift_onto_screen(buff=MED_SMALL_BUFF) left_arrow = right_arrow.copy() left_arrow.set_color(YELLOW) left_arrow.next_to(line.n2p(virt_N / 5), UP, buff=0) left_label = OldTexText("Guess: ", "$\\frac{1}{5} \\cdot 2^{2{,}000}$", font_size=36) left_label.next_to(left_arrow, UP) self.add(right_label) self.add(right_arrow) self.play( TransformFromCopy(right_arrow, left_arrow), FadeTransform(right_label.copy(), left_label), ) self.wait() # Not an integer guess_part = left_label[1] guess_rect = SurroundingRectangle(guess_part, buff=SMALL_BUFF) guess_rect.round_corners() guess_rect.set_stroke(RED, 2) nonint = Text("Not an integer!", color=RED) nonint.next_to(guess_rect, UP) self.play( ShowCreation(guess_rect), Write(nonint) ) self.wait() # More or less dot = GlowDot(color=TEAL) dot.move_to(line.n2p(virt_N / 5)) tip = Triangle(start_angle=-PI / 2) tip.set_stroke(width=0) tip.set_fill(TEAL, 1) tip.set_height(0.1) tip.add_updater(lambda t: t.move_to(dot.get_center(), DOWN)) self.play(FadeIn(dot), FadeIn(tip)) for dist in [0.2, 1.5]: for vect in [RIGHT, 2 * LEFT]: self.play(dot.animate.shift(dist * vect)) self.add(Group(dot, tip).copy().clear_updaters().set_opacity(0.5)) self.wait() for n in range(40): dot.move_to(line.n2p(virt_N / 5 + random.uniform(-8, 8))) self.wait(0.25) class WhoCares(TeacherStudentsScene): def construct(self): # Who cares? self.play( PiCreatureSays( self.students[2], "Who cares?", target_mode="angry", bubble_config=dict(direction=LEFT), ), self.teacher.change("guilty"), self.students[0].change("sassy"), self.students[0].change("hesitant"), ) self.wait(3) class ExampleWith5(InteractiveScene): elem_colors = color_gradient([BLUE_B, BLUE_D], 5) def construct(self): # Add full set N = 5 full_set = list(range(1, N + 1)) set_tex = get_set_tex(full_set) set_tex.to_edge(UP) self.add(set_tex) self.wait() # Construct all subsets subsets = self.construct_all_subsets(set_tex) # Show n choose k stacks stacks = self.get_subset_stacks(full_set) anims = [] for stack in stacks: for new_subset in stack: for subset in subsets: if set(subset.values) == set(new_subset.values): anims.append(FadeTransform(subset, new_subset)) self.play(LaggedStart(*anims, lag_ratio=0.05)) self.wait() # Show their sums sum_stacks = self.get_subset_sums(stacks) covered_sums = [] n_selections = 6 for n in range(n_selections): self.wait(note=f"Example sum {n + 1} / {n_selections}") # Show sum based on what's in self.selection anims = [] for stack, sum_stack in zip(stacks, sum_stacks): for subset, sum_mob in zip(stack, sum_stack): if set(subset.get_family()).intersection(self.selection.get_family()): if sum_mob not in covered_sums: covered_sums.append(sum_mob) anims.append(get_sum_animation(subset, sum_mob)) self.clear_selection() self.play(LaggedStart(*anims)) self.add(sum_stacks) # Group by sum self.highlight_rects = self.get_highlight_rects(stacks, sum_stacks) self.highlight_rects.set_stroke(width=0) self.group_by_sum(stacks, sum_stacks) self.wait() # Count Answer highlights = VGroup() for stack in self.common_sum_stacks[::5]: for subset in stack: highlights.add(VHighlight(subset, max_stroke_addition=10)) answer_word, answer_count = answer = VGroup( Text("Answer: "), Integer(0) ) answer.arrange(RIGHT) answer.next_to(self.common_sum_stacks[0], UP, LARGE_BUFF) answer_count.set_color(TEAL) self.add(highlights, self.common_sum_stacks, answer) self.play( ShowIncreasingSubsets(highlights), UpdateFromFunc(answer_count, lambda m: m.set_value(len(highlights))), run_time=1.5 ) self.play(FadeOut(highlights)) # Contrast with 1/5 count = OldTexText( "Total subsets:", " $2^5 = $", " $32$" ) count.set_color_by_tex("32", BLUE) count.match_x(set_tex).match_y(answer) counter = Integer(32) counter.set_color(BLUE) counter.replace(count[-1]) all_highlights = VGroup() for stack in self.common_sum_stacks: for subset in stack: all_highlights.add(VHighlight(subset, max_stroke_addition=10)) fifth_arrow = Vector(RIGHT) fifth_arrow.next_to(count, RIGHT) fifth = Tex("\\times 1 / 5", font_size=24) fifth.next_to(fifth_arrow, UP, buff=SMALL_BUFF) fifth_rhs = DecimalNumber(32 / 5, num_decimal_places=1) fifth_rhs.next_to(fifth_arrow, RIGHT) self.add(all_highlights, self.common_sum_stacks) self.play( FadeIn(count[:2]), ShowIncreasingSubsets(all_highlights, run_time=2), UpdateFromFunc(counter, lambda m: m.set_value(len(all_highlights))), ) self.play(FadeOut(all_highlights)) self.wait() self.play( GrowArrow(fifth_arrow), Write(fifth), ) self.wait() self.play(FadeTransform(count[-1].copy(), fifth_rhs, path_arc=-60 * DEGREES)) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( answer, *count[:2], counter, fifth_arrow, fifth, fifth_rhs, ))) # Show generating function self.show_generating_function(set_tex) self.transition_to_full_generating_function(set_tex) def construct_all_subsets(self, set_tex): # Preview binary choices value_parts = VGroup(*( get_part_by_value(set_tex, v) for v in range(1, 6) )) rects = VGroup(*( SurroundingRectangle(vp, buff=0.1).round_corners() for vp in value_parts )) rects.set_stroke(BLUE, 2) words = Text("5 binary choices") words.next_to(set_tex, DOWN, buff=1.5) lines = VGroup(*( Line(words.get_top(), rect.get_bottom(), buff=0.15) for rect in rects )) lines.match_style(rects) def match_n(rects, n): bits = it.chain( str(bin(n)[-1:1:-1]), it.repeat("0") ) for rect, bit in zip(rects, bits): rect.set_stroke(opacity=float(bit == "1")) self.add(rects) self.play( Write(words), Write(lines), UpdateFromAlphaFunc( rects, lambda r, a: match_n(r, int(31 * a)), run_time=4, rate_func=linear, ) ) self.wait() self.play( FadeOut(rects), LaggedStartMap(Uncreate, lines), FadeOut(words, 0.1 * DOWN), ) # Show construction subsets = VGroup(get_set_tex([])) for value in range(1, 6): value_mob = get_part_by_value(set_tex, value) marks = VGroup(Exmark(), Checkmark()) marks.match_height(value_mob) marks.next_to(value_mob, DOWN) subsets.generate_target() added_subsets = VGroup(*( get_set_tex([*ss.values, value]).move_to(ss) for ss in subsets )) for ss in added_subsets: self.color_set_tex(ss) get_integer_parts(ss)[-1].set_opacity(0) vect = [RIGHT, DOWN, RIGHT, DOWN, RIGHT][value - 1] buff = [2.25, 0.75, 2.0, 0.75, 1.0][value - 1] added_subsets.next_to(subsets, vect, buff=buff) new_subsets = VGroup(*subsets.target, *added_subsets) new_subsets.set_max_width(FRAME_WIDTH - 1) new_subsets.center() subsets_copy = subsets.copy() for ssc, nss in zip(subsets_copy, added_subsets): ssc.match_height(nss) ssc.move_to(nss) # self.wait() elem = get_part_by_value(set_tex, value) if value == 1: self.play(set_tex_transform(set_tex, subsets[0])) self.add(subsets) self.wait() self.play( MoveToTarget(subsets, path_arc=30 * DEGREES), ReplacementTransform( subsets.copy(), subsets_copy, path_arc=30 * DEGREES, ) ) self.remove(subsets_copy) self.play( LaggedStart(*( Transform( elem.copy(), get_integer_parts(st)[-1].copy().set_opacity(1), remover=True, ) for st in added_subsets ), lag_ratio=0.1), *( set_tex_transform(st1, st2) for st1, st2 in zip(subsets_copy, added_subsets) ), elem.animate.set_color(self.elem_colors[value - 1]), FlashAround(elem, color=self.elem_colors[value - 1]), ) self.remove(subsets_copy, new_subsets) subsets.set_submobjects(list(new_subsets)) self.add(subsets) subsets.set_opacity(1) # self.wait() self.wait() # Equation equation = Tex("2 \\cdot 2 \\cdot 2 \\cdot 2 \\cdot 2 = 2^5 = 32") equation.set_width(4) equation.to_corner(UL) equation.set_color(YELLOW) self.play(Write(equation)) self.wait() self.play(FadeOut(equation)) return subsets def get_highlight_rects(self, stacks, sum_stacks): rects = VGroup() anims = [] for stack, sum_stack in zip(stacks, sum_stacks): for set_tex, sum_group in zip(stack, sum_stack): if sum(set_tex.values) % 5 == 0: rect = SurroundingRectangle(VGroup(set_tex, sum_group)) rect.value = sum(set_tex.values) rects.add(rect) else: anims.append(set_tex.animate.set_opacity(0.25)) anims.append(sum_group.animate.set_opacity(0.25)) rects.set_stroke(TEAL, 2) for rect in rects: rect.round_corners() return rects def highlight_multiple_of_5(self, stacks, sum_stacks): # Blah rects = self.get_highlight_rects(stacks, sum_stacks) counter = Integer(0, font_size=72) counter.to_corner(UR) counter.set_color(TEAL) self.play(*anims, run_time=1) self.wait() self.play( FadeIn(rects, lag_ratio=0.9), ChangeDecimalToValue(counter, len(rects)), run_time=1.5 ) self.wait() self.highlight_rects = rects self.counter = counter def group_by_sum(self, stacks, sum_stacks): # Lock sums to subsets subset_groups = VGroup() for stack, sum_stack in zip(stacks, sum_stacks): for set_tex, sum_group in zip(stack, sum_stack): set_tex.sum_group = sum_group sum_group.set_tex = set_tex subset_groups.add(VGroup(set_tex, sum_group)) # Reorganize common_sum_stacks = VGroup() max_sum = max(sum(ssg[0].values) for ssg in subset_groups) for n in range(max_sum + 1): stack = VGroup(*filter( lambda ssg: sum(ssg[0].values) == n, subset_groups )) common_sum_stacks.add(stack) common_sum_stacks.generate_target() csst = common_sum_stacks.target for stack in common_sum_stacks.target: stack.arrange(DOWN, aligned_edge=RIGHT, buff=SMALL_BUFF) csst.arrange_in_grid(4, 5, buff=MED_LARGE_BUFF, aligned_edge=RIGHT) csst[10:15].set_y(np.mean([csst[5].get_y(DOWN), csst[15].get_y(UP)])) csst.refresh_bounding_box() csst.set_width(FRAME_WIDTH - 1) csst.to_corner(DL) csst.set_opacity(1) # Create new rectangles common_sum_rects = VGroup() for stack in common_sum_stacks.target: rect = SurroundingRectangle(stack, buff=SMALL_BUFF) rect.round_corners(radius=0.05) rect.value = sum(stack[0][0].values) color = TEAL if rect.value % 5 == 0 else GREY_B rect.set_stroke(color, 1) common_sum_rects.add(rect) rect_anims = [] for highlight_rect in self.highlight_rects: for rect in common_sum_rects: if rect.value == highlight_rect.value: rect_anims.append(Transform(highlight_rect, rect)) self.disable_interaction(common_sum_rects) # Transition to common sum self.play( MoveToTarget(common_sum_stacks), *rect_anims, run_time=2 ) self.play( FadeOut(self.highlight_rects), FadeIn(common_sum_rects), ) self.wait() self.subset_groups = subset_groups self.common_sum_stacks = common_sum_stacks self.common_sum_rects = common_sum_rects def show_generating_function(self, set_tex): # Setup expressions css = self.common_sum_stacks csr = self.common_sum_rects lower_group = self.lower_group = VGroup(csr, css) factored_terms = "(1 + x^1)", "(1 + x^2)", "(1 + x^3)", "(1 + x^4)", "(1 + x^5)" factored = Tex("".join(factored_terms), isolate=factored_terms) expanded_terms = ["1"] for n in range(1, 16): k = len(css[n]) expanded_terms.append(str(k) + f"x^{{{n}}}") expanded = Tex("+".join(expanded_terms), isolate=["+", *expanded_terms]) expanded.set_width(FRAME_WIDTH - 1) factored.next_to(set_tex, DOWN, MED_LARGE_BUFF) expanded.next_to(factored, DOWN, MED_LARGE_BUFF) lhs = OldTex("p(x) = ") lhs.next_to(factored, LEFT) self.play(FadeIn(lhs)) for term, elem in zip(factored_terms, get_integer_parts(set_tex)): part = factored.get_part_by_tex(term) self.play( FlashAround(elem, color=elem.get_color()), FadeIn(part[:-2]), FadeIn(part[-1]), ) part[-2].match_style(elem) self.play(FadeTransform(elem.copy(), part[-2])) self.wait() self.add(factored) self.wait() self.play(lower_group.animate.set_height(3.0, about_edge=DOWN)) # Emphasize 5 binary choices parts = VGroup(*( factored.get_part_by_tex(term) for term in factored_terms )) rects = VGroup(*( SurroundingRectangle(part, buff=0.05).round_corners() for part in parts )) rects.set_stroke(BLUE, 2) words = Text("5 binary choices", color=BLUE) words.next_to(rects, DOWN, MED_LARGE_BUFF) self.play( LaggedStartMap( VFadeInThenOut, rects, lag_ratio=0.25, run_time=4, ), Write(words), ) self.play(FadeOut(words)) # Animate expansion fac_term_parts = [factored.get_part_by_tex(term) for term in factored_terms] expanded_parts = [expanded.get_part_by_tex(term) for term in expanded_terms] super_expanded = VGroup() super_expanded.next_to(factored, DOWN, MED_LARGE_BUFF) collection_anims = [] subset_groups = self.subset_groups subset_groups.submobjects.sort( key=lambda ssg: sum(ssg[0].values) ) for subset_group in subset_groups: bits = [i + 1 in subset_group[0].values for i in range(5)] top_terms = [ part[3:-1] if bit else part[1] for bit, part in zip(bits, fac_term_parts) ] top_rects = VGroup(*( # VHighlight(part, color_bounds=(BLUE, BLUE_E), max_stroke_addition=3.0) SurroundingRectangle(part).set_stroke(BLUE, 2).round_corners() for part in top_terms )) n = sum(b * k for k, b in zip(range(1, 6), bits)) if n == 0: new_term = Tex("1", font_size=36) super_expanded.add(new_term) else: new_plus = Tex("+", font_size=36) new_term = Tex(f"x^{{{n}}}", font_size=36) super_expanded.add(new_plus, new_term) collection_anims.append(FadeOut(new_plus)) super_expanded.arrange(RIGHT, aligned_edge=DOWN, buff=SMALL_BUFF) super_expanded.next_to(factored, DOWN, MED_LARGE_BUFF) super_expanded.to_edge(LEFT) if len(super_expanded) > 33: super_expanded[33:].next_to( super_expanded[0], DOWN, MED_LARGE_BUFF, aligned_edge=LEFT ) low_rect = SurroundingRectangle(new_term, buff=0.5 * SMALL_BUFF) low_rect.set_stroke(BLUE, 2).round_corners() collection_anims.append( FadeTransform(new_term, expanded_parts[n], path_arc=10 * DEGREES) ) self.add(top_rects) self.add(super_expanded, low_rect) subset_groups.set_opacity(0.25) subset_group.set_opacity(1) self.wait() self.remove(top_rects, low_rect) self.wait() # Reorganize to expanded lower_group.generate_target() lower_group.target.set_height(4, about_edge=DOWN) lower_group.target[1].set_opacity(1) self.play( LaggedStart(*collection_anims), LaggedStartMap(FadeIn, expanded.get_parts_by_tex("+")), MoveToTarget( lower_group, rate_func=squish_rate_func(smooth, 0.5, 1.0) ), run_time=3, ) self.add(expanded) self.wait(note="Highlight multiples of 5") self.factored_func = VGroup(*lhs, *factored) self.expanded_func = expanded def transition_to_full_generating_function(self, set_tex): # Expressions factored = Tex( "f(x) = (1 + x^1)(1 + x^2)(1 + x^3) \\cdots \\left(1 + x^{1{,}999}\\right)\\left(1 + x^{2{,}000}\\right)", ) expanded = Tex( "f(x) = 1+x+x^{2}+2 x^{3}+2 x^{4}+ 3x^{5} +\\cdots + x^{2{,}001{,}000}", isolate="+", ) new_set_tex = get_set_tex(range(1, 2001)) new_set_tex.move_to(set_tex) self.color_set_tex(new_set_tex) get_integer_parts(new_set_tex)[-1].set_color( interpolate_color(BLUE_E, BLUE_D, 0.5) ) h_line = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) h_line.set_stroke(GREY_C, 1) h_line.set_y(0.5) factored_word = Text("Factored", font_size=60, color=BLUE_B) factored_word.next_to(set_tex, DOWN, MED_LARGE_BUFF) factored.next_to(factored_word, DOWN, MED_LARGE_BUFF) expanded_word = Text("Expanded", font_size=60, color=TEAL) expanded_word.next_to(h_line, DOWN, buff=1.25) expanded.next_to(expanded_word, DOWN, MED_LARGE_BUFF) for mob in [factored, factored_word, expanded, expanded_word]: mob.to_edge(LEFT) small_group = VGroup(set_tex, self.factored_func) self.play( small_group.animate.set_y(-1.5), FadeOut(self.expanded_func, 2 * DOWN), FadeOut(self.lower_group, DOWN), ) self.play(TransformMatchingShapes(set_tex.copy(), new_set_tex)) self.play(FadeTransform(self.factored_func.copy(), factored)) self.wait() for n, i, j in [(1, 5, 11), (2, 11, 17), (3, 17, 23), (2000, 36, 46)]: value_part = get_part_by_value(new_set_tex, n) self.play( FadeTransform(value_part.copy(), factored[i + 4:j - 1].copy(), remover=True), FlashAround(factored[i:j], color=BLUE), ) self.add(factored) self.wait() self.play( Write(factored_word), FadeOut(small_group, DOWN) ) self.play( FadeTransform(factored_word.copy(), expanded_word), ShowCreation(h_line), ) self.play(FadeIn(expanded, run_time=2, lag_ratio=0.5)) self.wait() # Emphasize scale words = OldTexText("Imagine collecting $2^{2{,}000}$ terms!") words.set_color(RED) words.next_to(h_line, DOWN) words.to_edge(RIGHT) morty = Mortimer(height=2) morty.next_to(words, DOWN, MED_LARGE_BUFF) morty.to_edge(RIGHT) self.play( VFadeIn(morty), morty.change("surprised", expanded), Write(words) ) self.play(Blink(morty)) self.wait() self.play(FadeOut(words), FadeOut(morty)) # Show example term n = 25 subsets = list(filter( lambda s: sum(s) == n, get_subsets(range(1, n + 1)) )) coef = len(subsets) term = OldTex(str(coef), f"x^{{{n}}}", "+", "\\cdots") term[:2].set_color(TEAL) term[2:].set_color(WHITE) tail = expanded[-11:] term.move_to(tail, DL) tail.generate_target() tail.target.next_to(term, RIGHT, buff=0.15, aligned_edge=DOWN) self.play( Write(term), MoveToTarget(tail), ) self.wait() subset_mobs = VGroup(*map(get_set_tex, subsets)) subset_mobs.arrange_in_grid(n_cols=10) subset_mobs.set_width(FRAME_WIDTH - 1) subset_mobs.to_edge(UP) subset_mobs.set_color(TEAL) top_rect = FullScreenFadeRectangle() top_rect.set_fill(BLACK, opacity=0.9) top_rect.set_height(4, about_edge=UP, stretch=True) term_rect = SurroundingRectangle(term[:2]) term_rect.round_corners() term_rect.set_stroke(YELLOW, 2) term_words = Text("Is there a snazzy\nway to deduce this?", font_size=36) term_words.next_to(term_rect, DOWN) term_words.set_color(YELLOW) self.play( FadeIn(top_rect), ShowIncreasingSubsets(subset_mobs, run_time=5) ) self.wait() self.play( ShowCreation(term_rect), Write(term_words), ) self.wait() self.play( LaggedStartMap(FadeOut, subset_mobs, shift=0.2 * UP), FadeOut(top_rect, rate_func=squish_rate_func(smooth, 0.6, 1)), run_time=3 ) self.wait() ## def color_set_tex(self, set_tex): for value in set_tex.values: elem = get_part_by_value(set_tex, value) if value - 1 < len(self.elem_colors): elem.set_color(self.elem_colors[value - 1]) def get_subset_stacks(self, full_set, buff=3.5): stacks = VGroup(*( VGroup(*( get_set_tex(subset) for subset in it.combinations(full_set, k) )) for k in range(len(full_set) + 1) )) for stack in stacks: stack.arrange(DOWN) for ss in stack: self.color_set_tex(ss) stacks.arrange(RIGHT, buff=buff, aligned_edge=DOWN) stacks[0].move_to(stacks[1]).align_to(stacks[2], UP) stacks[4].align_to(stacks[3], UP) stacks[5].match_x(stacks[4]) stacks.set_max_height(FRAME_HEIGHT - 3) stacks.set_max_width(FRAME_WIDTH - 2) stacks.center().to_edge(DOWN) return stacks def get_subset_sums(self, stacks): return VGroup(*( VGroup(*( get_sum_group(set_tex) for set_tex in stack )) for stack in stacks )) class SpecifyEmptySet(TeacherStudentsScene): def construct(self): # Ask morty = self.teacher ss = self.students self.student_says( "Do we count\nthe empty set?", bubble_config=dict(direction=RIGHT), target_mode="raise_right_hand", added_anims=[ morty.change("happy"), ss[0].change("hesitant"), ss[0].change("pondering"), ] ) self.wait() # Facts kw = dict(tex_to_color_map={"\\{\\}": YELLOW}) facts = VGroup( Tex("\\text{We do count } \\{\\}", **kw), Tex("\\text{sum}(\\{\\}) = 0", **kw), OldTexText("0 is a multiple of 5", **kw), ) facts.next_to(morty.get_corner(UL), UP, MED_LARGE_BUFF) last_facts = VGroup() for fact in facts: self.play( FadeIn(fact, 0.5 * UP), morty.change("raise_right_hand", fact), ss[0].change("pondering", fact), ss[1].change("pondering", fact), ss[2].change("pondering", fact), last_facts.animate.shift(UP) ) self.wait() last_facts.add(fact) self.wait() self.play( RemovePiCreatureBubble(ss[2], target_mode="happy"), ss[0].change("thinking"), ss[1].change("tease"), ) self.wait(3) class ShowHypercubeConstruction(InteractiveScene): def construct(self): # Intro v1 = np.array([1.5, 1.5, 0.5]) v2 = np.array([-2.5, 0.5, 1.5]) vects = 1.5 * np.array([ RIGHT, UP, OUT, v1, v2, 1.5 * (v1 + 2 * OUT), 2 * (v2 + 2 * UP), 5 * v1, 5 * v2, ]) colors = [GREEN_D, TEAL, BLUE_D, RED, PINK] * 2 curr_sets = VGroup(get_set_tex([])) lines = VGroup() frame = self.camera.frame self.play(Write(curr_sets)) self.wait() # Grow new sets # indices = list(range(1, 6)) indices = list(range(1, 10)) for n, vect, color in zip(indices, vects, colors): new_sets = VGroup(*( get_set_tex([*st.values, n]) for st in curr_sets )) for ns in new_sets: for value, c in zip(indices, colors): if value in ns.values: get_part_by_value(ns, value).set_color(c) ns.set_backstroke() if n >= 3: ns.rotate(70 * DEGREES, RIGHT) curr_set_copies = curr_sets.copy() curr_sets.generate_target() new_lines = VGroup() line_copies = VGroup() for ns, cst, csc in zip(new_sets, curr_sets.target, curr_set_copies): ns.move_to(cst) ns.shift(vect) cst.shift(-vect) csc.move_to(ns) new_lines.add(Line( cst.get_center(), ns.get_center(), # buff=MED_SMALL_BUFF + ns.length_over_dim(np.argmax(vect)), buff=MED_SMALL_BUFF + ns.get_height(), stroke_color=color, stroke_width=2, )) line_copies = lines.copy() diff = new_sets[0].get_width() - curr_sets[0].get_width() for line in line_copies: if abs(line.get_vector()[0]) > 1e-2: line.set_width(line.get_width() - diff) lines.generate_target() line_copies.shift(vect) lines.target.shift(-vect) anims = [ MoveToTarget(curr_sets), TransformFromCopy(curr_sets, curr_set_copies), MoveToTarget(lines), TransformFromCopy(lines, line_copies), *map(GrowFromCenter, new_lines), ] if n == 3: anims.append(ApplyMethod( frame.reorient, 10, 70, run_time=2, )) for st in [*curr_set_copies, *curr_sets.target]: st.rotate(70 * DEGREES, RIGHT) frame.add_updater(lambda m, dt: frame.increment_theta(0.01 * dt)) if n >= 4: anims.append(frame.animate.scale(1.5).reorient(-10, 70).move_to(2 * IN)) self.play(*anims) self.remove(curr_set_copies) self.play(*( set_tex_transform(csc, ns) for csc, ns in zip(curr_set_copies, new_sets) )) self.wait() curr_sets.set_submobjects([*curr_sets, *new_sets]) curr_sets.set_backstroke() lines.set_submobjects([*lines, *line_copies, *new_lines]) self.add(lines, curr_sets) if n == 3: for i in range(1, 4): self.highlight_direction(curr_sets, lines, i) self.wait(5) def highlight_direction(self, set_texs, lines, index): anims = [] for line in lines: if np.argmax(line.get_vector()) == index - 1: anims.append(ShowCreation(line)) self.play(LaggedStart(*anims, lag_ratio=0.25, run_time=1)) anims = [] for st in set_texs: if index in st.values: part = get_part_by_value(st, index) outline = part.family_members_with_points()[0].copy() outline.set_fill(opacity=0) outline.set_stroke(YELLOW, 5) anims.append(VShowPassingFlash(outline, time_width=2)) self.play(LaggedStart(*anims, lag_ratio=0.1, run_time=2)) self.wait() class QuestionPolynomial(InteractiveScene): def construct(self): # Start n_range = list(range(1, 6)) poly = Tex( "p(x) = " + "".join(f"(1 + x^{{{n}}})" for n in n_range), tex_to_color_map=dict(zip( (f"{{{n}}}" for n in n_range), color_gradient([BLUE_B, BLUE_D], 5) )), isolate=["x"], ) poly.move_to([-0.81438428, 2.25048456, 0.]) self.add(poly) # Questions questions = VGroup( Text("Where does this\ncome from?", font_size=36), Text("What do polynomials\nhave to do with anything?", font_size=36), OldTexText("What is $x$?", font_size=60, color=TEAL).set_backstroke(width=8), ) pis = VGroup(*(Randolph(color=c, height=2.5) for c in [BLUE_C, BLUE_E, BLUE_D])) pis.arrange(RIGHT, buff=LARGE_BUFF) pis.to_corner(DL) anims = [] for pi, mode, question in zip(pis, ["maybe", "confused", "pleading"], questions): anim = PiCreatureSays( pi, question, target_mode=mode, look_at=poly, bubble_config=dict(width=4, height=2.5), ) pi.set_opacity(0) anims.append(anim) if pi is pis[1]: anims.append(Animation(Mobject())) self.play(LaggedStart(*anims, lag_ratio=0.9)) # Highlight xs xs = poly.select_parts("x") rects = VGroup(*(SurroundingRectangle(x, buff=0.05).round_corners() for x in xs)) rects.set_stroke(TEAL, 2) self.play(LaggedStartMap(ShowCreationThenFadeOut, rects, lag_ratio=0.1)) self.wait() # x is just a symbol words = OldTexText("$x$", " is just a symbol") words.to_edge(UP) words[0].set_color(TEAL) self.play( LaggedStartMap( RemovePiCreatureBubble, pis, look_at=poly, ), TransformFromCopy(xs[0], words[0]), Write(words[1], time_span=(1, 2)) ) self.wait() # Expansion expansion = Tex("1+x^{1}+x^{2}+2 x^{3}+2 x^{4}+3 x^{5}+3 x^{6}+3 x^{7}+3 x^{8}+3 x^{9}+3 x^{10}+2 x^{11}+2 x^{12}+x^{13}+x^{14}+x^{15}") expansion.set_width(FRAME_WIDTH - 1) expansion.next_to(poly, DOWN, MED_LARGE_BUFF) expansion.set_x(0) self.play( TransformMatchingShapes(poly[5:].copy(), expansion, run_time=3, lag_ratio=0.01), LaggedStart(*(pi.change("pondering", expansion) for pi in pis)) ) self.play(LaggedStartMap(Blink, pis)) self.wait() class PolynomialConstruction(InteractiveScene): def construct(self): # (1 + x) set_group = VGroup( get_set_tex([]), get_set_tex([1]), ) set_group.scale(0.5) curr_poly = Tex("(1 + x^1)") curr_poly[0].set_opacity(0) curr_poly[-1].set_opacity(0) for st, sym in zip(set_group, curr_poly[1::2]): st.next_to(sym, DOWN, MED_LARGE_BUFF) self.add(curr_poly, set_group) # Expand via subset iteration process for n in range(2, 8): cp_l, cp_r = curr_poly.replicate(2) sg_l, sg_r = set_group.replicate(2) plus = Tex("+") cp_l.next_to(plus, LEFT, LARGE_BUFF) cp_r.next_to(plus, RIGHT, LARGE_BUFF) sg_l.match_x(cp_l) sg_r.match_x(cp_r) self.remove(curr_poly, set_group) added_anims = [] if n == 5: added_anims.append(self.camera.frame.animate.set_height(10)) if n >= 6: added_anims.append(self.camera.frame.animate.scale(1.4)) VGroup(cp_l, sg_l).shift(LEFT) VGroup(cp_r, sg_r).shift(RIGHT) self.play( TransformFromCopy(curr_poly, cp_l), TransformFromCopy(curr_poly, cp_r), TransformFromCopy(set_group, sg_l), TransformFromCopy(set_group, sg_r), *added_anims ) self.wait() new_term = Tex(f"x^{n}") new_poly = Tex("".join([ f"\\left(1 + x^{k}\\right)" for k in range(1, n + 1) ])) new_term.next_to(cp_r, LEFT, SMALL_BUFF) new_term.align_to(cp_r.family_members_with_points()[1], DOWN) new_sets = VGroup(*( get_set_tex([*st.values, n]) for st in sg_r )) anims = [Write(new_term), Write(plus)] for ns, s in zip(new_sets, sg_r): ns.match_height(s) new_sets.arrange_in_grid( n_cols=2**int(np.ceil(np.log2(len(new_sets)) / 2)) ) new_sets.move_to(sg_r) for ns, s in zip(new_sets, sg_r): anims.append(set_tex_transform(s, ns)) if n == 2: anims.append(cp_r.animate.set_opacity(1)) self.remove(sg_r) self.play(*anims) self.wait() new_set_group = VGroup(*sg_l, *new_sets) new_set_group.generate_target() new_set_group.target.arrange_in_grid( n_cols=2**int(np.ceil(np.log2(len(new_set_group)) / 2)) ) new_set_group.target.next_to(new_poly, DOWN, MED_LARGE_BUFF) group = VGroup(cp_l, cp_r, plus, new_term) self.play(group.animate.shift(2 * UP)) group_copy = group.copy() self.add(group_copy) self.play( LaggedStart( Transform( cp_l, new_poly[:-6].copy().set_opacity(0), path_arc=30 * DEGREES, remover=True, ), ReplacementTransform(new_term, new_poly[-3:-1]), ReplacementTransform(cp_r, new_poly[:-6], path_arc=30 * DEGREES), ReplacementTransform(plus, new_poly[-4], path_arc=45 * DEGREES), Write(new_poly[-6:-4]), Write(new_poly[-1]), ), MoveToTarget(new_set_group), run_time=2, ) self.add(new_poly) set_group = new_set_group curr_poly = new_poly self.play(FadeOut(group_copy)) self.wait() class GeneratingFunctions(InteractiveScene): def construct(self): # Title title = Text("Generating functions!", font_size=72) title.to_edge(UP) title.set_color(BLUE) underline = Underline(title, buff=-0.05) underline.scale(1.25) underline.insert_n_curves(50) underline.set_stroke(BLUE_B, width=[0, 3, 3, 3, 0]) self.play( Write(title), ShowCreation(underline), run_time=1 ) # First poly degree = 10 poly = OldTex( "f(x) = 1+1 x^{1}+1 x^{2}+2 x^{3}+2 x^{4}+" "3 x^{5}+4 x^{6}+5x^{7}+6x^{8}+" "8x^{9} + 10x^{10} + \\cdots", isolate=["=", "+", "x"] ) seps = [poly.get_part_by_tex("="), *poly.get_parts_by_tex("+")] shifter = 0.05 for sep in seps: i = poly.submobjects.index(sep) poly[i:].shift(shifter * LEFT) poly[i + 1:].shift(shifter * LEFT) poly.set_width(FRAME_WIDTH - 0.5) poly.next_to(underline, DOWN, LARGE_BUFF) self.add(poly) subsets = get_subsets(list(range(1, degree + 1))) subset_groups = VGroup().replicate(degree + 1) for subset in subsets: index = sum(subset) if index <= degree: subset_groups[index].add(get_set_tex(subset)) subset_groups.set_width(1.0) subset_groups.set_color(BLUE_B) self.play(FadeIn(poly, DOWN)) self.wait() rects = VGroup() for ssg, sep in zip(subset_groups, seps[:-1]): coef = poly[poly.submobjects.index(sep) + 1] ssg.arrange(DOWN, buff=SMALL_BUFF) ssg.next_to(coef, DOWN, buff=MED_LARGE_BUFF) rect = SurroundingRectangle(coef, buff=0.1) rect.round_corners() rect.set_stroke(BLUE, 1) rects.add(rect) coef.set_color(BLUE_B) self.add(rect, ssg) self.play(ShowIncreasingSubsets( ssg, int_func=np.ceil, run_time=max(0.5, 0.1 * len(ssg)), rate_func=linear, )) self.wait(0.5) self.remove(rect) # Fibbonacci poly fib_poly = OldTex( "F(x) = 0+1 x^{1}+1 x^{2}+2 x^{3}+3 x^{4}+" "5 x^{5}+ 8 x^{6} + 13 x^{7}+21 x^{8}+\\cdots", isolate=["=", "+", "x"] ) globals().update(locals()) coefs = VGroup(*( fib_poly[fib_poly.submobjects.index(sep) + 1] for sep in (fib_poly.get_part_by_tex("="), *fib_poly.get_parts_by_tex("+")) )) coefs.set_color(RED) fib_poly.match_width(poly) fib_poly.move_to(poly) fib_name = Text("Fibonacci numbers") fib_name.match_color(coefs) fib_name.next_to(fib_poly, DOWN, LARGE_BUFF) coefs.set_opacity(0) self.play( FadeOut(poly, DOWN), FadeIn(fib_poly, DOWN), LaggedStartMap(FadeOut, subset_groups, shift=DOWN), Write(fib_name), ) coefs.set_opacity(1) self.play(FadeIn(coefs, lag_ratio=0.5, run_time=3)) self.wait() # Show Fibbonaci property prop = Tex("f_{n} = f_{n - 1} + f_{n - 2}") func_prop1 = Tex("F(x) = xF(x) + x^2 F(x) + x") func_prop2 = Tex("F(x) = \\frac{x}{1 - x - x^2}") arrow = Tex("\\Updownarrow") prop.next_to(fib_poly, DOWN, LARGE_BUFF) prop.shift(3 * RIGHT) arrow.next_to(prop, DOWN) func_prop1.next_to(arrow, DOWN) func_prop2.next_to(func_prop1, DOWN, MED_LARGE_BUFF) def get_coef_arrows(n): return VGroup(*( Arrow( coefs[i].get_top(), coefs[n + 2].get_top(), path_arc=-75 * DEGREES, stroke_color=RED, stroke_width=3, ) for i in (n, n + 1) )) coef_arrows = get_coef_arrows(0) self.play( fib_name.animate.to_edge(LEFT), Write(prop), ShowCreation(coef_arrows, lag_ratio=0.5, run_time=1.5), ) self.wait() for n in range(1, 7): new_arrows = get_coef_arrows(n) self.play( FadeOut(coef_arrows), ShowCreation(new_arrows, lag_ratio=0.5) ) coef_arrows = new_arrows self.play( Write(arrow), Write(func_prop1), ) self.wait() self.play( TransformMatchingShapes(func_prop1.copy(), func_prop2) ) self.wait() # Show details left_group = VGroup(prop, arrow, func_prop1, func_prop2) details_box = Rectangle(7, 4.5) details_box.set_fill(GREY_E, 1) details_box.set_stroke(WHITE, 1) details_box.to_corner(DR) details_title = Text("Gritty details for the curious...", font_size=36) details_title.next_to(details_box.get_top(), DOWN, SMALL_BUFF) details_box.add(details_title) func_prop2.generate_target() func_prop2.target.scale(0.5) func_prop2.target.next_to(details_title, DOWN, MED_LARGE_BUFF).align_to(details_box, LEFT).shift(SMALL_BUFF * RIGHT) rhs = Tex( " = {x \\over (1 - \\varphi x)(1 + \\frac{1}{\\varphi} x)}" "= {1 / \\sqrt{5} \\over (1 - \\varphi x)} - {1 / \\sqrt{5} \\over (1 + \\frac{1}{\\varphi}x)}", font_size=24, ) rhs.next_to(func_prop2.target, RIGHT, SMALL_BUFF, submobject_to_align=rhs[0]) expansion = Tex( "\\frac{1}{\\sqrt{5}}\\sum_{n = 0}^\\infty \\varphi^n x^n - " "\\frac{1}{\\sqrt{5}}\\sum_{n = 0}^\\infty \\left({-1 \\over \\varphi}\\right)^n x^n", font_size=24 ) expansion.next_to(rhs, DOWN, MED_LARGE_BUFF) expansion.match_x(details_box) implication = Tex( "\\Rightarrow f_n = {\\varphi^n - (-1 / \\varphi)^n \\over \\sqrt{5}}", font_size=24, ) implication.next_to(expansion, DOWN, MED_LARGE_BUFF) self.play( left_group.animate.to_edge(LEFT), FadeOut(fib_name, LEFT), FadeIn(details_box, LEFT, time_range=(0.5, 1.5)) ) self.play(MoveToTarget(func_prop2)) self.play(Write(rhs)) self.play(FadeIn(expansion, DOWN)) self.play(FadeIn(implication, DOWN)) self.wait() class WideGraph(InteractiveScene): def construct(self): # Start def func(x, n=10): return np.product([1 + x**n for n in range(1, n + 1)]) plane = NumberPlane( x_range=(-1, 1, 1), y_range=(0, 10, 1), width=FRAME_WIDTH - 1, height=6, background_line_style={"stroke_width": 1.5}, faded_line_ratio=10, ) plane.to_edge(DOWN) graph = plane.get_graph(func, (-1, 0.75)) graph.set_stroke(YELLOW, 2) graph_label = OldTex("f(x)") graph_label.set_color(YELLOW) graph_label.next_to(plane.i2gp(0.73, graph), LEFT) graph_label.set_backstroke() x_tracker = ValueTracker(0.75) dot = GlowDot(color=WHITE) globals().update(locals()) dot.add_updater(lambda d: d.move_to(plane.i2gp(x_tracker.get_value(), graph))) self.add(plane, graph, graph_label, dot) self.add(x_tracker) self.play(x_tracker.animate.set_value(0), run_time=3) self.wait() class EvaluationTricks(InteractiveScene): def construct(self): # Setup function def func(x, n=10): return np.product([1 + x**n for n in range(1, n + 1)]) plane = NumberPlane( (-1, 1), (-10, 10, 5), width=10, faded_line_ratio=4, ) plane.set_height(FRAME_HEIGHT) plane.to_edge(LEFT, buff=0) plane.add_coordinate_labels(x_values=[-1, 1], y_values=range(-10, 15, 5)) for cl in plane.x_axis.numbers: cl.shift_onto_screen(buff=SMALL_BUFF) graph = plane.get_graph(func, x_range=(-1, 1, 0.05)) graph.set_stroke(YELLOW, 2) self.disable_interaction(plane) tex_kw = dict(tex_to_color_map={"x": BLUE}) factored = Tex("f(x) = (1 + x)(1 + x^2)(1 + x^3) \\cdots (1 + x^{2{,}000})", **tex_kw) factored.to_corner(UR) expanded = VGroup( Tex("f(x) = ", **tex_kw), Tex("\\sum_{n = 0}^{N} c_n x^n", **tex_kw), # Tex("= 1+x+x^{2}+2 x^{3}+2 x^{4}+ \\cdots", **tex_kw) Tex("= c_0 + c_1 x + c_2 x^{2} + c_3 x^{3} + \\cdots", **tex_kw) ) expanded.arrange(RIGHT, buff=0.2) expanded.next_to(factored, DOWN, LARGE_BUFF, LEFT) factored_label = Text("What we know", color=TEAL_B) expanded_label = Text("What we want", color=TEAL_C) for label, expr in [(factored_label, factored), (expanded_label, expanded)]: label.next_to(expr, LEFT, LARGE_BUFF) expr.arrow = Arrow(label, expr) self.add(factored) self.play( Write(factored_label), ShowCreation(factored.arrow), ) self.wait() self.play(FadeTransform(factored.copy(), expanded)) self.play( Write(expanded_label), ShowCreation(expanded.arrow), ) self.wait() # Black box lhs = expanded[0] rhs = expanded[2] box = SurroundingRectangle(rhs[1:]) box.set_stroke(WHITE, 1) box.set_fill(GREY_E, 1) q_marks = Tex("?").get_grid(1, 7, buff=0.7) q_marks.move_to(box) box.add(q_marks) self.play(FadeIn(box, lag_ratio=0.25, run_time=2)) self.wait() # Show example evaluations x_tracker = ValueTracker(0.5) get_x = x_tracker.get_value dot = GlowDot(color=WHITE) dot.add_updater(lambda m: m.move_to(plane.i2gp(get_x(), graph))) line = Line(DOWN, UP).set_stroke(WHITE, 1) line.add_updater(lambda l: l.put_start_and_end_on( plane.c2p(get_x(), 0), plane.i2gp(get_x(), graph) )) self.play( Write(plane, lag_ratio=0.01), LaggedStartMap(FadeOut, VGroup(factored_label, expanded_label, factored.arrow, expanded.arrow)), ) self.play(ShowCreation(graph)) self.wait() self.play( ShowCreation(line), FadeInFromPoint(dot, line.get_start()), ) self.play(x_tracker.animate.set_value(-0.5), run_time=2) self.play(x_tracker.animate.set_value(0.7), run_time=2) self.wait() # Plug in 0 f0 = Tex("f(0) = 1", tex_to_color_map={"0": BLUE}) f0[-1].set_opacity(0) f0.next_to(expanded, DOWN, LARGE_BUFF, aligned_edge=LEFT) c0_rhs = Tex("= c_0") c0_rhs.next_to(f0, RIGHT) c0_rhs.shift(0.05 * DOWN) self.play(FadeTransform(lhs.copy(), f0)) self.play(x_tracker.animate.set_value(0)) self.wait(note="Move box out of the way") f0.set_opacity(1) self.play(Write(f0[-1])) self.add(f0) self.wait() self.play(Write(c0_rhs)) f0.add(c0_rhs) # Take derivative at 0 dkw = dict(tex_to_color_map={"0": BLUE}) f_prime_0 = Tex("f'(0) = c_1", **dkw) f_prime_n = Tex("\\frac{1}{n!} f^{(n)}(0) = c_n", **dkw) f_prime_0.next_to(f0, RIGHT, buff=1.5) f_prime_n.next_to(f_prime_0, DOWN, MED_LARGE_BUFF, LEFT) tan_line = plane.get_graph(lambda x: x + 1) tan_line.set_stroke(PINK, 2, 0.8) self.play(FadeTransform(f0.copy(), f_prime_0)) self.add(tan_line, dot) self.play(ShowCreation(tan_line)) self.wait(note="Comment on derivative") self.play(FadeTransform(f_prime_0.copy(), f_prime_n)) self.wait(note="Comment on this being a nightmare") crosses = VGroup(*map(Cross, (f_prime_0, f_prime_n))) crosses.insert_n_curves(20) self.play(ShowCreation(crosses)) self.wait() self.play(LaggedStartMap(FadeOut, VGroup(f_prime_0, f_prime_n, *crosses))) # Plug in 1 f1 = Tex( "f({1}) \\,=\\, 2^{2{,}000} \\,=\\, c_0 + c_1 + c_2 + c_3 + \\cdots + c_N", tex_to_color_map={ "2^{2{,}000}": TEAL, "{1}": BLUE, "=": WHITE, } ) f1.move_to(f0, LEFT) self.play( TransformFromCopy(factored[:5], f1[:5]), f0.animate.shift(2 * DOWN), ) self.wait() self.play( Write(f1[5:11]), x_tracker.animate.set_value(1) ) self.wait(note="Comment on factored form") self.play(Write(f1[11:])) self.add(f1) # Plug in -1 fm1 = self.load_mobject("f_of_neg1.mob") # fm1 = Tex( # "f({-1}) \\,=\\, {0} \\,=\\," # "c_0 - c_1 + c_2 - c_3 + \\cdots + c_N", # tex_to_color_map={ # "{-1}": RED, # "{0}": TEAL, # "=": WHITE, # } # ) fm1.next_to(f1, DOWN, LARGE_BUFF, LEFT) self.play( TransformMatchingShapes(f1[:5].copy(), fm1[:5]), FadeOut(f0, DOWN) ) self.wait() self.play( Write(fm1[5:7]), ApplyMethod(x_tracker.set_value, -1, run_time=3) ) self.wait() self.play(Write(fm1[7:])) self.wait() # Show filtration expression f1_group = VGroup(f1, fm1) self.play( FadeOut(expanded), FadeOut(box), f1_group.animate.move_to(expanded, UL), ) h_line = Line(LEFT, RIGHT).match_width(f1_group) h_line.set_stroke(GREY_B, 3) h_line.next_to(f1_group, DOWN, MED_LARGE_BUFF) h_line.stretch(1.05, 0, about_edge=LEFT) filter_expr = Tex( "{1 \\over 2} \\Big(f({1}) + f({-1})\\Big)" "= c_0 + c_2 + c_4 + \\cdots + c_{N}", tex_to_color_map={ "{1}": BLUE, "{-1}": RED, } ) filter_expr.next_to(h_line, DOWN, MED_LARGE_BUFF) filter_expr.align_to(f1_group, LEFT) self.play( ShowCreation(h_line), TransformFromCopy(f1[:4], filter_expr[4:8]), TransformFromCopy(fm1[:4], filter_expr[9:14]), Write(filter_expr[:4]), Write(filter_expr[8]), Write(filter_expr[14:16]), ) self.wait() self.play(Write(filter_expr[16:])) self.wait() # Clarify goal parens = Tex("()") words = OldTexText("Some clever\\\\evaluation of $f$", font_size=36) words.set_color(WHITE) parens.match_height(words) parens[0].next_to(words, LEFT, buff=SMALL_BUFF) parens[1].next_to(words, RIGHT, buff=SMALL_BUFF) desire = VGroup( VGroup(parens, words), Tex("= c_0 + c_5 + c_{10} + \\cdots + c_{N}") ) desire.arrange(RIGHT) desire.next_to(expanded, DOWN, 1.0, LEFT) self.play( FadeIn(expanded), FadeOut(f1_group, DOWN), Uncreate(h_line), filter_expr.animate.to_edge(DOWN), ) self.wait() self.play( FadeIn(desire, DOWN), ) self.wait() # Show random values of f self.play( x_tracker.animate.set_value(0.5), FadeOut(tan_line), ) self.wait(0.5) for n in range(8): self.play( x_tracker.animate.set_value(random.uniform(-1, 1)), run_time=0.5, ) self.wait(0.5) self.play(FadeOut(dot), FadeOut(line)) # Indicator on x^n new_rhs = expanded[1] rect = SurroundingRectangle(new_rhs.get_part_by_tex("x^n"), buff=0.05) rect.set_stroke(BLUE_B, 2) rect.round_corners() outcomes = VGroup( OldTexText("$1$ if $\\; 5 \\mid n$", font_size=36, color=GREEN), OldTexText("$0$ if $\\; 5 \\nmid n$", font_size=36, color=RED_D), ) outcomes.arrange(DOWN, buff=0.75, aligned_edge=LEFT) outcomes.next_to(new_rhs, RIGHT, 1.5, UP) arrows = VGroup(*( Arrow( rect.get_right(), outcome.get_left(), buff=0.25, color=outcome.get_color(), stroke_width=2.0 ) for outcome in outcomes )) self.play( ShowCreation(rect), FadeOut(expanded[2]), ) self.wait(0.25) for arrow, outcome in zip(arrows, outcomes): self.play( ShowCreation(arrow), GrowFromPoint(outcome, rect.get_right()) ) self.wait() class MotivateRootsOfUnity(InteractiveScene): def construct(self): # Add generating function pieces = ["f(x)", "="] n_range = list(range(0, 7)) for n in n_range: pieces.extend([f"c_{{{n}}}", f"x^{{{n}}}", "+"]) pieces.extend(["\\cdots"]) polynomial = OldTex("".join(pieces), isolate=pieces) polynomial.to_edge(UP) exp_parts = VGroup(*( polynomial.get_part_by_tex(f"x^{{{n}}}") for n in n_range )) self.add(polynomial) # Add f(-1) m1_pieces = [ p.replace("(x)", "x").replace("x", "\\left(-1\\right)") for p in pieces ] fm1 = OldTex("".join(m1_pieces), isolate=pieces) fm1.set_color_by_tex("-1", GREY_B) fm1[0].set_color(WHITE) fm1[0][2:4].set_color(GREY_B) fm1.next_to(polynomial, DOWN, MED_LARGE_BUFF) fm1.set_width(polynomial.get_width() + 1.0) fm1_powers = fm1[3::3] # fm1_coefs = fm1[2::3] short_fm1 = Tex( "f({-1}) = c_0 - c_1 + c_2 - c_3 + c_4 - c_5 + c_6 - c_7 + c_8 - \\cdots", tex_to_color_map={"{-1}": GREY_B} ) short_fm1.scale(fm1[0].get_height() / short_fm1[:5].get_height()) short_fm1.next_to(fm1, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) # Real number line line = NumberLine((-4, 4), unit_size=2) line.move_to(2 * DOWN) line.add_numbers() morty = Mortimer(height=1.5) morty.next_to(line, UP, SMALL_BUFF).to_edge(RIGHT, buff=1.5) self.play( Transform(polynomial.copy(), fm1, lag_ratio=0.01, run_time=2, remover=True), Write(line), PiCreatureSays( morty, OldTexText("Visualize the\\\\rotations", font_size=36), bubble_config=dict(width=3, height=2) ), ) self.add(fm1) self.play(Blink(morty)) self.wait() self.play( morty.change("pondering", fm1).shift(UP), line.animate.shift(UP), FadeOut(VGroup(morty.bubble, morty.bubble.content), 0.5 * UP), ) # Show oscillation v1 = Arrow(line.n2p(0), line.n2p(1), buff=0, color=BLUE) vm1 = Arrow(line.n2p(0), line.n2p(-1), buff=0, color=RED) vect = v1.copy() neg1_powers = [ Tex(f"(-1)^{{{n}}}") for n in range(8) ] for n, neg1_power in enumerate(neg1_powers): v = [v1, vm1][n % 2] neg1_power.next_to(v, UP) power = neg1_powers[0].copy() for n in range(7): self.play( FlashAround(fm1_powers[n]), fm1_powers[n].animate.set_color([BLUE, RED][n % 2]) ) if n == 0: self.play( FadeTransform(fm1_powers[n].copy(), vect), FadeTransform(fm1_powers[n].copy(), power), morty.change("surprised").shift(2 * RIGHT).set_opacity(0), ) self.remove(morty) else: self.play( Transform(vect, [v1, vm1][n % 2], path_arc=PI), Transform(power, neg1_powers[n], path_arc=PI / 2), ) self.wait() self.play( Write(fm1[-2:]), FadeOut(power), ) self.wait() self.play(FadeIn(short_fm1, lag_ratio=0.5, run_time=2)) self.wait() # Bring in complex plane plane_unit = 1.75 plane = ComplexPlane( (-3, 3), (-2, 2), axis_config=dict(unit_size=plane_unit) ) plane.move_to(line.n2p(0) - plane.n2p(0)) plane.add_coordinate_labels(font_size=24) plane_label = Text("Complex plane", font_size=36) plane_label.set_backstroke() plane_label.next_to(plane.get_corner(UL), DR, SMALL_BUFF) self.add(plane, polynomial, vect) sf = plane_unit / line.get_unit_size() self.play( Write(plane, lag_ratio=0.01), FadeOut(fm1), FadeOut(short_fm1), line.animate.scale(sf).set_opacity(0), vect.animate.set_color(YELLOW).scale(sf, about_edge=LEFT), ) self.remove(line) self.play(Write(plane_label)) self.wait() # Preview roots of unity unit_circle = Circle(radius=plane_unit) unit_circle.move_to(plane.n2p(0)) unit_circle.set_stroke(GREY, 2) points = [ plane.n2p(np.exp(complex(0, angle))) for angle in np.arange(0, TAU, TAU / 5) ] dots = GlowDots(points) pentagon = Polygon(*points) pentagon.set_stroke(TEAL, 1) pentagon.set_fill(TEAL, 0.25) pentagon.save_state() pentagon.set_opacity(0) self.add(pentagon, unit_circle, vect, dots) self.play( ShowCreation(unit_circle), ShowCreation(dots) ) self.wait() self.play(pentagon.animate.restore()) self.wait() last_rect = VMobject() for n in range(14): if n == 0: continue if n < len(exp_parts): exp_part = exp_parts[n] else: exp_part = polynomial[-3:] rect = SurroundingRectangle(exp_part, buff=0.05) rect.round_corners() rect.set_stroke(YELLOW, 2) self.play( FadeOut(last_rect), ShowCreation(rect), ApplyMethod( vect.put_start_and_end_on, plane.n2p(0), points[n % 5], path_arc=TAU / 5, ) ) last_rect = rect self.wait() class FifthRootsOfUnity(InteractiveScene): def construct(self): # Setup plane plane = ComplexPlane((-2, 2), (-2, 2)) plane.set_height(FRAME_HEIGHT - 0.5) plane.add_coordinate_labels(font_size=24) for coord in plane.coordinate_labels: coord.shift_onto_screen(buff=SMALL_BUFF) coord.set_fill(WHITE) plane.to_edge(LEFT, buff=0.1) self.disable_interaction(plane) unit_circle = Circle(radius=plane.x_axis.get_unit_size()) unit_circle.move_to(plane.get_origin()) unit_circle.set_stroke(GREY_C, 2) self.disable_interaction(unit_circle) complex_plane_title = Text("Complex plane", font_size=42) complex_plane_title.next_to(plane.get_corner(UL), DR, buff=SMALL_BUFF) complex_plane_title.set_backstroke(width=8) self.add(plane) self.add(unit_circle) self.add(complex_plane_title) # Setup roots roots = [np.exp(complex(0, n * TAU / 5)) for n in range(5)] root_points = list(map(plane.n2p, roots)) root_dots = Group(*( GlowDot(point) for point in root_points )) root_lines = VGroup(*( Arrow( plane.get_origin(), point, buff=0, stroke_width=2, stroke_color=YELLOW, stroke_opacity=0.7 ) for point in root_points )) self.disable_interaction(root_dots) pentagon = Polygon(*root_points) pentagon.set_stroke(TEAL, 2) pentagon.set_fill(TEAL, 0.25) self.add(pentagon) # Add function label function = Tex( "f(x) = \\sum_{n = 0}^N c_n x^n", tex_to_color_map={"x": BLUE} ) function.move_to(midpoint(plane.get_right(), RIGHT_SIDE)) function.to_edge(UP, buff=MED_SMALL_BUFF) self.add(function) # Roots of unity arc = Arc(0, TAU / 5, radius=0.2, arc_center=plane.get_origin()) arc.set_stroke(WHITE, 2) arc_label = Tex("2\\pi / 5", font_size=24) arc_label.next_to(arc.pfp(0.5), UR, buff=SMALL_BUFF) arc_label.set_color(GREY_A) root_kw = dict( tex_to_color_map={"\\zeta": YELLOW}, isolate=["\\cos(72^\\circ)", "\\sin(72^\\circ)"], font_size=36, ) zeta_labels = VGroup( Tex("\\zeta^0 = 1", **root_kw), Tex("\\zeta", **root_kw), Tex("\\zeta^2", **root_kw), Tex("\\zeta^3", **root_kw), Tex("\\zeta^4", **root_kw), ) zeta_labels.set_backstroke(width=4) for point, label in zip(root_points, zeta_labels): vect = normalize(point - plane.get_origin()) if point is root_points[0]: vect = UR label.next_to(point, vect, buff=SMALL_BUFF) exp_rhs = Tex(" = e^{2\\pi i / 5}", **root_kw) trig_rhs = Tex("= \\cos(72^\\circ) + i\\cdot \\sin(72^\\circ)", **root_kw) last = zeta_labels[1] for rhs in exp_rhs, trig_rhs: rhs.set_backstroke(width=4) rhs.next_to(last, RIGHT, SMALL_BUFF) last = rhs exp_rhs.shift((trig_rhs[0].get_y() - exp_rhs[0].get_y()) * UP) self.play( FadeInFromPoint( root_dots[1], plane.n2p(1), path_arc=TAU / 5, ), pentagon.animate.set_fill(opacity=0.1) ) self.play(Write(zeta_labels[1])) self.wait() self.play( ShowCreation(arc), Write(arc_label), TransformFromCopy(root_lines[0], root_lines[1], path_arc=-TAU / 5) ) self.wait() self.play(Write(exp_rhs)) self.wait() # Show trig x_line = Line(plane.n2p(0), plane.n2p(math.cos(TAU / 5))) y_line = Line(plane.n2p(math.cos(TAU / 5)), plane.n2p(np.exp(complex(0, TAU / 5)))) x_line.set_stroke(RED, 2) y_line.set_stroke(PINK, 2) low_cos = Tex("\\cos(72^\\circ)", font_size=24) low_sin = Tex("\\sin(72^\\circ)", font_size=24) low_cos.next_to(x_line, DOWN, SMALL_BUFF, aligned_edge=LEFT) low_cos.shift(SMALL_BUFF * RIGHT) low_sin.next_to(y_line, RIGHT, SMALL_BUFF) VGroup(low_cos, low_sin).set_backstroke(BLACK) self.play(Write(trig_rhs)) self.wait() self.play( TransformFromCopy(trig_rhs.select_part("\\cos(72^\\circ)"), low_cos), ShowCreation(x_line), FadeOut(arc_label) ) self.wait() self.play( TransformFromCopy(trig_rhs.select_part("\\sin(72^\\circ)"), low_sin), ShowCreation(y_line), ) self.wait() self.play(LaggedStartMap(FadeOut, VGroup( trig_rhs, x_line, low_cos, y_line, low_sin ))) # Show all roots of unity for i in range(2, 6): self.play(*( TransformFromCopy(group[i - 1], group[i % 5], path_arc=-TAU / 5) for group in [root_lines, root_dots, zeta_labels] )) self.wait() # Name the roots of unity title = OldTexText("``Fifth roots of unity''") title.set_color(YELLOW) title.match_y(plane) title.match_x(function) equation = OldTex("z^5 = 1") equation.set_color(WHITE) equation.next_to(title, DOWN) self.play( Write(title), LaggedStart(*( FlashAround(zl, time_width=1.5) for zl in zeta_labels ), lag_ratio=0.1, run_time=3) ) self.wait() self.play(FadeIn(equation, 0.5 * DOWN)) self.wait() self.play( LaggedStartMap(FadeOut, VGroup(title, equation), shift=DOWN), FadeOut(VGroup(arc, arc_label)), ) # Key expression expr = Tex("+".join([f"f(\\zeta^{{{n}}})" for n in range(5)]), **root_kw) expr.next_to(function, DOWN, LARGE_BUFF) self.play( TransformMatchingShapes(function[:4].copy(), expr, run_time=1.5), FadeOut(pentagon), ) self.wait() # Examples, f(x) = x, f(x) = x^2, etc. ex_kw = dict(tex_to_color_map={"{x}": BLUE}, font_size=36) example_texts = [ Tex( "\\text{Example: } f({x}) = {x}" + ("^" + str(n) if n > 1 else ""), **ex_kw ) for n in range(1, 6) ] example_sums = [ Tex( "+".join([f"\\zeta^{{{k * n}}}" for n in range(5)]) + ("=5" if k == 5 else "=0"), **root_kw ) for k in range(1, 6) ] def update_root_lines(rl): for line, dot in zip(rl, root_dots): line.put_start_and_end_on(plane.get_center(), dot.get_center()) return rl root_lines.add_updater(update_root_lines) for k, ex_text, ex_sum in zip(it.count(1), example_texts, example_sums): ex_text.next_to(expr, DOWN, LARGE_BUFF) ex_sum.next_to(ex_text, DOWN, LARGE_BUFF) if k == 1: self.play(Write(ex_text)) self.wait() self.play(FadeTransform(expr.copy(), ex_sum)) root_lines.save_state() self.wait(note="Move root vectors tip to tail (next animation they restore)") self.play(root_lines.animate.restore()) self.wait() else: self.play( FadeOut(example_texts[k - 2], 0.5 * UP), FadeIn(ex_text, 0.5 * UP), FadeOut(example_sums[k - 2]) ) self.wait() self.play(FadeTransform(expr.copy(), ex_sum)) self.wait() # Show permutation arrows = VGroup(*( Arrow(root_dots[n], root_dots[(k * n) % 5], buff=0, stroke_width=3) for n in range(1, 5) )) arrows.set_opacity(0.8) for arrow in arrows: self.play(ShowCreation(arrow)) self.wait() self.play(FadeOut(arrows)) # Animate kth power self.animate_kth_power( plane, root_dots, k, ) self.wait() # Emphasize the upshot example = VGroup(example_texts[-1], example_sums[-1]) example.generate_target() example.target.arrange(DOWN) example.target.match_x(expr) example.target.to_edge(DOWN) brace = Brace(expr, DOWN, color=GREY_B) func_kw = dict(tex_to_color_map={"x": BLUE}) relations = VGroup( Tex("x^n \\rightarrow 0 \\qquad \\text{ if } 5 \\nmid n", **func_kw), Tex("x^n \\rightarrow 5 \\qquad \\text{ if } 5 \\mid n", **func_kw), ) relations.arrange(DOWN) relations.next_to(brace, DOWN) self.play( GrowFromCenter(brace), MoveToTarget(example) ) for relation in relations: self.play(Write(relation)) self.wait() # Write answer expression relation_group = VGroup(expr, brace, relations) answer = Tex( "c_0 + c_5 + c_{10} + \\cdots" "=\\frac{1}{5}\\sum_{k = 0}^4 f(\\zeta^k)", tex_to_color_map={"\\zeta": YELLOW} ) answer.set_width(5) answer.next_to(function, DOWN, LARGE_BUFF) answer_rect = SurroundingRectangle(answer, buff=0.2) answer_rect.round_corners() answer_rect.set_stroke(YELLOW, 2) self.disable_interaction(answer_rect) self.play( FadeOut(example, DOWN), relation_group.animate.set_width(4.5).to_edge(DOWN), Write(answer) ) self.play( VShowPassingFlash(answer_rect.copy()), FadeIn(answer_rect) ) self.add(answer_rect, answer) self.wait() # Bring back original definition factored = Tex( "f(x) = (1 + x)(1 + x^2)(1 + x^3)(1 + x^4)(1 + x^5)\\cdots\\left(1 + x^{2{,}000}\\right)", **func_kw ) factored.to_edge(UP) lower_group = VGroup( VGroup(answer_rect, answer), relation_group, ) lower_group.generate_target() lower_group.target.arrange(RIGHT, buff=MED_LARGE_BUFF) lower_group.target.set_width(8.5) lower_group.target.to_corner(DR) plane_group = Group( plane, unit_circle, root_lines, root_dots, zeta_labels, exp_rhs, complex_plane_title ) plane_group.generate_target() plane_group.target.set_height(4.5, about_edge=DL) self.play( Write(factored), function.animate.next_to(factored, DOWN, buff=0.4, aligned_edge=LEFT), MoveToTarget(lower_group), MoveToTarget(plane_group), ) self.wait() # Evaluate f at zeta eq_kw = dict( tex_to_color_map={"\\zeta": YELLOW, "{z}": GREY_A}, ) f_zeta = Tex( "f(\\zeta) = \\Big(" "(1+\\zeta)(1+\\zeta^{2})(1+\\zeta^{3})(1+\\zeta^{4})(1+\\zeta^{5})" "\\Big)^{400}", **eq_kw ) f_zeta.next_to(factored, DOWN, aligned_edge=LEFT) expr_copy = expr.copy() expr_copy.generate_target() expr_copy.target.scale(2).next_to(plane, RIGHT, LARGE_BUFF, UP) fz1 = expr_copy.target[6:11] fz1_rect = SurroundingRectangle(fz1, buff=SMALL_BUFF).round_corners() fz1_rect.set_stroke(TEAL, 2) want_label = Text("What we want") want_label.next_to(expr_copy.target, DOWN, MED_LARGE_BUFF) self.play(LaggedStart(MoveToTarget(expr_copy), Write(want_label))) self.wait() self.play(ShowCreation(fz1_rect)) self.play( TransformFromCopy(fz1, f_zeta[:5]), FadeOut(function, DOWN) ) self.wait() self.play(*map(FadeOut, [expr_copy, fz1_rect, want_label])) for i, n in zip([5, 10, 16, 22, 28], it.chain([5], it.cycle([6]))): self.play(TransformFromCopy(factored[i:i + n], f_zeta[i + 1:i + n + 1])) self.wait() self.play(Write(f_zeta[5]), Write(f_zeta[35:])) self.wait(note="Shift zeta values on next move") # Visualize roots moving shift_vect = plane.n2p(1) - plane.n2p(0) zp1_labels = VGroup(*( Tex(f"\\zeta^{{{n}}} + 1", **root_kw) for n in range(5) )) zp1_labels.match_height(zeta_labels[0]) for zp1_label, z_label in zip(zp1_labels, zeta_labels): zp1_label.set_backstroke(width=5) zp1_label.move_to(z_label, DL) zp1_label.shift(shift_vect) zp1_labels[0].next_to(root_dots[0].get_center() + shift_vect, UL, SMALL_BUFF) new_circle = unit_circle.copy() new_circle.set_stroke(GREY_B, opacity=0.5) self.disable_interaction(new_circle) self.replace(unit_circle, unit_circle, new_circle) self.remove(zeta_labels) self.play( root_dots.animate.shift(shift_vect), new_circle.animate.shift(shift_vect), TransformFromCopy(zeta_labels, zp1_labels), FadeOut(exp_rhs), run_time=2, ) self.wait() # Estimate answer faders = VGroup(lower_group, f_zeta[:6], f_zeta[-4:], factored) faders.save_state() estimate = Tex( "= 2 \\cdot L_1^2 \\cdot L_2^2", isolate=["= 2", "\\cdot L_1^2", "\\cdot L_2^2"], **eq_kw ) roughly_two = Tex("\\approx 2") estimate.next_to(plane, RIGHT, buff=1.5, aligned_edge=UP) roughly_two.next_to(estimate, DOWN, MED_LARGE_BUFF, LEFT) L1_label = Tex("L_1", font_size=24) L2_label = Tex("L_2", font_size=24) L1_label.next_to(root_lines[1].pfp(0.75), DR, buff=0.05) L2_label.next_to(root_lines[2].get_center(), LEFT, SMALL_BUFF) VGroup(L1_label, L2_label).set_backstroke() root_groups = Group(*( Group(*parts) for parts in zip(root_dots, root_lines, zp1_labels) )) self.wait() self.play(faders.animate.fade(0.75)) self.remove(faders) self.add(*faders) self.wait() self.play( root_groups[1:].animate.set_opacity(0.1), ) self.wait() self.play(Write(estimate.select_part("= 2"))) self.wait() self.play( root_groups[0].animate.set_opacity(0.1), root_groups[1:5:3].animate.set_opacity(1), ) self.wait() self.play(Write(L1_label)) self.wait() self.play(FadeTransform(L1_label.copy(), estimate.select_part("\\cdot L_1^2"))) self.wait() self.play( root_groups[1:5:3].animate.set_opacity(0.1), root_groups[2:4].animate.set_opacity(1), ) self.wait() self.play(Write(L2_label)) self.wait() self.play(FadeTransform(L2_label.copy(), estimate.select_part("\\cdot L_2^2"))) self.wait() self.play(root_groups.animate.set_opacity(1)) self.wait() self.play(Write(roughly_two)) self.wait() self.play( FadeOut(estimate), FadeOut(roughly_two), faders.animate.restore(), ) # Setup for the trick box = Rectangle( height=plane.get_height(), width=abs(plane.get_right()[0] - RIGHT_SIDE[0]) - 1, ) box.set_stroke(WHITE, 1) box.set_fill(GREY_E, 1) box.next_to(plane, RIGHT, buff=0.5) self.disable_interaction(box) trick_title = Text("The trick") trick_title.next_to(box.get_top(), DOWN, SMALL_BUFF) subsets = get_subsets(range(1, 6)) binom_pairs = [ (f_zeta[i], f_zeta[j:k]) for i, j, k in [(7, 9, 10), (12, 14, 16), (18, 20, 22), (24, 26, 28), (30, 32, 34)] ] rect_groups = VGroup(*( VGroup(*( SurroundingRectangle(bp[int(n + 1 in ss)], buff=SMALL_BUFF).round_corners().set_stroke(TEAL, 2) for n, bp in enumerate(binom_pairs) )) for ss in subsets )) terms = VGroup(*( Tex(f"\\zeta^{{{sum(ss)}}}") for ss in subsets )) terms.arrange_in_grid(4, 8, buff=MED_LARGE_BUFF) terms.set_width(7) terms.next_to(plane, RIGHT, LARGE_BUFF, UP) for term in terms: term[0].set_color(YELLOW) plus = Tex("+", font_size=36) plus.next_to(term, RIGHT, buff=(0.15 if term in terms[:25] else 0.05)) term.add(plus) terms[-1].remove(terms[-1][-1]) term_rects = VGroup(*( SurroundingRectangle(term).round_corners().set_stroke(TEAL, 2) for term in terms )) self.play(FadeOut(lower_group, DOWN)) self.play( ShowSubmobjectsOneByOne(rect_groups, int_func=np.ceil), ShowSubmobjectsOneByOne(term_rects, int_func=np.ceil), ShowIncreasingSubsets(terms, int_func=np.ceil), run_time=8, rate_func=linear, ) self.play(FadeOut(rect_groups[-1]), FadeOut(term_rects[-1])) self.wait() self.play( FadeOut(terms, DOWN), Write(box), Write(trick_title), ) self.wait() # The trick root_kw["tex_to_color_map"]["{z}"] = GREY_A root_kw["tex_to_color_map"]["{-1}"] = GREY_A root_kw["tex_to_color_map"]["="] = WHITE texs = [ "{z}^5 - 1 = ({z} - \\zeta^0)({z} - \\zeta^1)({z} - \\zeta^2)({z} - \\zeta^3)({z} - \\zeta^4)", "({-1})^5 - 1 = ({-1} - \\zeta^0)({-1} - \\zeta^1)({-1} - \\zeta^2)({-1} - \\zeta^3)({-1} - \\zeta^4)", "2 = (1 + \\zeta^0)(1 + \\zeta^1)(1 + \\zeta^2)(1 + \\zeta^3)(1 + \\zeta^4)", ] equations = VGroup(*(Tex(tex, **root_kw) for tex in texs)) equations[1].set_width(box.get_width() - 0.5) equations.arrange(DOWN, buff=0.75) equals_x = equations[0].get_part_by_tex("=").get_x() for eq in equations[1:]: eq.shift((equals_x - eq.get_part_by_tex("=").get_x()) * RIGHT) equations.next_to(trick_title, DOWN, MED_LARGE_BUFF) self.play(Write(equations[0])) self.wait() self.play(FadeTransform(equations[0].copy(), equations[1])) self.wait() self.play(FadeTransform(equations[1].copy(), equations[2])) self.wait() # Show value of 2 brace = Brace(f_zeta[6:35], DOWN).set_color(WHITE) brace.stretch(0.75, 1, about_edge=UP) two_label = brace.get_tex("2").set_color(WHITE) self.play(GrowFromCenter(brace)) self.play(TransformFromCopy(equations[2][0], two_label)) self.wait() self.play(LaggedStartMap(FadeOut, VGroup(box, trick_title, *equations))) self.play(FadeIn(lower_group)) self.wait() # Evaluate answer ans_group, expr_group = lower_group self.play( ans_group.animate.scale(0.5, about_edge=UL), expr_group.animate.scale(1.5, about_edge=DR), ) self.wait() parts = [expr.get_part_by_tex(f"f(\\zeta^{{{n}}})") for n in range(5)] arrows = VGroup(*( Vector(0.5 * UP).next_to(part, UP, SMALL_BUFF) for part in parts )) values = VGroup( Tex("2^{2{,}000}", font_size=36), *(Tex("2^{400}", font_size=36) for x in range(4)) ) for value, arrow in zip(values, arrows): value.next_to(arrow, UP, SMALL_BUFF) self.play( ShowCreation(arrows[1]), FadeIn(values[1], 0.5 * UP) ) self.wait() self.play( LaggedStartMap(ShowCreation, arrows[2:], lag_ratio=0.5), LaggedStartMap(FadeIn, values[2:], shift=0.5 * UP, lag_ratio=0.5), ) self.wait() self.play( ShowCreation(arrows[0]), FadeIn(values[0], 0.5 * UP) ) self.wait() self.remove(arrows, values) expr_group.add(*arrows, *values) # Rescale answer group plane_group = Group( plane, unit_circle, new_circle, root_lines, root_dots, zp1_labels, complex_plane_title, ) ans_group.generate_target() ans_group.target.set_width(6.5, about_edge=LEFT) ans_group.target.next_to(brace, DOWN) ans_group.target.shift(1 * LEFT) ans_group.target[0].set_stroke(opacity=0) f_zeta_rhs = OldTex("=2^{400}").set_color(WHITE) f_zeta_rhs.next_to(f_zeta, RIGHT) self.play( MoveToTarget(ans_group), expr_group.animate.scale(1 / 1.5, about_edge=DR), plane_group.animate.scale(0.7, about_edge=DL), TransformMatchingShapes(two_label, f_zeta_rhs), FadeOut(brace), run_time=2 ) self.wait() # Final answer final_answer = Tex( "= \\frac{1}{5}\\Big(" "2^{2{,}000} + 4 \\cdot 2^{400}\\Big)" ) final_answer.next_to(answer, RIGHT) final_answer_rect = SurroundingRectangle(final_answer[1:], buff=0.2) final_answer_rect.round_corners() final_answer_rect.set_stroke(YELLOW, 2) self.disable_interaction(final_answer_rect) self.play( Write(final_answer[:5]), Write(final_answer[-1]), ) self.wait() self.play( FadeTransform(values.copy(), final_answer[5:-1]) ) self.play(ShowCreation(final_answer_rect)) self.wait(note="Comment on dominant term") # Smaller case box = Rectangle( width=(RIGHT_SIDE[0] - plane.get_right()[0]) - 1, height=plane.get_height() ) box.to_corner(DR) box.align_to(plane, DOWN) box.set_stroke(WHITE, 1) box.set_fill(GREY_E, 1) set_tex = get_set_tex(range(1, 6)) set_tex.next_to(box.get_left(), RIGHT, SMALL_BUFF) rhs = Tex( "\\rightarrow \\frac{1}{5}" "\\Big(2^5 + 4 \\cdot 2^1\\Big)" "= \\frac{1}{5}(32 + 8)" "=8" ) rhs.scale(0.9) rhs.next_to(set_tex, RIGHT) self.play( FadeOut(expr_group), Write(box), Write(set_tex), ) self.wait() self.play( Write(rhs[0]), FadeTransform(final_answer.copy(), rhs[1:13]) ) self.wait() self.play(Write(rhs[13:])) self.wait() def animate_kth_power(self, plane, dots, k): # Try the rotation angles = np.angle([plane.p2n(dot.get_center()) for dot in dots]) angles = angles % TAU paths = [ ParametricCurve( lambda t: plane.n2p(np.exp(complex(0, interpolate(angle, k * angle, t)))), t_range=(0, 1, 0.01), ) for angle in angles ] dots.save_state() # pentagon.add_updater(lambda p: p.set_points_as_corners([ # d.get_center() for d in [*dots, dots[0]] # ])) self.play(*( MoveAlongPath(dot, path) for dot, path in zip(dots, paths) ), run_time=4) if k == 5: self.wait() self.play(dots.animate.restore()) else: # self.play(FadeOut(pentagon)) dots.restore() # self.play(FadeInFromDown(pentagon)) # pentagon.clear_updaters() def get_highlight(self, mobject): result = super().get_highlight(mobject) if isinstance(mobject, Arrow): result.set_stroke(width=result.get_stroke_width()) return result class RepeatingPowersOfUnity(InteractiveScene): n_steps = 25 def construct(self): # Setup plane plane = ComplexPlane((-2, 2), (-2, 2)) plane.set_height(FRAME_HEIGHT - 0.5) plane.add_coordinate_labels(font_size=24) for coord in plane.coordinate_labels: coord.shift_onto_screen(buff=SMALL_BUFF) coord.set_fill(WHITE) plane.to_edge(LEFT, buff=0.1) self.disable_interaction(plane) unit_circle = Circle(radius=plane.x_axis.get_unit_size()) unit_circle.move_to(plane.get_origin()) unit_circle.set_stroke(GREY_C, 2) self.disable_interaction(unit_circle) complex_plane_title = Text("Complex plane", font_size=42) complex_plane_title.next_to(plane.get_corner(UL), DR, buff=SMALL_BUFF) complex_plane_title.set_backstroke(width=8) self.add(plane) self.add(unit_circle) self.add(complex_plane_title) # Setup roots roots = [np.exp(complex(0, n * TAU / 5)) for n in range(5)] root_points = list(map(plane.n2p, roots)) root_dots = Group(*( GlowDot(point) for point in root_points )) root_lines = VGroup(*( Arrow( plane.get_origin(), point, buff=0, stroke_width=2, stroke_color=YELLOW, stroke_opacity=0.7 ) for point in root_points )) self.disable_interaction(root_dots) pentagon = Polygon(*root_points) pentagon.set_stroke(TEAL, 2) pentagon.set_fill(TEAL, 0.25) self.add(pentagon) # Labels zeta_labels = VGroup() for n in range(self.n_steps): label = Tex("\\zeta^2") label[0].set_color(YELLOW) exp = Integer(n) exp.match_height(label[1]) exp.move_to(label[1], DL) label.replace_submobject(1, exp) point = root_points[n % 5] vect = normalize(point - plane.get_origin()) if n % 5 == 0: vect = UR label.next_to(point, vect, buff=SMALL_BUFF) zeta_labels.add(label) zeta_labels.set_backstroke(width=4) # Animations line = root_lines[0].copy() dot = root_dots[0].copy() label = zeta_labels[0].copy() self.add(line, dot, label) self.wait() for n in range(1, self.n_steps): self.play( Transform(line, root_lines[n % 5]), Transform(dot, root_dots[n % 5]), Transform(label, zeta_labels[n]), path_arc=TAU / 5 ) self.wait() class JustifyLinearity(InteractiveScene): n_terms = 8 def construct(self): # Create polynomials x_poly = self.get_polynomial("{x}", BLUE) x_poly.to_edge(UP) zeta_polys = VGroup(*( self.get_polynomial("\\zeta", YELLOW, exp_multiple=n) for n in range(5) )) zeta_polys.arrange(DOWN, buff=0.65, aligned_edge=LEFT) zeta_polys.next_to(x_poly, DOWN, LARGE_BUFF) x_poly.align_to(zeta_polys, LEFT) polys = VGroup(x_poly, *zeta_polys) # Align parts low_poly = polys[-1] for poly in polys[:-1]: for i1, i2 in zip(poly.sep_indices, low_poly.sep_indices): shift = (low_poly[i2].get_x(LEFT) - poly[i1].get_x(LEFT)) * RIGHT poly[i1].shift(shift / 2) poly[i1 + 1:].shift(shift) # Discuss complexity simple_examples = VGroup(*( Tex(f"f(x) = x^{{{n}}}", tex_to_color_map={"x": BLUE}, font_size=36) for n in range(1, 6) )) simple_examples.arrange(DOWN, aligned_edge=LEFT) simple_examples.move_to(4 * RIGHT + DOWN) simple_box = SurroundingRectangle(simple_examples, buff=MED_SMALL_BUFF) simple_box.set_fill(GREY_E, 1) simple_box.set_stroke(WHITE, 1) simple_label = Text("Simple examples") simple_label.next_to(simple_box, UP, SMALL_BUFF) simple_box.match_width(simple_label, stretch=True) simple_group = VGroup(simple_box, simple_label, simple_examples) randy = Randolph(height=2) randy.align_to(simple_box, DOWN) randy.to_edge(LEFT) self.add(simple_group) self.play( PiCreatureSays( randy, OldTexText("But $f$ is more\\\\complicated than that!", font_size=36), bubble_config=dict(width=4, height=2), target_mode="pleading", ) ) self.play( Write(x_poly), randy.change("sad", x_poly), ) self.play(Blink(randy)) self.wait() # Prepare for grid sum lhss = VGroup(*( poly[:poly.sep_indices[0]] for poly in zeta_polys )) lhss.save_state() plusses = Tex("+", font_size=36).replicate(len(lhss) - 1) group = VGroup(*it.chain(*zip(lhss, plusses))) group.add(lhss[-1]) group.arrange(RIGHT, buff=MED_SMALL_BUFF) group.next_to(x_poly, DOWN, LARGE_BUFF) plusses.generate_target() for plus, lhs1, lhs2 in zip(plusses.target, lhss.saved_state, lhss.saved_state[1:]): plus.move_to(midpoint(lhs1.get_bottom(), lhs2.get_top())) plus.scale(0.7) self.play( Write(group), FadeOut(VGroup(randy.bubble, randy.bubble.content)), simple_group.animate.to_edge(DOWN), ) self.wait() for mob in x_poly, group: self.play( FlashAround(mob, time_width=2, run_time=2, color=mob[2].get_fill_color()), randy.change("pondering", mob), ) self.wait() self.play( lhss.animate.restore(), MoveToTarget(plusses), FadeOut(randy), FadeOut(simple_group), path_arc=-90 * DEGREES, ) self.wait() # Write all right hand sides anims = [] for poly in zeta_polys: anims.append(FadeTransformPieces( x_poly[x_poly.sep_indices[0]:].copy(), poly[poly.sep_indices[0]:], )) self.play(LaggedStart(*anims, lag_ratio=0.1, run_time=2)) self.wait() # Highlight columns lower_sum = VGroup() lp = polys[-1] for j in range(len(x_poly.sep_indices) - 1): polys.generate_target() col = VGroup() for poly in polys.target: col.add(poly[poly.sep_indices[j] + 1:poly.sep_indices[j + 1]]) polys.target.set_fill(opacity=0.5) col.set_fill(opacity=1) if j % 5 == 0: term = Tex(f"5c_{j}", font_size=36) else: term = Tex("0", font_size=36) i1, i2 = lp.sep_indices[j:j + 2] term.next_to(VGroup(lp[i1], lp[i2]), DOWN, buff=0.7) plus = Tex("+", font_size=36) plus.next_to(lp[i1], DOWN, buff=0.7) if j == 0: plus.set_opacity(0) else: plus.move_to(midpoint(lower_sum.get_right(), term.get_left())) lower_sum.add(plus, term) self.play( FlashAround(col, time_width=2), MoveToTarget(polys), plusses.animate.set_fill(opacity=0.5), ) self.wait() self.play( Write(plus), *( FadeTransform(piece.copy(), term) for piece in col[1:] ) ) self.wait() self.play(polys.animate.set_opacity(1)) self.wait() def get_polynomial(self, input_tex, color, exp_multiple=None, font_size=36): if exp_multiple is not None: tex = f"f({input_tex}^{exp_multiple}) =" else: tex = f"f({input_tex}) = " exp_multiple = 1 tex += "c_0 + " for n in range(1, self.n_terms): tex += f"c_{{{n}}}{input_tex}^{{{exp_multiple * n}}} + " tex += "\\cdots" result = Tex( tex, tex_to_color_map={ input_tex: color, "+": WHITE, "=": WHITE, }, font_size=font_size, ) result.sep_indices = [ result.submobjects.index(part.family_members_with_points()[0]) for part in (*result.get_parts_by_tex("="), *result.get_parts_by_tex("+")) ] # result.arrange(RIGHT, aligned_edge=DOWN) return result class Recap(InteractiveScene): def construct(self): # Step labels steps = VGroup(*(Text(f"{n}.") for n in range(1, 5))) VGroup(*reversed(steps)).arrange_to_fit_height(6, DOWN) steps.set_y(0) steps.to_edge(LEFT) # Question set_part = "$\\{1,\\dots,2000\\}$" kw = dict(font_size=40) question = OldTexText( f"Find the number of subsets of {set_part} whose sum is divisible by 5", tex_to_color_map={set_part: BLUE}, **kw ) question.set_width(FRAME_WIDTH - 1.5) question.next_to(steps[0], buff=MED_SMALL_BUFF) question.shift(0.025 * DOWN) self.play(Write(question), Write(steps[0])) self.wait() # Polynomial factored_tex = "(1 + x)(1 + x^2)(1 + x^3)\\cdots\\big(1 + x^{2{,}000}\\big)" rhs_tex = "\\sum_{n = 0}^\\infty c_n x^n" poly = Tex( f"f(x) &= {factored_tex} = {rhs_tex}", isolate=[factored_tex, rhs_tex, "c_n", "="], **kw, ) poly.next_to(steps[1], RIGHT) poly.shift((steps[1].get_y() - poly[0].get_y()) * UP) cn_part = poly.select_part("c_n") cn_rect = SurroundingRectangle(cn_part, buff=0.05) cn_rect.round_corners() cn_rect.set_stroke(TEAL, 2) cn_label = OldTexText("How many subsets sum to $n$", font_size=30) cn_label.set_color(TEAL) cn_label.next_to(cn_rect, UP, MED_LARGE_BUFF, aligned_edge=LEFT) cn_arrow = Arrow(cn_rect.get_top(), cn_label[0][:5], color=TEAL, buff=0.1) self.play(FadeIn(poly, lag_ratio=0.1), Write(steps[1])) self.wait() self.play( ShowCreation(cn_rect), ShowCreation(cn_arrow), ) self.play(FadeIn(cn_label, 0.25 * UP)) self.wait() # Evaluation evaluation = Tex( "c_{0} + c_{5} + c_{10} + c_{15} + \\cdots = " "\\frac{1}{5}\\Big(f(\\zeta^0) + f(\\zeta^1) + f(\\zeta^2) + f(\\zeta^3) + f(\\zeta^4) \\Big)", tex_to_color_map={ re.compile(r"c_{.+?}"): TEAL, "\\zeta": YELLOW, }, isolate=[re.compile(r"f(.+?)")], **kw ) evaluation.next_to(steps[2], RIGHT) self.play(Write(evaluation), Write(steps[2])) self.wait() # f(zeta) rhs = "\\Big(" + "".join(f"(1 + \\zeta^{n})" for n in range(1, 6)) + "\\Big)^{400}" fz = Tex( f"f(\\zeta) = {rhs}", tex_to_color_map={"\\zeta": YELLOW}, isolate=["f(\\zeta)", "=", rhs], **kw, ) fz.next_to(steps[3], RIGHT) self.play( TransformFromCopy( evaluation.select_part("f(\\zeta^1)"), fz.select_part("f(\\zeta)"), ), Write(fz.select_part("=")), Write(steps[3]), ) self.wait() self.play(Write(fz.select_part(rhs))) self.wait() class ReflectOnNumericalAnswer(InteractiveScene): def construct(self): pass class ReflectOnGeneratingFunctions(InteractiveScene): def construct(self): # Sequence subsets = get_subsets(list(range(1, 16))) seq = [ sum(sum(s) == n for s in subsets) for n in range(1, 15) ] seq_mobs = VGroup(*map(Integer, seq)) seq_mobs.scale(0.9) seq_mobs.add(Tex("\\cdots")) seq_mobs.arrange(RIGHT, aligned_edge=DOWN) seq_mobs.arrange_to_fit_width(FRAME_WIDTH - 1) seq_mobs.move_to(UP) brace = Brace(seq_mobs, UP) brace_label = Text("Sequence we want to understand") brace_label.next_to(brace, UP) self.play( Write(brace_label, run_time=1), GrowFromCenter(brace), ShowIncreasingSubsets(seq_mobs), ) self.wait() # Put into a polynomial poly_str = " + ".join(( f"{s} x^{{{n}}}" for n, s in enumerate(seq) )) poly_str += "+ \\cdots" poly = Tex( poly_str, tex_to_color_map={"x": BLUE, "+": WHITE}, ) poly.set_width(FRAME_WIDTH - 1) poly.next_to(seq_mobs, DOWN, buff=LARGE_BUFF) plus_indices = [-1, *(poly.submobjects.index(p[0]) for p in poly.select_parts("+"))] coefs = VGroup(*[ poly[i + 1:i + 1 + len(str(n))] for i, n in zip(plus_indices, seq) ]) self.play( LaggedStart(*( Transform(sm.copy(), coef.copy(), remover=True) for sm, coef in zip(seq_mobs, coefs) )), LaggedStart(*( FadeIn(sm, scale=3.0) for sm in poly if not set(sm.get_family()).intersection(coefs.get_family()) )), run_time=2 ) self.add(poly) self.wait() # Make way self.play( poly.animate.to_edge(UP), FadeOut(VGroup(seq_mobs, brace, brace_label), 2.5 * UP), ) # Evaluate on complex plane in_plane = ComplexPlane((-3, 3), (-3, 3)) out_plane = ComplexPlane( (-10, 10), (-10, 10), background_line_style=dict(stroke_width=1), faded_line_ratio=0, ) plane_labels = VGroup(Text("Input"), Text("Output")) for plane, vect, label in zip([in_plane, out_plane], [DL, DR], plane_labels): plane.add_coordinate_labels(font_size=20) plane.set_height(5) plane.to_corner(vect) label.scale(0.75) label.set_color(GREY_A) label.next_to(plane, UP) arrow = Arrow(in_plane.get_right(), out_plane.get_left(), path_arc=-45 * DEGREES) arrow.shift(UP) in_dot = GlowDot(in_plane.n2p(-1), color=YELLOW) out_dot = GlowDot(out_plane.n2p(0), color=RED) self.play( FadeIn(in_plane), Write(plane_labels[0]), FadeIn(in_dot), ) self.play( ShowCreation(arrow), FadeTransform(in_plane.copy(), out_plane, path_arc=-30 * DEGREES), TransformFromCopy(*plane_labels, path_arc=30 * DEGREES), TransformFromCopy(in_dot, out_dot, path_arc=30 * DEGREES), ) self.add(out_dot) # Paths def get_z(): return in_plane.p2n(in_dot.get_center()) def func(z): return np.prod([1 + z**n for n in range(10)]) globals().update(locals()) out_dot.add_updater(lambda od: od.move_to(out_plane.n2p(func(get_z())))) arc = ParametricCurve(lambda t: in_plane.n2p(np.exp(complex(0, PI - t))), t_range=(0, TAU)) # arc_image = ParametricCurve(lambda t: out_plane.n2p(func(np.exp(complex(0, PI - t)))), t_range=(0, TAU, 0.01)) # arc.set_stroke(YELLOW, 2) # arc_image.set_stroke(RED, 1) globals().update(locals()) paths = [ TracingTail(in_dot, stroke_color=YELLOW, stroke_width=(0, 3), time_traced=16), TracingTail(out_dot, stroke_color=RED, stroke_width=(0, 1.5), time_traced=16), ] self.add(*paths) self.wait(16) self.play( MoveAlongPath(in_dot, arc.copy()), run_time=16, rate_func=linear, ) self.wait(10) class GeneratingFunctionForPrimes(InteractiveScene): def construct(self): # Title title = Text("A prime generating function?") title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_backstroke() underline = Underline(title, buff=-0.05) underline.stretch(1.25, 0) underline.insert_n_curves(20) underline.set_stroke(WHITE, [0, 3, 3, 3, 0]) self.add(underline, title) # Attempt sequence n_range = range(1, 12) piece_groups = [ [str(int(sympy.isprime(n))) + f"\\cdot x^{{{n}}} " for n in n_range], [str(int(sympy.isprime(n))) + f"\\cdot {{{n}}}^x " for n in n_range], [str(int(sympy.isprime(n))) + f"\\cdot {{{n}}}^s " for n in n_range], ["{ " + str(int(sympy.isprime(n))) + f" \\over {{{n}}}^s }}" for n in n_range], ["{ " + von_mangoldt_str(n) + f" \\over {{{n}}}^s }}" for n in n_range], [f"{{1 \\over {{{n}}}^s }}" for n in range(1, 14)], ] lines = VGroup() for pieces in piece_groups: line = Tex(" + ".join([*pieces, "\\cdots"]), isolate=[*pieces, "+"]) line.set_width(FRAME_WIDTH - 1) for n, piece in zip(it.count(1), pieces): part = line.select_part(piece) if sympy.isprime(n): part.set_color(GREEN) elif len(sympy.factorint(n)) == 1 and "ln" in piece: part.set_color(TEAL) lines.add(line) line.pieces = pieces lines[0].shift(2 * UP) lines[4].shift(2.5 * DOWN) arrows = VGroup( Arrow(lines[0], lines[1]), Arrow(lines[3], lines[4]), ) for arrow in arrows: arrow.label = Text("or rather...", font_size=36) arrow.label.next_to(arrow, RIGHT) self.play(Write(lines[0])) self.wait() for i, l1, l2 in zip(it.count(), lines[0:4], lines[1:5]): added_anims = [] if i in [1, 2]: self.remove(l1) elif i in [0, 3]: arrow = arrows[i // 3] added_anims.append(GrowArrow(arrow)) added_anims.append(Write(arrow.label)) self.play( *( TransformMatchingShapes(l1.select_part(p1).copy(), l2.select_part(p2)) for p1, p2 in zip(l1.pieces, l2.pieces) ), ReplacementTransform(l1.select_parts("+").copy(), l2.select_parts("+")), ReplacementTransform(l1.select_parts("\\cdots").copy(), l2.select_parts("\\cdots")), *added_anims, ) self.wait() # Sweep away series = lines[4] self.play( series.animate.move_to(UP), FadeOut(VGroup(lines[0], arrows[0], arrows[0].label), UP), FadeOut(VGroup(lines[3], arrows[1], arrows[1].label), 0.5 * UP), ) self.wait() # Name Dirichlet series gf_part = title.select_part("generating function?") strike = Line().replace(gf_part, dim_to_match=0) strike.set_stroke(RED, 5) dirichlet = Text("Dirichlet series") dirichlet.set_color(BLUE) dirichlet.next_to(gf_part, DOWN) self.play( ShowCreation(strike), ) self.play(FadeIn(dirichlet, DOWN)) self.wait() # Von Mangoldt vm_name = Text("Von Mangoldt function: ") vm_def = VGroup( Tex("\\Lambda(n)= \\log p & \\text { if } n=p^{k} \\text { for some prime } p \\text { and integer } k \\geq 1"), Tex("\\Lambda(n)= 0 & \\text { otherwise }") ) vm_def.arrange(DOWN, aligned_edge=LEFT) vm = VGroup(vm_name, vm_def) vm.arrange(RIGHT) vm_name.align_to(vm_def[0], DOWN) vm.set_width(FRAME_WIDTH - 1) vm.next_to(series, DOWN, LARGE_BUFF) self.play(Write(vm_name, run_time=1)) self.wait() for part in vm_def: self.play(FadeIn(part)) self.wait() self.play( FadeOut(vm), FadeOut(VGroup(title, underline, strike), 0.5 * UP), FadeOut(dirichlet, UP), series.animate.move_to(2 * UP), ) # Contrast with zeta zeta_series = lines[5] zeta_series.center() zeta_series.set_color(WHITE) zeta_brace = Brace(zeta_series, DOWN, buff=SMALL_BUFF) zeta_sym = OldTex("\\zeta(s)") zeta_sym.next_to(zeta_brace, DOWN) zeta_group = VGroup(zeta_series, zeta_brace, zeta_sym) series_brace = Brace(series, DOWN, buff=SMALL_BUFF) series_label = Tex("-{\\zeta'(s) \\over \\zeta(s)}") series_label.next_to(series_brace, DOWN) self.play(FadeIn(zeta_series, DOWN)) self.play( GrowFromCenter(zeta_brace), Write(zeta_sym) ) self.wait() self.play( GrowFromCenter(series_brace), Write(series_label), zeta_group.animate.shift(1.5 * DOWN) ) self.wait() # Show the complex plane pass class DirichletSeries(InteractiveScene): def construct(self): # Framing h_line = Line().set_width(FRAME_WIDTH) h_line.set_stroke(WHITE, 1) titles = VGroup( Text("Our puzzle", font_size=36), Text(f"Studying primes", font_size=36), ) titles[0].to_corner(UL, buff=MED_SMALL_BUFF) titles[1].next_to(h_line, DOWN).align_to(titles[0], LEFT) self.add(titles, h_line) # Show series n_range = list(range(1, 14)) coef_texs = [von_mangoldt_str(n) for n in n_range] denom_texs = [f"{{{n}}}^s" for n in n_range] series_terms = [f"{{ {coef} \\over {denom} }}" for coef, denom in zip(coef_texs, denom_texs)] series = Tex( " + ".join(series_terms) + "+ \\cdots", isolate=["+", *coef_texs, *denom_texs] ) series.set_width(FRAME_WIDTH - 1) series.next_to(h_line, DOWN, buff=2.0) plusses = series.select_parts("+") denoms = VGroup(*(series.select_part(dt) for dt in denom_texs)) plus_indices = [series.submobjects.index(plus[0]) for plus in plusses] denom_indices = [series.submobjects.index(denom[0]) for denom in denoms] coefs = VGroup() overs = VGroup() for i, j, k in zip((-1, *plus_indices), denom_indices, plus_indices): coefs.add(series[i + 1:j - 1]) overs.add(series[j - 1]) for n, coef, denom in zip(n_range, coefs, denoms): if sympy.isprime(n): color = YELLOW elif len(sympy.factorint(n)) == 1: color = TEAL else: color = WHITE coef.set_color(color) denom.set_color(color) coefs.save_state() coefs.shift(DOWN) numbers = VGroup(*(Integer(n, font_size=36) for n in n_range)) arrows = VGroup() for number, coef_part in zip(numbers, coefs): number.next_to(coef_part, UP, buff=LARGE_BUFF) arrows.add(Arrow(number, coef_part, stroke_width=2)) arrows.set_stroke(GREY_B) vm_def = Tex("n \\rightarrow \\log p & \\text { if } n=p^{k} \\text { for some prime } p \\text { and integer } k \\geq 1") vm_def.scale(0.5) vm_def.next_to(h_line, DOWN) vm_def.to_edge(RIGHT) details = Text("(Why this sequence? That's a story for another day...)") details.scale(0.5) details.set_color(GREY_B) details.next_to(vm_def, DOWN) self.play( ShowIncreasingSubsets(numbers), ShowIncreasingSubsets(arrows), ShowIncreasingSubsets(coefs), FadeIn(vm_def, time_span=(1, 2)), run_time=3, rate_func=linear, ) self.play(FadeIn(details, 0.5 * DOWN)) self.wait(3) self.play( coefs.animate.restore(), *( ReplacementTransform(number, denom) for number, denom in zip(numbers, denoms) ), *(FadeOut(arrow, scale=0.2) for arrow in arrows), Write(overs, time_range=(0.75, 1.75)), Write(plusses, time_range=(0.75, 1.75)), ) self.add(series) self.wait() # Name Dirichlet series.generate_target() series.target.shift(0.5 * UP) brace = Brace(series.target, DOWN) name = Text("Dirichlet series") name.next_to(brace, DOWN) self.play( MoveToTarget(series), GrowFromCenter(brace), ) self.play(Write(name)) self.wait(2) # Move everything up func_name = Tex("f(s) = -\\zeta'(s) / \\zeta(s)", font_size=36) func_name.next_to(brace, DOWN) func_name.set_opacity(0) self.play(LaggedStart( FadeOut(h_line, 3 * UP), FadeOut(titles[0], UP), FadeOut(titles[1], 3 * UP), FadeOut(vm_def, 2 * UP), FadeOut(details, 2 * UP), FadeOut(name, 3 * UP), VGroup(series, brace, func_name).animate.set_opacity(1).to_edge(UP), lag_ratio=0.01 )) self.wait() # Complex plane kw = dict(background_line_style={"stroke_width": 1}) in_plane, out_plane = planes = VGroup( ComplexPlane((-5, 5), (-4, 4), **kw), ComplexPlane((-3, 3), (-3, 3), **kw), ) plane_labels = VGroup(Text("Input"), Text("Output")) for label, plane, vect in zip(plane_labels, planes, [DL, DR]): plane.set_height(4) plane.add_coordinate_labels(font_size=12) plane.to_corner(vect) label.scale(0.7) label.set_color(GREY_A) label.next_to(plane, UP) arrow = Arrow(in_plane.get_right(), out_plane.get_left(), path_arc=-45 * DEGREES) arrow.align_to(in_plane, UP).shift(DOWN) f_label = Tex("f(s)", font_size=36) f_label.next_to(arrow.pfp(0.5), DOWN) in_dot = GlowDot(in_plane.n2p(0.5), color=YELLOW) out_dot = GlowDot(out_plane.n2p(2), color=RED) def get_z(): return in_plane.p2n(in_dot.get_center()) def func(z): ep = 1e-3 zeta = mpmath.zeta(z) dzeta = (mpmath.zeta(z + ep) - zeta) / ep return -dzeta / zeta out_dot.add_updater(lambda d: d.move_to(out_plane.n2p(func(get_z())))) v_line = ParametricCurve(lambda t: in_plane.n2p(complex(2, t)), t_range=(-4, 4, 0.01)) v_line.set_stroke(YELLOW, 2) out_line = v_line.copy() out_line.set_stroke(RED, 2) out_line.add_updater(lambda m: m.set_points([ out_plane.n2p(func(in_plane.p2n(p))) for p in v_line.get_points() ])) # Complex mapping self.disable_interaction(in_plane, out_plane) self.play( FadeIn(in_plane), FadeIn(out_plane), FadeIn(plane_labels), FadeIn(in_dot) ) self.play( ShowCreation(arrow), FadeIn(f_label, RIGHT + 0.2 * UP), TransformFromCopy(in_dot, out_dot, path_arc=45 * DEGREES) ) self.play( in_dot.animate.move_to(v_line.get_start()), run_time=2, ) in_dot.add_updater(lambda d: d.move_to(v_line.get_end())) self.add(v_line, out_line) self.play( ShowCreation(v_line), ShowCreation(out_line), run_time=5, ) self.wait() self.play( v_line.animate.move_to(in_plane.n2p(-1)), run_time=6 ) self.wait() class AskAboutComplex(TeacherStudentsScene): def construct(self): # Ask morty = self.teacher ss = self.students self.student_says("Why complex\nnumbers?") self.play( ss[0].change("pondering"), ss[1].change("erm"), morty.change("tease"), ) self.wait(2) self.play( RemovePiCreatureBubble(ss[2], target_mode="erm", look_at=morty.eyes), morty.change("hesitant"), ) self.wait(2) # Hidden information kw = dict(tex_to_color_map={ "x": BLUE, "{0}": BLUE, "{1}": BLUE, "{-1}": BLUE, }) fx, f0, f1, fm1 = lines = VGroup( Tex("f(x) = \\sum_{n = 0}^N c_n x^n", **kw), Tex("f({0}) = c_0", **kw), Tex("f({1}) = c_0 + c_1 + c_2 + \\cdots + c_n", **kw), Tex("f({-1}) = c_0 - c_1 + c_2 - \\cdots + c_n", **kw), ) lines.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) lines.set_height(4) lines[0].next_to(lines[1], LEFT, LARGE_BUFF) lines.next_to(morty, UL).to_edge(UP) self.play( morty.change("raise_right_hand"), FadeInFromPoint(fx, morty.get_center(), run_time=2), ss[1].change("hesitant", lines) ) for line in lines[1:]: self.play(FadeIn(line, 0.5 * DOWN)) self.wait() self.play(morty.change("tease")) self.wait() # Blank check new_line = Tex( "f(\\dots) = \\text{(more information)}", tex_to_color_map={"\\dots": BLUE} ) new_line.match_height(lines[-1]) new_line.next_to(lines[-1], DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) dots_in_set = Tex( "x \\in \\mathds{R}", isolate=["\\mathds{R}", "\\dots"], tex_to_color_map={"x": BLUE}, font_size=60 ) dots_in_set.next_to(morty, UR, MED_LARGE_BUFF).shift_onto_screen() set_part = dots_in_set.select_part("\\mathds{R}") C_set = Tex("\\mathds{C}", color=TEAL, font_size=60) C_set.move_to(set_part) self.play( Write(new_line), self.change_students( "thinking", "hesitant", "pondering", look_at=new_line, ), ) self.wait() self.play( TransformFromCopy( new_line.select_part("\\dots"), dots_in_set.select_part("x"), path_arc=-45 * DEGREES, ), morty.change("raise_left_hand", dots_in_set), ) self.play(Write(dots_in_set[1:])) self.wait() self.play( morty.change("shruggie"), ss[0].change("pondering"), ss[2].change("hesitant"), FadeOut(dots_in_set.select_part("\\mathds{R}"), UP), FadeIn(C_set, UP), ) self.wait(5) class ReferenceFilter(InteractiveScene): def construct(self): # Grid c_grid = Tex("c_{10}").get_grid(10, 10, buff=MED_LARGE_BUFF) c_grid.set_height(FRAME_HEIGHT - 1) for n, c_mob in zip(it.count(1), c_grid): sub = Integer(n) sub.match_height(c_mob[1:]) sub.move_to(c_mob[1:], UL) c_mob.remove(*c_mob[1:]) c_mob.add(sub) self.play(FadeIn(c_grid, run_time=2, lag_ratio=0.025)) c_grid.generate_target() c_grid.target.set_opacity(0.25) c_grid.target[4::5].set_fill(TEAL, 1) self.play(MoveToTarget(c_grid, run_time=2, lag_ratio=0.025)) self.wait() # Name frequency c_grid.generate_target() c_grid.target.set_height(4.0) c_grid.target.set_y(0).to_edge(LEFT) freq_label = Text("Frequency question") freq_label.next_to(c_grid.target, UP, MED_LARGE_BUFF) self.play( MoveToTarget(c_grid), Write(freq_label), ) self.wait() # Roots of unity (to be overlaid) uc_label = OldTexText("Values of the form $e^{it}$") uc_label.match_y(freq_label, UP) uc_label.set_x(-freq_label.get_x()) arrow = Vector(2.0 * RIGHT).next_to(c_grid, RIGHT) self.play(ShowCreation(arrow), Write(uc_label)) self.wait() class PracticeQuestions(InteractiveScene): def construct(self): # Blah division = VGroup(Line().set_width(FRAME_WIDTH), Line(UP, DOWN).set_height(FRAME_HEIGHT)) division.set_stroke(WHITE, 1) self.disable_interaction(division) self.add(division) questions = VGroup( self.load_mobject("Question1.mob"), self.load_mobject("Question2.mob"), self.load_mobject("Question3.mob"), self.load_mobject("Question4.mob"), ) self.play(LaggedStartMap(FadeIn, questions, lag_ratio=0.25, run_time=2)) self.wait() # Quick filler class ProblemStatement(TeacherStudentsScene): def construct(self): # Title title = Text("Useless puzzles with useful lessons", font_size=60) title.to_edge(UP) title.set_color(BLUE_C) underline = Underline(title, buff=-0.05) underline.insert_n_curves(20) underline.set_stroke(width=[1, 3, 3, 3, 1]) words = VGroup(*( title.get_part_by_text(text) for text in title.get_text().split(" ") )) morty = self.teacher self.play( LaggedStart(*( FadeInFromPoint(word, morty.get_corner(UL)) for word in words )), morty.change("raise_right_hand", title), self.change_students("happy", "thinking", "happy", look_at=title) ) self.remove(words) self.add(title) self.play(ShowCreation(underline)) self.wait(2) self.play_student_changes("pondering", "erm", "tease", look_at=title) self.wait(3) # Statement statement = get_question_title() set_tex = statement[1] self.play( FadeIn(statement), self.change_students(*3 * ["pondering"], look_at=statement), FadeOut(VGroup(title, underline), UP) ) self.wait() self.play( LaggedStart(*( FlashAround(int_part) for int_part in get_integer_parts(set_tex) ), lag_ratio=0.05, run_time=3), self.change_students("erm", "sassy", "confused", look_at=statement), ) self.wait(2) # Example subsets subsets = VGroup( get_set_tex([3, 1, 4]), get_set_tex([2, 3, 5]), get_set_tex(range(1, 2000, 2)), ) subsets.move_to(UP) sum_wrappers = VGroup(*map(get_sum_wrapper, subsets)) mode_triples = [ ("erm", "pondering", "plain"), ("pondering", "thinking", "pondering"), ("thinking", "happy", "thinking"), ] sum_groups = VGroup() for subset, sum_wrapper, mode_triple in zip(subsets, sum_wrappers, mode_triples): self.play( morty.change("tease", subset), self.change_students(*mode_triple, look_at=subset), set_tex_transform(set_tex, subset), ) elem_rects = VGroup(*( SurroundingRectangle( get_part_by_value(set_tex, value) ).set_stroke(TEAL, 2).round_corners() for value in subset.values )) self.play(LaggedStartMap(ShowCreation, elem_rects, lag_ratio=0.5)) self.wait() self.play( Write(sum_wrapper), morty.change("hooray" if subset is subsets[-1] else "tease", subset), ) self.wait(2) mark = Checkmark() if sum(subset.values) % 5 == 0 else Exmark() sum_wrapper.refresh_bounding_box() mark.next_to(sum_wrapper, RIGHT) self.play(Write(mark)) self.wait() anims = [FadeOut(elem_rects)] sum_group = VGroup(subset, sum_wrapper, mark) if subset is subsets[0]: self.play( sum_group.animate.scale(0.5).to_edge(LEFT).set_y(2), *anims ) else: self.play( sum_group.animate.scale(0.5).next_to(sum_groups, DOWN, MED_LARGE_BUFF, LEFT), *anims ) sum_groups.add(sum_group) self.play( self.change_students( "erm", "confused", "hesitant", look_at=statement, ) ) # Who cares? statement.generate_target() statement.target.scale(0.5) statement.target.to_corner(UL) title.set_opacity(0) title.scale(0.5) title.generate_target() title.target.set_opacity(1) title.target.scale(2) title.target.next_to(self.hold_up_spot, UP, MED_LARGE_BUFF) title.target.to_edge(RIGHT) self.play( PiCreatureSays( self.students[2], "Who cares?", target_mode="angry", bubble_config=dict(direction=LEFT), ), morty.change("guilty"), MoveToTarget(statement), FadeOut(sum_groups, LEFT) ) self.wait() self.play( RemovePiCreatureBubble( self.students[2], target_mode="plain", look_at=ORIGIN, ), morty.change("sassy", self.students[2].eyes), self.change_students( "pondering", "pondering", look_at=ORIGIN, ), MoveToTarget(title), ) self.play(Blink(morty)) self.play( FlashAround(title, time_width=1), morty.change("raise_right_hand"), ) self.wait() return # Start simpler small_set = get_set_tex(range(1, 6)) small_set.to_edge(UP) case_words = Text("Start simple") case_words.next_to(small_set, DOWN) case_words.set_color(BLUE) self.play( statement.animate.set_y(0), set_tex_transform(set_tex, small_set), LaggedStartMap( FadeOut, self.pi_creatures, shift=DOWN, ), FadeOut(self.background), Write(case_words), run_time=2, ) self.wait() self.play(FadeOut(statement), FadeOut(case_words)) class TopicRolidex(InteractiveScene): def construct(self): words = VGroup( Text("Algebra"), Text("Number theory"), Text("Analysis"), Text("Topology"), Text("Geometry"), Text("Combinatorics"), Text("Group theory"), ) words.set_submobject_colors_by_gradient(BLUE, GREEN, YELLOW) words.arrange(DOWN, aligned_edge=LEFT) words.next_to(ORIGIN, DR) words.shift(UP) def update_words(ws): for word in ws: word.set_opacity(1.0 - clip(1.25 * abs(word.get_y()), 0, 1)) words.add_updater(update_words) lhs = Text("Example in ") lhs.center() words.next_to(lhs, RIGHT, submobject_to_align=words[0]) self.add(lhs) self.add(words) self.play( words.animate.shift(-words[-2].get_y() * UP), UpdateFromFunc(words, update_words), run_time=4 ) self.wait() class IMOLogo(InteractiveScene): def construct(self): # Intro logo = ImageMobject("IMO_logo") logo.set_width(3) logo.to_corner(UL, buff=0.25) us_flag = ImageMobject("US_Flag") us_flag.set_height(0.5 * logo.get_height()) us_flag.move_to(logo) title = Text("International\nMath\nOlympiad") title.next_to(logo, DOWN).to_edge(LEFT) self.play(FadeIn(us_flag, scale=0.75)) self.wait() self.play( FadeOut(us_flag, UP), FadeIn(logo, UP), Write(title, run_time=1.5), ) title.set_stroke(background=True) self.play(title.animate.set_backstroke(width=5)) self.wait() class BookQuestionHighlight(InteractiveScene): def construct(self): # Temp img = ImageMobject("/Users/grant/Dropbox/3Blue1Brown/videos/2022/puzzles/subsets/images/BookQuestion.jpg") img.set_height(FRAME_HEIGHT) self.disable_interaction(img) # Highlight rect = FullScreenFadeRectangle(fill_color=BLACK, fill_opacity=0.975) lil_rect = Rectangle(5, 0.55) lil_rect.move_to([-0.2, 0, 0]) lil_rect.reverse_points() rect.append_vectorized_mobject(lil_rect) self.play( FlashAround( lil_rect, color=BLACK, stroke_width=5, time_width=1.5, buff=0, run_time=2, ), FadeIn(rect, time_span=(0.5, 2)), ) self.wait() # Title title = get_question_title() title.set_backstroke(width=7) self.play( FadeTransform(lil_rect.copy().set_opacity(0), title) ) self.wait() self.play( LaggedStart(*( FlashAround(int_part) for int_part in get_integer_parts(title[1]) ), lag_ratio=0.05, run_time=3), ) self.wait(2) last_part = title[-1][-12:] self.play( FlashUnder(last_part, color=TEAL, buff=0, time_width=1.5, run_time=2), last_part.animate.set_fill(TEAL), ) self.wait() class ConfusedPi(InteractiveScene): def construct(self): randy = Randolph(mode="erm", height=2) self.play(randy.change("maybe").look(UP)) self.play(Blink(randy)) self.wait() self.play(randy.change("pondering").look(DL)) self.play(Blink(randy)) self.wait(2) class HowManyIntotal(TeacherStudentsScene): def construct(self): self.teacher_says( OldTexText("How many total\\\\subsets are there?"), bubble_config=dict(width=4, height=3), added_anims=[self.change_students( "happy", "pondering", "tease", look_at=self.screen, )], run_time=2, ) self.wait(4) class StrangeTurnsFraming(InteractiveScene): def construct(self): # Title self.add(FullScreenRectangle()) screens = Square().replicate(2) screens.set_stroke(WHITE, 1) screens.set_fill(BLACK, 1) screens.set_height(5.5) screens.arrange_to_fit_width(FRAME_WIDTH - 2) screens.to_edge(DOWN, buff=LARGE_BUFF) titles = VGroup(*( Text(f"Strange turn {n}", font_size=48) for n in [1, 2] )) for title, screen in zip(titles, screens): title.next_to(screen, UP) self.add(screens) for title in reversed(titles): self.play(FadeIn(title, 0.5 * UP)) self.wait() class IsThereAGeometry(InteractiveScene): def construct(self): randy = Randolph(height=1.5) randy.shift(RIGHT) self.play(PiCreatureBubbleIntroduction( randy, OldTexText("Is there a\\\\geometric structure?"), target_mode="pondering", look_at=[10, -3, 0], bubble_type=ThoughtBubble, bubble_config=dict(width=3, height=1.75) )) for x in range(2): self.play(Blink(randy)) self.wait(2) self.play(randy.change("thinking")) class RotationAnnotation(InteractiveScene): def construct(self): arc = Arc(0, PI, radius=0.5) label = Integer(180, unit="^\\circ", font_size=24) label.next_to(arc.pfp(0.25), UR, SMALL_BUFF) morty = Mortimer(height=1.5) morty.next_to(arc, RIGHT, LARGE_BUFF, aligned_edge=DOWN) self.play( CountInFrom(label, 0), ShowCreation(arc), PiCreatureSays( morty, OldTexText("Think about\\\\the half turn", font_size=24), look_at=arc, bubble_config=dict(width=2, height=1.5) ) ) self.play(Blink(morty)) self.wait() class SimpleQuestionTitle(InteractiveScene): def construct(self): self.add(get_question_title()) class FinalAnswerTitle(InteractiveScene): def construct(self): answer = Tex("\\frac{1}{5}\\big(2^{2{,}000} + 4 \\cdot 2^{400}\\big)") self.add(answer) class ComingUpWrapper(VideoWrapper): title = "Generating functions" wait_time = 0 def construct(self): super().construct() self.wait(10) kw = self.title_config new_title = OldTexText("A Complex trick".replace("C", "$\\mathds{C}$"), **kw) parens = OldTexText("(secretly Fourier)", **kw) new_title.move_to(self.title_text, DOWN) new_title.generate_target() group = VGroup(new_title.target, parens) group.arrange(RIGHT, MED_LARGE_BUFF) group.move_to(self.title_text, DOWN) self.boundary.clear_updaters() self.play( FadeOut(self.title_text, UP), FadeIn(new_title, UP), ) self.wait(4) self.play( Write(parens), MoveToTarget(new_title) ) self.wait(10) class IsItHelpful(TeacherStudentsScene): def construct(self): self.student_says( "Is that helpful here?", index=2, added_anims=[LaggedStart( self.students[0].change("confused", self.screen), self.students[1].change("maybe", self.screen), lag_ratio=0.5, )] ) self.wait(2) self.teacher_says( "Honestly...\nnot really.", target_mode="shruggie", added_anims=[self.change_students( "sassy", "erm", look_at=self.teacher.eyes, )] ) self.play(self.students[2].change("angry")) self.wait(3) class AskAboutOrganization(InteractiveScene): def construct(self): pass class NoteToPatrons(InteractiveScene): def construct(self): morty = Mortimer() morty.to_corner(DR) title = Text("(Note for patrons)", font_size=60) title.to_edge(UP) self.play( morty.change("raise_right_hand"), FadeInFromPoint(title, morty.get_corner(UL)), ) modes = ["happy", "tease", "shruggie", "gracious"] for x in range(70): if random.random() < 0.3: self.play(Blink(morty)) elif random.random() < 0.1: self.play(morty.change( random.choice(modes), title, )) else: self.wait() class QuestionMorph(InteractiveScene): def construct(self): question = OldTexText( "How many subsets are there\\\\", "with a sum divisible by 5", "?" ) self.play(Write(question)) self.wait(2) self.play( question[1].animate.scale(0.75).set_opacity(0.5).to_corner(DL), question[2].animate.next_to(question[0], RIGHT, SMALL_BUFF), ) self.wait() class SimpleRect(InteractiveScene): def construct(self): rect = Rectangle(2, 0.5) rect.set_stroke(YELLOW, 2) self.play(ShowCreation(rect)) self.wait() self.play(FadeOut(rect)) class FirstTrick(TeacherStudentsScene): def construct(self): self.teacher_says( "Here's our\nfirst trick", target_mode="tease", run_time=1 ) self.play_student_changes( "pondering", "thinking", "sassy", look_at=self.screen ) self.wait(4) # Here self.student_says( OldTexText("Huh? What is $x$?"), index=2, target_mode="confused", look_at=self.teacher.eyes, ) self.play_student_changes( "erm", "pondering", look_at=self.screen, ) self.wait(4) class BeyondOurExample(TeacherStudentsScene): def construct(self): self.teacher_says( "Generating functions\n" "are useful beyond\n" "our one example.", bubble_config=dict(width=4, height=3), added_anims=[self.change_students( "happy", "jamming", "tease", look_at=self.screen, )] ) self.wait(3) self.play(self.teacher.change("tease")) self.play_student_changes("thinking", "tease", "tease") self.wait(2) class MoriaEntrance(InteractiveScene): def construct(self): # Show path = SVGMobject("mines-of-moria-entrance") path.set_height(FRAME_HEIGHT - 1) outline = path.copy() outline.set_stroke(WHITE, 2) outline.set_fill(opacity=0) outline.insert_n_curves(20) self.play( LaggedStartMap( VShowPassingFlash, VGroup(*outline.family_members_with_points()), lag_ratio=0.001, time_width=1.5, ), FadeIn(path), run_time=5, ) class WaitWhat(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("Wait...can you\\\\explain that?", target_mode="confused"), added_anims=[ self.teacher.change("guilty"), self.students[0].change("erm", self.screen), self.students[1].change("maybe", self.screen), ] ) self.wait() self.look_at(self.screen) self.play_student_changes( "pondering", "confused", "maybe", look_at=self.screen, ) self.wait(2) class HalfTheTotal(InteractiveScene): def construct(self): tex = Tex( "\\frac{1}{2}\\Big( 2^{2{,}000} + {0} \\Big)", tex_to_color_map={ "2^{2{,}000}": TEAL, "{0}": TEAL, }, font_size=60 ) self.play(Write(tex)) self.wait() class SquaringZeta(InteractiveScene): def construct(self): # Magnitude kw = dict(tex_to_color_map={"\\zeta": YELLOW}) mag = Tex("|\\zeta^2| = |\\zeta|^2 = 1^2 = 1", **kw) mag.move_to(2 * UR) self.play(FadeIn(mag[:4])) self.play(TransformMatchingShapes(mag[:4].copy(), mag[4:9])) self.play(TransformMatchingShapes(mag[4:9].copy(), mag[9:12])) self.play(TransformMatchingShapes(mag[9:12].copy(), mag[12:])) self.wait() # Explicit exp = Tex( "\\zeta^2 =" "\\big(e^{2\\pi i / 5}\\big)^2 =" "e^{4\\pi i / 5}", **kw ) exp.next_to(mag, DOWN, LARGE_BUFF, aligned_edge=LEFT) rect = SurroundingRectangle(exp[-5:], buff=0.05) rect.set_stroke(YELLOW, 2) self.play(FadeIn(exp, lag_ratio=0.1)) self.play(ShowCreation(rect)) self.wait() self.play(FadeOut(rect)) class FifthRootsOfOneOverlay(InteractiveScene): def construct(self): lines = [ "z^5 &= 1 ", "z &= \\sqrt[5]{1}", ] tex = OldTex("\\\\ ".join(lines), isolate=lines) self.add(tex[0]) self.wait() self.play(TransformMatchingShapes(tex[0].copy(), tex[1])) self.wait() class ObviouslyOne(TeacherStudentsScene): def construct(self): eq = Tex("z^5 = 1", font_size=72) self.teacher_holds_up(eq) self.wait() self.student_says( OldTexText("Obviously $z = 1$!"), target_mode="angry", bubble_config=dict(direction=RIGHT), added_anims=[self.change_students("sassy", "hesitant")] ) self.wait(4) class EqualsZeta3(InteractiveScene): def construct(self): arrow = Vector(0.5 * DOWN) tex = Tex("\\zeta^3", tex_to_color_map={"\\zeta": YELLOW}) tex.next_to(arrow, DOWN) self.play( GrowArrow(arrow), FadeIn(tex, DOWN) ) self.wait() class Roughly2(InteractiveScene): def construct(self): self.play(Write(Tex("\\approx 2"))) self.wait() class EvaluateF1(InteractiveScene): def construct(self): tex_x = "f(x) = (1 + x)(1 + x^2)(1 + x^3)(1 + x^4)(1 + x^5)\\cdots\\left(1 + x^{2{,}000}\\right)" tex_1 = tex_x.replace("x", "{1}") fx = Tex(tex_x, tex_to_color_map={"x": BLUE}) f1 = Tex(tex_1, tex_to_color_map={"{1}": GREEN}) f1.match_width(fx) fx.to_edge(UP) f1.next_to(fx, DOWN, MED_LARGE_BUFF) xs = fx.select_parts("x") ones = f1.select_parts("{1}") fx_copy = fx.copy().move_to(f1) fx_copy.select_parts("x").set_opacity(0) brace = Brace(f1[5:], DOWN, buff=SMALL_BUFF) brace.stretch(0.5, 1, about_edge=UP) ans = Tex("2^{2{,}000}") ans.next_to(brace, DOWN, SMALL_BUFF) self.add(fx) self.play(TransformFromCopy(fx, fx_copy)) self.play(Transform(xs.copy(), ones, lag_ratio=0.1, run_time=2, remover=True)) self.remove(fx_copy) self.add(f1) self.wait() self.play( GrowFromCenter(brace), FadeIn(ans, 0.25 * DOWN) ) self.wait() class CoefPoly(InteractiveScene): def construct(self): mid_str = "".join((f"c_{{{n}}} x^{{{n}}} + " for n in range(2, 8))) self.add(Tex( "f(x) = c_0 + c_1 x + " + mid_str + "\\cdots", tex_to_color_map={"x": BLUE} ).to_edge(UP).shift(DOWN)) class AskAboutTaylorSeries(TeacherStudentsScene): def construct(self): self.student_says( OldTexText("Can we use derivatives\\\\in some way?"), bubble_config=dict(width=4, height=3, direction=LEFT), index=2, ) self.play( self.teacher.change("tease"), self.change_students( None, "confused", "thinking", look_at=self.students[2].bubble, ), ) self.wait(4) self.teacher_says( "It's not a\nbad idea...", target_mode="hesitant", ) self.play_student_changes("plain", "maybe", "pondering", look_at=self.screen) self.wait(4) class TantalizinglyClose(InteractiveScene): def construct(self): brace = Brace(Line(ORIGIN, 4.5 * RIGHT), DOWN) brace.to_edge(RIGHT, buff=LARGE_BUFF) brace.set_y(-2) words = brace.get_text("Tantalizingly close to\nwhat we want", font_size=36) randy = Randolph(height=1.5) randy.next_to(brace, DL) randy.shift(0.5 * RIGHT) self.play( GrowFromCenter(brace), FadeIn(randy), ) self.play( randy.change("hooray"), Write(words), ) self.play(Blink(randy)) self.wait() self.play( LaggedStartMap(FadeOut, VGroup(brace, words, randy), shift=DOWN) ) class ToTheComplexPlane(InteractiveScene): def construct(self): plane = ComplexPlane() plane.add_coordinate_labels() label = Text("Complex plane") label.to_corner(UL, buff=MED_SMALL_BUFF) label.set_backstroke(width=10) poly = Tex( "f(x) = (1 + x)(1 + x^2)\\cdots\\left(1+x^{2{,}000}\\right)", tex_to_color_map={"x": YELLOW} ) poly.scale(0.75) poly.next_to(label, DOWN, MED_LARGE_BUFF, LEFT) poly.set_backstroke(width=8) self.play( Write(plane), Write(label), ) self.play(FadeIn(poly, DOWN)) self.wait() class StudentSaysWhat(TeacherStudentsScene): def construct(self): self.student_says( "I'm sorry, what?!", target_mode="angry" ) self.play( self.teacher.change("happy"), self.change_students("confused", "sassy", "angry") ) self.look_at(self.screen) self.wait(4) class FocusOnPropertiesNotValues(TeacherStudentsScene): def construct(self): morty = self.teacher kw = dict( tex_to_color_map={"\\zeta": YELLOW} ) words = VGroup( Tex("\\text{Don't worry about the}\\\\ \\text{numerical value of } \\zeta", **kw), Tex("\\text{Focus on properties}\\\\ \\text{of } \\{\\zeta^1, \\zeta^2, \\zeta^3, \\zeta^4\\, \\zeta^5\\}", **kw), ) words.move_to(self.hold_up_spot, DOWN).shift_onto_screen() self.play( morty.change('raise_right_hand'), self.change_students("erm", "confused", "hesitant", look_at=words[0]), FadeIn(words[0], UP) ) self.wait(3) self.play( morty.change("hooray", words[1]), FadeIn(words[1], UP), words[0].animate.shift(2.5 * UP), self.change_students("tease", "happy", "tease") ) self.wait(4) class CanYouComputeThis(InteractiveScene): def construct(self): text = Text("Can you compute this?") text.move_to(2 * RIGHT) arrow = Arrow(text.get_bottom(), 2 * DOWN) VGroup(text, arrow).set_color(GREEN_B) self.play(Write(text), ShowCreation(arrow)) self.wait() class ConjugatePairFact(InteractiveScene): def construct(self): # Plane plane = ComplexPlane((-2, 2), (-1, 1)) plane.set_height(3) plane.to_corner(DR) plane.add_coordinate_labels([-1, 0, 1, 2, -1j, 1j], font_size=18) plane.coordinate_labels[-2].set_y(plane.c2p(0, -1)[1] + SMALL_BUFF, DOWN) # Numbers z0 = complex(1.5, 0.5) zs = [z0, z0.conjugate()] points = [plane.n2p(z) for z in zs] dots = Group(*(GlowDot(point, color=RED) for point in points)) lines = Line().replicate(2) lines.set_stroke(RED, 2) lines.add_updater(lambda ls: [line.put_start_and_end_on(plane.n2p(0), dot.get_center()) for line, dot in zip(ls, dots)]) labels = VGroup( Tex("a + bi", font_size=24).next_to(points[0], UP, SMALL_BUFF), Tex("a - bi", font_size=24).next_to(points[1], DOWN, SMALL_BUFF), ) # Equation lhs = "(a + bi)(a - bi)" rhs = "||a + bi|| \\cdot ||a - bi||" eq = Tex( lhs + " = a^2 + b^2 = " + rhs, isolate=[lhs, rhs] ) eq.match_width(plane) eq.next_to(plane, UP) lhs_brace = Brace(eq.select_part(lhs), UP, buff=SMALL_BUFF) rhs_brace = Brace(eq.select_part(rhs), UP, buff=SMALL_BUFF) lhs_brace.add(lhs_brace.get_text("Product", font_size=30)) rhs_brace.add(rhs_brace.get_text("Product of magnitudes", font_size=30)) lines.update() self.play( FadeIn(VGroup(plane, labels), lag_ratio=0.01), ShowCreation(lines), FadeIn(dots), ) self.play(FadeIn(eq, UP)) self.wait() self.play(Swap(*dots)) self.add(lines) self.add(dots) self.wait() self.play(LaggedStart( FadeIn(lhs_brace, 0.5 * UP), FadeIn(rhs_brace, 0.5 * UP), )) self.wait(4) class HangInThereRecapPrep(TeacherStudentsScene): def construct(self): # Hang on self.play_student_changes( "dejected", "tired", "concerned_musician", look_at=self.screen, ) self.wait(2) self.teacher_says( "Hang in\nthere!", target_mode="tease", added_anims=[self.change_students("plain", "tease", "hesitant")] ) self.wait(4) self.student_says( "Can you recap\nwhere we are?", ) self.play_student_changes("confused", "thinking", added_anims=[self.teacher.change("happy")]) self.wait(3) class AskIfItMakesSense(InteractiveScene): def construct(self): randy = Randolph(height=2) randy.to_edge(DOWN) self.play(PiCreatureBubbleIntroduction( randy, Text("Does this...\nmake sense?", font_size=36), bubble_config=dict(width=3.5, height=2), target_mode="maybe", )) self.play(Blink(randy)) self.wait() class RootOfUnityRearranging(InteractiveScene): def construct(self): kw = dict(tex_to_color_map={"\\zeta": YELLOW}) expressions = VGroup( Tex("z^5 = 1", **kw), Tex("z^5 - 1 = 0", **kw), Tex("z^5 - 1 = (z - \\zeta^0)(z - \\zeta^1)(z - \\zeta^2)(z - \\zeta^3)(z - \\zeta^4)", **kw), ) expressions[:2].scale(1.5, about_edge=UP) subtexts = VGroup( Tex("\\text{Solutions: } \\zeta^0,\\, \\zeta^1,\\, \\zeta^2,\\, \\zeta^3,\\, \\zeta^4", **kw), Tex("\\text{Roots: } \\zeta^0,\\, \\zeta^1,\\, \\zeta^2,\\, \\zeta^3,\\, \\zeta^4", **kw), ) subtexts.next_to(expressions, DOWN, LARGE_BUFF) self.play(FadeIn(expressions[0])) self.play(Write(subtexts[0])) self.wait() self.play( TransformMatchingShapes(*expressions[:2]), FadeTransform(*subtexts[:2]), ) self.wait() self.play( expressions[1].animate.move_to(expressions[2], LEFT) ) self.play( FadeOut(expressions[1][-1]), FadeTransform(expressions[1][:5], expressions[2][:5]), TransformMatchingShapes(subtexts[1], expressions[2][5:]), ) self.wait() class RotationalSum(InteractiveScene): n_iterations = 40 def construct(self): # Intro outer_r = 3 inner_r = 2.0 circle = Circle(radius=outer_r) circle.set_stroke(GREY_B, 2) points = outer_r * compass_directions(5) values = VGroup(*( Integer(0, edge_to_fix=ORIGIN).move_to(point) for point in points )) values[0].edge_to_fix = LEFT rects = VGroup(*(BackgroundRectangle(v) for v in values)) rects.set_fill(BLACK, 1) def update_rects(rects): for rect, value in zip(rects, values): rect.replace(value, stretch=True) rect.set_width(value.get_width() + SMALL_BUFF) rects.add_updater(update_rects) def update_values(values): for v in values: v.set_max_width(1, about_edge=v.edge_to_fix) values.add_updater(update_values) values[0].increment_value() self.add(circle) self.add(rects, values) # Add labels labels = VGroup(*( OldTexText(f"sum $\\equiv$ {n}\\\\mod 5", font_size=30) for n in range(5) )) colors = [YELLOW, *color_gradient([BLUE_B, BLUE_D], 4)] for label, rect, color in zip(labels, rects, colors): label.set_fill(color) label.add_background_rectangle() # label.next_to(rect, DOWN, SMALL_BUFF) label.next_to(rect, normalize(rect.get_center()), SMALL_BUFF) labels[0].next_to(rects[0], DR, SMALL_BUFF) self.add(labels) # Corner set set_tex = get_set_tex([]) set_tex.scale(0.75) set_tex.to_corner(UL) set_tex.shift(LEFT) self.camera.frame.move_to(LEFT) self.add(set_tex) # Iterative all for n in range(1, self.n_iterations + 1): value_copies = values.copy() to_add = [0] * 5 for i, vc in enumerate(value_copies): new_i = (i + n) % 5 vc.move_to((inner_r / outer_r) * points[new_i]) to_add[new_i] = vc.get_value() vc.target = VectorizedPoint(values[new_i].get_center()) vc.target.set_opacity(0) reduced_n = n % 5 path_arc = min(reduced_n * TAU / 5, TAU / 3) rot_label = Text(f"Add {n}", font_size=30) arcs = VGroup(Arc(0, path_arc), Arc(TAU / 2, path_arc)) for arc in arcs: arc.add_tip(width=0.1, length=0.1) if reduced_n == 0: arcs.set_opacity(0) new_set_tex = get_set_tex([*set_tex.values, n]) new_set_tex.match_height(set_tex) new_set_tex.move_to(set_tex, LEFT) self.remove(set_tex) self.play( TransformFromCopy( values, value_copies, path_arc=-path_arc ), FadeIn(rot_label), TransformMatchingTex( set_tex, new_set_tex, fade_transform_mismatches=(len(set_tex) == len(new_set_tex)), remover=True, ), *map(ShowCreation, arcs) ) set_tex = new_set_tex self.add(set_tex) self.play(*map(FadeOut, [rot_label, *arcs])) self.play( *( ChangeDecimalToValue( v, v.get_value() + ta, time_span=(0.5, 1), ) for v, ta in zip(values, to_add) ), *( MoveToTarget(vc, remover=True) for v, vc in zip(values, value_copies) ), ) self.wait() class HighlightAnswerParts(InteractiveScene): def construct(self): self.add(get_question_title()) frac = "\\frac{1}{5}" e1 = "2^{2{,}000}" e2 = "4 \\cdot 2^{400}" answer = Tex( f"{frac} \\Big({e1} + {e2} \\Big)", isolate=[frac, e1, e2], font_size=60 ) answer.move_to(UP) p1 = VGroup(answer.select_part(frac), answer.select_part(e1)) p2 = answer.select_part(e2) p1_rect = SurroundingRectangle(p1) p2_rect = SurroundingRectangle(p2) self.add(answer) self.wait() self.play(ShowCreation(p1_rect)) self.wait() self.play(ShowCreation(p2_rect), FadeOut(p1_rect)) self.wait() self.play(FadeOut(p2_rect)) class ReferenceZetaPromise(TeacherStudentsScene): def construct(self): morty = self.teacher ss = self.students self.student_says( OldTexText("Didn't you once promise\\\\a video about $\\zeta(s)$ and primes?"), target_mode="sassy", index=0, added_anims=[ ss[1].change("hesitant"), ss[2].change("angry"), ] ) self.play(morty.change("guilty")) self.wait(3) self.play( RemovePiCreatureBubble(ss[0], target_mode="pondering", look_at=self.screen), ss[1].change("pondering", self.screen), ss[2].change("thinking", self.screen), morty.change("raise_right_hand", self.screen) ) self.wait(4) class FactorLargeInteger(InteractiveScene): def construct(self): p_value = 314159265359 q_value = 271828182863 p, q, N = [ Tex("{:,}".format(value).replace(",", "{,}")) for value in (p_value, q_value, p_value * q_value) ] p.set_color(TEAL) q.set_color(BLUE) N.to_edge(UP) eq = Tex("=", font_size=72).rotate(90 * DEGREES) eq.next_to(N, DOWN) prod = VGroup(p, Tex('\\times'), q) prod.arrange(RIGHT, buff=MED_SMALL_BUFF) prod.next_to(eq, DOWN) self.play(FadeIn(N)) self.wait() self.play( LaggedStart( TransformMatchingShapes(N.copy(), p.copy()), Write(prod[1]), TransformMatchingShapes(N.copy(), q.copy()), lag_ratio=0.5, ) ) self.wait() class WriteDFTMatrix(InteractiveScene): def construct(self): matrix = Tex(r"""\frac{1}{\sqrt{N}}\left[\begin{array}{cccccc} 1 & 1 & 1 & 1 & \cdots & 1 \\ 1 & \zeta & \zeta^{2} & \zeta^{3} & \cdots & \zeta^{N-1} \\ 1 & \zeta^{2} & \zeta^{4} & \zeta^{6} & \cdots & \zeta^{2(N-1)} \\ 1 & \zeta^{3} & \zeta^{6} & \zeta^{9} & \cdots & \zeta^{3(N-1)} \\ \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \\ 1 & \zeta^{N-1} & \zeta^{2(N-1)} & \zeta^{3(N-1)} & \cdots & \zeta^{(N-1)(N-1)} \end{array}\right] """ ) self.play(Write(matrix, lag_ratio=0.05, run_time=5)) class FourierSeriesWrapper(VideoWrapper): title = "Fourier series" wait_time = 4 class GeneratingfunctionologyTitle(InteractiveScene): def construct(self): title = Text("Generatingfunctionology", font_size=60) author = Text("by Herbert Wilf") author.next_to(title, DOWN, MED_LARGE_BUFF, LEFT) author.set_color(GREY_B) self.play(Write(title)) self.play(FadeIn(author, LEFT)) self.wait() class EndScreen(PatreonEndScreen): pass class Thumbnail(InteractiveScene): def construct(self): # Add plane plane = ComplexPlane( (-3, 3), (-3, 3), background_line_style=dict(stroke_color=BLUE_D, stroke_width=3), faded_line_ratio=1, axis_config=dict(stroke_color=GREY_B), ) plane.set_width(FRAME_WIDTH) plane.scale(1.2) # plane.move_to(0.75 * DOWN) # plane.add_coordinate_labels(font_size=24) circle = Circle(radius=get_norm(plane.n2p(1) - plane.n2p(0))) circle.move_to(plane.n2p(0)) circle.set_stroke(WHITE, 2) globals().update(locals()) points = [plane.n2p(np.exp(complex(0, angle))) for angle in np.arange(0, TAU, TAU / 5)] glow_dots = GlowDots(points, radius=0.5) dots = DotCloud(points, radius=0.05, color=YELLOW) lines = VGroup(*(Line(plane.n2p(0), point) for point in points)) lines.set_stroke(YELLOW, 4) self.add(plane) self.add(circle) self.add(lines) self.add(dots) self.add(glow_dots) # Question st = "$\\big\\{1,\\dots, 2000\\big\\}$" question = OldTexText( f"How many subsets of {st}\\\\", "have a sum divisible by 5?", tex_to_color_map={st: TEAL} ) question.set_backstroke(BLACK, width=20) # question.set_width(FRAME_WIDTH - 0.5) question.set_width(FRAME_WIDTH - 3.5) question.to_edge(UP, buff=0.25) br = VGroup(BackgroundRectangle(question[:2], buff=SMALL_BUFF), BackgroundRectangle(question[2], buff=SMALL_BUFF)) br.set_fill(BLACK, 2) # self.add(br, question) # Complex words = Text("Use complex numbers of course...", color=YELLOW) words.set_backstroke(width=20) # words.add_background_rectangle(opacity=0.95, buff=MED_SMALL_BUFF) words.set_width(FRAME_WIDTH / 2 - 0.1) words.to_corner(DL, buff=SMALL_BUFF) # self.add(words) # self.wait() class AltThumbnail(InteractiveScene): def construct(self): # Organize sets subsets = [ subset for subset in get_subsets(range(1, 10)) if sum(subset) % 5 == 0 ] n_shown = 28 shown_sets = VGroup(*(get_set_tex(ss) for ss in subsets[:n_shown])) shown_sets.arrange(DOWN, aligned_edge=LEFT) shown_sets[n_shown // 2:].next_to(shown_sets[:n_shown // 2], RIGHT, MED_LARGE_BUFF) shown_sets.refresh_bounding_box() shown_sets.set_height(FRAME_HEIGHT - 1) shown_sets.center().to_edge(LEFT) dots = OldTex("\\vdots") dots.replace(shown_sets[-1], dim_to_match=1) shown_sets.replace_submobject(-1, dots) self.add(shown_sets) # Phrase text = Text("Use complex numbers", font_size=90) text.set_color(YELLOW) text.set_x(2) text.to_edge(UP) text.set_backstroke(width=20) subtext = Text("...of course") subtext.next_to(text, DOWN, buff=MED_LARGE_BUFF, aligned_edge=RIGHT) self.add(text) self.add(subtext) # Unit circle plane = ComplexPlane( (-2, 2), (-2, 2), background_line_style=dict(stroke_color=BLUE_D, stroke_width=3), faded_line_ratio=1, axis_config=dict(stroke_color=GREY_B), ) plane.set_width(9.5) plane.match_x(text) plane.to_edge(UP, buff=0) circle = Circle(radius=get_norm(plane.n2p(1) - plane.n2p(0))) circle.move_to(plane.n2p(0)) circle.set_stroke(WHITE, 2) points = [plane.n2p(np.exp(complex(0, angle))) for angle in np.arange(0, TAU, TAU / 5)] glow_dots = GlowDots(points, radius=0.5) dots = DotCloud(points, radius=0.05, color=YELLOW) lines = VGroup(*(Line(plane.n2p(0), point) for point in points)) lines.set_stroke(YELLOW, 4) self.add(plane) self.add(circle) self.add(lines) self.add(dots) self.add(glow_dots) self.add(text, subtext)
from manim_imports_ext import * class IntersectionAndUnion(InteractiveScene): def construct(self): self.camera.frame.scale(1.1) # Title title = Text("Educational content creation by individuals", font_size=60) title.to_edge(UP) title_start = title.select_part("Educational content creation") by_ind = title.select_part("by individuals") by_ind.set_color(TEAL) self.add(title_start) self.play( Write(by_ind), FlashUnder(by_ind, run_time=3, color=TEAL, buff=0.1) ) # Circles circles = Circle(radius=2.5).replicate(2) circles.arrange(RIGHT, buff=-2.0) circles.set_stroke(WHITE, width=0) circles[0].set_fill(BLUE_D, 0.5) circles[1].set_fill(TEAL_D, 0.5) circles.next_to(title, DOWN, LARGE_BUFF) circle_titles = VGroup( Text("People with\ngood lessons"), Text("People with the\ntime and know-how\nto produce videos,\ninteractives, etc.", alignment="LEFT"), ) circle_titles.scale(0.75) for ct, circ, vect in zip(circle_titles, circles, [LEFT, RIGHT]): ct.next_to(circ, vect, buff=0, aligned_edge=UP) ct.match_color(circ) self.play( LaggedStartMap(Write, circle_titles, lag_ratio=0.25), LaggedStartMap(DrawBorderThenFill, circles, lag_ratio=0.25), ) self.wait() # Intersection inter = Intersection(*circles) inter.set_stroke(WHITE, 3) inter.set_fill(TEAL, 1.0) inter.flip() inter.refresh_triangulation() self.play( DrawBorderThenFill(inter), circles.animate.set_fill(opacity=0.25) ) self.wait() # Collaboration cross = Cross(by_ind) new_text = Text("from collaborations", font_size=60) new_text.set_color(YELLOW) new_text.move_to(by_ind, UL) title_start.generate_target() VGroup(title_start.target, new_text).set_x(0) union = Union(*circles) union.set_stroke(WHITE, 3) self.play(ShowCreation(cross)) self.play( VGroup(by_ind, cross).animate.scale(0.5).shift(0.75 * DOWN), FadeIn(new_text, 0.5 * DOWN), MoveToTarget(title_start), FadeOut(inter), circles.animate.set_fill(opacity=0.7), ShowCreation(union) ) self.wait(3) class WinnerCategories(InteractiveScene): def construct(self): # Text title = Text("In choosing winners, we will select:", font_size=60) title.to_edge(UP) kw = dict(t2c={"non-video": BLUE, "video": RED, "collaboration": YELLOW}) cats = VGroup( Text("At least one video entry", **kw), Text("At least one non-video entry", **kw), Text("At least one collaboration", **kw), ) cats[1].select_part("non-video").set_color(BLUE) cats.arrange(DOWN, buff=0.75, aligned_edge=LEFT) cats.next_to(title, DOWN, LARGE_BUFF) details = Text("(See initial substack post for details)", font_size=36) details.next_to(cats, DOWN, LARGE_BUFF) details.set_fill(GREY_B) self.add(title) self.play(Write(cats[0], run_time=1)) self.wait(0.5) self.play(TransformMatchingStrings(cats[0].copy(), cats[1])) self.wait(0.5) self.play(TransformMatchingStrings(cats[1].copy(), cats[2])) self.play(FlashAround(cats[2], run_time=2)) self.wait() self.play(FadeIn(details, 0.5 * DOWN)) self.wait() class ComplainAboutGithub(TeacherStudentsScene): def construct(self): pis = self.students morty = self.teacher self.play( pis[1].says( "Aren't GitHub issues\nmeant for, like, tracking\nbugs with code?", mode="sassy" ), morty.change("guilty"), pis[0].change("confused"), pis[2].change("erm"), ) self.wait(2) self.play(morty.change("shruggie")) self.wait(2) class Triumverate(PiCreatureScene): def construct(self): # Introduce team morty, prof, artist = self.pi_creatures self.clear() self.add(morty) prof_label = Text("Domain expert", font_size=36).next_to(prof, DOWN) artist_label = Text("Artist/animator", font_size=36).next_to(artist, DOWN) morty_label = Text("Animations/Writing\n(Whatever is most helpful)", font_size=36) morty_label.next_to(morty, UP) self.play( FadeIn(prof_label, RIGHT), FadeIn(prof, RIGHT), morty.change("tease", prof.eyes) ) self.play(prof.change("pondering")) self.wait(2) self.play( FadeIn(artist, RIGHT), FadeIn(artist_label, RIGHT), morty.change("tease", artist.eyes), ) self.play( artist.change("hooray", morty.eyes), prof.change("thinking", artist.eyes), ) self.wait(2) self.play(FadeIn(morty_label, UP)) # Show video logo = Logo() logo.set_height(1.5) logo.move_to(UP) video = VideoIcon() video.set_color(RED_E) video.match_width(logo) video.next_to(logo, DOWN, LARGE_BUFF) self.play( Write(logo.iris_background, stroke_width=1), GrowFromCenter(logo.spike_layers, lag_ratio=0.1, run_time=2), Animation(logo.pupil), morty.change("thinking", logo), prof.change("pondering", logo), artist.change("tease", logo) ) self.play(FadeIn(video, DOWN)) # Footnote footnote = Text(""" *Needless to say, such a collaboration would not be considered for winning SoME2, but I'd be happy to compensate collaborators here for their time. """, font_size=24, alignment="LEFT") footnote.to_corner(DR) self.play(FadeIn(footnote)) self.wait(2) def create_pi_creatures(self): kw = dict(height=2.0) morty = Mortimer(**kw) prof = PiCreature(color=GREY_D, **kw) artist = PiCreature(color=TEAL, **kw) morty.to_edge(RIGHT, buff=1.5) VGroup(prof, artist).arrange(DOWN, buff=1.5).to_edge(LEFT, buff=1.5) return VGroup(morty, prof, artist) class Winners(InteractiveScene): def construct(self): # Winners winners = PiCreature(color=YELLOW_D).replicate(5) for winner in winners: winner.body.set_gloss(0.5) winners.set_height(1.5) winners.arrange_to_fit_width(12) winners.set_opacity(0) brilliant_logo = SVGMobject("BrilliantLogo").set_height(1) brilliant_logo.insert_n_curves(100) brilliant_name = Text("Brilliant", font="Simplo Soft Medium") brilliant_name.set_height(brilliant_logo.get_height() * 0.5) brilliant_name.next_to(brilliant_logo, RIGHT) brilliant_logo.add(brilliant_name) brilliant_logo.set_fill(WHITE) brilliant_logo.set_x(0) brilliant_logo.to_edge(UP) cash = Text("$1,000").set_color(GREY_A).replicate(5) for c, pi in zip(cash, winners): c.next_to(pi, DOWN) self.play(LaggedStart(*( pi.change("hooray").set_opacity(1) for pi in winners )), lag_ratio=0.2) self.wait() self.play(Write(brilliant_logo, run_time=1)) self.play( LaggedStart(*(pi.animate.look(DOWN) for pi in winners)), LaggedStartMap(FadeIn, cash, shift=DOWN, lag_ratio=0.5) ) self.play(LaggedStartMap(Blink, winners)) self.wait() class EndingAnimation(InteractiveScene): def construct(self): self.add(FullScreenRectangle()) frame = ScreenRectangle(height=4) frame.set_fill(BLACK, 1) frame.set_stroke(WHITE, 0) boundary = AnimatedBoundary(frame) self.add(frame) self.add(boundary) self.wait(20) class Thumbnail(InteractiveScene): def construct(self): # text = Text("More\nMath\nPlease", alignment="LEFT") # text.set_height(6) # text.to_edge(LEFT, buff=1.0) text = Text("Summer\nof\nMath\nExposition", alignment="LEFT") text.set_height(FRAME_HEIGHT - 1) text.to_edge(LEFT) self.add(text) randy = Randolph(mode="thinking", color=YELLOW, height=5) randy.to_corner(UR, buff=1.0) randy.look_at(text) self.add(randy) two = Text("Round 2") two.set_height(1) two.set_color(YELLOW) two.next_to(text[-1], RIGHT, buff=0.7, aligned_edge=DOWN) self.add(two)
from manim_imports_ext import * import pandas as pd import requests from _2021.some1_winners import AllVideosOrdered DOC_DIR = os.path.join(get_output_dir(), "2022/some2/winners/") def get_entry_tile(): rect = ScreenRectangle(height=1) rect.set_fill(GREY_D, 1) rect.set_stroke(WHITE, 1) rect.set_gloss(0) qmarks = Text("???") qmarks.move_to(rect) return Group(rect, qmarks) def save_thumbnails(slugs): for slug in slugs: url = f"https://img.youtube.com/vi/{slug}/maxresdefault.jpg" img_data = requests.get(url).content with open(os.path.join(DOC_DIR, "thumbnails", f'{slug}.jpg'), 'wb') as handler: handler.write(img_data) def url_to_image(self, url): if url.startswith("https://youtu.be/"): name = url.split("/")[-1] # Get slug else: name = [p for p in url.split("/") if p][-1].split(".")[0] return ImageMobject(os.path.join(DOC_DIR, f"thumbnails/{name}")) class ExampleChannels(InteractiveScene): def construct(self): # Channel titles self.add(FullScreenFadeRectangle(fill_color=GREY_E, fill_opacity=1)) channels = [ ("Eric Rowland", "8.9k", "3gyHKCDq1YA", 423816), ("A Well-Rested Dog", "15k", "5M2RWtD4EzI", 381953), ("polylog", "10k", "-64UT8yikng", 225508), ("A Bit Wiser", "6.5k", "_DaTsI42Wvo", 104138), ("SithDev", "7.3k", "6JxvKfSV9Ns", 134753), ("Another Roof", "11k", "dKtsjQtigag", 136517), ("Marc Evanstein", "3.1k", "8x374slJGuo", 161853), ("Armando Arredondo", "4.6k", "_lb1AxwXLaM", 272279), ("HexagonVideos", "2.8k", "-vxW42R47bc", 219047), ("SackVideo", "12k", "UJp4q2D2Nh0", 233851), ("Morphocular", "31k", "2dwQUUDt5Is", 281021), ] # save_thumbnails([c[2] for c in channels]) tile = ScreenRectangle() tile.stretch(0.8, 0) tile.set_stroke(WHITE, 0) tile.set_fill(GREY_E, 0) globals().update(locals()) tiles = Group(*(Group(tile.copy()) for x in range(9))).arrange_in_grid(3, 3, buff=0) tiles.set_height(FRAME_HEIGHT) for tile, channel in zip(tiles, channels): name, subs, slug, views = channel video = ImageMobject(os.path.join(DOC_DIR, "thumbnails", slug)) video.set_height(tile.get_height() * 0.55) video.move_to(tile) title = Text(f"{name} ({subs} subs)", font_size=18, color=GREY_A) title.next_to(video, UP, SMALL_BUFF) count = VGroup( # Text(f"{subs} subs,", font_size=24), Integer(views, font_size=30), Text("Views", font_size=30) ) count.arrange(RIGHT, buff=0.1, aligned_edge=UP) count.next_to(video, DOWN, buff=0.15) tile.add(title, video, count) self.add(tiles) # Show tiles self.play( LaggedStart(*( UpdateFromAlphaFunc(tile, lambda m, a: m.set_opacity(a)) for tile in tiles ), lag_ratio=0.5), LaggedStart(*( CountInFrom(tile[-1][0], 0, run_time=2.5) for tile in tiles ), lag_ratio=0.2) ) class AllVideos(AllVideosOrdered): os.path.join(DOC_DIR, "some2_video_urls.txt") grid_size = 3 time_per_image = 0.2 class IntroScene(InteractiveScene): def construct(self): # Intro logos = Group(ImageMobject("Leios"), Logo()) for logo in logos: logo.set_height(1.5) logos.arrange(DOWN, buff=LARGE_BUFF) logos.to_edge(LEFT) title = Text("Summer of Math\nExposition", font_size=96) title.move_to(midpoint(logos.get_right(), RIGHT_SIDE)) self.add(title) self.play(LaggedStart( FadeIn(logos[0], LEFT), Write(logos[1], run_time=1, lag_ratio=0.01, stroke_width=0.1, stroke_color=BLACK), lag_ratio=0.3, )) self.wait() # Compress name words = ["Summer", "of", "Math", "Exposition"] inits = VGroup() to_fade = VGroup() for word in words: part = title.select_part(word) inits.add(part[0]) to_fade.add(*part[1:]) inits.generate_target() inits.target.arrange(RIGHT, aligned_edge=DOWN, buff=SMALL_BUFF) inits.target.set_height(0.8) inits.target.set_stroke(WHITE, 1) inits.target.center().to_edge(UP) self.play( FadeOut(to_fade, lag_ratio=0.1, shift=UP, run_time=1.5), MoveToTarget(inits, time_span=(0.25, 1.5)), FadeOut(logos, LEFT) ) # Add 2 two = Text("2") two.match_height(inits) two.set_color(YELLOW) inits.generate_target() inits.target.shift(0.25 * LEFT) two.next_to(inits.target, RIGHT, buff=0.2, aligned_edge=DOWN) globals().update(locals()) self.play( LaggedStart(*( FadeTransform(init.copy(), two) for init in inits ), lag_ratio=0.1), MoveToTarget(inits), ) inits.add(two) self.wait() # View count count = VGroup( Integer(7000000, edge_to_fix=RIGHT), Text("collective views"), ) count.arrange(RIGHT, aligned_edge=UP) count.set_height(0.6) count.to_corner(UR) self.play( inits.animate.set_height(0.6).to_corner(UL), FadeIn(count[1]), CountInFrom(count[0], 0, run_time=3), ) self.add(count) count[0].edge_to_fix = LEFT count[0].add_updater(lambda m, dt: m.increment_value(int(dt * 1000))) self.wait(5) class PeerReview(InteractiveScene): def construct(self): # Add everyone n_peers = 10 peers = VGroup(*( PiCreature(color=random.choice([BLUE_E, BLUE_D, BLUE_C, BLUE_B])) for x in range(n_peers) )) peers.arrange(RIGHT) peers.set_width(FRAME_WIDTH - 1) peers.to_edge(DOWN) copies = VGroup(peers.copy().set_y(0), peers.copy().to_edge(UP, LARGE_BUFF)) all_pis = VGroup(*peers, *it.chain(*copies)) videos = VGroup(*(VideoIcon() for peer in all_pis)) for video, pi in zip(videos, all_pis): video.set_height(0.25) video.set_color(random_bright_color()) video.next_to(pi.get_corner(UR), UP, SMALL_BUFF) self.add(peers) pairs = list(zip(videos, all_pis)) random.shuffle(pairs) self.play(LaggedStart(*( AnimationGroup( pi.change("raise_right_hand"), FadeIn(video, 0.5 * UP) ) for video, pi in pairs ))) # Entry box entry_box = Rectangle(4, 4) entry_box.set_fill(GREY_E, 1) entry_box.set_stroke(WHITE, 1) entry_box.to_edge(UP, buff=0.5) entry_box_label = Text("All entries") entry_box_label.next_to(entry_box.get_top(), DOWN, SMALL_BUFF) entry_box_label.set_backstroke(BLACK, 5) videos.generate_target() videos.target.arrange_in_grid(buff=0.25) videos.target.move_to(entry_box) self.add(entry_box, videos, entry_box_label) self.play( FadeIn(entry_box), FadeIn(entry_box_label), FadeOut(copies, lag_ratio=0.1), MoveToTarget(videos), LaggedStart(*(peer.change("tease", ORIGIN) for peer in peers)) ) # Peer review process peers.shuffle() for pi in peers: pi.watchlist = list(videos.copy()) random.shuffle(pi.watchlist) self.play(LaggedStart(*( AnimationGroup( pi.watchlist[0].animate.next_to(pi.get_top(), UL, buff=0.1).shift(0.025 * RIGHT), pi.watchlist[1].animate.next_to(pi.get_top(), UR, buff=0.1).shift(0.025 * LEFT), pi.change("pondering", pi.get_top() + UP), ) for pi in peers ), lag_ratio=0.1)) for x in range(10): globals().update(locals()) self.play(LaggedStart(*( AnimationGroup( pi.change( ["raise_right_hand", "raise_left_hand"][1 - bit], pi.watchlist[x + bit], ).set_anim_args(run_time=0.5), pi.watchlist[x + bit].animate.scale(1.2), pi.watchlist[x + 1 - bit].animate.scale(0.8), ) for pi in peers for bit in [random.randint(0, 1)] ), lag_ratio=0.1)) self.play(LaggedStart(*( AnimationGroup( pi.change("sassy", pi.get_top() + UP).set_anim_args(run_time=0.5), FadeOut(pi.watchlist[x], scale=0.5), pi.watchlist[x + 1].animate.set_height(0.25).next_to(pi.get_top(), UL, buff=0.1).shift(0.025 * RIGHT), pi.watchlist[x + 2].animate.next_to(pi.get_top(), UR, buff=0.1).shift(0.025 * LEFT), ) for pi in peers ))) def get_judgement_animation(self, pi, videos): vids = list(videos.copy()) random.shuffle(vids) anims = [Animation(Mobject(), run_time=3 * random.random())] anims.append(AnimationGroup( vids[0].animate.next_to(pi.get_top(), UL, buff=0.1), vids[1].animate.next_to(pi.get_top(), UR, buff=0.1), pi.change("pondering", pi.get_top() + UP), )) for i in range(8): anims.append(pi.animate.change(random.choice(["raise_right_hand", "raise_left_hand"]))) anims.append(AnimationGroup( FadeOut(vids[i], LEFT), vids[i + 1].animate.next_to(pi.get_top(), UL, buff=0.1), videos[i + 2].animate.next_to(pi.get_top(), UR, buff=0.1), )) return Succession(*anims) class Over10KComparisons(InteractiveScene): def construct(self): # Start count = VGroup( Integer(10000), Text("Comparisons") ) count.arrange(DOWN) count.scale(2) plus = Text("+").scale(2) plus.next_to(count[0], RIGHT, buff=SMALL_BUFF) self.play( CountInFrom(count[0], 0, run_time=3), Write(count[1], run_time=1), ) self.add(plus) self.wait() class YTStatement(InteractiveScene): def construct(self): # Start words = VGroup( Text("Shared viewer base"), OldTex("\\Downarrow", font_size=96).set_stroke(WHITE, 0), Text(""" YT is more likely to recommend one video to viewers of another. """, alignment="LEFT") ) words.arrange(DOWN, buff=MED_LARGE_BUFF) self.add(words[0]) self.play( Write(words[1]), FadeIn(words[2], DOWN) ) self.wait() class HistogramOfViews(InteractiveScene): data = [ 628083, 396785, 359233, 301850, 245930, 243370, 231732, 212708, 209343, 208586, 167442, 153613, 145692, 135465, 130783, 126159, 101919, 93069, 92110, 89790, 82160, 81311, 79598, 67092, 63373, 63239, 62246, 56242, 52840, 47267, 45942, 43032, 42558, 41618, 41201, 39059, 36675, 36138, 35999, 35999, 35805, 34057, 33137, 33009, 31064, 30855, 30616, 30122, 30016, 28817, ] def construct(self): # Add axes axes = Axes((0, 50, 50), (0, 6e5, 1e5), width=12, height=6) axes.to_corner(DR) y_step = 100000 axes.add_coordinate_labels( x_values=range(0), y_values=range(y_step, 7 * y_step, y_step), ) self.add(axes) # Bars bars = VGroup(*( Rectangle( width=axes.x_axis.get_width() / len(self.data), height=value * axes.y_axis.unit_size, ) for value in self.data )) bars.arrange(RIGHT, aligned_edge=DOWN, buff=0) bars.set_fill(opacity=1) bars.set_submobject_colors_by_gradient(BLUE_D, TEAL) bars.set_stroke(BLACK, 2) bars.move_to(axes.get_origin(), DL) bars.shift(0.01 * UR) self.add(bars) # Title title = Text( "Distribution of SoME2 views (top 50 shown)" ) title.move_to(axes, UP) subtitle = Text("7,000,000+ total", font_size=36, fill_color=GREY_B) subtitle.next_to(title, DOWN) self.add(title, subtitle) # Animate bars self.remove(bars) bars.sort(lambda p: -p[0]) self.play(LaggedStart(*( ReplacementTransform(bar.copy().stretch(0, 1, about_edge=DOWN), bar) for bar in bars )), lag_ratio=0.2) self.add(bars) # SoME1 some1_words = Text(""" 2,000,000+ Additional SoME1 views during this time """, font_size=36) box = SurroundingRectangle(some1_words, buff=MED_LARGE_BUFF) box.set_fill(GREY_E, 1) box.set_stroke(WHITE, 1) VGroup(box, some1_words).to_edge(RIGHT) self.play( FadeIn(box), Write(some1_words), ) self.wait() class ValueInSharedGoals(TeacherStudentsScene): def construct(self): # Start morty = self.teacher self.play( morty.says("Never underestimate\ncommunity and\ndeadlines"), self.change_students("happy", "tease", "thinking"), ) self.wait(5) self.play( morty.debubble(mode="raise_right_hand", look_at=self.screen), self.change_students("pondering", "thinking", "erm", look_at=self.screen), ) self.wait(2) # Show links links = VGroup( Text("explanaria.github.io/crystalgroups"), Text("thenumb.at/Autodiff"), Text("xperimex.com/blog/panorama-homography"), Text("calmcode.io/blog/inverse-turing-test.html"), Text("summbit.com/blog/bezier-curve-guide"), Text("lukelavalva.com/theoryofsliding"), Text("chessengines.org"), OldTex("\\vdots") ) links.arrange(DOWN, aligned_edge=LEFT) links[-1].match_x(links[-2]) links.set_width(5) links.to_corner(UR) self.play( morty.change("raise_left_hand", links), self.change_students("tease", "happy", "thinking", look_at=links), FadeIn(links, lag_ratio=0.3, run_time=2) ) self.wait(4) # Who won stds = self.students self.play( FadeOut(links, RIGHT), morty.change("guilty"), stds[0].says("But, like, who actually\nwon the contest?"), stds[1].change("erm", stds[0].eyes), stds[2].change("sassy", stds[0].eyes), ) self.wait(3) class OneHundredEntries(InteractiveScene): def construct(self): # Logos logos = Group(ImageMobject("Leios"), Logo()) for logo in logos: logo.set_height(0.75) logos.arrange(RIGHT, buff=MED_LARGE_BUFF) logos.to_corner(UL) logos[1].flip().flip() # Winners title = Text("Winners", font_size=72) title.add(Underline(title).scale(1.5).insert_n_curves(20).set_stroke(width=(0, 3, 3, 3, 0))) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_color(GREY_A) winners = VGroup( VideoIcon(), self.written_icon(), *(VideoIcon() for x in range(3)) ) winners.set_fill(BLUE_D) winners[1].set_fill(GREY_A) for winner in winners: winner.set_height(0.75) winners.arrange(DOWN, buff=MED_LARGE_BUFF) winners.next_to(title, DOWN, buff=MED_LARGE_BUFF) winners.shift(1.5 * LEFT) prizes = VGroup(*( VGroup( Text("$1,000 + ", color=GREEN), Randolph(mode="thinking", height=0.5, color=YELLOW) ).arrange(RIGHT, buff=MED_SMALL_BUFF).next_to(winner, RIGHT) for winner in winners )) self.add(title) self.play(LaggedStartMap(FadeIn, winners, shift=0.5 * DOWN, lag_ratio=0.1, run_time=1)) self.play(LaggedStartMap(FadeIn, prizes, shift=0.25 * RIGHT, lag_ratio=0.1, run_time=1)) self.wait() self.play(LaggedStartMap(GrowFromCenter, logos, lag_ratio=0.7, run_time=1)) self.wait() # Large batches videos = VideoIcon().get_grid(10, 8, fill_rows_first=False) videos.set_height(6) videos.set_fill(BLUE_D) articles = self.written_icon().get_grid(10, 3, fill_rows_first=False) articles.remove(*articles[-5:]) articles.match_height(videos) articles.next_to(videos, RIGHT, buff=2.0) VGroup(videos, articles).center().to_edge(DOWN, buff=MED_SMALL_BUFF) video_title = Text("80 top videos").next_to(videos, UP, buff=MED_LARGE_BUFF) article_title = Text("25 top non-video entries").next_to(articles, UP, buff=MED_LARGE_BUFF) self.play( LaggedStart(*( ReplacementTransform(vid, random.choice(videos)) for vid in (winners[0], *winners[2:]) )), ReplacementTransform(winners[1], random.choice(articles)), LaggedStartMap(FadeIn, videos), LaggedStartMap(FadeIn, articles), FadeOut(title, UP), LaggedStartMap(FadeOut, prizes, shift=UP), ) self.add(videos, articles) self.play( Write(video_title), Write(article_title), ) self.wait() # Mention added judges guest_words = Text("With guest judging help from:") guest_words.next_to(videos, LEFT, LARGE_BUFF).align_to(video_title, UP) guest_words.set_color(GREY_A) frame = self.camera.frame frame.save_state() judges = VGroup( Text("Alex Kontorovich"), Text("Henry Reich"), Text("Mithuna Yoganathan"), Text("Nicky Case"), Text("Tai-Danae Bradley"), Text("Deniz Ozbay"), Text("Jeffrey Wack"), Text("Fran Herr"), ) judges.arrange(DOWN, aligned_edge=LEFT) judges.next_to(guest_words, DOWN, LARGE_BUFF) momath_brace = Brace(judges[-3:], RIGHT) momath_words = momath_brace.get_text("MoMath\nMuseum", buff=MED_SMALL_BUFF) momath = VGroup(momath_brace, momath_words) momath.set_color(YELLOW) self.play( frame.animate.scale(1.5, about_edge=RIGHT), FadeIn(guest_words), logos.animate.next_to(guest_words, UP), LaggedStartMap(FadeIn, judges, shift=0.5 * RIGHT, lag_ratio=0.5, run_time=6), ) self.play( FadeIn(momath) ) self.wait() # Return self.play( frame.animate.restore(), LaggedStart(*( FadeOut(mob, UL) for mob in [video_title, article_title, *logos, guest_words, *judges, momath] ), run_time=1) ) self.wait() def written_icon(self): rect = Rectangle(height=0.1, width=1.5) rect.set_fill(WHITE, 1) rect.set_stroke(WHITE, 0) result = rect.get_grid(4, 1, buff=0.2) result[-1].stretch(0.5, 0, about_edge=LEFT) return result class FeaturedContentFrame(InteractiveScene): title = "Example Title" thumbnail = "Lion" author = "author" frame_scale_factor = 0.75 def construct(self): # Frames self.add(FullScreenRectangle()) frame = ScreenRectangle() frame.set_fill(BLACK, 1) frame.set_stroke(WHITE, 2) frame.set_height(self.frame_scale_factor * FRAME_HEIGHT) frame.to_edge(DOWN, buff=MED_SMALL_BUFF) self.add(frame) # Title title = Text(self.title, font_size=66) title.set_max_width(FRAME_WIDTH - 1) title.to_edge(UP, buff=MED_SMALL_BUFF) author = Text("by " + self.author, font_size=48, color=GREY_A) author.move_to(midpoint(title.get_bottom(), frame.get_top())) if self.thumbnail: thumbnail = ImageMobject(self.thumbnail) thumbnail.replace(frame, dim_to_match=1) else: thumbnail = Mobject() self.play( Write(title, run_time=1), DrawBorderThenFill(frame), FadeIn(thumbnail), ) self.play(FadeIn(author, shift=0.5 * DOWN)) self.wait() class FourCategories(InteractiveScene): frame_scale_factor = 0.75 def setup(self): super().setup() df = pd.read_csv(os.path.join(DOC_DIR, "featured_entries.csv")) self.titles = df['Title'] self.authors = df['Author'] self.urls = df['Link'] def construct(self): # Four categories regions = VGroup(*(ScreenRectangle() for x in range(4))) regions.set_height(FRAME_HEIGHT / 2) regions.arrange_in_grid(2, 2, buff=0) regions.set_stroke(width=0) regions.set_fill(opacity=0.3) regions.set_submobject_colors_by_gradient( BLUE_D, BLUE_C, BLUE_E, GREY_BROWN, ) titles = VGroup(*( Text(word, font_size=60) for word in ["Motivation", "Clarity", "Novelty", "Memorability"] )) for title, region in zip(titles, regions): title.next_to(region.get_top(), DOWN, buff=MED_SMALL_BUFF) self.play( LaggedStartMap(FadeIn, regions, lag_ratio=0.5), LaggedStartMap(Write, titles, lag_ratio=0.8), run_time=3 ) self.wait() # Lesson tiles tile = self.get_entry_tile().set_height(0.5) regions[0].tiles = tile.get_grid(2, 5) regions[1].tiles = tile.get_grid(2, 2) regions[2].tiles = tile.get_grid(1, 1) regions[3].tiles = tile.get_grid(1, 2) self.tiles = VGroup() for region in regions: region.tiles.move_to(region) self.tiles.add(*region.tiles) self.play(LaggedStart(*( FadeIn(tile, scale=0.8) for tile in self.tiles )), run_time=5, lag_ratio=0.1) self.wait() # Accentuate titles icons = VGroup(*( SVGMobject(file) for file in ["teaching", "gem", "lightbulb", "memory"] )) icons.set_stroke(WHITE, width=0) icons.set_fill(WHITE, opacity=1) icons.set_color_by_gradient(GREY_A, BLUE_B, YELLOW, GREY_B) icons[2].set_opacity(0.8) icons[1].set_opacity(0.7) for title, icon in zip(titles, icons): icon.set_height(1.5 * title[0].get_height()) icon.next_to(title, RIGHT).match_y(title[0]) title.icon = icon self.play( FadeIn(icon, lag_ratio=0.25), FlashUnder(title), ) title.add(icon) self.wait() # Relative importance self.play(LaggedStart( regions[:2].animate.stretch(1.4, 1, about_edge=UP), regions[2:].animate.stretch(0.6, 1, about_edge=DOWN), titles[:2].animate.shift(MED_SMALL_BUFF * DOWN), titles[2:].animate.shift(2 * DOWN), regions[0].tiles.animate.shift(DOWN), regions[1].tiles.animate.shift(DOWN), regions[2].tiles.animate.shift(1.4 * DOWN), regions[3].tiles.animate.shift(1.4 * DOWN), lag_ratio=0.025, run_time=2 )) self.wait() # Isolate Motivation regions[0].save_state() titles[0].save_state() self.add(regions[0], regions[0].tiles) self.play( regions[0].animate.replace(FullScreenRectangle()).set_opacity(0), titles[0].animate.set_x(0), regions[0].tiles.animate.scale(2).center(), FadeOut(regions[1:]), FadeOut(titles[1:]), *(FadeOut(regions[i].tiles) for i in range(1, 4)), ) # Subregions subregions = Rectangle(height=7, width=FRAME_WIDTH / 2).get_grid(1, 2, buff=0) subregions.to_edge(DOWN, buff=0) subregions.set_stroke(WHITE, 1) subregions.set_fill(GREY_E, 1) subtitles = VGroup(Text("Macro"), Text("Micro")) subtitles.scale(1.2) for st, sr in zip(subtitles, subregions): st.next_to(sr.get_top(), DOWN) descriptions = VGroup( Text("Have you generated a\ndesire to learn?"), Text("Is each new idea given\na good reason to be there?"), ) descriptions.scale(0.8) for desc, st in zip(descriptions, subtitles): desc.next_to(st, DOWN, MED_LARGE_BUFF) self.play( Write(subregions), titles[0].animate.to_edge(UP, buff=SMALL_BUFF), regions[0].tiles[:7].animate.scale(0.9).arrange_in_grid(3, 3).move_to(subregions[0]).align_to(ORIGIN, UP), regions[0].tiles[7:].animate.scale(0.9).arrange_in_grid(2, 2).move_to(subregions[1]).align_to(ORIGIN, UP), LaggedStartMap(FadeIn, subtitles, shift=0.5 * DOWN) ) self.wait() self.play(Write(descriptions[0])) for i in range(7): self.highlight_tile(i) self.play(Write(descriptions[1])) for i in range(7, 10): self.highlight_tile(i) # Intersection with clarity frame = self.camera.frame titles[1].save_state() c_region = subregions[0].copy() c_region.set_fill(regions[1].get_fill_color(), 0.2) c_region.set_stroke(BLUE, 3) c_region.next_to(subregions, RIGHT, buff=0.1) titles[1].match_y(titles[0]) titles[1].match_x(c_region) regions[1].tiles.scale(regions[0].tiles[0].get_height() / regions[1].tiles[0].get_height()) regions[1].tiles.arrange_in_grid(buff=0.3) regions[1].tiles.move_to(c_region) regions[1].tiles.align_to(regions[0].tiles[0], UP) self.play( frame.animate.scale(1.55).move_to(subregions[1]), FadeIn(titles[1]), FadeIn(c_region), FadeIn(regions[1].tiles), ) self.wait() c_region.save_state() self.play( c_region.animate.stretch(2, 0, about_edge=RIGHT) ) self.wait() # Attention and focus randy = Randolph() randy.next_to(subregions[0], UP) bucket = VMobject().set_points_as_corners([UL, LEFT, RIGHT, UR]) bucket.set_stroke(WHITE, 1.5) bucket.set_width(1.0).set_height(1.5, stretch=True) bucket.next_to(randy.get_corner(UL), UP, buff=0) bucket_label = Text("Attention and focus", color=YELLOW) bucket_label.next_to(bucket, RIGHT, buff=MED_LARGE_BUFF, aligned_edge=UP) bucket_arrow = Arrow( bucket_label.get_corner(DL) + 0.7 * RIGHT + 0.1 * DOWN, bucket.get_right(), color=YELLOW ) focus_dots = Group(*( GlowDot([ interpolate(bucket.get_x(LEFT) + 0.1, bucket.get_x(RIGHT) - 0.1, random.random()), interpolate(bucket.get_y(DOWN) + 0.1, bucket.get_y(TOP) - 0.1, random.random()), 0, ]) for x in range(40) )) focus_dots.sort(lambda p: p[1]) self.play( frame.animate.move_to(subregions[1], DOWN).shift(MED_SMALL_BUFF * DOWN), VFadeIn(randy), randy.change("tease"), FadeIn(bucket), ) self.play( FadeIn(bucket_label), ShowCreation(bucket_arrow), FadeIn(focus_dots, lag_ratio=0.5), ) self.wait() self.play(Blink(randy)) self.wait() # Draining attention and focus randy_copy = randy.copy() randy_copy.generate_target() randy_copy.target.next_to(subregions.get_corner(UR), UR) randy_copy.target.change_mode("pondering").look(DOWN) bucket_copy = bucket.copy() bucket_copy.generate_target() bucket_copy.target.next_to(randy_copy.target.get_corner(UL), UP, buff=0) bucket_copy.set_opacity(0) focus_dots_copy = focus_dots.copy().set_opacity(0) self.play( MoveToTarget(randy_copy), MoveToTarget(bucket_copy), focus_dots_copy.animate.move_to(bucket_copy.target).set_opacity(1) ) focus_dots_copy.sort(lambda p: -p[1]) self.play( LaggedStartMap(FadeOut, focus_dots_copy, shift=0.2 * UP, scale=3, lag_ratio=0.4, run_time=6), randy_copy.change("erm", regions[1].tiles).set_anim_args(time_span=(4, 5)) ) self.wait() self.play(Blink(randy_copy)) self.wait() # Transition to clarity self.play( titles[1].animate.center().to_edge(UP), regions[1].tiles.animate.scale(1.5).center(), c_region.animate.become(FullScreenRectangle(fill_color=BLACK, fill_opacity=0)), frame.animate.set_height(FRAME_HEIGHT).center(), *( FadeOut(mob, shift=LEFT, time_span=(0.05 * i, 0.05 * i + 1)) for i, mob in enumerate([ randy, bucket, focus_dots, bucket_label, randy_copy, bucket_copy, titles[0], subregions, subtitles, descriptions, *regions[0].tiles, ]) ), run_time=2 ) for i in range(10, 14): self.highlight_tile(i) # Novelty regions[0].restore() regions[0].tiles.scale(0.7) regions[0].tiles.arrange_in_grid(4, 3) regions[0].tiles.move_to(regions[0]).shift(0.5 * DOWN) titles[0].restore() self.remove(titles[1]) self.play( FadeIn(regions), *map(FadeIn, (titles[0], titles[2], titles[3])), *(FadeIn(regions[i].tiles) for i in [0, 2, 3]), regions[1].tiles.animate.scale(regions[0].tiles[0].get_height() / regions[1].tiles[0].get_height()).move_to(regions[1]), titles[1].animate.restore() ) self.play(FlashAround(regions[2], buff=-0.01, run_time=3, time_width=2)) # Isolate novelty self.og_mobjects = Group(*self.mobjects) self.og_mobjects.save_state() self.play( regions[2].animate.replace(FullScreenRectangle(), stretch=True).set_opacity(0), titles[2].animate.center().to_edge(UP), *map(FadeOut, [*titles[:2], titles[3], *regions[:2], regions[3], *self.tiles]) ) # Components of novelty rects = Rectangle().get_grid(1, 2, buff=0) rects.set_height(1.5) rects.set_width(12, stretch=True) rects.next_to(titles[2], DOWN, buff=2.0) rects.set_stroke(WHITE, 1) rects[0].set_fill(BLUE_E, 1) rects[1].set_fill(GREY_BROWN, 1) subtitles = VGroup( Text("Stylistic\noriginality"), Text("Content\noriginality"), ) for st, rect in zip(subtitles, rects): st.rect = rect st.start_width = st.get_width() st.add_updater(lambda m: m.set_max_width(min(m.start_width, 0.8 * m.rect.get_width()))) st.add_updater(lambda m: m.move_to(m.rect)) lines = VGroup(*(Line(titles[2].get_bottom(), st.get_top(), buff=0.25) for st in subtitles)) lines.set_stroke(WHITE, 2) subtitles.suspend_updating() self.play( LaggedStartMap(ShowCreation, lines, lag_ratio=0.5), LaggedStartMap(FadeInFromPoint, subtitles, point=titles[2].get_bottom(), lag_ratio=0.5), ) subtitles.resume_updating() self.wait() self.add(*rects, *subtitles) self.play(*map(FadeIn, rects), FadeOut(lines)) self.play( rects[0].animate.set_width(rects[0].get_width() - 5, stretch=True, about_edge=LEFT), rects[1].animate.set_width(rects[1].get_width() + 5, stretch=True, about_edge=RIGHT), ) self.wait() self.og_mobjects.restore() self.clear() self.add(*self.og_mobjects) # Last couple for i in range(14, 17): self.highlight_tile(i) def get_entry_tile(self): return get_entry_tile() def highlight_tile(self, index): bg = FullScreenFadeRectangle(fill_color=GREY_E, fill_opacity=1) tile = self.tiles[index] title = Text(self.titles[index], font_size=60) author = Text("by " + self.authors[index], font_size=48, color=GREY_A) image = self.url_to_image(self.urls[index]) image.set_width(0.97 * tile.get_width()) image.move_to(tile) image.set_opacity(0.0) original_tile = tile.copy() tile.generate_target() tile.target[1].set_opacity(0) tile.target[0].set_fill(BLACK, 1) tile.target.set_height(self.frame_scale_factor * FRAME_HEIGHT) tile.target.center().to_edge(DOWN, buff=MED_SMALL_BUFF) title.set_max_width(FRAME_WIDTH - 1) title.to_edge(UP, buff=MED_SMALL_BUFF) author.move_to(midpoint(title.get_bottom(), tile.target.get_top())) bg.save_state() bg.replace(tile) bg.set_opacity(0) self.add(bg, tile, image, title) self.play( bg.animate.restore(), MoveToTarget(tile), image.animate.replace(tile.target).set_opacity(1.0), Write(title, time_span=(0.5, 2.0)), ) # self.play() self.play(FadeIn(author, 0.5 * DOWN)) self.wait() tile.replace_submobject(1, image) self.play( tile.animate.replace(original_tile), *map(FadeOut, (bg, title, author)), ) def url_to_image(self, url): return url_to_image(url) class WhoCares(TeacherStudentsScene): def construct(self): # Start morty = self.teacher stds = self.students equation = OldTex("\\sum_{n=1}^N n^2 = \\frac{N(N + 1)(2N + 1)}{6}") equation.set_stroke(WHITE, 1) equation.move_to(self.hold_up_spot, DOWN).shift(UL) self.play( morty.change("raise_right_hand", look_at=equation), Write(equation), self.change_students("pondering", "pondering", "pondering", look_at=equation), ) self.wait() self.play(self.change_students("sassy", "confused", "erm")) self.wait() self.play( stds[0].says("Why should\nI care?", mode="angry"), morty.change("guilty"), ) self.wait() self.play( morty.says("Well...hmmm...", mode="sassy", look_at=equation), stds[1].change("maybe"), ) self.wait(5) class Overphilosophizing(TeacherStudentsScene): def construct(self): # Start morty = self.teacher rects = VGroup(*( Rectangle(width=w) for w in [2, 9, 2] )) rects.set_height(1.0, stretch=True) rects.arrange(RIGHT, buff=0) rects.set_stroke(WHITE, 1) rects.set_fill(opacity=0.5) rects.set_submobject_colors_by_gradient(YELLOW_E, BLUE, GREY_BROWN) rects.set_y(2) words = VGroup(*map(Text, ["Motivation", "Core lesson", "Broader\nconnections"])) words.scale(0.7) for word, rect in zip(words, rects): word.rect = rect word.start_width = word.get_width() word.add_updater(lambda m: m.set_max_width(min(m.rect.get_width() * 0.8, m.start_width))) word.add_updater(lambda m: m.move_to(m.rect)) self.add(*rects, *words) # Shift sizes def left_shift(x, rects=rects, **kw): return ( rects[0].animate.set_width(rects[0].get_width() + x, about_edge=LEFT, stretch=True).set_anim_args(**kw), rects[1].animate.set_width(rects[1].get_width() - x, about_edge=RIGHT, stretch=True).set_anim_args(**kw), ) def right_shift(x, rects=rects, **kw): return ( rects[1].animate.set_width(rects[1].get_width() + x, about_edge=LEFT, stretch=True).set_anim_args(**kw), rects[2].animate.set_width(rects[2].get_width() - x, about_edge=RIGHT, stretch=True).set_anim_args(**kw), ) self.play( morty.change("guilty"), self.change_students("erm", "erm", "erm", look_at=rects), ) self.wait() self.play(*left_shift(2, run_time=3)) self.play(self.change_students("tired", "dejected", "tired", look_at=rects)) self.wait() self.play( morty.change("raise_right_hand"), self.change_students("thinking", "thinking", "thinking", look_at=rects), *left_shift(-3), ) self.wait() self.play(*right_shift(-1)) # Examples beat philosophy exs = OldTexText("Examples", " > Sweeping statements", font_size=36) exs.to_edge(UP) exs.align_to(rects, LEFT) arrow = Arrow(exs[0].get_bottom(), rects[0].get_top(), buff=0.1) self.play( Write(exs), ShowCreation(arrow), ) self.wait(4) class MusicSidenote(InteractiveScene): def construct(self): # Randy randy = Randolph(height=2) randy.to_corner(DL) self.add(randy) # Add notes notes = SVGMobject("quarter-note").replicate(24) notes.arrange(RIGHT, buff=LARGE_BUFF) notes.set_width(FRAME_WIDTH + 5) notes.set_fill(GREY_B, 1) notes.set_stroke(WHITE, 0) for note in notes: note.shift(random.randint(0, 6) * 0.2 * UP) notes.center().to_edge(UP).to_edge(LEFT) self.play( LaggedStart(*( FadeIn(note, 0.2 * LEFT) for note in notes ), lag_ratio=0.3), randy.change("thinking", notes), ) self.play( notes.animate.to_edge(RIGHT).set_anim_args(run_time=3), randy.change("tease"), ) # Technical explanation outline = ScreenRectangle().set_height(4) outline.set_stroke(WHITE, 2) outline.next_to(randy, RIGHT, buff=1.0) outline.to_edge(DOWN, buff=1.0) self.play( ShowCreation(outline), randy.change("confused"), ) self.play(Blink(randy)) self.wait(2) self.play( LaggedStart(*( note.copy().animate.set_opacity(0).scale(0.5).move_to(randy.get_top()) for note in notes ), lag_ratio=0.2), randy.change("concentrating") ) self.play(Blink(randy)) self.wait() class NoveltySubdivision(InteractiveScene): def construct(self): pass class NotAsUnique(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("It's not as\nunique these days", mode="shruggie"), self.change_students("happy", "tease", "happy") ) self.wait(3) class Winners(InteractiveScene): def construct(self): # Add title title = Text("Winners", font_size=72) underline = Underline(title) underline.scale(1.5) underline.insert_n_curves(20) underline.set_stroke(width=(0, 3, 3, 3, 0)) title.add(underline) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_color(YELLOW) self.add(title) # Winner tiles winner_data = [ ("a-767WnbaCQ", "Percolation: a Mathematical Phase Transition", "Spectral Collective"), ("crystalgroups", "Clear Crystal Conundrums", "Ex Planaria"), ("5M2RWtD4EzI", "This Is the Calculus They Won't Teach You", "A Well-Rested Dog"), ("gsZiJeaMO48", "How Realistic CGI Works (And How To Do It Way Faster)", "Joshua Maros"), ("6hVPNONm7xw", "The Coolest Hat Puzzle You've Probably Never Heard", "Going Null"), ] def get_winner_tile(slug, name, author): image = ImageMobject(os.path.join(DOC_DIR, "thumbnails", slug)) image.set_height(2) label = Text(name) label.next_to(image, DOWN) sublabel = Text("by " + author, font_size=36) sublabel.next_to(image, DOWN) sublabel.set_color(GREY_A) return Group(image, sublabel) winners = Group(*(get_winner_tile(*d) for d in winner_data)) winners.arrange_in_grid(2, 3, buff=0.5) winners[3:].match_x(winners[:3]) winners.center().to_edge(DOWN) mystery_tiles = Group(*( get_entry_tile().replace(winner[0]) for winner in winners )) first_outline = SurroundingRectangle(mystery_tiles[0], buff=0) first_outline.set_stroke(BLUE, 3) group_label = Text("Collaboration", color=BLUE) group_label.next_to(mystery_tiles[0], UP, SMALL_BUFF) self.play(LaggedStartMap(FadeIn, mystery_tiles, scale=2, lag_ratio=0.2)) self.play( ShowCreation(first_outline), FadeIn(group_label, 0.2 * UP) ) self.wait() for tile, winner in zip(mystery_tiles, winners): self.play( FadeOut(tile, scale=0.5), FadeIn(winner[0], scale=2), FadeIn(winner[1], DOWN, time_span=(0.5, 1.5)) ) self.add(winner) self.wait() # Honorable mentions hm_slugs = [ "v_HeaeUUOnc", "piF6D6CQxUw", "QC3CjBZLHXs", "KufsL2VgELo", "zR_hpai3XkY", "HeBP3MG-WHg", "2dwQUUDt5Is", "3gyHKCDq1YA", "nK2jYk37Rlg", "l7bYY2U5ld8", "dwNxVpbEVcc", "CFBa2ezTQJQ", "gnUYoQ1pwes", "LUCvSsx6-EU", "-vxW42R47bc", "inverse-turing-test", "bezier-curve-guide", "does-every-game-have-a-winner", "Autodiff", "panorama-homography", ] random.shuffle(hm_slugs) to_fade = VGroup(title, first_outline, group_label, *(winner[1] for winner in winners)) winner_tiles = Group(*(winner[0] for winner in winners)) hm_tiles = Group(*( ImageMobject(os.path.join(DOC_DIR, "thumbnails", slug)) for slug in hm_slugs )) winner_tiles.generate_target() tile_grid = Group(*winner_tiles.target, *hm_tiles) for tile in tile_grid: tile.set_width(1) tile_grid.arrange_in_grid(5, 5, buff=SMALL_BUFF) tile_grid.set_height(7.5) self.play( FadeOut(to_fade, run_time=2, lag_ratio=0.5), MoveToTarget(winner_tiles), ) self.play(LaggedStartMap(FadeIn, hm_tiles, lag_ratio=0.5)) # Wandering outline outline = SurroundingRectangle(winner_tiles[0], buff=0) outline.set_stroke(YELLOW, 3) self.play(FadeIn(outline)) search_list = list(tile_grid[1:]) random.shuffle(search_list) for tile in search_list[:12]: self.play(outline.animate.move_to(random.choice(tile_grid))) self.wait() class Sponsors(InteractiveScene): def construct(self): # Images self.add(FullScreenFadeRectangle(fill_color=interpolate_color(GREY_A, WHITE, 0.5))) img_dir = os.path.join(DOC_DIR, "sponsor_logos") brilliant = ImageMobject(os.path.join(img_dir, "Brilliant")) risczero = ImageMobject(os.path.join(img_dir, "RiscZero")) google = SVGMobject(os.path.join(img_dir, "GoogleFonts")) google.set_stroke(width=0) pl = ImageMobject(os.path.join(img_dir, "ProtocolLabs")) logos = Group(brilliant, risczero, google, pl) for logo in logos: logo.set_width(5) logos.arrange(DOWN) logos[0].shift(0.35 * UP) logos[2:].shift(0.75 * DOWN) logos.center().to_corner(DL) logos.to_edge(DOWN, buff=0) # Contributions contributions = VGroup( Text("$1,000 for each winner").next_to(brilliant, RIGHT, buff=2.0), Text("$500 for each\nhonorable mention").next_to(logos[1:3], RIGHT, buff=2.0), Text("Operations costs").next_to(pl, RIGHT, buff=2.0), ) contributions.set_fill(BLACK) contributions.set_stroke(BLACK, 0) brace = Brace(logos[1:3], RIGHT) brace.set_fill(BLACK, 1) arrows = VGroup() for logo, j in zip(logos, [0, 1, 1, 2]): arrows.add(Arrow(logo.get_right(), contributions[j].get_left(), color=BLACK)) # Animations self.play(FadeIn(brilliant, 0.5 * DOWN)) self.play(ShowCreation(arrows[0]), Write(contributions[0])) self.wait() self.play(LaggedStartMap(FadeIn, logos[1:3], shift=DOWN, lag_ratio=0.7)) self.play(*map(ShowCreation, arrows[1:3]), Write(contributions[1])) self.wait() self.play(FadeIn(pl, DOWN)) self.play(ShowCreation(arrows[3]), Write(contributions[2])) self.wait() class EndScreen(PatreonEndScreen): CONFIG = { "title_text": "Playlist of all entries", "scroll_time": 30, "thanks_words": "Many additional thanks to these Patreon supporters" }
from manim_imports_ext import * import argparse import matplotlib.pyplot as plt import mido from collections import namedtuple from tqdm import tqdm as ProgressDisplay from scipy.signal import fftconvolve from scipy.signal import convolve from scipy.signal import argrelextrema from scipy.io import wavfile from IPython.terminal.embed import InteractiveShellEmbed embed = InteractiveShellEmbed() SAMPLED_VELOCITY = 100 SAMPLED_VELOCITIES = list(range(25, 150, 25)) DATA_DIR = os.path.join( os.path.dirname(os.path.realpath(__file__)), "data", ) Note = namedtuple( 'Note', [ 'value', 'velocity', 'position', # In seconds 'duration', # In seconds ] ) major_scale = [0, 2, 4, 5, 7, 9, 11] piano_midi_range = list(range(21, 109)) def square(vect): return np.dot(vect, vect) def norm(vect): return np.linalg.norm(vect) def projection_factor(v, w): """ If projecting v onto w produces the vector f * w, this returns f """ return np.dot(v, w) / np.dot(w, w) def gaussian_kernel(length=100, spread=0.5): """ creates gaussian kernel with side length `l` and a sigma of `sigma` """ sigma = spread * length ax = np.linspace(-(length - 1) / 2., (length - 1) / 2., length) gauss = np.exp(-0.5 * np.square(ax) / np.square(sigma)) return gauss / gauss.sum() # Functions for creating MIDI files def hz_to_midi_value(frequencies): freqs = np.atleast_1d(frequencies) return (12 * np.log2(freqs / 440) + 69).astype(int) def midi_value_to_hz(midis): midis = np.atleast_1d(midis) return 440 * 2**((midis - 69) / 12) def add_notes(track, notes, sec_per_tick): """ Adapted from https://github.com/aniawsz/rtmonoaudio2midi """ curr_tick = 0 for index, note in enumerate(notes): pos_in_ticks = int(note.position / sec_per_tick) dur_in_ticks = int(note.duration / sec_per_tick) if index < len(notes) - 1: next_pos_in_ticks = int(notes[index + 1].position / sec_per_tick) dur_in_ticks = min(dur_in_ticks, next_pos_in_ticks - pos_in_ticks) track.append( mido.Message( 'note_on', note=int(note.value), velocity=int(note.velocity), time=pos_in_ticks - curr_tick ) ) curr_tick = pos_in_ticks track.append( mido.Message( 'note_off', note=int(note.value), # velocity=int(note.velocity), time=dur_in_ticks, ) ) curr_tick = pos_in_ticks + dur_in_ticks def create_midi_file_with_notes(filename, notes, bpm=240): """ From https://github.com/aniawsz/rtmonoaudio2midi """ with mido.MidiFile() as midifile: # Tempo is microseconds per beat sec_per_tick = (60.0 / bpm) / midifile.ticks_per_beat # Create one track for each piano key tracks = [] for key in piano_midi_range: track = mido.midifiles.MidiTrack() matching_notes = list(filter(lambda n: n.value == key, notes)) matching_notes.sort(key=lambda n: n.position) if len(matching_notes) == 0: continue add_notes(track, matching_notes, sec_per_tick) tracks.append(track) master_track = mido.midifiles.MidiTrack() # master_track.append(mido.MetaMessage('instrument_name', name='Steinway Grand Piano', time=0)) master_track.append(mido.MetaMessage('instrument_name', name='Learner\'s Piano', time=0)) master_track.append(mido.MetaMessage('set_tempo', tempo=tempo)) master_track.extend(mido.merge_tracks(tracks)) midifile.tracks.append(master_track) midifile.save(filename) def midi_to_wav(mid_file): wav_file = mid_file.replace(".mid", ".wav") mp3_file = mid_file.replace(".mid", ".mp3") if os.path.exists(wav_file): os.remove(wav_file) os.system(" ".join([ "timidity", mid_file, "-Ow -o -", "|", "ffmpeg", "-i - -acodec libmp3lame -ab 64k", "-ar 48000", "-hide_banner -loglevel error", mp3_file, ])) os.system(" ".join([ "ffmpeg", "-hide_banner -loglevel error", "-i", mp3_file, wav_file, ])) os.remove(mp3_file) return wav_file def generate_pure_piano_key_files(velocities=[SAMPLED_VELOCITY], duration=0.025, folder="digital_piano_samples"): folder = os.path.join(DATA_DIR, folder) if not os.path.exists(folder): os.makedirs(folder) for key in piano_midi_range: for vel in velocities: note = Note(key, vel, 0, duration) mid_file = os.path.join(folder, f"{key}_{vel}.mid") create_midi_file_with_notes(mid_file, [note]) midi_to_wav(mid_file) os.remove(mid_file) def generate_piano_sample_midi(delay=5, duration=0.025, velocity=100): notes = [] for n, key in enumerate(piano_midi_range): notes.append(Note( key, velocity=velocity, position=n * delay, duration=duration, )) mid_file = os.path.join(DATA_DIR, "individual_key_samples.mid") create_midi_file_with_notes(mid_file, notes) midi_to_wav(mid_file) # Processing sample signals from piano def load_piano_key_signals(folder="piano_samples", duration=0.5, velocity=50): key_signals = [] for key in piano_midi_range: sample_rate, full_signal = wav_data( os.path.join(DATA_DIR, folder, f"{key}_{velocity}.wav") ) key_signal = full_signal[:int(duration * sample_rate)] key_signals.append(key_signal) return np.array(key_signals, dtype=float) def get_volume_to_velocity_func_map(folder="true_piano_samples", sampled_velocities=[26, 101]): """ Functions are encoded as a pair (c0, c1) for the linear function c0 + c1 * x """ result = dict() vels = sampled_velocities for key in piano_midi_range: globals().update(locals()) volumes = [ wav_data(os.path.join(DATA_DIR, folder, f"{key}_{vel}.wav"))[1].max() for vel in vels ] # Coefficients for const + (slope) * x function fit slope = (vels[1] - vels[0]) / (volumes[1] - volumes[0]) const = vels[0] - slope * volumes[0] result[key] = (const, slope) return result def get_velocity(key, signal, scale_factor, v2v_func_map): c0, c1 = v2v_func_map[key] return c0 + c1 * (signal.max() * scale_factor) def shift_pitch(signal, sample_rate, shift_in_hz, frame_size=4800): result = [] for lh in range(0, len(signal), frame_size): rh = lh + frame_size fft_spectrum = np.fft.rfft(signal[lh:rh]) freq = sample_rate / (rh - lh) shift = int(shift_in_hz / freq) shifted_spectrum = np.zeros_like(fft_spectrum) shifted_spectrum[shift:] = fft_spectrum[:-shift] shifted_signal = np.fft.irfft(shifted_spectrum) result.append(shifted_signal) return np.hstack(result) def wav_to_midi(sound_file, output_file=None, key_block_time=0.075, key_signal_time=0.075, key_play_time=0.020, step_size=0.001, sample_velocity=100, sample_folder="digital_piano_samples", key_signal_max=0.15, # This has a very large effect volume_ratio_threshold=1.0, scale_factor_cutoff=0.1, min_velocity=5, max_velocity=60, # Honestly, low keys are trash, so many are supressed n_supressed_lower_keys=32, supression_factor=0.25, ): """ Walk through a series of windows over the original signal, and for each one, find the top several key sounds which correlate most closely with that window. More specifically, do a convolution to let that piano key signal 'slide' along the window to find the best possible match. Room for improvement: - Duration shouldn't necessarily be fixed """ # Read in audio file, normalize sample_rate, signal = wav_data(sound_file) signal /= signal.max() new_signal = np.zeros_like(signal) # We (potentially) add one note per step_size. A single note cannot be played # multiple times within a key_block_size window. step_size = int(sample_rate * step_size) key_block_size = int(sample_rate * key_block_time) notes = [] key_signals = load_piano_key_signals( folder=sample_folder, duration=key_signal_time, velocity=sample_velocity, ) key_signals *= key_signal_max / key_signals.max() velocities = [] # Just for debugging, can delete # Compute correlations between all notes at all points along the signal full_convs = np.array([ fftconvolve(signal, ks[::-1])[len(ks) - 1:] for ks in key_signals ]) # Repress lower keys. TODO: Instead of multiplying by an arbitrary factor, use some smoothing function full_convs[:n_supressed_lower_keys, :] *= supression_factor # The signal is divided into many little windows, with these "positions" marking # the first index of each such window. These are sorted based on which ones # have the highest correlation with some particular key. positions = list(range(0, len(signal), step_size)) positions.sort(key=lambda p: -full_convs[:, p:p + step_size].max()) for pos in positions: window = signal[pos:pos + step_size] new_window = new_signal[pos:pos + step_size] # When volume is larger than original window, stop adding new notes if norm(new_window) > volume_ratio_threshold * norm(window): continue convs = full_convs[:, pos:pos + step_size] key_index, offset = np.unravel_index(np.argmax(convs), convs.shape) opt_pos = pos + offset ks = key_signals[key_index] # Consider the segment of the original signal which lines up # with this key signal as a vector. If you project that segment # onto the key signal itself, producing a vector which is f * (key signal), # this factor gives f. diff = (signal - new_signal)[opt_pos:opt_pos + len(ks)] # What's the right length here? factor = projection_factor(diff, ks[:len(diff)]) if factor > scale_factor_cutoff: velocity = int(interpolate(min_velocity, max_velocity, clip(factor, 0, 1))) velocities.append((factor, velocity)) # Add the key_signal to new_window, which will in turn be added to new_signal piece = new_signal[opt_pos:opt_pos + len(ks)] piece += (velocity / sample_velocity) * ks[:len(piece)] # Mark this key as unavailable for the next len(ks) samples full_convs[key_index, opt_pos:opt_pos + key_block_size] = 0 # Add the note, which will ultimately be used to create the MIDI file notes.append(Note( value=piano_midi_range[key_index], velocity=velocity, position=opt_pos / sample_rate, # Always hit with a short staccato duration=key_play_time, )) if output_file is None: output_file = sound_file.replace(".wav", "_as_piano.mid") create_midi_file_with_notes(output_file, notes) midi_to_wav(output_file) # plt.plot(signal, linewidth=1.0) # plt.plot(new_signal, linewidth=1.0) # plt.plot(smooth_signal, linewidth=1.0) # plt.show() return # Functions for processing sound files def show_down_midi_file(mid_file, slow_factor=4): mid = mido.MidiFile(mid_file, clip=True) track = mid.tracks[0] for msg in track: if msg.type in ['note_on', 'note_off']: msg.time *= slow_factor new_file = mid_file.replace(".mid", f"_slowed_by_{slow_factor}.mid") mid.save(new_file) return new_file def wav_data(file_name): rate, arr = wavfile.read(file_name) arr = arr.astype(float) if len(arr.shape) > 1 and arr.shape[1] > 1: arr = arr.mean(1) # Collapse to single channel return rate, arr def extract_pure_keys(key_sample_file, output_folder="true_piano_samples", start=3.9, spacing=3, velocities=[1, 26, 51, 76, 101, 126]): """ For a file """ output_folder = os.path.join(DATA_DIR, output_folder) sample_rate, arr = wav_data(key_sample_file) # Create function whose local maxima correspond to key starts kernel = np.ones(sample_rate) / sample_rate smoothed = fftconvolve(np.abs(arr).astype(float), kernel, mode='valid') smoothed = fftconvolve(smoothed, kernel, mode='valid') smooth_to_true_shift = int(0.7 * sample_rate) smoothed = np.hstack([np.zeros(smooth_to_true_shift), smoothed]) local_maxima = argrelextrema(smoothed, np.greater)[0] def true_peak_near(index): return local_maxima[np.argmin(np.abs(local_maxima - index))] spacing_in_samples = int(spacing * sample_rate) index = true_peak_near(start * sample_rate) for key in piano_midi_range: for vel in velocities: wavfile.write( filename=os.path.join(output_folder, f"{key}_{vel}.wav"), rate=sample_rate, data=arr[index:index + spacing_in_samples], ) index = true_peak_near(index + spacing_in_samples) return def normalize_data(data): return data / np.abs(data).max() def data_to_audio_segment(segment): pass def test_midi_file_writing(): notes = [ Note( value=hz_to_midi_value(240 * 2**((5 * x % 12) / 12)), velocity=random.randint(20, 64), position=x / 120, duration=1 / 120, ) for x in range(64) for y in range(10) ] test_file = os.path.join(DATA_DIR, "test.mid") create_midi_file_with_notes( test_file, notes ) mid = mido.MidiFile(test_file, clip=True) track = mid.tracks[0] print(track) def plot_velocity_data(): key = 55 folder = os.path.join(DATA_DIR, "true_piano_samples") signals = [] vels = list(range(1, 127, 25)) for vel in vels: file = os.path.join(folder, f"{key}_{vel}.wav") rate, signal = wav_data(file) signals.append(signal) maxes = [s.max() for s in signals] plt.plot(maxes, vels) plt.plot(np.linspace(0, maxes[-1], len(maxes)), vels) plt.show() embed() def main(): parser = argparse.ArgumentParser() parser.add_argument("wav_file") parser.add_argument("output_file", nargs="?") args = parser.parse_args() wav_to_midi(args.wav_file, args.output_file) if __name__ == "__main__": main() # mid1 = mido.MidiFile("/Users/grant/cs/videos/_2022/piano/data/better_midis/TrappedInAPiano.wav.mid") # mid2 = mido.MidiFile("/Users/grant/cs/videos/_2022/piano/data/3-9-attempts/DensityTest_5ms.mid") # track1 = mid1.tracks[0] # track2 = mid2.tracks[0]
from manim_imports_ext import * import mido from _2022.piano.wav_to_midi import DATA_DIR from _2022.piano.wav_to_midi import piano_midi_range from _2022.piano.wav_to_midi import midi_to_wav class AnimatedMidi(Scene): midi_file = "3-16-attempts/Help_Long_as_piano_5ms.mid" dist_per_sec = 4.0 bpm = 240 CONFIG = { "camera_config": { "anti_alias_width": 0, "samples": 4, } } hit_depth = 0.025 note_color = BLUE hit_color = TEAL note_to_key_width_ratio = 0.5 sound_file_time_offset = 0.3 def construct(self): self.add_piano() self.add_note_rects() self.add_piano_sound() self.scroll() def add_piano(self): piano = Piano3D() piano.set_width(9) piano.move_to(5 * DOWN) frame = self.camera.frame frame.set_phi(70 * DEGREES) self.piano = piano self.add(piano) def add_note_rects(self): mid_file = self.mid_file = os.path.join(DATA_DIR, self.midi_file) # Pull out track mid = mido.MidiFile(mid_file, clip=True) track = mido.midifiles.MidiTrack() track.extend([ msg for msg in mido.merge_tracks(mid.tracks) if msg.type not in ['pitchwheel', 'time_signature'] ]) # Relevant constants offset = piano_midi_range[0] tempo = 250000 # microseconds per quarter note # (ms / beat) * (s / ms) * (beats / tick) sec_per_tick = tempo * 1e-6 / mid.ticks_per_beat dist_per_tick = self.dist_per_sec * sec_per_tick pending_notes = {key: None for key in piano_midi_range} notes_to_time_spans = {key: [] for key in piano_midi_range} note_rects = VGroup() time_in_ticks = 0 for msg in track: time_in_ticks += msg.time if msg.type == 'set_tempo': sec_per_tick *= msg.tempo / tempo dist_per_tick *= msg.tempo / tempo tempo = msg.tempo if msg.type == 'note_on' and msg.velocity > 0: pending_notes[msg.note] = (time_in_ticks, msg.velocity) elif msg.type == 'note_off': if msg.note not in pending_notes or pending_notes[msg.note] is None: continue if msg.note not in piano_midi_range: continue print(pending_notes[msg.note]) start_time_in_ticks, velocity = pending_notes.pop(msg.note) key = self.piano[msg.note - offset] rect = Rectangle( width=self.note_to_key_width_ratio * key.get_width(), height=(time_in_ticks - start_time_in_ticks) * dist_per_tick ) rect.next_to(key, UP, buff=start_time_in_ticks * dist_per_tick) rect.set_stroke(width=0) rect.set_fill(self.note_color, opacity=clip(0.25 + velocity / 100, 0, 1)) note_rects.add(rect) notes_to_time_spans[msg.note].append(( start_time_in_ticks * sec_per_tick, time_in_ticks * sec_per_tick )) self.note_rects = note_rects self.notes_to_time_spans = notes_to_time_spans self.add(note_rects) def add_piano_sound(self): self.add_sound( midi_to_wav(self.mid_file), self.sound_file_time_offset ) def scroll(self): piano = self.piano note_rects = self.note_rects notes_to_time_spans = self.notes_to_time_spans for key in piano: key.original_z = key.get_z() key.original_color = key[0].get_fill_color() piano.time = 0 def update_piano(piano, dt): piano.time += dt for note, key in zip(piano_midi_range, piano): hit = False for start, end in notes_to_time_spans[note]: if start - 1 / 60 < piano.time < end + 1 / 60: hit = True if hit: key.set_z(key.original_z - self.hit_depth) key.set_fill(interpolate_color( key[0].get_fill_color(), self.hit_color, 0.5 )) else: key.set_z(key.original_z) key.set_fill(key.original_color) piano.add_updater(update_piano) note_rects_start = note_rects.get_center().copy() note_rects.add_updater(lambda m: m.move_to( note_rects_start + self.dist_per_sec * self.time * DOWN )) black_rect = Rectangle(width=piano.get_width(), height=5) black_rect.set_fill(BLACK, 1) black_rect.set_stroke(width=0) black_rect.move_to(piano, UP) self.add(note_rects, black_rect, piano) self.wait(note_rects.get_height() / self.dist_per_sec + 3.0) class AnimatedMidiTrapped5m(AnimatedMidi): midi_file = "3-16-attempts/Help_Long_as_piano_5ms.mid" class STFTAlgorithmOnTrapped(AnimatedMidi): midi_file = "3-16-attempts/Help_Long_STFT.mid" class HelpLongOnlineConverter(AnimatedMidi): midi_file = "3-16-attempts/Help_Long_online.mid"
from manim_imports_ext import * from _2022.piano.wav_to_midi import DATA_DIR from scipy.io import wavfile def get_wave_sum(axes, freqs, amplitudes=None, phases=None): if amplitudes is None: amplitudes = np.ones(len(freqs)) if phases is None: phases = np.zeros(len(freqs)) return axes.get_graph(lambda t: sum( amp * math.sin(TAU * freq * (t - phase)) for freq, amp, phase in zip(freqs, amplitudes, phases) )) def get_ellipsis_vector(values, n_top_shown=3, n_bottom_shown=2, height=2): values = list(map(str, (*values[:n_top_shown], *values[-n_bottom_shown:]))) values.insert(n_top_shown, "\\vdots") vector = Matrix(np.transpose([values])) vector.set_height(3) return vector class SumOfWaves(Scene): def construct(self): # Show single pure wave axes = Axes( (0, 12), (-1, 1), height=2, ) base_freq = 0.5 wave = get_wave_sum(axes, [base_freq]) wave.set_stroke(BLUE, 2) x = 4.5 brace = Brace( Line(axes.i2gp(x, wave), axes.i2gp(x + 1 / base_freq, wave)), UP, buff=SMALL_BUFF ) brace_label = brace.get_text( "220 cycles / sec.", buff=SMALL_BUFF, font_size=36, ) axes_labels = VGroup(*( Text(word, font_size=30) for word in ["Air pressure", "Time"] )) axes_labels[0].next_to(axes.y_axis, UP).to_edge(LEFT) axes_labels[1].next_to(axes.x_axis, UP).to_edge(RIGHT) self.add(axes) brace_rf = squish_rate_func(smooth, 0.25, 0.5) label_rf = squish_rate_func(smooth, 0.25, 1) self.play( ShowCreation(wave, rate_func=linear), GrowFromCenter(brace, rate_func=brace_rf), Write(brace_label, rate_func=label_rf), run_time=3, ) self.play(LaggedStartMap( Write, axes_labels, lag_ratio=0.8 )) self.wait() # Show multiple waves freq_multiples = [1, 6 / 5, 3 / 2, 21 / 12] freqs = [base_freq * r for r in freq_multiples] low_axes_group = VGroup(*( Axes((0, 12), (-1, 1), height=0.65) for freq in freqs )) low_axes_group.arrange(UP, buff=0.4) low_axes_group.to_edge(DOWN) low_axes_group.to_edge(RIGHT) waves = VGroup(*( get_wave_sum(la, [freq]) for la, freq in zip(low_axes_group, freqs) )) waves.set_submobject_colors_by_gradient(BLUE, YELLOW) waves.set_stroke(width=2) axes_labels = VGroup(*( Text(f"{int(mult * 220)} Hz", font_size=24) for mult in freq_multiples )) for low_axes, label in zip(low_axes_group, axes_labels): label.next_to(low_axes, LEFT) self.play( FadeOut(VGroup(axes_labels[1], brace), DOWN), ReplacementTransform(brace_label, axes_labels[0]), ReplacementTransform(axes, low_axes_group[0]), ReplacementTransform(wave, waves[0]), *( TransformFromCopy(axes, low_axes) for low_axes in low_axes_group[1:] ) ) self.play( LaggedStartMap( ShowCreation, waves[1:], lag_ratio=0.5, rate_func=linear, ), LaggedStartMap( FadeIn, axes_labels[1:], lag_ratio=0.5, ), run_time=2, ) self.wait() # Show sum top_axes = Axes((0, 12), (-4, 4), height=2.25) top_axes.to_edge(UP, buff=MED_SMALL_BUFF) top_axes.align_to(low_axes_group, RIGHT) top_rect = Rectangle(FRAME_WIDTH, top_axes.get_height() + 0.5) top_rect.move_to(top_axes) top_rect.set_x(0) top_rect.set_stroke(WHITE, 0) top_rect.set_fill(GREY_E, 1.0) sum_label = Text("Sum") sum_label.to_edge(UP, buff=0.25) amp_tracker = ValueTracker(np.ones(len(freqs))) comp_wave = always_redraw(lambda: get_wave_sum( top_axes, freqs, amplitudes=amp_tracker.get_value(), ).set_stroke(TEAL, 2)) self.play( FadeIn(top_rect), FadeIn(top_axes), FadeIn(sum_label), *( Transform(wave.deepcopy(), comp_wave, remover=True) for wave in waves ) ) self.add(comp_wave) self.wait() # Tweak magnitudes for index in range(len(waves)): wave = waves[index] wave.index = index wave.max_height = wave.get_height() wave.add_updater(lambda w: w.set_height( amp_tracker.get_value()[w.index] * w.max_height, stretch=True )) self.add(*waves) changes = [ # (index, d_value) (3, -0.8), (2, -0.9), (1, 0.6), (0, 0.5), (3, 0.8), (0, -1.1), (1, 0.5), ] for index, d_value in changes: values = amp_tracker.get_value().copy() values[index] += d_value arrows = VGroup( Vector(0.5 * UP), Vector(0.5 * DOWN), ) arrows.arrange(DOWN if d_value > 0 else UP) axes = low_axes_group[index] arrows.match_height(axes) arrows.next_to(axes, LEFT) self.play( amp_tracker.animate.set_value(values), FadeIn(arrows[0], 0.25 * UP), FadeIn(arrows[1], 0.25 * DOWN), ) self.play(FadeOut(arrows, run_time=0.75)) self.wait() class DecomposeAudioSegment(Scene): audio_file = os.path.join(DATA_DIR, "audio_clips", "SignalFromSpeech.wav") sample_density = 1 / 5 n_sine_waves = 5 signal_graph_style = dict( stroke_color=BLUE, stroke_width=1, ) graph_point = 0.428 zoom_rect_dims = (0.4, 4.0) def construct(self): self.add_full_waveform() self.zoom_in_on_segment( self.axes, self.graph, self.graph_point, self.zoom_rect_dims ) self.prepare_for_3d() self.break_down_into_fourier_components() self.back_to_full_signal() def add_full_waveform(self, run_time=5): axes, graph = self.get_signal_graph() self.add(axes) self.play( ShowCreation( graph, rate_func=squish_rate_func(linear, 0.05, 1), ), VShowPassingFlash( graph.copy().set_stroke(BLUE_B, 3), time_width=0.1, rate_func=linear, ), run_time=run_time, ) self.axes = axes self.graph = graph def zoom_in_on_segment(self, axes, graph, graph_point, zoom_rect_dims, run_time=4, fade_in_new_axes=True): point = graph.pfp(graph_point)[0] * RIGHT zoom_rect = Rectangle(*zoom_rect_dims) zoom_rect.move_to(point) zoom_rect.set_stroke(WHITE, 2) graph_snippet = VMobject() graph_points = graph.get_anchors() lx = zoom_rect.get_left()[0] rx = zoom_rect.get_right()[0] xs = graph_points[:, 0] snippet_points = graph_points[(xs > lx) * (xs < rx)] graph_snippet.set_points_as_corners(snippet_points) graph_snippet.match_style(graph) point = graph_snippet.get_center().copy() point[1] = axes.get_origin()[1] zoom_rect.move_to(point) movers = [axes, graph, graph_snippet, zoom_rect] frame = self.camera.frame for mover in movers: mover.save_state() mover.generate_target() mover.target.stretch(frame.get_width() / zoom_rect.get_width(), 0, about_point=point) mover.target.stretch(frame.get_height() / zoom_rect.get_height(), 1, about_point=point) mover.target.shift(-point) graph_snippet.target.set_stroke(width=3) zoom_rect.target.set_stroke(width=0) axes.target.set_stroke(opacity=0) new_axes = Axes((-2, 12), (-1, 1, 0.25), width=FRAME_WIDTH + 1) new_axes.shift(LEFT_SIDE + RIGHT - new_axes.get_origin()) self.play(Write(zoom_rect)) self.play( *map(MoveToTarget, movers), FadeIn(new_axes), run_time=run_time, ) self.remove(graph, axes) # Swap axes # if fade_in_new_axes: # self.play(FadeIn(new_axes)) self.original_graph = graph self.original_axes = axes self.axes = new_axes self.graph = graph_snippet return new_axes, graph_snippet def prepare_for_3d(self): frame = self.camera.frame for mob in self.mobjects: mob.rotate(PI / 2, RIGHT) frame.reorient(0, 90) self.add(frame) def break_down_into_fourier_components(self): t_axes = self.axes graph = self.graph # Take the fourier transform t_max = t_axes.x_range[1] ts, values = t_axes.p2c(graph.get_points()[::6]) signal = values[(ts > 0) * (ts < t_max)] signal_fft = np.fft.fft(signal) signal_fft /= len(signal) signal_fft_abs = np.abs(signal_fft) signal_fft_phase = np.log(signal_fft).imag # Prepare the graph max_freq = signal.size / t_max f_axes = Axes( (0, max_freq / 2, max_freq / len(signal) / 2), (0, 1, 1 / 8), height=t_axes.get_depth(), width=150, ) f_axes.rotate(PI / 2, RIGHT) f_axes.rotate(PI / 2, OUT) f_axes.shift(t_axes.get_origin() - f_axes.get_origin()) freqs = np.fft.fftfreq(signal.size, 1 / max_freq) % max_freq fft_graph = VMobject() fft_graph.set_points_as_corners([ f_axes.c2p(freq, 2 * value) for freq, value in zip(freqs, signal_fft_abs) ]) fft_graph.set_stroke(GREEN, 3) freq_label = Text("Frequency", font_size=60) freq_label.rotate(PI / 2, RIGHT) freq_label.rotate(PI / 2, OUT) freq_label.next_to(f_axes.c2p(1.3, 0), OUT + UP) # Express the most dominant signals as sine waves sine_waves = VGroup() amps = [] for index in range(1, 50): freq = freqs[index] amp = signal_fft_abs[index] phase = signal_fft_phase[index] wave = t_axes.get_graph( lambda t: 2 * amp * np.cos(TAU * freq * (t + phase)), x_range=(0, t_max), ) wave.match_y(f_axes.c2p(freq, 0)) wave.set_stroke(opacity=clip(15 * amp, 0.35, 1)) wave.amp = amp wave.freq = freq wave.phase = phase amps.append(amp) sine_waves.add(wave) sine_waves.set_submobject_colors_by_gradient(YELLOW, GREEN, RED, ORANGE) sine_waves.set_stroke(width=3) top_waves = VGroup(*[sine_waves[i] for i in [4, 9, 13, 14]]).copy() # Break down frame = self.camera.frame frame.generate_target() frame.target.set_euler_angles(1.2, 1.35) frame.target.set_height(10.5) frame.target.move_to([1.5, 5.0, 0.7]) self.play( FadeIn(f_axes), MoveToTarget(frame, run_time=8), LaggedStart( *(TransformFromCopy(graph, wave) for wave in top_waves), lag_ratio=0.8, run_time=3, ) ) frame.add_updater(lambda f, dt: f.increment_theta(0.25 * dt * DEGREES)) self.play(Write(freq_label)) self.wait(3) self.play( FadeIn(sine_waves, lag_ratio=0.1, run_time=3), ) self.wait(3) # Collapse into FFT graph lines = VGroup(*( Line(f_axes.c2p(freqs[i], 0), f_axes.i2gp(freqs[i], fft_graph)) for i in range(1, len(sine_waves)) )) lines.set_stroke(GREEN, 2) lines.set_flat_stroke(False) frame.clear_updaters() frame.generate_target() frame.target.set_euler_angles(1.22, 1.54) frame.target.move_to([1.92, 7.29, 1.05]) fft_label = OldTexText("|Fourier Transform|", font_size=60) fft_label.rotate(PI / 2, RIGHT).rotate(PI / 2, OUT) fft_label.next_to(f_axes.i2gp(freqs[5], fft_graph), OUT) fft_label.set_color(GREEN) piano = Piano() f_step = f_axes.x_range[2] piano.set_width(get_norm(f_axes.c2p(88 * f_step) - f_axes.get_origin())) piano.rotate(PI / 2, OUT) piano.move_to(f_axes.get_origin(), DR) piano.set_opacity(0.5) wave_shadows = sine_waves.copy().set_stroke(opacity=0.1) self.remove(top_waves, sine_waves) self.add(wave_shadows) self.play( LaggedStart( *( TransformFromCopy(wave, line) for wave, line in zip(sine_waves, lines) ), lag_ratio=0.1, run_time=8, ), graph.animate.set_stroke(width=1, opacity=0.5), ShowCreation(fft_graph, run_time=5), Write(fft_label), MoveToTarget(frame, run_time=5), ) self.wait(2) self.add(piano, freq_label, fft_graph, lines) self.play( Write(piano), frame.animate.set_phi(1.25), run_time=3, ) self.wait() # Pull out dominant signals glow_keys = VGroup(*( piano[np.argmin([ get_norm(k.get_center() - wave.get_left()) for k in piano ])] for wave in top_waves )) peak_dots = GlowDots([ lines[np.argmin([ get_norm(line.get_start() - wave.get_left()) for line in lines ])].get_end() for wave in top_waves ]) self.play( ShowCreation(peak_dots), LaggedStartMap(ShowCreation, top_waves), frame.animate.set_euler_angles(0.72, 1.15).move_to([2., 4., 1.]), ApplyMethod(glow_keys.set_fill, RED, 1, rate_func=squish_rate_func(smooth, 0, 0.2)), run_time=6, ) self.wait() # Reconstruct approx_wave = graph.copy() # Cheating approx_wave.set_points_smoothly(graph.get_points()[::150]) approx_wave.set_stroke(TEAL, 3, 1.0) self.play( frame.animate.reorient(0, 90).move_to(ORIGIN).set_height(10), graph.animate.set_stroke(width=2, opacity=0.5), *(ReplacementTransform(wave, approx_wave) for wave in top_waves), LaggedStartMap(FadeOut, VGroup(fft_graph, lines, fft_label, freq_label, f_axes)), FadeOut(peak_dots), FadeOut(wave_shadows), FadeOut(piano), run_time=3, ) self.wait() self.approx_wave = approx_wave def back_to_full_signal(self): # Back to original graph self.play( FadeOut(self.axes), FadeOut(self.approx_wave), self.graph.animate.set_stroke(opacity=1), ) self.camera.frame.reorient(0, 0) self.graph.rotate(-PI / 2, RIGHT) self.play( Restore(self.original_axes), Restore(self.original_graph), Restore(self.graph), run_time=3, ) # Show windows axes = self.original_axes graph = self.original_graph windows = Rectangle().get_grid(1, 75, buff=0) windows.replace(graph, stretch=True) windows.stretch(1.1, 1) windows.set_stroke(WHITE, 1) piano = Piano() piano.set_width(12) piano.next_to(axes, UP).set_x(0) piano.save_state() self.add(piano) for window in windows[:40]: fade_rect = BackgroundRectangle(axes) fade_rect.scale(1.01) fade_rect = Difference(fade_rect, window) fade_rect.set_fill(BLACK, 0.6) fade_rect.set_stroke(width=0) piano.restore() VGroup(*random.sample(list(piano), random.randint(1, 4))).set_color(RED) self.add(fade_rect, window) self.wait(0.25) self.remove(fade_rect, window) def get_signal_graph(self): sample_rate, signal = wavfile.read(self.audio_file) signal = signal[:, 0] / np.abs(signal).max() signal = signal[::int(1 / self.sample_density)] axes = Axes( (0, len(signal), sample_rate * self.sample_density), (-1, 1, 0.25), height=6, width=15, ) axes.to_edge(LEFT) xs = np.arange(len(signal)) points = axes.c2p(xs, signal) graph = VMobject() graph.set_points_as_corners(points) graph.set_style(**self.signal_graph_style) return axes, graph class WaveformDescription(DecomposeAudioSegment): def construct(self): self.add_full_waveform() # Line passing over waveform axes = self.axes graph = self.graph line = Line(DOWN, UP) line.set_stroke(WHITE, 1) line.match_height(axes) line.move_to(axes.get_origin()) line.add_updater(lambda l, dt: l.shift(0.1 * dt * RIGHT)) dot = GlowDot() dot.add_updater(lambda d: d.move_to(axes.i2gp( axes.x_axis.p2n(line.get_x()), graph ))) self.add(line, dot) # Words waveform = Text("Waveform", font_size=72) waveform.to_edge(UP) y_label = Text("Intensity", font_size=36) y_label.next_to(axes.y_axis, UP).shift_onto_screen() x_label = Text("Time", font_size=36) x_label.next_to(axes.x_axis, UP).to_edge(RIGHT, buff=SMALL_BUFF) self.wait(4) self.play(Write(waveform)) self.wait(2) self.play(Write(y_label), run_time=1) self.play(Write(x_label), run_time=1) self.wait(10) class SignalsAsVectors(DecomposeAudioSegment): audio_file = os.path.join(DATA_DIR, "audio_clips", "SignalFromSpeech.wav") # Change? sample_density = 1.0 def construct(self): self.zoom_in_on_waveform() self.describe_fourier_basis() def zoom_in_on_waveform(self): # Two sets of zooming axes, graph = self.get_signal_graph() self.add(axes, graph) axes, graph = self.zoom_in_on_segment( axes, graph, 0.35, (0.2, 4.0), run_time=3, fade_in_new_axes=False ) axes.set_stroke(opacity=0) axes, graph = self.zoom_in_on_segment( axes, graph, 0.5, (0.15, 6.0), run_time=3, fade_in_new_axes=False ) # Pull out true points from graph points = [] for point in graph.get_anchors(): if not any((point == p).all() for p in points): points.append(point) # Create axes with alternate line representation of values axes = Axes( (0, len(points) - 1), (-1, 1, 0.25), width=graph.get_width(), height=graph.get_height(), ) axes.shift(graph.get_left() - axes.get_origin()) self.play(FadeIn(axes)) # Lines and dots new_graph, lines, dots = self.get_graph_with_lines_and_dots(axes, points) new_graph.match_style(graph) self.remove(graph) graph = new_graph self.add(graph) self.play( ShowCreation(lines, lag_ratio=0.5), FadeIn(dots), graph.animate.set_stroke(width=1) ) self.wait() self.signal_graph_group = Group(axes, graph, lines, dots) def describe_fourier_basis(self): # Vars frame = self.camera.frame graph_group = self.signal_graph_group axes, graph, lines, dots = graph_group # Show as a list of numbers values = axes.y_axis.p2n(dots.get_points()) vector = get_ellipsis_vector((100 * values).astype(int)) vector.next_to(graph, UP, buff=MED_LARGE_BUFF) vector.to_edge(LEFT, buff=LARGE_BUFF) self.play( frame.animate.move_to(axes.get_bottom() + MED_LARGE_BUFF * DOWN, DOWN), LaggedStart( Write(vector.get_brackets()), *( GrowFromPoint(mob, point) for point, mob in zip(dots.get_points()[:3], vector.get_entries()[:3]) ), Write(vector.get_entries()[3]), *( GrowFromPoint(mob, point) for point, mob in zip(dots.get_points()[-2:], vector.get_entries()[-2:]) ), ), run_time=3, ) self.wait() # Show fourier basis as graphs signal_fft = np.fft.fft(values) fourier_basis = np.array([ np.fft.ifft(basis) for basis in np.identity(values.size) ]) component_values = np.array([ part * len(signal_fft) for coef, fb in zip(signal_fft, fourier_basis) for part in (fb.real, fb.imag) ]) xs = list(range(len(signal_fft))) component_graphs = VGroup(*( self.get_graph_with_lines_and_dots(axes, axes.c2p(xs, vals))[0] for vals in component_values )) component_graphs.make_smooth() component_graphs.set_submobject_colors_by_gradient(YELLOW, RED, GREEN) n_parts_shown = 6 comp_groups = VGroup(*( VGroup(axes.deepcopy(), cg) for cg in component_graphs[2:2 + n_parts_shown] )) comp_groups.add(OldTex("\\vdots").set_height(comp_groups.get_height() / 2)) comp_groups.arrange(DOWN, buff=0.75 * comp_groups.get_height()) comp_groups.set_height(7.5) comp_groups.move_to(frame).to_edge(RIGHT, buff=MED_SMALL_BUFF) self.play( graph_group.animate.set_width( graph_group.get_width() - comp_groups.get_width() - LARGE_BUFF, about_edge=DL ), vector.animate.to_edge(LEFT, buff=MED_LARGE_BUFF), LaggedStartMap(FadeIn, comp_groups), ) self.wait() # Show fourier basis as vectors c_dots_group = Group() c_lines_group = VGroup() c_vectors = VGroup() for c_axes, c_graph in comp_groups[:-1]: g, c_lines, c_dots = self.get_graph_with_lines_and_dots( c_axes, c_graph.get_points()[::6] ) c_dots.set_color(c_graph.get_color()) c_dots.set_radius(0.1) c_lines.set_stroke(width=0.5) c_dots_group.add(c_dots) c_lines_group.add(c_lines) c_values = c_axes.y_axis.p2n(c_dots.get_points()) c_vector = get_ellipsis_vector((100 * c_values).astype(int)) c_vector.set_color(c_graph.get_color()) c_vectors.add(c_vector) syms = VGroup(OldTex("="), *(OldTex("+") for v in c_vectors[1:])) coef_syms = VGroup(*(OldTex(f"c_{i}") for i in range(1, 4))) coef_syms.add(OldTex("\\cdots")) last_vect = vector buff = 0.15 for sym, coef_sym, c_vect in zip(syms, coef_syms, c_vectors): sym.next_to(last_vect, RIGHT, buff=buff) coef_sym.next_to(sym, RIGHT, buff=buff) c_vect.next_to(coef_sym, RIGHT, buff=buff) last_vect = c_vect for i in range(3): self.play( ShowCreation(c_dots_group[i]), ShowCreation(c_lines_group[i]), ) self.play( FadeIn(syms[i]), Write(coef_syms[i]), FadeTransform(c_dots_group[i].copy(), c_vectors[i]) ) self.play( *map(ShowCreation, c_dots_group[3:]), *map(ShowCreation, c_lines_group[3:]), Write(syms[3]), Write(coef_syms[3]), ) self.wait() for comp, dots, lines in zip(comp_groups, c_dots_group, c_lines_group): c_axes, c_graph = comp stretcher = Group(c_graph, dots, lines) self.play( stretcher.animate.stretch( random.uniform(-1, 1), dim=1, about_point=c_axes.get_center(), ), ) self.wait() def get_graph_with_lines_and_dots(self, axes, points, color=BLUE): graph = VMobject() graph.set_points_as_corners(points) graph.set_stroke(color, 1) # Alternate representation of values with lines lines = VGroup(*( axes.get_v_line(point, line_func=Line) for point in points )) lines.set_stroke(WHITE, 1) dots = GlowDots(points) dots.set_color(color) return graph, lines, dots class SampleRateOverlay(Scene): def construct(self): text = VGroup( OldTexText("48,000 samples / sec"), OldTex("\\Downarrow"), OldTexText("20 ms window", " = 960-dimensional vector") ) text.arrange(DOWN) text.to_edge(UP) text[2][1].set_color(YELLOW) text[2][0].save_state() text[2][0].match_x(text) self.play(Write(text[0]), run_time=1) self.wait() self.play( GrowFromPoint(text[1], text[0].get_bottom()), FadeIn(text[2][0], DOWN) ) self.wait() self.play(Restore(text[2][0]), FadeIn(text[2][1])) self.wait() class ThreeDChangeOfBasisExample(Scene): def construct(self): # Add axes and standard basis frame = self.camera.frame frame.reorient(-20, 75) frame.shift(OUT) frame.add_updater(lambda m: m.set_theta( -20 * math.cos(TAU * self.time / 60) * DEGREES, )) axes = ThreeDAxes(axis_config=dict(tick_size=0.05)) axes.set_stroke(width=1) plane = NumberPlane(faded_line_ratio=0) plane.set_stroke(GREY, 1, 0.5) basis_mobs = VGroup( Vector(RIGHT, color=RED), Vector(UP, color=GREEN), Vector(OUT, color=BLUE), ) signal = Vector([-3, 1, 2], color=YELLOW) signal.set_opacity(0.75) signal_label = Text("Signal") signal_label.rotate(90 * DEGREES, RIGHT) signal_label.match_color(signal) signal_label.add_updater(lambda m: m.next_to(signal.get_end(), OUT)) coef_label = self.get_coef_label(signal, basis_mobs) self.add(axes) self.add(plane) self.add(basis_mobs) self.add(signal) self.add(signal_label) self.add(coef_label) for mob in self.mobjects: mob.apply_depth_test() # Show components components = always_redraw( self.get_linear_combination, signal, basis_mobs ) components.suspend_updating() self.animate_linear_combination(basis_mobs, components) self.wait(2) components.resume_updating() self.add(components) for v in [[-1, 1, 0.5], [1, 1, 0.25], [2, 1, 2]]: self.play( signal.animate.put_start_and_end_on(ORIGIN, v), run_time=3 ) self.wait() self.wait(5) # Change of basis rot_matrix = rotation_between_vectors([1, 1, 1], OUT) new_basis = rot_matrix.T basis_mobs.generate_target() for basis_mob, new_vector in zip(basis_mobs.target, new_basis): basis_mob.put_start_and_end_on(ORIGIN, new_vector) self.play(FadeOut(components)) self.play(MoveToTarget(basis_mobs, run_time=2)) self.wait() components.update() for comp in components: self.play(GrowArrow(comp)) self.add(components) for vect in [[1, 0, 2]]: self.play(signal.animate.put_start_and_end_on(ORIGIN, vect), run_time=3) self.wait() frame.suspend_updating() self.embed() def get_coefficients(self, vect_mob, basis_mobs): cob_inv = np.array([ b.get_vector() for b in basis_mobs ]).T cob = np.linalg.inv(cob_inv) return np.dot(cob, vect_mob.get_vector()) def get_linear_combination(self, vect_mob, basis_mobs): coefs = self.get_coefficients(vect_mob, basis_mobs) components = VGroup() last_point = vect_mob.get_start() for coef, basis in zip(coefs, basis_mobs): comp = Vector(coef * basis.get_vector()) comp.match_style(basis) comp.set_stroke(opacity=0.5) comp.shift(last_point - comp.get_start()) last_point = comp.get_end() components.add(comp) return components def animate_linear_combination(self, basis_mobs, components): for basis, part in zip(basis_mobs, components): self.play(TransformFromCopy(basis, part)) def get_coef_label(self, vect_mob, basis_mobs, lhs_tex="\\vec{\\textbf{s}}"): label = VGroup() lhs = OldTex(lhs_tex + "=") label.numbers = VGroup(*( DecimalNumber(include_sign=True) for b in basis_mobs )) label.basis_labels = VGroup(*( OldTex("\\vec{\\textbf{v}}_1", color=RED), OldTex("\\vec{\\textbf{v}}_2", color=GREEN), OldTex("\\vec{\\textbf{v}}_3", color=BLUE), )) label.add(lhs) label.add(*it.chain(*zip( label.numbers, label.basis_labels ))) label.fix_in_frame() label.arrange(RIGHT, buff=SMALL_BUFF) label.to_corner(UL) def update_label(label): coefs = self.get_coefficients(vect_mob, basis_mobs) for coef, number in zip(coefs, label.numbers): number.set_value(coef) label.add_updater(update_label) return label class ContrastPureToneToPianoKey(Scene): def construct(self): pass
from manim_imports_ext import * from _2022.borwein.main import * # Pi creature scenes and quick supplements class UniverseIsMessingWithYou(TeacherStudentsScene): def construct(self): pass class ExpressAnger(TeacherStudentsScene): def construct(self): self.remove(self.background) self.students[1].change_mode("maybe") self.play( self.teacher.change("raise_left_hand", look_at=3 * RIGHT + UP), self.change_students("pondering", "confused", "thinking", look_at=3 * RIGHT + UP) ) self.wait(2) self.play( self.teacher.change("tease", look_at=3 * RIGHT + UP), self.change_students("angry", "erm", "pleading", look_at=3 * RIGHT + UP) ) self.wait(5) class LooksCanBeDeceiving(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("Looks can be\ndeceiving", mode="tease"), self.change_students("angry", "erm", "pleading", look_at=self.screen) ) self.wait(3) class AstuteAmongYou(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.play( stds[2].says( OldTexText("What about\\\\$x=0$?"), bubble_direction=LEFT, mode="raise_right_hand" ), stds[0].change("hesitant"), stds[1].change("pondering"), morty.change("happy", stds[2].eyes), ) self.wait(2) self.play( stds[0].says("The squeeze theorem!", mode="hooray"), RemovePiCreatureBubble(stds[2]) ) self.look_at(stds[0].get_corner(UR)) self.wait(3) # Hold Up point = stds.get_top() + 2 * UP self.play( stds[0].debubble(mode="raise_right_hand", look_at=point), stds[1].change("thinking", point), stds[2].change("erm", point), morty.change("tease", point) ) self.wait(5) class AreaToSignedArea(InteractiveScene): def construct(self): # Words equals = OldTex("=") equals.to_edge(UP, buff=1.0).shift(2.5 * LEFT) area = Text("Area") area.next_to(equals, RIGHT) arrow = Arrow(area.get_bottom(), UP) signed_area = Text("Signed area", t2s={"Signed": ITALIC}) signed_area.next_to(equals, RIGHT) blue_minus_red = OldTexText( "= (Blue area) - (Red area)", tex_to_color_map={"(Blue area)": BLUE, "(Red area)": RED} ) blue_minus_red.next_to(signed_area, RIGHT) self.play(FadeIn(equals), Write(area), ShowCreation(arrow)) self.wait() self.play(TransformMatchingShapes(area, signed_area)) self.wait() self.play(FadeIn(blue_minus_red[:2])) self.wait() self.play(FadeIn(blue_minus_red[2:])) self.wait() class HoldOffUntilEnd(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("I'll mention the\ntrick at the end"), self.change_students("confused", "hesitant", "maybe", look_at=self.screen) ) self.wait() self.teacher_says("But first...", target_mode="tease") self.wait() class WhatsGoingOn(InteractiveScene): def construct(self): randy = Randolph(height=2) randy.to_corner(DL).look(RIGHT) self.play(randy.says("What on earth\nis going on?", mode="angry")) self.play(randy.animate.look(DR)) self.play(Blink(randy)) self.wait(2) self.play(randy.change("confused")) self.play(Blink(randy)) self.wait(2) class SeemsUnrelated(InteractiveScene): def construct(self): # Test morty = Mortimer(height=2.0) morty.to_edge(DOWN) self.play(morty.says("That should modify\nthe area, right?", mode="maybe")) self.play(Blink(morty)) self.wait() class WhatsThePoint(TeacherStudentsScene): def construct(self): stds = self.students self.play( stds[2].says( OldTexText(R"So it computes $\pi$ \\ what's the point?"), bubble_direction=LEFT, mode="angry", ), stds[1].change("sassy", self.screen), stds[0].change("pondering", self.screen), self.teacher.change("guilty") ) self.wait(2) self.play( self.teacher.says("Look what \n happens next", mode="tease", bubble_direction=RIGHT), stds[2].debubble(), stds[1].change("erm"), stds[0].change("thinking"), ) self.wait(2) class BillionBillionBillion(InteractiveScene): def construct(self): fraction = OldTex(get_fifteenth_frac_tex())[0] # self.add(fraction) for x in (4, 16, 28): part = VGroup(*fraction[x:x + 11], *fraction[x + 40:x + 40 + 11]) vh = VHighlight(part, color_bounds=(YELLOW, BLACK), max_stroke_addition=8) self.add(vh, part) self.wait(0.5) self.remove(vh, part) self.wait() class MovingAverageFrames(InteractiveScene): def construct(self): # Frames self.add(FullScreenRectangle()) screens = ScreenRectangle(height=4).replicate(2) screens.arrange(RIGHT, buff=1.0) screens.set_width(FRAME_WIDTH - 1) screens.set_stroke(WHITE, 1) screens.set_fill(BLACK, 1) screens.move_to(0.5 * DOWN) self.add(screens) # Titles titles = VGroup( Text("Step 1:\nAn easier analogy", alignment="LEFT"), Text("Step 2:\nReveal it's more than an analogy", alignment="LEFT"), ) titles.match_width(screens[0]) for title, screen in zip(titles, screens): title.next_to(screen, UP, aligned_edge=LEFT) # Animations n = len("Step1:") for i in range(2): self.play(Write(titles[i][:n])) self.play(FadeIn(titles[i][n:], 0.5 * DOWN)) self.wait() class FirstInASequence(InteractiveScene): def construct(self): morty = Mortimer(height=2).flip() morty.to_corner(DR) self.play(morty.says("First in a\nsequence")) self.play(Blink(morty)) self.wait(2) class XInMovingAverageGraphs(MovingAverages): def construct(self): axes1, axes2 = self.get_axes(), self.get_axes() axes1.to_edge(UP) axes2.to_edge(DOWN).shift(0.15 * DOWN) # self.add(axes1, axes2) # Remove # Labels x = -0.61 y = 0.1 xp1 = axes1.c2p(x, 0) x_label = OldTex(f"x = {x}", tex_to_color_map={"x": YELLOW}) x_label.next_to(xp1, DOWN, buff=LARGE_BUFF) arrow = Arrow(x_label[0].get_top(), xp1, buff=0.2).set_color(YELLOW) h_line = DashedLine(axes2.c2p(0, y), axes2.c2p(x, y)) h_line.set_stroke(RED, 2) us = axes1.x_axis.unit_size brace = Brace(Line(xp1 + us * LEFT / 6, xp1 + us * RIGHT / 6), DOWN) brace_text = brace.get_text("Average value\nin this window", font_size=36) self.play( Write(x_label), ShowCreation(arrow) ) self.wait() self.play(ShowCreation(h_line)) self.wait() self.play( FadeOut(x_label), FadeOut(arrow), GrowFromCenter(brace), FadeIn(brace_text, 0.5 * DOWN) ) self.wait() class ThisConstant(InteractiveScene): def construct(self): words1 = Text("This constant\nhere") words1.to_edge(RIGHT) arrow = Arrow(words1.get_bottom() + 0.1 * DOWN, words1.get_bottom() + DOWN + 1.5 * LEFT) VGroup(words1, arrow).set_color(YELLOW) same = Text("Same").match_style(words1) same.move_to(words1.select_part("This"), DR) self.play(Write(words1), ShowCreation(arrow), run_time=1) self.wait() self.play( FadeIn(same, 0.5 * UP), FadeOut(words1.select_part("This"), 0.5 * UP), ) class HeavyMachinery(TeacherStudentsScene): def construct(self): stds = self.students morty = self.teacher self.play( stds[2].says("Why on earth are\nthose two related?", bubble_direction=LEFT, look_at=self.screen), morty.change("tease"), stds[0].change("pleading", self.screen), stds[1].change("confused", self.screen), ) self.wait(2) self.play(self.change_students("maybe", "confused", "hesitant")) self.wait(2) # Heavy machinery kw = dict(font_size=60) ft = Text("Fourier Transforms", **kw) conv = OldTexText("Convolution", "s", **kw) conv_thm = OldTexText("The ", "Convolution", R"\\Theorem", **kw) for text in ft, conv, conv_thm: text.move_to(self.hold_up_spot, DOWN) self.play( morty.change("raise_right_hand"), FadeIn(ft, UP), stds[2].debubble(mode="guilty", look_at=ft), stds[0].change("erm", look_at=ft), stds[1].change("sad", look_at=ft), ) self.wait() self.play( FadeIn(conv, UP), ft.animate.next_to(conv, UP, MED_LARGE_BUFF) ) self.wait(2) self.play(morty.change("tease")) self.wait() # Don't want to assume ft.save_state() conv.save_state() self.play( morty.says("First, a high\nlevel overview", bubble_direction=RIGHT), self.change_students("skeptical", "erm", "pondering"), VGroup(ft, conv).animate.scale(0.55).to_corner(UR), ) self.wait(3) self.play( morty.debubble(mode="raise_right_hand"), conv.animate.restore(), self.change_students("pondering", "thinking", "thinking", look_at=self.screen), ) self.wait(4) # Mention theorem self.play( TransformMatchingTex(conv, conv_thm), morty.change("hooray", conv_thm), ) self.play(self.change_students("thinking", "hesitant", "pondering", look_at=conv_thm)) self.wait(3) class EngineersSinc(InteractiveScene): def construct(self): # Blah sinc = OldTex(R"{\text{sin}(\pi x) \over \pi x}", tex_to_color_map={R"\pi": TEAL}) sinc.shift(UP) rect = SurroundingRectangle(sinc, buff=SMALL_BUFF) rect.set_stroke(YELLOW, 2) rect.round_corners() rect.insert_n_curves(20) label = Text("sinc\n(to an engineer)") label.select_part("sinc").scale(1.5, about_edge=DOWN) label.next_to(rect, DOWN, MED_LARGE_BUFF) label.set_color(GREY_A) # self.add(sinc) self.play(FadeIn(label, DOWN)) self.wait() self.play(ShowCreation(rect)) self.wait() class ThinkAboutMovingAverages(TeacherStudentsScene): def construct(self): morty = self.teacher self.play( morty.change("raise_right_hand", self.screen), self.change_students("pondering", "thinking", "happy", look_at=self.screen) ) self.wait(3) self.play( morty.says("Think about\nmoving averages"), ) self.play(self.change_students(*3 * ["pondering"])) self.wait(3) class ConceptAndNotationFrames(InteractiveScene): def construct(self): # Screens self.add(FullScreenRectangle()) screens = Rectangle(height=3, width=4).replicate(2) screens.arrange(RIGHT, buff=0.25) screens.set_width(FRAME_WIDTH - 0.5) screens.set_stroke(WHITE, 1) screens.set_fill(BLACK, 1) screens.move_to(0.5 * DOWN) self.add(screens) # Titles titles = VGroup( Text("Moving average fact"), Text("In our new notation"), Text("How does this..."), Text("...relate to this"), # Text("These computations..."), # Text("...are (in a sense)\nthe same as these"), ) for i, title in enumerate(titles): title.next_to(screens[i % 2], UP) titles[1].align_to(titles[0], UP) # Animations for i in range(2): self.play(FadeIn(titles[i])) self.wait() for i in range(2, 4): self.play(FadeIn(titles[i], 0.5 * UP), FadeOut(titles[i - 2], 0.5 * UP)) self.wait() class WhatsThat(InteractiveScene): def construct(self): randy = Randolph(height=2) self.play(randy.says("...meaning?", mode="maybe", look_at=DR)) self.play(Blink(randy)) self.wait() class SubPiComment(InteractiveScene): def construct(self): morty = Mortimer(height=2).flip() morty.to_corner(DL) self.play( morty.says(OldTex(R"x \rightarrow \pi x", tex_to_color_map={R"\pi": TEAL})) ) self.play(morty.animte.look(RIGHT)) for x in range(2): self.play(Blink(morty)) self.play(morty.animate.look(DR + x * DOWN)) self.wait(2) class HowDoYouCompute(TeacherStudentsScene): def construct(self): morty = self.teacher stds = self.students self.student_says( "But how do you\ncompute this\nFourier Transform?", mode="angry", run_time=2 ) self.play( morty.change("guilty"), stds[0].change("confused", self.screen), stds[1].change("maybe", self.screen), ) self.wait(2) self.play( stds[2].debubble(), morty.says("We'll get there"), ) self.play(self.change_students("erm", "hesitant", "hesitant")) self.wait(2) class TranslateToFourierLand(InteractiveScene): def construct(self): # Setup right side right_rect = FullScreenRectangle() right_rect.set_fill(TEAL, 0.2) right_rect.set_stroke(width=0) right_rect.stretch(0.5, 0, about_edge=RIGHT) ft_label = Text("Fourier Land", font_size=60) ft_label.next_to(right_rect.get_top(), DOWN, MED_SMALL_BUFF) ft_label.set_backstroke(width=5) ft_label.set_fill(TEAL) self.add(right_rect, ft_label) # Break up a wave? left_rect = right_rect.copy().to_edge(LEFT, buff=0) axes_kw = dict(width=FRAME_WIDTH - 2, height=3) left_axes = VGroup(*( Axes((0, 12, 1), (-2, 2), **axes_kw).scale(0.5) for x in range(3) )) left_axes.arrange(DOWN, buff=0.7) left_axes.move_to(left_rect).to_edge(DOWN, buff=SMALL_BUFF) left_graphs = VGroup( left_axes[0].get_graph(lambda x: math.sin(3 * x)), left_axes[1].get_graph(lambda x: math.sin(4 * x)), left_axes[2].get_graph(lambda x: math.sin(3 * x) + math.sin(4 * x)), ) left_graphs.set_submobject_colors_by_gradient(BLUE, YELLOW, GREEN) left_symbols = VGroup(OldTex("+"), OldTex("=").rotate(PI / 2)).scale(1.5) left_symbols[0].move_to(left_axes[0:2]) left_symbols[1].move_to(left_axes[1:3]) # Peaks in Fourier land right_axes = VGroup(*( Axes((0, 5), (0, 3), **axes_kw).scale(0.5) for x in range(3) )) for a1, a2 in zip(left_axes, right_axes): a2.match_y(a1).match_x(right_rect) def bell(x, n): return 3 * np.exp(-40 * (x - n)**2) right_graphs = VGroup( right_axes[0].get_graph(lambda x: bell(x, 3)), right_axes[1].get_graph(lambda x: bell(x, 4)), right_axes[2].get_graph(lambda x: bell(x, 3) + bell(x, 4)), ) right_graphs.match_style(left_graphs) right_symbols = left_symbols.copy().match_x(right_rect).shift(0.5 * DOWN) self.play( LaggedStartMap(FadeIn, left_axes, lag_ratio=0.7), LaggedStartMap(ShowCreation, left_graphs, lag_ratio=0.7), LaggedStartMap(Write, left_symbols, lag_ratio=0.7), run_time=3 ) self.wait() self.play(LaggedStart( TransformFromCopy(left_axes, right_axes), TransformFromCopy(left_graphs, right_graphs), TransformFromCopy(left_symbols, right_symbols), )) self.wait(3) # Other properties to_fade = VGroup( left_axes, left_graphs, left_symbols, right_axes, right_graphs, right_symbols, ) property_pairs = [ VGroup( OldTex(R"\int_{-\infty}^\infty f(t) dt"), OldTex(R"\hat f(0)"), ), VGroup( OldTex(R"f(t) \cdot g(t)"), # OldTex(R"\hat f(\omega) * \hat g(\omega)", tex_to_color_map={R"\omega": YELLOW}), OldTex(R"\int_{-\infty}^\infty \hat f(\xi) \hat g(\omega - \xi) d\xi", tex_to_color_map={R"\omega": YELLOW}), ), VGroup( OldTex(R"\sum_{n = -\infty}^\infty f(n)"), OldTex(R"\sum_{k = -\infty}^\infty \hat f(k)"), ), ] for pair in property_pairs: pair.scale(1.5) m1, m2 = pair m1.move_to(left_rect) m2.move_to(right_rect) self.play(FadeOut(to_fade), FadeIn(pair)) self.wait(3) to_fade = pair class KeyFactFrame(VideoWrapper): title = "Key fact" class TranslatedByFourier(InteractiveScene): def construct(self): # Two expressions # left_expr = Tex(R"\int_{-\infty}^\infty f(t) \cdot g(t) dt") # right_expr = Tex( # R"\Big[ \mathcal{F}[f(t)] * \mathcal{F}[g(t)] \Big](0)", # tex_to_color_map={R"\mathcal{F}": TEAL} # ) left_expr = Text("Multiplication\nand\nIntegration") right_expr = Text("Moving averages\nand\nEvaluating at 0") left_expr.move_to(2 * UP).set_x(-FRAME_WIDTH / 4) right_expr.match_y(left_expr).set_x(FRAME_WIDTH / 4) equals = OldTex("=").move_to(midpoint(left_expr.get_right(), right_expr.get_left())) arrow = Vector(2 * RIGHT, color=TEAL) arrow.move_to(equals) arrow_label = Text("Translate to\nFourier land", font_size=24) arrow_label.next_to(arrow, UP) arrow_label.match_color(arrow) # brace = Brace(right_expr[:-3], UP, buff=SMALL_BUFF) # brace_text = OldTexText("To be explained,\\\\think ``moving average''", font_size=36) # brace_text.next_to(brace, UP, SMALL_BUFF) self.play(Write(left_expr)) self.wait(2) self.play(LaggedStart( # Write(equals), GrowArrow(arrow), FadeIn(arrow_label, lag_ratio=0.1), FadeTransform(left_expr.copy(), right_expr, path_arc=-PI / 5), lag_ratio=0.5 )) self.wait(2) # self.play(GrowFromCenter(brace), FadeIn(brace_text, 0.5 * UP)) self.wait() class UnsatisfyingEnd(TeacherStudentsScene): def construct(self): # Ask self.remove(self.background) morty = self.teacher stds = self.students self.play( stds[0].says("But you haven't explained\nwhy any of that is true?", mode="angry"), stds[1].change("hesitant"), stds[2].change("pleading"), morty.change("guilty"), ) stds[0].bubble.insert_n_curves(20) self.wait(3) self.play( morty.says("Patience.", mode="tease"), stds[0].debubble(), stds[2].change("hesitant") ) self.wait(2) class EndScreen(PatreonEndScreen): pass
from manim_imports_ext import * SUB_ONE_FACTOR = "0.99999999998529" def sinc(x): return np.sinc(x / PI) def multi_sinc(x, n): return np.prod([sinc(x / (2 * k + 1)) for k in range(n)]) def rect_func(x): result = np.zeros_like(x) result[(-0.5 < x) & (x < 0.5)] = 1.0 return result def get_fifteenth_frac_tex(): return R"{467{,}807{,}924{,}713{,}440{,}738{,}696{,}537{,}864{,}469 \over 467{,}807{,}924{,}720{,}320{,}453{,}655{,}260{,}875{,}000}" def get_sinc_tex(k=1): div_k = f"/ {k}" if k > 1 else "" return Rf"{{\sin(x {div_k}) \over x {div_k}}}" def get_multi_sinc_integral(ks=[1], dots_at=None, rhs="", insertion=""): result = OldTex( R"\int_{-\infty}^\infty", insertion, *( get_sinc_tex(k) if k != dots_at else R"\dots" for k in ks ), "dx", rhs, ) t2c = { R"\sin": BLUE, "x / 3": TEAL, "x / 5": GREEN_B, "x / 7": GREEN_C, "x / 9": interpolate_color(GREEN, YELLOW, 1 / 3), "x / 11": interpolate_color(GREEN, YELLOW, 2 / 3), "x / 13": YELLOW, "x / 15": RED_B, } for tex, color in t2c.items(): result.set_color_by_tex(tex, color) return result class ShowIntegrals(InteractiveScene): # add_axis_labels = True add_axis_labels = False def construct(self): # Setup axes axes = self.get_axes() graph = axes.get_graph(sinc, color=BLUE) graph.set_stroke(width=3) points = graph.get_anchors() right_sinc = VMobject().set_points_smoothly(points[len(points) // 2:]) left_sinc = VMobject().set_points_smoothly(points[:len(points) // 2]).reverse_points() VGroup(left_sinc, right_sinc).match_style(graph).make_jagged() func_label = Tex(R"{\sin(x) \over x}") func_label.move_to(axes, UP).to_edge(LEFT) self.add(axes) self.play( Write(func_label), ShowCreation(right_sinc, remover=True, run_time=3), ShowCreation(left_sinc, remover=True, run_time=3), ) self.add(graph) self.wait() # Discuss sinc function? sinc_label = OldTex(R"\text{sinc}(x)") sinc_label.next_to(func_label, UR, buff=LARGE_BUFF) arrow = Arrow(func_label, sinc_label) one_over_x_graph = axes.get_graph(lambda x: 1 / x, x_range=(0.1, 8 * PI)) one_over_x_graph.set_stroke(YELLOW, 2) one_over_x_label = OldTex("1 / x") one_over_x_label.next_to(axes.i2gp(1, one_over_x_graph), RIGHT) sine_wave = axes.get_graph(np.sin, x_range=(0, 8 * PI)).set_stroke(TEAL, 3) half_sinc = axes.get_graph(sinc, x_range=(0, 8 * PI)).set_stroke(BLUE, 3) self.play( GrowArrow(arrow), FadeIn(sinc_label, UR) ) self.wait() self.play( ShowCreation(sine_wave, run_time=2), graph.animate.set_stroke(width=1, opacity=0.5) ) self.wait() self.play( ShowCreation(one_over_x_graph), FadeIn(one_over_x_label), Transform(sine_wave, half_sinc), ) self.wait() self.play( FadeOut(one_over_x_graph), FadeOut(one_over_x_label), FadeOut(sine_wave), graph.animate.set_stroke(width=3, opacity=1), ) # At 0 hole = Dot() hole.set_stroke(BLUE, 2) hole.set_fill(BLACK, 1) hole.move_to(axes.c2p(0, 1)) zero_eq = OldTex(R"{\sin(0) \over 0} = ???") zero_eq.next_to(hole, UR) lim = OldTex(R"\lim_{x \to 0} {\sin(x) \over x} = 1") lim.move_to(zero_eq, LEFT) x_tracker = ValueTracker(1.5 * PI) get_x = x_tracker.get_value dots = GlowDot().replicate(2) globals().update(locals()) dots.add_updater(lambda d: d[0].move_to(axes.i2gp(-get_x(), graph))) dots.add_updater(lambda d: d[1].move_to(axes.i2gp(get_x(), graph))) dots.update() self.play(Write(zero_eq), FadeIn(hole, scale=0.35)) self.wait() self.play(FadeTransform(zero_eq, lim)) self.add(dots) self.play( x_tracker.animate.set_value(0).set_anim_args(run_time=2), UpdateFromAlphaFunc(dots, lambda m, a: m.set_opacity(a)), ) self.wait() self.play(FadeOut(dots), FadeOut(hole), FadeOut(lim)) self.play(FadeOut(arrow), FadeOut(sinc_label)) # Area under curve area = self.get_area(axes, graph) int1 = self.get_integral(1) rhs = OldTex(R"=\pi") rhs.next_to(int1, RIGHT) origin = axes.get_origin() pos_area = VGroup(*(r for r in area if r.get_center()[1] > origin[1])) neg_area = VGroup(*(r for r in area if r.get_center()[1] < origin[1])) self.add(area, axes, graph) area.set_fill(opacity=1) self.play( Write(area, stroke_color=WHITE, lag_ratio=0.01, run_time=4), ReplacementTransform(func_label, int1[1]), Write(int1[::2]), graph.animate.set_stroke(width=1), ) self.add(int1) self.wait() self.play(FadeOut(neg_area)) self.wait() self.play(FadeIn(neg_area), FadeOut(pos_area)) self.wait() self.play(FadeIn(pos_area)) self.add(area) self.wait() self.play(Write(rhs)) self.play(FlashAround(rhs, run_time=2)) self.wait() # Show sin(x / 3) / (x / 3) frame = self.camera.frame midpoint = 1.5 * DOWN top_group = VGroup(axes, graph, area) top_group.generate_target().next_to(midpoint, UP) low_axes = self.get_axes(height=2.5) low_axes.next_to(midpoint, DOWN, buff=MED_LARGE_BUFF) low_sinc = low_axes.get_graph(sinc) low_sinc.set_stroke(BLUE, 2) low_graph = low_axes.get_graph(lambda x: sinc(x / 3)) low_graph.set_stroke(WHITE, 2) low_label = OldTex(R"{\sin(x / 3) \over x / 3}") low_label.match_x(int1[1]).shift(1.75 * LEFT).match_y(low_axes.get_top()) self.play( MoveToTarget(top_group), FadeTransform(axes.copy(), low_axes), FadeIn(low_label), frame.animate.set_height(10), VGroup(int1, rhs).animate.shift(UP + 1.75 * LEFT), ) self.wait() self.play(TransformFromCopy(graph, low_sinc)) self.play(low_sinc.animate.stretch(3, 0).match_style(low_graph), run_time=2) self.remove(low_sinc) self.add(low_graph) self.wait() # Sequence of integrals curr_int = int1 for n in range(2, 9): new_int = self.get_integral(n) if n == 4: new_int.scale(0.9) elif n == 5: new_int.scale(0.8) elif n > 5: new_int.scale(0.7) new_int.move_to(curr_int, LEFT) if n < 8: # TODO new_rhs = Tex(R"=\pi") else: new_rhs = Tex(R"\approx \pi - 4.62 \times 10^{-11}") new_rhs.next_to(new_int, RIGHT) new_graph = axes.get_graph(lambda x, n=n: multi_sinc(x, n)) new_graph.set_stroke(BLUE, 2) new_area = self.get_area(axes, new_graph) self.play( ReplacementTransform(curr_int[:n], new_int[:n]), TransformFromCopy(low_label[0], new_int[n]), ReplacementTransform(curr_int[-1], new_int[-1]), FadeOut(rhs), FadeOut(area), ReplacementTransform(graph, new_graph), TransformFromCopy(low_graph, new_graph.copy(), remover=True), ) self.play(Write(new_area, stroke_color=WHITE, stroke_width=1, lag_ratio=0.01)) self.wait(0.25) self.play(FadeIn(new_rhs, scale=0.7)) self.play(FlashAround(new_rhs)) self.wait() if n < 8: new_low_graph = low_axes.get_graph(lambda x, n=n: sinc(x / (2 * n + 1))) new_low_graph.match_style(low_graph) new_low_label = OldTex(fR"{{\sin(x / {2 * n + 1}) \over x / {2 * n + 1}}}") new_low_label.move_to(low_label) if n == 4: new_low_label.shift(0.5 * UP) self.play( FadeOut(low_label, UP), FadeIn(new_low_label, UP), ReplacementTransform(low_graph, new_low_graph), ) self.wait(0.25) curr_int = new_int rhs = new_rhs graph = new_graph area = new_area low_graph = new_low_graph low_label = new_low_label # More accurate rhs new_rhs = OldTex(Rf"= {get_fifteenth_frac_tex()} \pi") new_rhs.next_to(curr_int, DOWN, buff=LARGE_BUFF) self.play( FadeOut(VGroup(low_axes, low_graph, low_label), DOWN), VGroup(axes, graph, area).animate.shift(2 * DOWN), Write(new_rhs) ) self.wait() def get_axes(self, x_range=(-10 * PI, 10 * PI, PI), y_range=(-0.5, 1, 0.5), width=1.3 * FRAME_WIDTH, height=3.5, ): axes = Axes(x_range, y_range, width=width, height=height) axes.center() if self.add_axis_labels: axes.y_axis.add_numbers(num_decimal_places=1, font_size=20) for u in -1, 1: axes.x_axis.add_numbers( u * np.arange(PI, 15 * PI, PI), unit=PI, unit_tex=R"\pi", font_size=20 ) return axes def get_area(self, axes, graph, dx=0.01 * PI, fill_opacity=0.5): rects = axes.get_riemann_rectangles( graph, dx=dx, colors=(BLUE_D, BLUE_D), negative_color=RED, ) rects.set_fill(opacity=fill_opacity) rects.set_stroke(width=0) rects.sort(lambda p: abs(p[0])) return rects def get_integral(self, n): return OldTex( R"\int_{-\infty}^\infty", R"{\sin(x) \over x}", *( Rf"{{\sin(x/{k}) \over x / {k} }}" for k in range(3, 2 * n + 1, 2) ), "dx" ).to_corner(UL) class SineLimit(InteractiveScene): def construct(self): axes = Axes((-4, 4), (-2, 2), width=14, height=7, axis_config=dict(tick_size=0)) radius = axes.x_axis.unit_size circle = Circle(radius=radius) circle.move_to(axes.get_origin()) circle.set_stroke(WHITE, 1) self.add(axes, circle) # Set up components x_tracker = ValueTracker(1) get_x = x_tracker.get_value origin = axes.get_origin() def get_point(): x = get_x() return axes.c2p(math.cos(x), math.sin(x)) arc = VMobject().set_stroke(YELLOW, 3) arc.add_updater(lambda m: m.match_points(Arc( radius=radius, arc_center=origin, start_angle=0, angle=get_x(), ))) h_line = Line() h_line.set_stroke(RED) h_line.add_updater(lambda m: m.put_start_and_end_on( get_point(), get_point()[0] * RIGHT, )) radial_line = Line() radial_line.add_updater(lambda m: m.put_start_and_end_on(origin, get_point())) one_label = Integer(1, font_size=24) one_label.add_updater(lambda m: m.next_to( radial_line.get_center(), normalize(rotate_vector(radial_line.get_vector(), PI / 2)), buff=SMALL_BUFF, )) sine_label = OldTex(R"\sin(x)", font_size=24) sine_label.set_backstroke() sine_label.add_updater(lambda m: m.set_max_height(0.2 * h_line.get_height())) sine_label.add_updater(lambda m: m.next_to(h_line, LEFT, buff=0.25 * m.get_width())) x_label = OldTex("x", font_size=24) x_label.add_updater(lambda m: m.match_width(sine_label[0][4])) x_label.add_updater(lambda m: m.next_to(arc.pfp(0.5), RIGHT, buff=m.get_height())) self.add(arc, h_line, radial_line) self.add(one_label) self.add(sine_label) self.add(x_label) value_label = VGroup( OldTex(R"\frac{\sin(x)}{x} = "), DecimalNumber(1, num_decimal_places=4) ) value_label.arrange(RIGHT, buff=SMALL_BUFF) value_label.fix_in_frame() value_label.to_corner(UR) value_label.add_updater(lambda m: m[1].set_value(math.sin(get_x()) / get_x())) self.add(value_label) # Zoom in frame = self.camera.frame frame.set_height(4) x_tracker.add_updater(lambda m: m.set_value((1 / (self.time**1.5 + 1.5)))) self.add(x_tracker) target_frame = frame.deepcopy() target_frame.add_updater(lambda m: m.set_height(4 * h_line.get_height()).move_to(h_line.get_bottom())) self.add(target_frame) alpha_tracker = ValueTracker(0) get_alpha = alpha_tracker.get_value self.play( UpdateFromFunc( frame, lambda m: m.interpolate(m, target_frame, get_alpha()), run_time=15, ), alpha_tracker.animate.set_value(1 / 30).set_anim_args(run_time=1) ) class WriteFullIntegrals(InteractiveScene): def construct(self): # Integrals ints = VGroup(*( get_multi_sinc_integral(range(1, n, 2), rhs=R"= \pi") for n in range(3, 19, 2) )) ints.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) ints.center().to_corner(UL) for inter in ints: inter[-1].scale(1.5, about_edge=LEFT) q_marks = OldTex("???", color=RED).scale(2) q_marks.next_to(ints[-1], RIGHT, buff=MED_LARGE_BUFF) correction = OldTex("- 0.0000000000462...").scale(1.25) correction.next_to(ints[-1], RIGHT, SMALL_BUFF) # Show all frame = self.camera.frame ds = ValueTracker(0) frame.add_updater(lambda m, dt: m.scale(1 + 0.02 * dt, about_edge=UL).shift(ds.get_value() * dt * DOWN)) self.add(ints[0], ds) for i in range(len(ints) - 1): self.wait(2) anims = [TransformMatchingTex(ints[i].copy(), ints[i + 1])] if i < 6: anims.append(ds.animate.increment_value(0.1)) self.play(*anims) frame.clear_updaters() self.play(Write(q_marks), frame.animate.scale(1.1, about_edge=UL).shift(2 * DOWN), run_time=2) self.wait() self.play(FadeTransform(q_marks, correction)) self.wait() class WriteMoreFullIntegrals(InteractiveScene): def construct(self): # Unfortunate copy pasting, but I'm in a rush # Integrals ints = VGroup(*( get_multi_sinc_integral(range(1, n, 2), rhs=R"= \pi") for n in range(3, 17, 2) )) ints.add(get_multi_sinc_integral(range(1, 17, 2), rhs=R"= (0.99999999998529)\pi")) ints.add(get_multi_sinc_integral(range(1, 19, 2), rhs=R"= (0.99999998807962)\pi")) ints.add(get_multi_sinc_integral(range(1, 21, 2), rhs=R"= (0.99999990662610)\pi")) ints.add(get_multi_sinc_integral(range(1, 23, 2), rhs=R"= (0.99999972286332)\pi")) ints.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=LEFT) ints.center().to_corner(UL) for inter in ints: inter[-1].scale(1.5, about_edge=LEFT) # Show all frame = self.camera.frame ds = ValueTracker(0) frame.add_updater(lambda m, dt: m.scale(1 + 0.04 * dt, about_edge=UL).shift(ds.get_value() * dt * DOWN)) key_map = dict( (ints[n][-1].get_tex(), ints[n + 1][-1].get_tex()) for n in range(-4, -1, 1) ) self.add(ints[0], ds) for i in range(len(ints) - 1): self.wait() anims = [TransformMatchingTex(ints[i].copy(), ints[i + 1], key_map=key_map)] if i < 6: anims.append(ds.animate.increment_value(0.1)) self.play(*anims) self.wait(3) frame.clear_updaters() class WriteOutIntegrals(InteractiveScene): def construct(self): # Integrals ints = self.get_integrals() ints.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=RIGHT) ints.set_height(FRAME_HEIGHT - 1) ints[-1][:-2].align_to(ints[:-1], RIGHT) ints[-1][-2:].next_to(ints[-1][:-2], RIGHT, SMALL_BUFF) ints[3].shift(SMALL_BUFF * LEFT) ints.center() # Show all self.add(ints[0]) ints[-1][-2].set_opacity(0) ints[-1][-1].save_state() ints[-1][-1].move_to(ints[-1][-2], LEFT) for i in range(4): if i < 3: src = ints[i].copy() else: src = ints[i + 1].copy() if i < 2: target = ints[i + 1] elif i == 2: target = VGroup(*ints[i + 1], *ints[i + 2]) else: target = ints[i + 2] self.play(TransformMatchingTex(src, target)) self.wait(0.5) ints[-1][-2].set_opacity(1) self.play(Write(ints[-1][-2]), ints[-1][-1].animate.restore()) self.wait() def get_integrals(self): return VGroup( get_multi_sinc_integral([1], rhs=R"= \pi"), get_multi_sinc_integral([1, 3], rhs=R"= \pi"), get_multi_sinc_integral([1, 3, 5], rhs=R"= \pi"), OldTex(R"\vdots"), get_multi_sinc_integral([1, 3, 5, 7, 13], dots_at=7, rhs=R"= \pi"), get_multi_sinc_integral([1, 3, 5, 7, 13, 15], dots_at=7, rhs=Rf"= ({SUB_ONE_FACTOR}\dots)\pi"), ) class WriteOutIntegralsWithPi(WriteOutIntegrals): def get_integrals(self): t2c = { R"\sin": BLUE, "x/3": TEAL, "x/5": GREEN_B, "x/7": GREEN_C, "x/9": interpolate_color(GREEN, YELLOW, 1 / 3), "x/11": interpolate_color(GREEN, YELLOW, 2 / 3), "x/13": YELLOW, "x/15": RED_B, } result = VGroup( OldTex( R"\int_{-\infty}^\infty", R"\frac{\sin(\pi x)}{\pi x}", R"dx = ", "1.0" ), OldTex( R"\int_{-\infty}^\infty", R"\frac{\sin(\pi x)}{\pi x}", R"\frac{\sin(\pi x/3)}{\pi x/3}", R"dx = ", "1.0" ), OldTex( R"\int_{-\infty}^\infty", R"\frac{\sin(\pi x)}{\pi x}", R"\frac{\sin(\pi x/3)}{\pi x/3}", R"\frac{\sin(\pi x/5)}{\pi x/5}", R"dx = ", "1.0" ), OldTex(R"\vdots"), OldTex( R"\int_{-\infty}^\infty", R"\frac{\sin(\pi x)}{\pi x}", R"\frac{\sin(\pi x/3)}{\pi x/3}", # R"\frac{\sin(\pi x/5)}{\pi x/5}", R"\dots", R"\frac{\sin(\pi x/13)}{\pi x/13}", R"dx = ", "1.0" ), OldTex( R"\int_{-\infty}^\infty", R"\frac{\sin(\pi x)}{\pi x}", R"\frac{\sin(\pi x/3)}{\pi x/3}", # R"\frac{\sin(\pi x/5)}{\pi x/5}", R"\dots", R"\frac{\sin(\pi x/13)}{\pi x/13}", R"\frac{\sin(\pi x/15)}{\pi x/15}", R"dx = ", fR"{SUB_ONE_FACTOR}\dots", "." ), ) result[-1][-1].scale(0) for mob in result: for tex, color in t2c.items(): mob.set_color_by_tex(tex, color) return result class InsertTwoCos(InteractiveScene): dx = 0.025 def construct(self): # Formulas n_range = list(range(3, 17, 2)) integrals = VGroup( get_multi_sinc_integral([1], rhs=R"= \pi"), *( get_multi_sinc_integral(range(1, n, 2), insertion=R"2\cos(x)", rhs=R"= \pi") for n in n_range ) ) integrals.scale(0.75) for inter in integrals: inter.to_edge(UP) self.add(integrals[0]) # Graphs axes = Axes((-4 * PI, 4 * PI, PI), (-2, 2, 1), width=FRAME_WIDTH + 1, height=6) axes.to_edge(DOWN, buff=SMALL_BUFF) axes.x_axis.add_numbers(unit_tex=R"\pi", unit=PI) graphs = VGroup( axes.get_graph(sinc), *( axes.get_graph( lambda x, n=n: 2 * math.cos(x) * multi_sinc(x, n + 1), x_range=(-4 * PI, 4 * PI, 0.01) ) for n in range(len(n_range)) ) ) graphs.set_stroke(WHITE, 2) areas = VGroup(*( axes.get_riemann_rectangles( graph, dx=self.dx, colors=(BLUE_D, BLUE_D), fill_opacity=1 ) for graph in graphs )) self.add(areas[0], axes, graphs[0]) # Progress for i in range(len(integrals) - 1): self.play( TransformMatchingTex(integrals[i], integrals[i + 1]), ReplacementTransform(graphs[i], graphs[i + 1]), ReplacementTransform(areas[i], areas[i + 1]), ) self.add(areas[i + 1], axes, graphs[i + 1]) if i == 0: self.play(FlashAround(integrals[i + 1][1], run_time=2, time_width=1)) self.wait() class WriteTwoCosPattern(InteractiveScene): def construct(self): # Integrals integrals = VGroup( *( get_multi_sinc_integral(range(1, n, 2), insertion=R"2\cos(x)", rhs=R"= \pi") for n in range(1, 7, 2) ), OldTex(R"\vdots"), get_multi_sinc_integral([1, 3, 5, 111], dots_at=5, insertion=R"2\cos(x)", rhs=R"= \pi"), get_multi_sinc_integral([1, 3, 5, 111, 113], dots_at=5, insertion=R"2\cos(x)", rhs=R"= \pi"), ) integrals.scale(0.75) for inter in integrals: inter[-1].scale(1.5, about_edge=LEFT) integrals.arrange(DOWN, buff=0.8, aligned_edge=RIGHT) integrals.set_height(FRAME_HEIGHT - 1) integrals.move_to(2 * LEFT) integrals[-1][-3].set_color(RED) self.add(integrals[0]) for i in [0, 1, 2, 4]: j = i + 2 if i == 2 else i + 1 anims = [TransformMatchingTex(integrals[i].copy(), integrals[j])] if i == 2: anims.append(Write(integrals[3], run_time=1)) self.play(*anims) self.wait(0.5) self.add(integrals) # RHS text = Text("A tiny-but-definitely-positive number\nthat my computer couldn't evaluate\nin a reasonable amount of time") text.scale(0.5) parens = OldTex("()")[0] parens.match_height(text) parens[0].next_to(text, LEFT, SMALL_BUFF) parens[1].next_to(text, RIGHT, SMALL_BUFF) minus = OldTex("-").next_to(parens, LEFT) rhs = VGroup(minus, parens, text) rhs.next_to(integrals[-1], RIGHT, buff=SMALL_BUFF) self.play(Write(rhs)) self.wait() class MovingAverages(InteractiveScene): sample_resolution = 1000 graph_color = BLUE window_color = GREEN window_opacity = 0.35 n_iterations = 8 rect_scalar = 1.0 quick_transitions = False def construct(self): # Add rect graph axes = self.get_axes() rs = self.rect_scalar rect_graph = axes.get_graph( lambda x: rect_func(x / rs), discontinuities=[-0.5 * rs, 0.5 * rs] ) rect_graph.set_stroke(self.graph_color, 3) rect_def = self.get_rect_func_def() rect_def.to_corner(UR) rect_graph.axes = axes drawing_dot = GlowDot() drawing_dot.path = rect_graph drawing_dot.add_updater(lambda m: m.move_to(m.path.pfp(1))) self.add(axes) self.add(rect_def) self.add(drawing_dot) self.play(ShowCreation(rect_graph), run_time=3, rate_func=linear) self.play(FadeOut(drawing_dot)) self.wait() # Add f1 label f1_label = OldTex("f_1(x) = ") f1_label.next_to(rect_def, LEFT, buff=0.2) self.play(Write(f1_label, stroke_color=WHITE)) self.wait() f1_label_group = VGroup(f1_label, rect_def) rect_graph.func_labels = f1_label_group # Make room for new graph low_axes = self.get_axes().to_edge(DOWN, buff=MED_SMALL_BUFF) self.play( f1_label_group.animate.set_height(0.7, about_edge=UR), VGroup(axes, rect_graph).animate.to_edge(UP), TransformFromCopy(axes, low_axes) ) self.wait() # Create all convolutions sample_resolution = self.sample_resolution xs = np.linspace(-rs, rs, int(2 * rs * sample_resolution + 1)) k_range = list(range(3, self.n_iterations * 2 + 1, 2)) graphs = [rect_graph, *self.get_all_convolution_graphs( xs, rect_func(xs / rs), low_axes, k_range )] for graph in graphs: graph.match_style(rect_graph) # Show all convolutions prev_graph = rect_graph prev_graph_label = f1_label_group for n in range(1, self.n_iterations): anim_time = (0.01 if self.quick_transitions else 1.0) # Show moving average, first with a pass, then with time to play window_group = self.show_moving_average(axes, low_axes, graphs[n], k_range[n - 1]) # Label low graph fn_label = OldTex(f"f_{{{n + 1}}}(x)", font_size=36) fn_label.move_to(low_axes.c2p(0.5 * rs, 1), UL) fn0_label = OldTex(f"f_{{{n + 1}}}(0) = " + ("1.0" if n < self.n_iterations - 1 else "0.9999999999852937..."), font_size=36) fn0_label.next_to(fn_label, DOWN, aligned_edge=LEFT) self.play(Write(fn_label, stroke_color=WHITE), run_time=anim_time) self.wait(anim_time) # Note plateau width, color plateau width = max(rs - sum((1 / k for k in range(3, 2 * n + 3, 2))), 0) plateau = Line(low_axes.c2p(-width / 2, 1), low_axes.c2p(width / 2, 1)) if width < 0: plateau.set_width(0) plateau.set_stroke(YELLOW, 3) brace = Brace(plateau, UP) brace_label = brace.get_tex(self.get_brace_label_tex(n)) brace_label.scale(0.75, about_edge=DOWN) self.play( GrowFromCenter(brace), GrowFromCenter(plateau), Write(brace_label, stroke_color=WHITE), run_time=anim_time, ) graphs[n].add(plateau) self.wait(anim_time) self.play(FadeIn(fn0_label, 0.5 * DOWN), run_time=anim_time) self.wait() # Remove window self.play(LaggedStartMap(FadeOut, window_group), run_time=anim_time) # Put lower graph up top new_low_axes = self.get_axes() new_low_axes.move_to(low_axes) shift_value = axes.c2p(0, 0) - low_axes.c2p(0, 0) if n < self.n_iterations - 1: anims = [ FadeOut(mob, shift_value) for mob in [axes, prev_graph, prev_graph_label] ] anims.append(FadeIn(new_low_axes, shift_value)) else: shift_value = ORIGIN anims = [] anims.extend([ *( mob.animate.shift(shift_value) for mob in [low_axes, graphs[n], fn_label, fn0_label] ), FadeOut(VGroup(brace, brace_label), shift_value), ]) self.play(*anims) prev_graph = graphs[n] prev_graph_label = VGroup(fn_label, fn0_label) axes = low_axes low_axes = new_low_axes graphs[n].axes = axes graphs[n].func_labels = prev_graph_label # Show all graphs together graphs[0].add(Line( graphs[0].axes.c2p(-0.5, 1), graphs[0].axes.c2p(0.5, 1), stroke_color=YELLOW, stroke_width=3.0, )) graph_groups = VGroup(*( VGroup(graph.axes, graph, graph.func_labels[1]) for graph in graphs[:8] )) graph_groups.save_state() graph_groups.generate_target() graph_groups[:-2].set_opacity(0) graph_groups.target.arrange_in_grid( 4, 2, v_buff=2.0, h_buff=1.0, aligned_edge=LEFT, fill_rows_first=False ) for group in graph_groups.target: group[2].scale(2, about_edge=DL) graph_groups.target.set_height(FRAME_HEIGHT - 1) graph_groups.target.center().to_edge(LEFT) self.play( MoveToTarget(graph_groups), FadeOut(graphs[7].func_labels[0]), FadeOut(graphs[6].func_labels[0]), ) self.wait() def get_all_convolution_graphs(self, xs, ys, axes, k_range): result = [] func_samples = [ys] for k in k_range: kernel = rect_func(k * xs) kernel /= sum(kernel) func_samples.append(np.convolve( func_samples[-1], # Last function kernel, mode='same' )) new_graph = VMobject() new_graph.set_points_smoothly(axes.c2p(xs, func_samples[-1])) new_graph.origin = axes.c2p(0, 0) result.append(new_graph) result[0].make_jagged() return result def show_moving_average(self, top_axes, low_axes, low_graph, k): rs = self.rect_scalar window = Rectangle( width=top_axes.x_axis.unit_size / k, height=top_axes.y_axis.unit_size * 1.5, ) window.set_stroke(width=0) window.set_fill(self.window_color, self.window_opacity) window.move_to(top_axes.c2p(-rs, 0), DOWN) arrow_buff = min(SMALL_BUFF, window.get_width() / 2) arrow = Arrow(window.get_left(), window.get_right(), stroke_width=4, buff=arrow_buff) arrows = VGroup(arrow, arrow.copy().flip()) arrows[0].shift(0.5 * arrow_buff * RIGHT) arrows[1].shift(0.5 * arrow_buff * LEFT) arrows.next_to(window.get_bottom(), UP, buff=0.5) width_label = OldTex(f"1 / {k}", font_size=24) width_label.set_backstroke(width=4) width_label.set_max_width(min(arrows.get_width(), 0.5)) width_label.next_to(arrows, UP) window.add(arrows, width_label) window.add_updater(lambda w: w.align_to(top_axes.get_origin(), DOWN)) v_line = DashedLine( window.get_top(), low_axes.c2p(low_axes.x_axis.p2n(window.get_bottom()), 0) ) v_line.add_updater(lambda m, w=window: m.move_to(w.get_top(), UP)) v_line.set_stroke(WHITE, 1) self.add(window) self.add(v_line) drawing_dot = GlowDot(color=window.get_color()) drawing_dot.add_updater(lambda m, w=window, g=low_graph.copy(): m.move_to( g.quick_point_from_proportion( (low_axes.x_axis.p2n(w.get_center()) + rs) / (2 * rs) ) )) drawing_dot.set_glow_factor(1) drawing_dot.set_radius(0.15) self.add(drawing_dot) self.play( ShowCreation(low_graph), window.animate.move_to(top_axes.c2p(rs, 0), DOWN), rate_func=bezier([0, 0, 1, 1]), run_time=(2.5 if self.quick_transitions else 5), ) self.wait() return Group(window, v_line, drawing_dot) def get_brace_label_tex(self, n): result = "1" for k in range(3, 2 * n + 3, 2): result += "- " + f"1 / {k}" return result def get_rect_func_def(self): return Tex( R"""\text{rect}(x) := \begin{cases} 1 & \text{if } \text{-}\frac{1}{2} < x < \frac{1}{2} \\ 0 & \text{otherwise} \end{cases}""" ) def get_axes(self, x_range=(-1, 1, 0.25), y_range=(0, 1, 0.25), width=13.0, height=2.5): axes = Axes(x_range=x_range, y_range=y_range, width=width, height=height) axes.add_coordinate_labels( x_values=np.arange(*x_range)[::2], y_values=np.arange(0, 1.0, 0.5), num_decimal_places=2, font_size=20 ) return axes class LongerTimescaleMovingAverages(MovingAverages): sample_resolution = 4000 n_iterations = 58 # n_iterations = 16 rect_scalar = 2.0 quick_transitions = True def get_rect_func_def(self): return Tex( R"""\text{long\_rect}(x) := \begin{cases} 1 & \text{if } \text{-}1 < x < 1 \\ 0 & \text{otherwise} \end{cases}""" ) def get_axes(self, x_range=(-2, 2, 0.25), *args, **kwargs): return super().get_axes(x_range, *args, **kwargs) def get_brace_label_tex(self, n): result = "2" for k in range(3, min(2 * n + 3, 9), 2): result += "- " + f"1 / {k}" if n > 3: result += fR" - \cdots - 1 / {2 * n + 1}" return result class ShowReciprocalSums(InteractiveScene): max_shown_parts = 10 def construct(self): # Equations equations = VGroup(*( self.get_sum(n) for n in range(1, 8) )) for equation in equations: t2c = dict(zip( [f"1 / {2 * k + 1}" for k in range(1, 10)], color_gradient([BLUE, YELLOW, RED], 8) )) equation.set_color_by_tex_to_color_map(t2c) equations[-1][-1].set_color(RED) equations.arrange(DOWN, aligned_edge=RIGHT, buff=MED_LARGE_BUFF) equations.center() self.add(equations[0]) for eq1, eq2 in zip(equations, equations[1:]): self.play(TransformMatchingTex(eq1.copy(), eq2, fade_transform_mismatches=True)) self.wait() self.wait() def get_sum(self, n): tex_parts = [] tally = 0 msp = self.max_shown_parts for k in range(1, n + 1): new_parts = [f"1 / {2 * k + 1}", "+"] if n > msp: if k < msp - 1 or k == n: tex_parts.extend(new_parts) elif k == msp - 1: tex_parts.extend([R"\cdots", "+"]) else: tex_parts.extend(new_parts) tally += 1 / (2 * k + 1) tex_parts[-1] = "=" tex_parts.append(R"{:.06f}\dots".format(tally)) return OldTex(*tex_parts) class LongerReciprocalSums(ShowReciprocalSums): max_shown_parts = 5 def construct(self): # Test equations = VGroup(*( self.get_sum(n) for n in [1, 2, 3, 4, 54, 55, 56] )) dots = OldTex(R"\vdots") group = VGroup(*equations[:4], dots, *equations[4:]) group.arrange(DOWN, buff=0.35, aligned_edge=RIGHT) dots.shift(2 * LEFT) for eq in equations: eq.set_color_by_tex_to_color_map({ "1 / 3": BLUE, "1 / 5": interpolate_color(BLUE, GREEN, 1 / 3), "1 / 7": interpolate_color(BLUE, GREEN, 2 / 3), "1 / 9": GREEN, "1 / 109": YELLOW, "1 / 111": interpolate_color(YELLOW, RED, 1 / 2), "1 / 113": RED, }) self.add(equations[0]) for eq1, eq2 in zip(equations, equations[1:]): anims = [FadeTransformPieces(eq1.copy(), eq2)] if eq1 is equations[3]: anims.append(Write(dots)) self.play(*anims) self.wait(0.5) class MoreGeneralFact(InteractiveScene): dx = 0.025 def construct(self): # Equation inters = VGroup(*( get_multi_sinc_integral(range(1, n, 2), rhs=R"= \pi") for n in range(3, 11, 2) )) inters.scale(0.75) inters.to_edge(UP) # Graph axes = Axes((-4 * PI, 4 * PI, PI), (-0.5, 1, 0.5), width=FRAME_WIDTH + 1, height=4) axes.x_axis.add_numbers(unit=PI, unit_tex=R"\pi") axes.to_edge(DOWN) graphs = VGroup(*( axes.get_graph(lambda x, n=n: multi_sinc(x, n)) for n in range(1, 5) )) graphs.set_stroke(WHITE, 2) areas = VGroup(*( axes.get_riemann_rectangles( graph, colors=(BLUE_D, BLUE_D), dx=self.dx, fill_opacity=1, ) for graph in graphs )) for area in areas: area.sort(lambda p: abs(p[0])) self.add(areas[0], axes, graphs[0], inters[0]) for i in range(3): self.play( ReplacementTransform(areas[i], areas[i + 1]), TransformMatchingTex(inters[i], inters[i + 1]), ReplacementTransform(graphs[i], graphs[i + 1]), ) self.add(areas[i + 1], axes, graphs[i + 1], inters[i + 1]) self.wait() # Generalize inner_group = inters[-1][2:5] rect = SurroundingRectangle(inner_group, buff=SMALL_BUFF).set_stroke(YELLOW, 1) brace = Brace(rect) brace_text = brace.get_text("Nothing special", font_size=36) general_group = OldTex( R"\frac{\sin(a_1 x)}{a_1 x}", R"\cdots", R"\frac{\sin(a_n x)}{a_n x}", ) general_group.set_submobject_colors_by_gradient(TEAL, GREEN) general_group.match_height(inner_group) general_group.move_to(inner_group, LEFT) self.play( ShowCreation(rect), GrowFromCenter(brace), FadeIn(brace_text, 0.5 * DOWN), ) self.wait() self.play( FadeOut(inner_group, UP), FadeIn(general_group, UP), rect.animate.match_points(SurroundingRectangle(general_group, buff=SMALL_BUFF)), brace.animate.become(Brace(general_group, DOWN, buff=MED_SMALL_BUFF)), FadeOut(brace_text), inters[-1][5:].animate.next_to(general_group, RIGHT, SMALL_BUFF), ) self.wait() # Sum condition sum_tex = brace.get_tex(R"a_1 + \cdots + a_n < 1")[0] lt = OldTex("<") eq = inters[-1][-1][0] lt.move_to(eq) self.play(FadeIn(sum_tex, 0.5 * DOWN)) self.play(FlashAround(inters[-1][-1], run_time=2, time_width=1)) self.wait() self.play(Rotate(sum_tex[-2], PI)) self.play( FadeOut(eq, 0.5 * UP), FadeIn(lt, 0.5 * UP), ) self.wait() class WaysToCombineFunctions(InteractiveScene): def construct(self): # Axes axes1, axes2, axes3 = all_axes = VGroup(*( Axes((-5, 5), (0, 2), width=FRAME_WIDTH - 2, height=FRAME_HEIGHT / 3 - 1.0) for x in range(3) )) all_axes.arrange(DOWN, buff=1.0) self.add(all_axes) # Functions def f(x): return np.sin(x) + 1 def g(x): return np.exp(-x**2) f_graph = axes1.get_graph(f, color=BLUE) g_graph = axes2.get_graph(g, color=YELLOW) f_label = OldTex(R"f(x) = \sin(x) + 1", color=BLUE)[0] g_label = OldTex(R"g(x) = e^{-x^2}", color=YELLOW)[0] f_label.move_to(axes1.c2p(-1.5, 1.5)) g_label.move_to(axes2.c2p(-1.5, 1.5)) self.play( LaggedStart(FadeIn(f_graph), FadeIn(g_graph)), LaggedStart(FadeIn(f_label), FadeIn(g_label)), ) self.wait() # Combinations sum_graph = axes3.get_graph(lambda x: f(x) + g(x), color=GREEN) prod_graph = axes3.get_graph(lambda x: f(x) * g(x), color=GREEN) dx = 0.1 x_samples = np.arange(*axes1.x_range[:2], dx) conv_samples = np.convolve(f(x_samples), g(x_samples), mode="same") * dx * 0.5 conv_graph = VMobject().set_points_smoothly(axes3.c2p(x_samples, conv_samples)) conv_graph.match_style(prod_graph) graphs = (sum_graph, prod_graph, conv_graph) sum_label = OldTex("[f + g](x)") prod_label = OldTex(R"[f \cdot g](x)") conv_label = OldTex(R"[f * g](x)") labels = (sum_label, prod_label, conv_label) for label in labels: label.move_to(axes3.c2p(-1.5, 1.5)) words = VGroup(*map(Text, ["Addition", "Multiplication", "Convolution"])) for word, label in zip(words, labels): word.next_to(label, UP) for graph, label, word in zip(graphs, labels, words): self.play( Transform(f_graph.copy(), graph.copy(), remover=True), TransformFromCopy(g_graph, graph), TransformMatchingShapes(VGroup(*f_label[:4], *g_label[:4]).copy(), label), FadeIn(word) ) self.wait() self.play(*map(FadeOut, [graph, label, word])) class ReplaceXWithPiX(InteractiveScene): def construct(self): # Setup graphs axes = Axes((-int(8 * PI), int(8 * PI)), (-0.5, 1.0, 0.5), width=FRAME_WIDTH * PI + 1, height=4) axes.shift(DOWN) axes.x_axis.add_numbers(num_decimal_places=0, font_size=20) axes.y_axis.add_numbers(num_decimal_places=1, font_size=20) sinc_graph = axes.get_graph(sinc) sinc_graph.set_stroke(BLUE, 1) sinc_pi_graph = sinc_graph.copy().stretch(1 / PI, 0, about_point=axes.get_origin()) dx = 0.01 sinc_area = axes.get_riemann_rectangles( sinc_graph, dx=dx, colors=(BLUE_E, BLUE_E), negative_color=RED_E, fill_opacity=1.0, ) sinc_area.sort(lambda p: abs(p[0])) sinc_pi_area = sinc_area.copy().stretch(1 / PI, 0, about_point=axes.get_origin()) partial_area = sinc_area[:len(sinc_area) // 3] self.add(partial_area, axes, sinc_graph) # Setup labels sinc_label = Tex(R"\int_{-\infty}^\infty \frac{\sin(x)}{x} dx = \pi") sinc_label.next_to(axes, UP).to_edge(LEFT) kw = dict(tex_to_color_map={R"\pi": TEAL}) sinc_pi_label = Tex( R"\int_{-\infty}^\infty \frac{\sin(\pi x)}{\pi x} dx = 1.0", **kw ) sinc_pi_label.move_to(sinc_label).to_edge(RIGHT) eq_pi = sinc_label[-2:] eq_one = sinc_pi_label[-4:] pi_rect = SurroundingRectangle(eq_pi).set_stroke(BLUE, 2) one_rect = SurroundingRectangle(eq_one).set_stroke(BLUE, 2) want_to_show = Text("want to show", font_size=36) want_to_show.next_to(pi_rect, DOWN, aligned_edge=LEFT) want_to_show.set_color(BLUE) instead_of = Text("Instead of", color=YELLOW, font_size=60) instead_of.next_to(sinc_label, UP, buff=0.7, aligned_edge=LEFT) focus_on = Text("Focus on", color=YELLOW, font_size=60) focus_on.next_to(sinc_pi_label, UP, buff=0.7, aligned_edge=LEFT) self.add(instead_of, sinc_label) self.play(Write(partial_area, stroke_width=1.0)) self.add(sinc_area, axes, sinc_graph) self.wait() self.play( ShowCreation(pi_rect), FadeIn(want_to_show, 0.5 * DOWN) ) self.wait() # Squish x_to_pix = Tex(R"x \rightarrow \pi x", **kw) x_to_pix.match_y(instead_of) squish_arrows = VGroup(Vector(RIGHT), Vector(LEFT)) squish_arrows.arrange(RIGHT, buff=1.5) squish_arrows.move_to(axes.c2p(0, 0.5)) rect_kw = dict(buff=MED_SMALL_BUFF, stroke_width=1.5) rect = SurroundingRectangle(sinc_pi_label, **rect_kw) sinc_graph.save_state() sinc_area.save_state() self.play(LaggedStart( FadeIn(x_to_pix), TransformMatchingShapes(sinc_label.copy(), sinc_pi_label), FadeTransform(instead_of.copy(), focus_on) )) self.wait() self.play( Transform(sinc_graph, sinc_pi_graph), Transform(sinc_area, sinc_pi_area), FadeIn(squish_arrows, scale=0.35), run_time=2 ) self.wait() self.play(ShowCreation(one_rect)) self.wait() self.play(ShowCreation(rect)) self.wait() self.play( FadeOut(squish_arrows, scale=3), sinc_area.animate.restore(), sinc_graph.animate.restore(), rect.animate.become(SurroundingRectangle(VGroup(sinc_label, want_to_show), **rect_kw)), ) self.wait() class FourierWrapper(VideoWrapper): title = "Fourier Transforms" class FourierProblemSolvingSchematic(InteractiveScene): def construct(self): pass class WhatWeNeedToShow(InteractiveScene): def construct(self): # Title title = Text("What we must show", font_size=60) title.to_edge(UP, buff=MED_SMALL_BUFF) title.set_backstroke(width=5) underline = Line(LEFT, RIGHT) underline.set_width(6) underline.set_stroke(GREY_A, width=(0, 3, 3, 3, 3, 0)) underline.insert_n_curves(100) underline.next_to(title, DOWN, buff=0.05) self.add(underline, title) # Expressions t2c = { R"\mathcal{F}": TEAL, R"{t}": BLUE, R"{\omega}": YELLOW, R"{k}": RED, } kw = dict(tex_to_color_map=t2c, font_size=36) expressions = VGroup( Tex(R"\mathcal{F}\left[\frac{\sin(\pi {t})}{\pi {t}} \right]({\omega}) = \text{rect}({\omega})", **kw), Tex(R"\mathcal{F}\left[\frac{\sin(\pi {t} / {k})}{\pi {t} / {k}} \right]({\omega}) = {k} \cdot \text{rect}({k}{\omega})", **kw), Tex(R"\int_{-\infty}^\infty f({t}) dt = \mathcal{F}\left[ f({t}) \right](0)", **kw), Tex(R"\int_{-\infty}^\infty \frac{\sin(\pi {t})}{\pi {t}} dt = \text{rect}(0) = 1", **kw), Tex(R"\mathcal{F}\left[ f({t}) \cdot g({t}) \right] = \mathcal{F}[f({t})] * \mathcal{F}[g({t})]", **kw), Tex( R"""\mathcal{F}\left[ \frac{\sin(\pi {t})}{\pi {t}} \cdot \frac{\sin(\pi {t} / 3)}{\pi {t} / 3} \right] = \big[ \text{rect} * \text{rect}_3 \big]""", **kw ), ) expressions.set_stroke(width=0) key_facts = expressions[0::2] examples = expressions[1::2] key_facts.arrange(DOWN, buff=1.5, aligned_edge=LEFT) key_facts.next_to(underline, DOWN, MED_LARGE_BUFF).to_edge(LEFT) for fact, example in zip(key_facts, examples): example.next_to(fact, RIGHT, buff=2.0) ft_sinc, int_to_eval, conv_theorem = key_facts ft_sinck, sinc_int_to_rect_0, conv_theorem_ex = examples # FT of sinc ft_sinc.next_to(underline, DOWN, MED_LARGE_BUFF) width = FRAME_WIDTH / 2 - 1 axes1 = Axes((-4, 4), (-1, 1), width=width, height=3) axes2 = Axes((-1, 1, 0.25), (0, 2), width=width, height=1.5) axes1.to_corner(DL) axes2.shift(axes1.get_origin() - axes2.get_origin()) axes2.to_edge(RIGHT) axes1.add(OldTex("t", color=BLUE, font_size=24).next_to(axes1.x_axis.get_right(), UP, 0.2)) axes2.add(OldTex(R"\omega", color=YELLOW, font_size=24).next_to(axes2.x_axis.get_right(), UP, 0.2)) axes1.add_coordinate_labels(font_size=20) axes2.add_coordinate_labels(x_values=np.arange(-1, 1.5, 0.5), font_size=20, num_decimal_places=1) k_tracker = ValueTracker(1) get_k = k_tracker.get_value globals().update(locals()) graph1 = axes1.get_graph(lambda x: 0, color=BLUE) axes1.bind_graph_to_func(graph1, lambda x: np.sinc(x / get_k())) graph2 = VMobject().set_stroke(YELLOW, 3) def update_graph2(graph): k = get_k() graph.set_points_as_corners([ axes2.c2p(-1, 0), axes2.c2p(-0.5 / k, 0), axes2.c2p(-0.5 / k, k), axes2.c2p(0.5 / k, k), axes2.c2p(0.5 / k, 0), axes2.c2p(1, 0), ]) return graph graph2.add_updater(update_graph2) graph1_label = Tex(R"{\sin(\pi {t}) \over \pi {t} }", **kw) graph2_label = Tex(R"\text{rect}({\omega})", **kw) graph1_label.move_to(axes1.c2p(-2, 1)) graph2_label.move_to(axes2.c2p(0.5, 2)) arrow = Arrow(axes1.c2p(2, 0.5), axes2.c2p(-0.5, 1), path_arc=-PI / 3) arrow.set_color(TEAL) arrow_copy = arrow.copy() arrow_copy.rotate(PI, about_point=midpoint(axes1.c2p(4, 0), axes2.c2p(-1, 0))) arrow_label = Tex(R"\mathcal{F}", color=TEAL) arrow_label.next_to(arrow, UP, SMALL_BUFF) arrow_label_copy = arrow_label.copy() arrow_label_copy.next_to(arrow_copy.pfp(0.5), UP) self.play( FadeIn(axes1), ShowCreation(graph1), FadeIn(graph1_label, UP) ) self.wait() self.play( ShowCreation(arrow), FadeIn(arrow_label, RIGHT + 0.2 * UP), FadeIn(axes2), ) self.play( Write(graph2_label), ShowCreation(graph2) ) self.wait() self.play( TransformFromCopy(arrow, arrow_copy, path_arc=PI / 2), TransformFromCopy(arrow_label, arrow_label_copy, path_arc=PI / 2), ) self.wait() self.play(LaggedStart( FadeTransform(arrow_label.copy(), ft_sinc[0]), FadeTransform(graph1_label.copy(), ft_sinc[2:12]), Write(VGroup(ft_sinc[1], ft_sinc[12])), )) self.wait() self.play(Write(ft_sinc[13:17])) self.play( FadeTransform(graph2_label.copy(), ft_sinc[17:]) ) self.add(ft_sinc) self.wait() # Generalize graph1_gen_label = Tex(R"{\sin(\pi {t} / {k}) \over \pi {t} / {k} }", **kw) graph2_gen_label = Tex(R"{k} \cdot \text{rect}({k} {\omega})", **kw) graph1_gen_label.move_to(graph1_label) graph2_gen_label.move_to(graph2_label) ft_sinck.move_to(ft_sinc) self.play(LaggedStart( FadeOut(graph1_label, UP), FadeIn(graph1_gen_label, UP), FadeOut(graph2_label, UP), FadeIn(graph2_gen_label, UP), )) self.play( FadeOut(ft_sinc, UP), FadeIn(ft_sinck, UP) ) self.wait() self.play(k_tracker.animate.set_value(3), run_time=3) self.wait() self.play(k_tracker.animate.set_value(1), run_time=3) self.wait() self.play(ft_sinck.animate.set_height(0.5).to_corner(UL)) self.wait() # Area to evaluate k_tracker.set_value(1) int_to_eval.next_to(underline, DOWN, MED_LARGE_BUFF) sinc_int_to_rect_0.move_to(int_to_eval) area = axes1.get_riemann_rectangles( axes1.get_graph(np.sinc), colors=(BLUE, BLUE), dx=0.01 ) area.set_stroke(WHITE, 0) x0 = axes1.get_origin()[0] area.sort(lambda p, x0=x0: abs(p[0] - x0)) dot = GlowDot(color=BLUE) dot.set_glow_factor(0.5) dot.set_radius(0.1) dot.move_to(int_to_eval[11:].get_center()) self.play(FadeIn(int_to_eval, DOWN)) self.play(FlashAround(int_to_eval[:10], run_time=2, time_width=1.5)) self.play(Write(area)) self.wait() self.play(FlashAround(int_to_eval[11:], run_time=2, time_width=1.5)) self.play(dot.animate.move_to(axes2.c2p(0, 1)), run_time=1.5) self.wait() self.play( int_to_eval.animate.set_height(0.5).next_to(ft_sinck, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) ) self.play(FadeIn(sinc_int_to_rect_0, RIGHT)) self.wait() self.play(FadeOut(sinc_int_to_rect_0)) # Many dots dx = 0.1 dots = Group(*( GlowDot( axes2.c2p(x, rect_func(x)), color=TEAL ) for x in np.arange(-1, 1 + dx, dx) )) thick_graph = VGroup( axes1.get_graph(np.sinc, x_range=(-1, 4)), axes1.get_graph(np.sinc, x_range=(-4, 1)).reverse_points(), ) thick_graph.set_stroke(YELLOW, 6) self.play(FadeIn(dots, DOWN, lag_ratio=0.5, run_time=5)) self.wait() self.play( VShowPassingFlash(thick_graph[0], run_time=4, time_width=1), VShowPassingFlash(thick_graph[1], run_time=4, time_width=1), FadeOut(area) ) self.wait() self.play(FadeOut(dots)) # Convolution fact conv_theorem.set_height(0.45) conv_theorem.next_to(underline, DOWN, MED_LARGE_BUFF) conv_theorem_ex.next_to(underline, DOWN, MED_LARGE_BUFF) conv_theorem_name = OldTexText("``Convolution theorem''", font_size=60) conv_theorem_name.next_to(conv_theorem, DOWN, buff=MED_LARGE_BUFF) conv_theorem_name.set_color(YELLOW) self.play(FadeIn(conv_theorem, DOWN)) self.wait() self.play( FadeIn(conv_theorem_ex, DOWN), FadeOut(conv_theorem, DOWN), ) self.wait() self.play( FadeOut(conv_theorem_ex, UP), FadeIn(conv_theorem, UP), ) self.play(Write(conv_theorem_name)) # Reorganize facts = VGroup(ft_sinck, int_to_eval, conv_theorem) facts.generate_target() facts.target[:2].scale(1.7) facts.target.scale(0.8) facts.target.arrange(DOWN, buff=MED_LARGE_BUFF, aligned_edge=LEFT) facts.target.next_to(ORIGIN, RIGHT).to_edge(UP, buff=MED_SMALL_BUFF) bullets = VGroup(*( Dot().next_to(fact, LEFT) for fact in facts.target )) self.play( MoveToTarget(facts), title.animate.next_to(facts.target, LEFT, LARGE_BUFF), Uncreate(underline), FadeOut(conv_theorem_name), Write(bullets) ) self.wait() class ConvolutionTheoremDiagram(InteractiveScene): def construct(self): # Axes width = FRAME_WIDTH / 2 - 1 height = 1.5 left_axes = VGroup(*( Axes((-4, 4), (-0.5, 1, 0.5), width=width, height=height) for x in range(3) )) right_axes = VGroup(*( Axes((-1, 1, 0.5), (0, 1), width=width, height=2 * height / 3) for x in range(3) )) left_axes.arrange(DOWN, buff=1.0) left_axes[-1].to_edge(DOWN, buff=MED_SMALL_BUFF) left_axes.set_x(-FRAME_WIDTH / 4) for a1, a2 in zip(left_axes, right_axes): a2.shift(a1.get_origin() - a2.get_origin()) right_axes.set_x(FRAME_WIDTH / 4) # Graphs left_graphs = VGroup( left_axes[0].get_graph(np.sinc, color=BLUE), left_axes[1].get_graph(lambda x: np.sinc(x / 2), color=YELLOW), left_axes[2].get_graph(lambda x: np.sinc(x) * np.sinc(x / 2), color=GREEN), ) left_graphs.set_stroke(width=2) right_graphs = VGroup( VMobject().set_points_as_corners([ right_axes[0].c2p(x, y) for x, y in [ (-1, 0), (-0.5, 0), (-0.5, 1), (0.5, 1), (0.5, 0), (1, 0), ] ]).set_stroke(BLUE, 2), VMobject().set_points_as_corners([ right_axes[1].c2p(x, y) for x, y in [ (-1, 0), (-0.5 / 2, 0), (-0.5 / 2, 2), (0.5 / 2, 2), (0.5 / 2, 0), (1, 0), ] ]).set_stroke(YELLOW, 2), VMobject().set_points_as_corners([ right_axes[2].c2p(x, y) for x, y in [ (-1, 0), (-0.75, 0), (-0.25, 1), (0.25, 1), (0.75, 0), (1, 0), ] ]).set_stroke(GREEN, 2), ) left_plots = VGroup(*(VGroup(axes, graph) for axes, graph in zip(left_axes, left_graphs))) right_plots = VGroup(*(VGroup(axes, graph) for axes, graph in zip(right_axes, right_graphs))) # Labels left_labels = VGroup( OldTex(R"\frac{\sin(\pi x)}{\pi x}")[0], OldTex(R"\frac{\sin(\pi x / 2)}{\pi x / 2}")[0], OldTex(R"\frac{\sin(\pi x)}{\pi x} \cdot \frac{\sin(\pi x / 2)}{\pi x / 2}")[0], ) right_labels = VGroup(*( OldTex( Rf"\mathcal{{F}}\left[{ll.get_tex()}\right]", tex_to_color_map={R"\mathcal{F}": TEAL} ) for ll in left_labels )) VGroup(left_labels, right_labels).scale(0.5) for label_group, axes_group, x in (left_labels, left_axes, -2), (right_labels, right_axes, -0.85): for label, axes in zip(label_group, axes_group): label.move_to(axes.c2p(x, 1)) VGroup(left_labels[2], right_labels[2]).shift(0.5 * UP) ft_arrows = VGroup(*( Arrow(l1.get_right(), l2.get_left(), buff=0.2, path_arc=arc, color=TEAL, stroke_width=3) for l1, l2, arc in zip(left_labels, right_labels, (-0.3, -0.75, -1.0)) )) # Left animations self.play( LaggedStartMap(FadeIn, left_plots[:2], lag_ratio=0.5), LaggedStartMap(FadeIn, left_labels[:2], lag_ratio=0.5), run_time=1 ) self.wait() self.play( Transform(left_plots[0].copy(), left_plots[2].copy(), remover=True), TransformFromCopy(left_plots[1], left_plots[2], remover=True), FadeTransform(left_labels[0].copy(), left_labels[2][:len(left_labels[0])]), FadeTransform(left_labels[1].copy(), left_labels[2][len(left_labels[0]):]), ) self.add(left_plots[2]) self.wait() self.play( ShowCreation(ft_arrows[2]), FadeTransform(left_labels[2].copy(), right_labels[2]), FadeIn(right_plots[2]), ) self.wait() # Right animations for i in range(2): self.play( ShowCreation(ft_arrows[i]), FadeTransform(left_labels[i].copy(), right_labels[i]), FadeIn(right_plots[i]), ) self.wait() right_labels[2].generate_target() equation = VGroup( right_labels[2].target, OldTex("=").scale(0.75), right_labels[0].copy(), OldTex("*").scale(0.75), right_labels[1].copy(), ) equation.arrange(RIGHT, buff=SMALL_BUFF) equation.next_to(right_axes[2], UP, SMALL_BUFF) self.play(LaggedStart( ft_arrows[2].animate.put_start_and_end_on( ft_arrows[2].get_start(), right_labels[2].target.get_left() + SMALL_BUFF * UL, ), MoveToTarget(right_labels[2]), Write(equation[1]), FadeTransform(right_labels[0].copy(), equation[2]), Write(equation[3]), FadeTransform(right_labels[1].copy(), equation[4]), run_time=2 )) # Show convolution x_unit = right_axes[1].x_axis.unit_size y_unit = right_axes[1].y_axis.unit_size rect = Rectangle(width=x_unit / 2, height=2 * y_unit) rect.set_stroke(YELLOW, 1) rect.set_fill(YELLOW, 0) rect.move_to(right_axes[1].get_origin(), DOWN) dot = GlowDot(color=GREEN) dot.move_to(right_graphs[2].get_start()) self.add(rect, right_plots) self.play( rect.animate.move_to(right_axes[0].c2p(-1, 0), DOWN).set_fill(opacity=0.5), FadeIn(dot), ) self.play( MoveAlongPath(dot, right_graphs[2]), UpdateFromFunc(rect, lambda m: m.match_x(dot)), run_time=8, ) self.play(FadeOut(rect), FadeOut(dot)) # Show signed area area = left_axes[2].get_riemann_rectangles( left_graphs[2], dx=0.01, colors=(BLUE_D, BLUE_D), fill_opacity=1.0, ) o = area.get_center() area.sort(lambda p: abs(p[0] - o[0])) self.add(area, left_axes[2], left_graphs[2]) self.play(Write(area, stroke_width=1, run_time=2)) self.wait() rect.set_fill(opacity=0.2) rect.set_stroke(width=0) self.play( MoveAlongPath(dot, right_graphs[2], rate_func=lambda t: smooth(1 - 0.5 * t)), MoveAlongPath(dot.copy(), right_graphs[2], rate_func=lambda t: smooth(0.5 * t)), # UpdateFromFunc(rect, lambda m: m.match_x(dot)), run_time=1, ) self.play(FlashAround(dot, buff=0, run_time=2, time_width=1)) self.wait() class MultiplyBigNumbers(InteractiveScene): def construct(self): # Numbers numbers = VGroup( Tex("3{,}141{,}592{,}653{,}589{,}793{,}238"), Tex("2{,}718{,}281{,}828{,}459{,}045{,}235"), ) numbers.arrange(DOWN, aligned_edge=RIGHT) numbers.scale(1.5) numbers.move_to(1.0 * DOWN) underline = Underline(numbers).set_stroke(WHITE, 2) underline.stretch(1.2, 0, about_edge=RIGHT) times = OldTex(R"\times") times.scale(1.5) times.next_to(underline.get_left(), UR) self.add(numbers) self.add(underline, times) # Prep run time d_label = OldTexText("Two $N$-digit numbers", tex_to_color_map={"$N$": YELLOW}) d_label.next_to(numbers, UP, buff=LARGE_BUFF) d2_label = OldTex(R"\mathcal{O}(N^2)", font_size=60, tex_to_color_map={"N": YELLOW}) dlogd_label = OldTex(R"\mathcal{O}({N} \cdot \text{log}({N}))", font_size=60, tex_to_color_map={"{N}": YELLOW}) os = VGroup(d2_label, dlogd_label) os.arrange(RIGHT, buff=2.5) os.next_to(d_label, UP, buff=LARGE_BUFF) # cross = Exmark().scale(2).next_to(d2_label, RIGHT) cross = Cross(d2_label) cross.insert_n_curves(50).set_stroke(RED, (0, 8, 8, 8, 8, 0)) check = Checkmark().scale(2).next_to(dlogd_label, RIGHT) q_marks = OldTex("?", font_size=72) q_marks.next_to(d2_label, RIGHT) # Square run time for num in numbers: num.digits = num[::-1] num.digits.remove(*num[-4::-4]) num.digit_highlights = VGroup(*( VHighlight(digit, color_bounds=(YELLOW, YELLOW_E), max_stroke_addition=8) for digit in num.digits )) self.add(d_label) self.play(FadeIn(d2_label, UP), FadeIn(q_marks, UP)) for dh2 in numbers[1].digit_highlights: self.add(dh2, numbers[1]) self.play( ShowSubmobjectsOneByOne( numbers[0].digit_highlights.copy(), remover=True ), run_time=1.0 ) self.remove(dh2) # d * log(d) self.play( ShowCreation(cross), FadeOut(q_marks), FadeTransform(d2_label.copy(), dlogd_label) ) self.play(Write(check)) self.wait() class Graph15Case(ShowIntegrals): def construct(self): # Test axes = self.get_axes( x_range=(-3 * PI, 3 * PI, PI), y_range=(0, 1), width=1.0 * FRAME_WIDTH, ) graph = axes.get_graph(lambda x: multi_sinc(x, 8)) graph.set_stroke(width=1) area = self.get_area(axes, graph, dx=0.005 * PI) area.set_fill(opacity=0.9) self.add(axes, area, graph)
from manim_imports_ext import * from _2022.convolutions.discrete import * class HoldUpLists(TeacherStudentsScene): def construct(self): self.remove(self.background) self.play( self.teacher.change("raise_right_hand", look_at=self.screen), self.change_students("pondering", "thinking", "pondering", look_at=self.screen), ) self.wait() self.play( self.change_students("thinking", "thinking", "pondering", look_at=3 * UR), self.teacher.change("raise_left_hand", look_at=3 * UR) ) self.wait(2) self.play(LaggedStartMap(FadeOut, self.pi_creatures, shift=2 * DOWN)) class FunToVisualize(TeacherStudentsScene): def construct(self): # Test self.play( self.teacher.says("Boy are they fun\nto visualize!", mode="hooray"), self.change_students("tease", "happy", "well") ) self.wait(3) class ILearnedSomething(TeacherStudentsScene): def construct(self): # Test implication = VGroup( Text("Making\nvisuals"), OldTex(R"\Rightarrow", font_size=60), Text("Deeper\nunderstanding") ) implication.arrange(RIGHT, buff=0.4) implication.move_to(self.hold_up_spot, DOWN) implication.shift_onto_screen() self.play( self.teacher.change("raise_right_hand", implication), FadeIn(implication, UP), self.change_students("confused", "hesitant", "tease", look_at=implication) ) self.wait(5) class NormalFunctionPreview(InteractiveScene): def construct(self): # Setup axes frame = self.camera.frame axes2d = Axes((-2, 2), (-1, 2), width=10, height=6) axes3d = ThreeDAxes((-2, 2), (-2, 2), (-1, 2), width=10, height=10, depth=6) axes3d.shift(axes2d.get_origin() - axes3d.get_origin()) curve = axes2d.get_graph(lambda x: math.exp(-x**2)) curve.set_stroke(BLUE) label = OldTex("e^{-x^2}", font_size=60) label.next_to(curve.get_top(), UR).shift(RIGHT) label3d = OldTex("e^{-x^2 - y^2}", font_size=60) label3d.move_to(label, DL) VGroup(axes2d, curve, label, label3d).rotate(PI / 2, RIGHT, about_point=axes3d.get_origin()) frame.reorient(0, 90) self.add(axes2d) self.play(ShowCreation(curve), Write(label)) # Show in 3d surface = axes3d.get_graph(lambda x, y: math.exp(-x * x - y * y)) surface.always_sort_to_camera(self.camera) surface_mesh = SurfaceMesh(surface) surface_mesh.set_stroke(WHITE, 0.5, 0.5) self.add(axes3d, surface, curve) self.play( FadeIn(axes3d), frame.animate.reorient(-10, 70).set_anim_args(run_time=2), FadeIn(surface, time_span=(1, 2)), FadeIn(label3d), FadeOut(label), Rotate(curve, PI, run_time=3) ) frame.add_updater(lambda m, dt: m.increment_theta(0.02 * dt)) self.play(Write(surface_mesh)) self.wait(8) class JuliaVideoFrame(VideoWrapper): title = "Lecture on convolutions for image processing" class Intimidation(InteractiveScene): def construct(self): pis = VGroup(*(Randolph(color=color) for color in (BLUE_C, BLUE_E, BLUE_D))) pis.arrange(DOWN, buff=LARGE_BUFF) pis.set_height(FRAME_HEIGHT - 1) pis.move_to(FRAME_WIDTH * LEFT / 4) self.play(LaggedStart(*( pi.change("pondering", look_at=3 * UR) for pi in pis ))) self.play(LaggedStart(*(Blink(pi) for pi in pis))) self.wait() self.play(LaggedStart(*( pi.change(mode, look_at=3 * UR) for pi, mode in zip(pis, ("horrified", "maybe", "pleading")) ))) for x in range(2): self.play(Blink(random.choice(pis))) self.wait() class SideBySideForContinuousConv(InteractiveScene): def construct(self): self.add(FullScreenRectangle()) squares = Square().replicate(2) squares.set_fill(BLACK, 1) squares.set_stroke(WHITE, 2) squares.set_height(6) squares.arrange(RIGHT, buff=0.5) squares.set_width(FRAME_WIDTH - 1) squares.to_edge(DOWN) self.add(squares) class ThereIsAnother(TeacherStudentsScene): def construct(self): self.play( self.teacher.says("There is another"), self.change_students("pondering", "thinking", "erm", look_at=self.screen) ) self.wait(2) class SharedInsights(InteractiveScene): def construct(self): # Rects rects = ScreenRectangle().get_grid(2, 2, h_buff=2.0, v_buff=2.0) rects.set_width(FRAME_WIDTH - 3) rects.set_stroke(WHITE, 2) rects.set_fill(BLACK, 1) self.add(FullScreenRectangle()) self.add(rects) # Inter-relate kw = dict(stroke_width=5, stroke_color=YELLOW) arrows = VGroup( Arrow(rects[3].get_top(), rects[1].get_bottom(), **kw), Arrow(rects[3].get_corner(UL), rects[0].get_corner(DR), **kw), Arrow(rects[3].get_left(), rects[2].get_right(), **kw), ) self.wait() self.play(LaggedStartMap(GrowArrow, arrows, lag_ratio=0.5)) self.wait() class HoldUpImageProcessing(TeacherStudentsScene): def construct(self): self.play( self.teacher.change("raise_right_hand"), self.change_students("pleading", "hesitant", "horrified", look_at=2 * UP) ) self.wait(2) self.play(self.change_students("pondering", "thinking", "pondering", look_at=2 * UP)) self.wait(6) class OtherVisualizations(TeacherStudentsScene): def construct(self): self.play(self.change_students("happy", "thinking", "tease", look_at=self.screen)) self.play( self.teacher.says("Can you think of\nother visualizations?"), self.change_students("pondering", "pondering", "pondering", look_at=self.screen), ) self.wait(2) self.play( self.change_students("confused", "erm", "thinking") ) self.wait(4) self.play( self.students[2].change("raise_right_hand", self.teacher.eyes), self.teacher.change("tease"), ) self.wait(2) class Boring(TeacherStudentsScene): def construct(self): # Test self.play(LaggedStart( self.students[2].says("Boring!", mode="dejected", look_at=self.teacher.eyes, bubble_direction=LEFT), self.teacher.change("hesitant"), self.students[0].change("hesitant", self.screen), self.students[1].change("guilty", self.screen), lag_ratio=0.25, )) self.wait(3) class AskForExample(TeacherStudentsScene): def construct(self): self.play( self.teacher.change("raise_right_hand", self.screen), self.change_students("pondering", "thinking", "confused", look_at=self.screen) ) self.wait(3) self.play( self.students[2].says("Can we go do\na concrete example?", mode="raise_left_hand", bubble_direction=LEFT) ) self.wait(3) class MarioConvolutionLabel(BoxBlurMario): label_conv = True def construct(self): self.clear() pa = self.pixel_array ka = self.kernel_array ka.clear_updaters() pa.set_stroke(width=0.1) expr = VGroup(pa, OldTex("*", font_size=72), ka) for arr in expr[::2]: arr.set_height(1.5) expr.arrange(RIGHT) expr.move_to(FRAME_WIDTH * RIGHT / 4).to_edge(UP, buff=0.9) conv_label = Text("Convolution", font_size=36) conv_label.next_to(expr, UP, buff=0.5) arrow = Arrow(conv_label, expr[1], buff=0.2) self.play(FadeIn(expr, lag_ratio=0.001)) if self.label_conv: self.play( Write(conv_label), ShowCreation(arrow), ) self.wait() kw = dict(rate_func=smooth, run_time=1) self.play(Rotate(ka, PI, **kw)) squares = ka.copy() for square in squares: square.remove(square[0]) self.add(squares) self.remove(ka) self.play(LaggedStart(*( Rotate(square[0], -PI, **kw) for square in ka ))) self.wait(2) class CatConvolutionLabel(MarioConvolutionLabel, GaussianBluMario): image_name = "PixelArtCat" kernel_tex = None def construct(self): MarioConvolutionLabel.construct(self) class SobelKernelLabel(MarioConvolutionLabel, SobelFilter2): image_name = "BitRandy" kernel_tex = None def construct(self): for square in self.kernel_array: square.set_stroke(WHITE, 1) value = square[0].get_value() square.set_fill(rgb_to_color([ max(-value, 0), max(value, 0), max(value, 0) ]), 1) square[0].set_stroke(width=0) square[0].set_fill(WHITE, 1) MarioConvolutionLabel.construct(self) class SharpenKernelLabel(MarioConvolutionLabel, SharpenFilter): image_name = "KirbySmall" kernel_tex = None label_conv = False def construct(self): for square in self.kernel_array: square[0].scale(0.6) MarioConvolutionLabel.construct(self) class SobelCatKernelLabel(SobelKernelLabel, SobelFilter1): image_name = "PixelArtCat" kernel_tex = None label_conv = False grayscale = False def get_kernel(self): return SobelFilter1.get_kernel(self) class MakeAPrediction(TeacherStudentsScene): def construct(self): # Blah self.teacher_says("Try thinking\nthrough what\nwill happen") self.play(self.change_students("pondering", "confused", "thinking", look_at=self.screen)) self.wait() self.play(self.teacher.change("tease")) self.wait(4) class ThinkDifferently(TeacherStudentsScene): def construct(self): self.play( self.teacher.change("raise_right_hand"), self.change_students("pondering", "confused", "thinking", look_at=self.screen), ) self.wait() self.play(self.teacher.change("tease")) self.play(self.change_students("thinking", "pondering", "tease", look_at=self.screen)) self.wait(4) class ThisIsTheCoolPart(TeacherStudentsScene): def construct(self): # Blah self.play( self.teacher.says("Now for the\ncool part!", mode="hooray"), self.change_students("happy", "tease", "well") ) self.wait(2) self.play( self.change_students("thinking", "thinking", "happy", look_at=self.screen), self.teacher.change("tease") ) self.wait(3) class MentionONSquared(InteractiveScene): def construct(self): # Blah morty = Mortimer(height=2) kw = dict(tex_to_color_map={"{N}": YELLOW}) bigO = Tex(R"\mathcal{O}({N}^2)", **kw) explanation = VGroup( Text("# Operations"), OldTex("=").rotate(PI / 2), OldTex( R"\text{const}", R"\cdot {N}^2 +", R"\left(\substack{\text{stuff asymptotically} \\ \text{smaller than $N^2$}}\right)", **kw ), ) explanation[2][0].set_color(GREY_B) explanation[2][-1].scale(0.6, about_edge=LEFT) explanation.arrange(DOWN) explanation.next_to(morty, UR, SMALL_BUFF) self.play(morty.says(bigO)) self.play(Blink(morty)) self.play( FadeIn(explanation, 0.5 * UP), morty.change("raise_left_hand", look_at=explanation) ) for x in range(2): self.play(Blink(morty)) self.wait(2) class MentionLinearSystem(InteractiveScene): def construct(self): # Blah morty = Mortimer(height=3).flip().to_edge(DOWN) self.play(morty.says("And it's\nlinear!", mode="hooray")) self.play(Blink(morty)) self.play(morty.change("tease")) for x in range(2): self.play(Blink(morty)) self.wait(2) class DumbIdea(TeacherStudentsScene): def construct(self): # Bad idea morty = self.teacher stds = self.students self.play( morty.change("happy", look_at=self.screen), self.change_students("pondering", "pondering", "frustrated", look_at=self.screen) ) self.wait() self.student_says("Uh...", target_mode="hesitant", bubble_direction=LEFT, index=2) self.play(Blink(stds[2])) self.student_says( "That's idiotic!", target_mode="angry", index=2, added_anims=[morty.change("guilty"), stds[1].change("erm")] ) self.wait(2) # Samples self.student_says( OldTexText(R"Calculating the samples\\is already $\mathcal{O}(N^2)$"), target_mode="concentrating", look_at=self.screen, added_anims=[stds[0].change("erm"), stds[1].change("hesitant")] ) self.wait(5) self.student_says( "And so is solving\nthe linear system!", target_mode="surprised", look_at=morty.eyes, added_anims=[morty.change("tease"), stds[0].change("sassy"), stds[1].change("hesitant")] ) self.wait() self.play(stds[2].change("angry")) self.wait(4) # Hold up new screen new_point = 3 * UR self.play( stds[2].debubble(mode="raise_right_hand", look_at=new_point), stds[0].change("pondering", look_at=new_point), stds[1].change("pondering", look_at=new_point), ) self.wait(3) self.play(self.change_students("erm", "hesitant", "angry")) self.wait(3) # There's a trick self.play( morty.says("But there's\na trick"), self.change_students("tease", "happy", "hesitant") ) self.wait(2) fft = Text("FFT") fft.next_to(stds[0].get_corner(UR), UP) self.play( stds[0].change("raise_right_hand"), FadeIn(fft, UP), morty.change("tease", fft), *(pi.animate.look_at(fft) for pi in self.students[1:]), ) self.wait() self.student_says( "What...is that?", target_mode="dance_3", index=1, ) self.play(morty.change("happy")) self.wait(2) self.play(stds[0].change("tease")) self.play(stds[1].change("maybe", stds[0].eyes)) self.wait(2) self.play(morty.change("well")) self.wait(3) class UhWhy(InteractiveScene): def construct(self): randy = Randolph(height=3) randy.to_corner() point = LEFT_SIDE + 2 * UR self.play(randy.says("Uh...friendlier?", mode="sassy")) self.play(Blink(randy)) self.wait() self.play(randy.change("erm", look_at=point)) self.play(Blink(randy)) self.wait() self.play(randy.debubble(mode="pondering", look_at=point)) for x in range(3): self.play(Blink(randy)) self.wait(2) class GenericScreen(VideoWrapper): pass class EnthusiasticAboutRunTime(TeacherStudentsScene): def construct(self): run_time = OldTex(R"\mathcal{O}\big(N \log(N)\big)") run_time.move_to(self.hold_up_spot, DOWN) self.play( self.teacher.change("raise_right_hand"), FadeIn(run_time, UP), self.change_students("thinking", "tease", "happy", look_at=run_time), ) self.wait(2) self.play( self.teacher.says("That feels\nlike magic!", mode="hooray"), run_time.animate.to_edge(UP), self.change_students("tease", "happy", "tease") ) self.wait(3)
from __future__ import annotations from manim_imports_ext import * from _2022.borwein.main import * import scipy.signal def get_die_faces(**kwargs): result = VGroup(*(DieFace(n, **kwargs) for n in range(1, 7))) result.arrange(RIGHT, buff=MED_LARGE_BUFF) return result def get_aligned_pairs(group1, group2, n): return VGroup(*( VGroup(m1, m2) for m1 in group1 for m2 in group2 if m1.index + m2.index == n )) def get_pair_rects(pairs, together=True, buff=SMALL_BUFF, corner_radius=0.1): if together: return VGroup(*( SurroundingRectangle(pair, buff=buff).round_corners(corner_radius) for pair in pairs )) else: return VGroup(*( VGroup(*( SurroundingRectangle(m, buff=buff).round_corners(corner_radius) for m in pair )) for pair in pairs )) def get_row_shift(top_row, low_row, n): min_index = low_row[0].index max_index = top_row[-1].index max_sum = min_index + max_index if n <= max_sum: x_shift = top_row[n - 2 * min_index].get_x() - low_row[0].get_x() else: x_shift = top_row[-1].get_x() - low_row[n - max_sum].get_x() return low_row.animate.shift(x_shift * RIGHT) def dist_to_bars(dist, bar_width=0.5, height=2.0, bar_colors=(BLUE_D, GREEN_D)): bars = Rectangle(width=bar_width).get_grid(1, len(dist), buff=0) bars.set_color_by_gradient(*bar_colors) bars.set_fill(opacity=1) bars.set_stroke(WHITE, 1) for bar, value, index in zip(bars, dist, it.count()): bar.set_height(value, stretch=True, about_edge=DOWN) bar.index = index bars.set_height(height, stretch=True) bars.center() return bars def get_bar_dividing_lines(bars): v_lines = VGroup() for bar in bars: v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line.set_stroke(GREY_C, 1, 0.75) v_line.set_x(bar.get_left()[0]) v_line.set_y(0) v_lines.add(v_line) v_lines.add(v_lines[-1].copy().set_x(bars.get_right()[0])) return v_lines def add_labels_to_bars(bars, dist, width_ratio=0.7, **number_config): labels = VGroup(*(DecimalNumber(x, **number_config) for x in dist)) labels.set_max_width(width_ratio * bars[0].get_width()) for label, bar in zip(labels, bars): label.next_to(bar, UP, SMALL_BUFF) bar.value_label = label bar.push_self_into_submobjects() bar.add(label) return bars def prod(values): return reduce(op.mul, values, 1) def get_lagrange_polynomial(data): def poly(x): return sum( y0 * prod( (x - x1) for x1, y1 in data if x1 != x0 ) / prod( (x0 - x1) for x1, y1 in data if x1 != x0 ) for x0, y0 in data ) return poly def kinked_function(x): if x < -2: return 0 elif x < -1: return -x - 2 elif x < 1: return x elif x < 2: return -x + 2 else: return 0 # Introduction class WaysToCombine(InteractiveScene): def construct(self): # Functions v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line.set_stroke(WHITE, 2) axes1, axes2, axes3 = all_axes = VGroup(*( Axes((-3, 3), (-1, 1), height=2.0, width=FRAME_WIDTH * 0.5 - 1) for x in range(3) )) all_axes.arrange(DOWN, buff=LARGE_BUFF) all_axes.set_height(FRAME_HEIGHT - 1) all_axes.move_to(midpoint(ORIGIN, RIGHT_SIDE)) def f(x): return kinked_function(x) def g(x): return np.exp(-0.5 * x**2) f_graph = axes1.get_graph(f).set_stroke(BLUE, 2) g_graph = axes2.get_graph(g).set_stroke(YELLOW, 2) sum_graph = axes3.get_graph(lambda x: f(x) + g(x)).set_stroke(TEAL, 2) prod_graph = axes3.get_graph(lambda x: f(x) * g(x)).set_stroke(TEAL, 2) x_samples = np.linspace(*axes1.x_range[:2], 100) f_samples = list(map(f, x_samples)) g_samples = list(map(g, x_samples)) conv_samples = np.convolve(f_samples, g_samples, mode='same') conv_samples *= 0.1 # Artificially scale down conv_points = axes3.c2p(x_samples, conv_samples) conv_graph = VMobject().set_points_smoothly(conv_points) conv_graph.set_stroke(TEAL, 2) kw = dict(font_size=30, tex_to_color_map={"f": BLUE, "g": YELLOW}) f_label = Tex("f(x)", **kw).move_to(axes1.get_corner(UL), UL) g_label = Tex("g(x)", **kw).move_to(axes2.get_corner(UL), UL) sum_label = Tex("[f + g](x)", **kw).move_to(axes3.get_corner(UL), UL) prod_label = Tex(R"[f \cdot g](x)", **kw).move_to(axes3.get_corner(UL), UL) conv_label = Tex(R"[f * g](x)", **kw).move_to(axes3.get_corner(UL), UL) graph_labels = VGroup(f_label, g_label, sum_label, prod_label, conv_label) # Sequences seq1 = np.array([1, 2, 3, 4]) seq2 = np.array([5, 6, 7, 8]) kw = dict( font_size=48, tex_to_color_map={"a": BLUE, "b": YELLOW}, isolate=[",", "[", "]"] ) seq1_tex, seq2_tex, sum_seq, prod_seq, conv_seq = seqs = VGroup( OldTex(f"a = {list(seq1)}", **kw), OldTex(f"b = {list(seq2)}", **kw), OldTex(f"a + b = {list(seq1 + seq2)}", **kw), OldTex(Rf"a \cdot b = {list(seq1 * seq2)}", **kw), OldTex(Rf"a * b = {list(np.convolve(seq1, seq2))}", **kw), ) seqs.move_to(midpoint(ORIGIN, LEFT_SIDE)) seq1_tex.match_y(axes1) seq2_tex.match_y(axes2) for seq in seqs[2:]: seq.match_y(axes3) # Operation labels op_labels = VGroup() left_op_labels = VGroup(*map(Text, ["Addition", "Multiplication", "Convolution"])) left_op_labels.set_color(TEAL) for left_op_label, seq, graph_label in zip(left_op_labels, seqs[2:], graph_labels[2:]): left_op_label.next_to(seq, UP, MED_LARGE_BUFF, aligned_edge=LEFT) right_op_label = left_op_label.copy().scale(0.7) right_op_label.next_to(graph_label, UP, aligned_edge=LEFT) op_labels.add(VGroup(left_op_label, right_op_label)) # Introduce kw = dict(lag_ratio=0.7) self.play( LaggedStartMap(Write, seqs[:2], **kw), run_time=2, ) self.play( FadeIn(v_line), LaggedStartMap(FadeIn, all_axes[:2], **kw), LaggedStartMap(ShowCreation, VGroup(f_graph, g_graph), **kw), LaggedStartMap(FadeIn, graph_labels[:2], **kw), run_time=2 ) self.wait() # Ways to combine? all_boxes = VGroup(*(SurroundingRectangle(m[2:]) for m in seqs[:3])) all_boxes.set_stroke(width=2) boxes = all_boxes[:2] boxes[0].set_color(BLUE) boxes[1].set_color(YELLOW) mystery_box = all_boxes[2] mystery_box.set_color(GREEN) q_marks = Text("????") q_marks.space_out_submobjects(1.5) q_marks.move_to(mystery_box) box_arrows = VGroup(*( Arrow(box.get_right(), mystery_box.get_corner(UR), path_arc=-PI / 3) for box in boxes )) self.play( *map(Write, box_arrows), FadeIn(boxes), *( Transform( box.copy().set_stroke(width=0, opacity=0), mystery_box.copy(), path_arc=-PI / 3, remover=True ) for box in boxes ) ) self.add(mystery_box) comb_graph = sum_graph.copy() self.play( Write(q_marks), ReplacementTransform(axes1.copy(), axes3), Transform(axes2.copy(), axes3.copy(), remover=True), ReplacementTransform(f_graph.copy(), comb_graph), Transform(g_graph.copy(), comb_graph.copy(), remover=True), ) self.play(Transform(comb_graph, prod_graph)) self.play(Transform(comb_graph, conv_graph)) self.play(LaggedStartMap(FadeOut, VGroup( *boxes, *box_arrows, mystery_box, q_marks, comb_graph ))) # Sums and products tuples = [ (sum_seq, sum_label, axes3, sum_graph, op_labels[0]), (prod_seq, prod_label, axes3, prod_graph, op_labels[1]) ] for seq, label, axes, graph, op_label in tuples: self.play(LaggedStart( TransformMatchingShapes( VGroup(*seq1_tex[:2], *seq2_tex[:2]).copy(), seq[:4] ), TransformMatchingShapes(graph_labels[:2].copy(), label), FadeIn(op_label, DOWN) )) self.add(axes) # Go point by point value_rects = VGroup(*( VGroup(*map(SurroundingRectangle, s[-8::2])) for s in [seq1_tex, seq2_tex, seq] )) dots = Group(*(GlowDot(color=WHITE) for x in range(3))) self.play( *map(FadeIn, [seq[4], seq[-1]]), *( VFadeInThenOut(rects, lag_ratio=0.5) for rects in value_rects ), LaggedStart(*( FadeIn(seq[n:n + 2 if n < 11 else n + 1]) for n in range(5, 12, 2) ), lag_ratio=0.5), run_time=2 ) self.play( ShowCreation(graph, rate_func=linear), UpdateFromFunc(dots[2], lambda m: m.move_to(graph.get_end())), *( UpdateFromAlphaFunc(dot, lambda d, a: d.set_opacity(min(10 * a * (1 - a), 1))) for dot in dots ), *( MoveAlongPath(dot, graph) for dot, graph in zip(dots, [f_graph, g_graph]) ), run_time=4 ) self.wait() self.play(*map(FadeOut, [seq, label, graph, op_label])) # Convolutions self.play(LaggedStart( TransformMatchingShapes( VGroup(*seq1_tex[:2], *seq2_tex[:2]).copy(), conv_seq[:4], ), FadeIn(op_labels[2][0], DOWN), TransformMatchingShapes(graph_labels[:2].copy(), conv_label), FadeIn(op_labels[2][1], DOWN), )) self.play(FadeIn(conv_seq[4:], lag_ratio=0.2, run_time=2)) # Hint at computation nums1 = seq1_tex[3::2] nums2 = seq2_tex[3::2] for mobs in nums1, nums2: for i, mob in enumerate(mobs): mob.index = i nums3 = conv_seq[5::2] nums1.set_color(BLUE) nums2.set_color(YELLOW) last_group = VGroup() for n, num3 in enumerate(nums3): rect = SurroundingRectangle(num3, buff=SMALL_BUFF) rect.set_stroke(TEAL, 2) rect.round_corners() pairs = get_aligned_pairs(nums1, nums2, n) lines = VGroup(*(Line(m1, m2) for m1, m2 in pairs)) lines.set_stroke(TEAL, 2) group = VGroup(rect, lines) self.play(FadeIn(group), FadeOut(last_group), run_time=0.25) self.wait(0.25) last_group = group self.play(FadeOut(last_group, run_time=0.5)) self.wait() # Conv graph self.play(ShowCreation(conv_graph, run_time=3)) self.wait() self.play(MoveAlongPath(GlowDot(color=WHITE), conv_graph, run_time=5, remover=True)) self.wait() # Probabilities class DiceExample(InteractiveScene): def construct(self): # Start showing grid blue_dice = get_die_faces(fill_color=BLUE_E, dot_color=WHITE) red_dice = get_die_faces(fill_color=RED_E, dot_color=WHITE) VGroup(blue_dice, red_dice).arrange(DOWN, buff=LARGE_BUFF) grid = Square().get_grid(6, 6, buff=0) grid.set_height(6) grid.to_edge(LEFT, buff=2.0) grid.shift(0.5 * DOWN) grid.set_stroke(WHITE, 1) blue_dice.save_state() red_dice.save_state() self.play(LaggedStart( FadeIn(blue_dice, lag_ratio=0.1, shift=0.25 * UP, run_time=2, rate_func=overshoot), FadeIn(red_dice, lag_ratio=0.1, shift=0.25 * UP, run_time=2, rate_func=overshoot), lag_ratio=0.2 )) self.wait() self.play( Write(grid, run_time=2, stroke_color=YELLOW, stroke_width=4), *( die.animate.set_width(0.6 * square.get_width()).next_to(square, UP, SMALL_BUFF) for die, square in zip(blue_dice, grid[:6]) ), *( die.animate.set_width(0.6 * square.get_width()).next_to(square, LEFT, SMALL_BUFF) for die, square in zip(red_dice, grid[0::6]) ), ) # Add all mini dice mini_dice = VGroup() for n, square in enumerate(grid): j, i = n // 6, n % 6 blue = blue_dice[i].copy() red = red_dice[j].copy() blue.sum = i + j + 2 red.sum = i + j + 2 blue.generate_target() red.generate_target() group = VGroup(blue.target, red.target) group.set_stroke(width=1) group.arrange(RIGHT, buff=SMALL_BUFF) group.set_width(square.get_width() * 0.8) group.move_to(square) mini_dice.add(blue, red) combinations_label = VGroup( OldTex("6^2 = "), Integer(36), Text("Combinations") ) combinations_label.arrange(RIGHT, aligned_edge=DOWN) combinations_label.to_edge(RIGHT) self.play( LaggedStartMap(MoveToTarget, mini_dice, lag_ratio=0.02, run_time=2), FadeIn(combinations_label[0]), CountInFrom(combinations_label[1], 1, run_time=2), VFadeIn(combinations_label[1]), FadeIn(combinations_label[2], 0), ) self.wait() # Go Through diagonals last_prob_label = VMobject() for n in range(2, 13): to_fade = VGroup() to_highlight = VGroup() for die in mini_dice: if die.sum == n: to_highlight.add(die) else: to_fade.add(die) pairs = VGroup(*(VGroup(m1, m2) for m1, m2 in zip(to_highlight[::2], to_highlight[1::2]))) num = len(pairs) prob_label = self.get_p_sum_expr(n, Rf"\frac{{{num}}}{{36}}") prob_label.next_to(combinations_label, UP, buff=1.5) self.play( FadeIn(prob_label, UP), FadeOut(last_prob_label, UP), to_highlight.animate.set_opacity(1), to_fade.animate.set_opacity(0.2), blue_dice.animate.set_opacity(0.5), red_dice.animate.set_opacity(0.5), ) if n <= 4: self.play( LaggedStart(*( FlashAround(pair.copy(), remover=True, time_width=1, run_time=1.5) for pair in pairs ), lag_ratio=0.2), ) self.wait() last_prob_label = prob_label self.wait() # Reset self.play( FadeOut(grid), FadeOut(mini_dice, lag_ratio=0.01), FadeOut(combinations_label, RIGHT), FadeOut(prob_label, RIGHT), blue_dice.animate.restore(), red_dice.animate.restore(), ) self.wait() # Slide rows across self.play( Rotate(red_dice, PI), ) self.wait() last_prob_label = VMobject() last_rects = VMobject() for n in range(2, 13): pairs = self.get_aligned_pairs(blue_dice, red_dice, n) prob_label = self.get_p_sum_expr(n, Rf"\frac{{{len(pairs)}}}{{36}}") prob_label.to_edge(UP) self.play( self.get_dice_shift(blue_dice, red_dice, n), FadeOut(last_rects, run_time=0.5) ) rects = get_pair_rects(pairs) self.play( FadeOut(last_prob_label, UP), FadeIn(prob_label, UP), LaggedStartMap(ShowCreation, rects, lag_ratio=0.2), ) self.wait() last_prob_label = prob_label last_rects = rects # Realign self.play( FadeOut(last_rects), FadeOut(last_prob_label, UP), red_dice.animate.next_to(blue_dice, DOWN, buff=1.5), ) # Show implicit probabilities, and alternates all_dice = VGroup(*blue_dice, *red_dice) sixths = VGroup(*( OldTex("1 / 6", font_size=36).next_to(die, UP, SMALL_BUFF) for die in all_dice )) sixths.set_stroke(WHITE, 0) blue_probs, red_probs = [ np.random.uniform(0, 1, 6) for x in range(2) ] for probs in blue_probs, red_probs: probs[:] = (probs / probs.sum()).round(2) probs[-1] = 1.0 - probs[:-1].sum() # Ensure it's a valid distribution new_prob_labels = VGroup() all_dice.generate_target() for die, prob in zip(all_dice.target, (*blue_probs, *red_probs)): label = DecimalNumber(prob, font_size=36) label.next_to(die, UP, SMALL_BUFF) die.set_opacity(prob / (2 / 6)) new_prob_labels.add(label) question = Text("Non-uniform probabilities?") question.to_edge(UP) self.play(LaggedStartMap(Write, sixths, lag_ratio=0.1)) self.wait() self.play( Write(question, run_time=1), FadeOut(sixths, 0.25 * UP, lag_ratio=0.03, run_time=4), FadeIn(new_prob_labels, 0.25 * UP, lag_ratio=0.03, run_time=4), MoveToTarget(all_dice, run_time=3) ) self.wait() for die, prob_label in zip(all_dice, new_prob_labels): die.prob_label = prob_label die.prob = prob_label.get_value() die.add(prob_label) # March! last_rects = VMobject() last_prob_label = question n = 2 while n < 13: pairs = self.get_aligned_pairs(blue_dice, red_dice, n) prob_label = self.get_p_sum_expr(n, rhs=" ") rhs = self.get_conv_rhs(pairs, prob_label) VGroup(prob_label, rhs).center().to_edge(UP) self.play( self.get_dice_shift(blue_dice, red_dice, n), FadeOut(last_rects, run_time=0.5), FadeOut(last_prob_label, 0.5 * UP), FadeIn(prob_label, 0.5 * UP), ) rects = self.get_pair_rects(pairs) self.play(FadeIn(rects, lag_ratio=0.2)) self.play(TransformMatchingShapes( VGroup(*( VGroup(blue.prob_label, red.prob_label) for blue, red in pairs )).copy(), rhs )) self.wait() if n == 4 and isinstance(blue_dice[0].prob_label, DecimalNumber): # Make more general blue_labels = VGroup(*(OldTex(f"a_{{{i}}}", font_size=42) for i in range(1, 7))) red_labels = VGroup(*(OldTex(f"b_{{{i}}}", font_size=42) for i in range(1, 7))) blue_labels.set_color(BLUE) red_labels.set_color(RED) old_prob_labels = VGroup() for die, label in zip(all_dice, (*blue_labels, *red_labels)): label.next_to(die[0], UP, SMALL_BUFF) die.remove(die.prob_label) old_prob_labels.add(die.prob_label) die.prob_label = label die.add(label) self.play( FadeIn(VGroup(*blue_labels, *red_labels), shift=0.25 * UP, lag_ratio=0.04), FadeOut(old_prob_labels, shift=0.25 * UP, lag_ratio=0.04), FadeOut(rhs, time_span=(0, 1)), run_time=4 ) else: n += 1 last_prob_label = VGroup(prob_label, rhs) last_rects = rects # Show all formulas n_range = list(range(2, 13)) lhss = VGroup(*(self.get_p_sum_expr(n) for n in n_range)) pairss = VGroup(*(self.get_aligned_pairs(blue_dice, red_dice, n) for n in n_range)) rhss = VGroup(*(self.get_conv_rhs(pairs, lhs) for pairs, lhs in zip(pairss, lhss))) prob_labels = VGroup() for lhs, rhs in zip(lhss, rhss): prob_labels.add(VGroup(lhs, rhs)) prob_labels.arrange(DOWN, aligned_edge=LEFT) prob_labels.set_height(FRAME_HEIGHT - 1) prob_labels.to_edge(LEFT) dice = VGroup(blue_dice, red_dice) dice.generate_target() dice.target[1].rotate(PI) for m in dice.target[1]: m.prob_label.rotate(PI) m.prob_label.next_to(m, UP, SMALL_BUFF) dice.target.arrange(DOWN, buff=MED_LARGE_BUFF) dice.target.set_width(5) dice.target.to_edge(RIGHT) dice.target.to_corner(DR) self.play( LaggedStartMap(FadeIn, prob_labels[:-1], lag_ratio=0.2, run_time=2), FadeTransform(last_prob_label, prob_labels[-1], time_span=(0.5, 2.0)), MoveToTarget(dice, path_arc=PI / 2), FadeOut(last_rects), ) self.wait() # Name convolution a_rect = SurroundingRectangle(VGroup(*(die.prob_label for die in blue_dice))) b_rect = SurroundingRectangle(VGroup(*(die.prob_label for die in red_dice))) rhs_rects = VGroup(*(SurroundingRectangle(rhs) for rhs in rhss)) VGroup(a_rect, b_rect, *rhs_rects).set_stroke(YELLOW, 2) conv_name = OldTexText( R"Convolution of ", "$(a_i)$", " and ", "$(b_i)$", tex_to_color_map={"$(a_i)$": BLUE, "$(b_i)$": RED} ) conv_eq = Tex( R"(a * b)_n = \sum_{\substack{i, j \\ i + j = n}} a_i \cdot b_j", isolate=["a_i", "*", "b_j", "(a * b)_n"] ) conv_label = VGroup(conv_name, conv_eq) conv_label.arrange(DOWN, buff=LARGE_BUFF) conv_label.scale(0.9) conv_label.to_corner(UR) self.play( LaggedStartMap( ShowCreationThenFadeOut, VGroup(a_rect, b_rect), lag_ratio=0.5, run_time=3, ), LaggedStartMap( FadeIn, conv_name[1:5:2], shift=UP, lag_ratio=0.5, run_time=2, ) ) self.wait() self.play(FadeIn(conv_name[0:4:2], lag_ratio=0.1)) self.play(LaggedStartMap( ShowCreationThenFadeOut, rhs_rects, lag_ratio=0.1, run_time=5 )) self.wait() # Show grid again diagonals = VGroup() plusses = VGroup() rhss.save_state() for n, rhs in zip(it.count(2), rhss): diag = VGroup() for i in range(0, len(rhs), 4): diag.add(rhs[i:i + 3]) if i > 0: plusses.add(rhs[i - 1]) diagonals.add(diag) diagonals.generate_target() for k, square in enumerate(grid): i = k // 6 j = k % 6 i2 = j if (i + j <= 5) else 5 - i diagonals.target[i + j][i2].move_to(square) blue_dice.save_state() blue_dice.generate_target() red_dice.save_state() red_dice.generate_target() for dice, squares, vect in (blue_dice, grid[:6], UP), (red_dice, grid[::6], LEFT): dice.save_state() dice.generate_target() for die, square in zip(dice.target, squares): die.scale(0.75) die.next_to(square, vect, SMALL_BUFF) self.play( plusses.animate.set_opacity(0), FadeOut(lhss, LEFT, run_time=0.5, lag_ratio=0.01), MoveToTarget(diagonals), MoveToTarget(blue_dice), MoveToTarget(red_dice), run_time=2 ) self.play(FadeIn(grid, lag_ratio=0.01)) self.add(diagonals) self.wait() for n in range(len(diagonals)): diagonals.generate_target() diagonals.target.set_opacity(0.2) diagonals.target[n].set_opacity(1) self.play(MoveToTarget(diagonals)) self.wait() self.play( Restore(blue_dice), Restore(red_dice), diagonals.animate.set_opacity(1) ) self.remove(diagonals) self.play( FadeOut(grid), Restore(rhss), FadeIn(lhss, time_span=(1, 2), lag_ratio=0.01), run_time=2 ) self.wait() # Write equation self.wait(2) self.play(FadeIn(conv_eq, DOWN)) self.wait() # Highlight example n = 4 pairs = self.get_aligned_pairs(blue_dice, red_dice, n + 2) pair_rects = get_pair_rects(pairs, together=False) self.play( prob_labels[:n].animate.set_opacity(0.35), prob_labels[n + 1:].animate.set_opacity(0.35), ) self.wait() self.play(ShowSubmobjectsOneByOne(pair_rects, remover=True, rate_func=linear, run_time=3)) self.wait() # Alternate formula notation alt_rhs = OldTex(R"\sum_{i = 1}^6 a_i \cdot b_{n - i}") alt_rhs.scale(0.9) alt_rhs.move_to(conv_eq[7], LEFT) self.play( FadeIn(alt_rhs, 0.5 * DOWN), conv_eq[7:].animate.shift(1.5 * DOWN).set_opacity(0.5), dice.animate.to_edge(DOWN) ) self.wait() def get_p_sum_expr(self, n, rhs=" "): raw_expr = Tex( fR"P\big(O + O = {n}\big) = \, {rhs}", isolate=("O", str(n), "=", rhs) ) for index, color in zip([2, 4], [BLUE_E, RED_E]): square = DieFace(1, fill_color=color, stroke_width=1)[0] square.replace(raw_expr[index]) square.match_y(raw_expr[3]) raw_expr.replace_submobject(index, square) return raw_expr def get_dice_shift(self, top_dice, low_dice, n): return get_row_shift(top_dice, low_dice, n) def get_aligned_pairs(self, top_dice, low_dice, n): return get_aligned_pairs(top_dice, low_dice, n) def get_pair_rects(self, pairs, together=True): return get_pair_rects(pairs, together) def get_conv_rhs(self, pairs, prob_label): rhs = VGroup() for (blue, red) in pairs: rhs.add(blue.prob_label.copy().set_color(BLUE)) rhs.add(OldTex(R"\cdot")) rhs.add(red.prob_label.copy().set_color(RED)) rhs.add(OldTex("+")) rhs.remove(rhs[-1]) rhs.arrange(RIGHT, buff=SMALL_BUFF) rhs.next_to(prob_label, RIGHT, buff=0.2) return rhs class SimpleExample(InteractiveScene): def construct(self): # Question question = Text("What is") conv = Tex("(1, 2, 3) * (4, 5, 6)") group = VGroup(question, conv) group.arrange(DOWN) group.to_edge(UP) self.play(Write(question, run_time=1.5), FadeIn(conv, 0.5 * DOWN, time_span=(0.5, 1.5))) self.wait() # Blocks top_row = Square(side_length=0.75).get_grid(1, 3, buff=0) top_row.set_stroke(GREY_B, 2) top_row.set_fill(GREY_E, 1) low_row = top_row.copy() for row, values in (top_row, range(1, 4)), (low_row, range(4, 7)): for index, value, square in zip(it.count(), values, row): value_label = Integer(value) value_label.move_to(square) square.value_label = value_label square.add(value_label) square.value = value square.index = index VGroup(top_row, low_row).arrange(RIGHT, buff=LARGE_BUFF) self.play( TransformMatchingShapes(conv[1:6:2].copy(), top_row), TransformMatchingShapes(conv[9:14:2].copy(), low_row), ) self.wait() # Labels self.add_block_labels(top_row, "a", BLUE) self.add_block_labels(low_row, "b", RED) # Set up position top_row.generate_target() low_row.generate_target() low_row.target.rotate(PI) for square in low_row.target: square.value_label.rotate(PI) square.label.rotate(PI) top_row.target.center() low_row.target.next_to(top_row.target, DOWN, MED_LARGE_BUFF) conv_result = np.convolve([1, 2, 3], [4, 5, 6]) rhs_args = ["=", R"\big("] for k in conv_result: rhs_args.append(str(k)) rhs_args.append(",") rhs_args[-1] = R"\big)" rhs = OldTex(*rhs_args) rhs[1:].set_color(YELLOW) conv.generate_target() group = VGroup(conv.target, rhs) group.arrange(RIGHT, buff=0.2) group.next_to(top_row, UP, buff=2), self.play(LaggedStart( MoveToTarget(top_row), MoveToTarget(low_row, path_arc=PI), MoveToTarget(conv), Write(VGroup(*rhs[:2], rhs[-1])), FadeOut(question, UP), )) self.wait() # March! c_labels = VGroup() for n in range(len(conv_result)): self.play(get_row_shift(top_row, low_row, n)) pairs = get_aligned_pairs(top_row, low_row, n) label_pairs = VGroup(*( VGroup(m1.value_label, m2.value_label) for m1, m2 in pairs )) new_label_pairs = label_pairs.copy() expr = VGroup() symbols = VGroup() for label_pair in new_label_pairs: label_pair.arrange(RIGHT, buff=MED_SMALL_BUFF) label_pair.next_to(expr, RIGHT, SMALL_BUFF) dot = OldTex(R"\dot") dot.move_to(label_pair) plus = OldTex("+") plus.next_to(label_pair, RIGHT, SMALL_BUFF) expr.add(*label_pair, dot, plus) symbols.add(dot, plus) symbols[-1].scale(0, about_point=symbols[-2].get_right()) expr.next_to(label_pairs, UP, LARGE_BUFF) c_label = OldTex(f"c_{n}", font_size=30, color=YELLOW).next_to(rhs[2 * n + 2], UP) rects = VGroup(*( SurroundingRectangle(lp, buff=0.2).set_stroke(YELLOW, 1).round_corners() for lp in label_pairs )) self.play(FadeIn(rects, lag_ratio=0.5)) self.play( LaggedStart(*( TransformFromCopy(lp, nlp) for lp, nlp in zip(label_pairs, new_label_pairs) ), lag_ratio=0.5), Write(symbols), ) self.wait() anims = [ FadeTransform(expr.copy(), rhs[2 * n + 2]), c_labels.animate.set_opacity(0.35), FadeIn(c_label) ] if n < 4: anims.append(Write(rhs[2 * n + 3])) self.play(*anims) self.wait() self.play(FadeOut(expr), FadeOut(rects)) c_labels.add(c_label) self.play(FadeOut(c_labels)) # Grid of values equation = VGroup(conv, rhs) values1 = VGroup(*(block.value_label for block in top_row)).copy() values2 = VGroup(*(block.value_label for block in low_row)).copy() grid = Square(side_length=1.0).get_grid(3, 3, buff=0) grid.set_stroke(WHITE, 2) grid.set_fill(GREY_E, 1.0) grid.move_to(DL) self.play( Write(grid, time_span=(0.5, 2.0)), LaggedStart( *( value.animate.next_to(square, UP, buff=0.2) for value, square in zip(values1, grid[:3]) ), *( value.animate.next_to(square, LEFT, buff=0.2) for value, square in zip(values2, grid[0::3]) ), run_time=2 ), *( MaintainPositionRelativeTo(block, value) for row, values in [(top_row, values1), (low_row, values2)] for block, value in zip(row, values) ), VFadeOut(top_row), VFadeOut(low_row), equation.animate.center().to_edge(UP) ) # Products products = VGroup() diag_groups = VGroup().replicate(5) for n, square in enumerate(grid): i, j = n // 3, n % 3 v1 = values1[j] v2 = values2[i] product = Integer(v1.get_value() * v2.get_value()) product.match_height(v1) product.move_to(square) product.factors = (v1, v2) square.product = product products.add(product) diag_groups[i + j].add(product) products.set_color(GREEN) self.play(LaggedStart(*( ReplacementTransform(factor.copy(), product) for product in products for factor in product.factors ), lag_ratio=0.1)) self.wait() # Circle diagonals products.rotate(PI / 4) ovals = VGroup() radius = 0.3 for diag in diag_groups: oval = SurroundingRectangle(diag, buff=0.19) oval.set_width(2 * radius, stretch=True) oval.set_stroke(YELLOW, 2) oval.round_corners(radius=radius) ovals.add(oval) VGroup(products, ovals).rotate(-PI / 4) ovals[0].become(Circle(radius=radius).match_style(ovals[0]).move_to(products[0])) arrows = VGroup(*( Vector(0.5 * UP).next_to(part, DOWN) for part in rhs[2::2] )) arrows.set_color(YELLOW) curr_arrow = arrows[0].copy() curr_arrow.shift(0.5 * DOWN).set_opacity(0) for n, oval, arrow in zip(it.count(), ovals, arrows): self.play( ShowCreation(oval), ovals[:n].animate.set_stroke(opacity=0.25), Transform(curr_arrow, arrow) ) self.wait(0.5) self.play(ovals.animate.set_stroke(opacity=0.25), FadeOut(curr_arrow)) self.wait() grid_group = VGroup(grid, values1, values2, products, ovals) # Show polynomial polynomial_eq = Tex( R"\left(1 + 2x + 3x^2\right)\left(4 + 5x + 6x^2\right)" R"={4} + {13}x + {28}x^2 + {27}x^3 + {18}x^4", tex_to_color_map=dict( (f"{{{n}}}", YELLOW) for n in conv_result ) ) polynomial_eq.next_to(equation, DOWN, MED_LARGE_BUFF) self.play( FadeIn(polynomial_eq, DOWN), grid_group.animate.center().to_edge(DOWN) ) self.wait() # Replace terms self.play(grid_group.animate.set_height(4.5, about_edge=DOWN)) for i, value in zip((*range(3), *range(3)), (*values1, *values2)): tex = ["", "x", "x^2"][i] value.target = Tex(f"{value.get_value()}{tex}") value.target.scale(value.get_height() / value.target[0].get_height()) value.target.move_to(value, DOWN) values2[1].target.align_to(values2[0].target, RIGHT) values2[2].target.align_to(values2[0].target, RIGHT) for n, diag_group in enumerate(diag_groups): tex = ["", "x", "x^2", "x^3", "x^4"][n] for product in diag_group: product.target = Tex(f"{product.get_value()}{tex}") product.target.match_style(product) product.target.scale(0.9) product.target.move_to(product) eq_values1 = VGroup(polynomial_eq[1], polynomial_eq[3:5], polynomial_eq[6:9]) eq_values2 = VGroup(polynomial_eq[11], polynomial_eq[13:15], polynomial_eq[16:19]) for values, eq_values in [(values1, eq_values1), (values2, eq_values2)]: self.play( LaggedStart(*(TransformMatchingShapes(ev.copy(), v.target) for ev, v in zip(eq_values, values))), LaggedStart(*(FadeTransform(v, v.target[0]) for v in values)), ) self.wait() old_rects = VGroup() for n, prod in enumerate(products): new_rects = VGroup( SurroundingRectangle(values1[n % 3].target), SurroundingRectangle(values2[n // 3].target), ) new_rects.set_stroke(GREEN, 2) self.play( FadeIn(new_rects), FadeOut(old_rects), FadeTransform(prod, prod.target[:len(prod)]), FadeIn(prod.target[len(prod):], scale=2), FlashAround(prod.target, time_width=1), run_time=1.0 ) old_rects = new_rects self.play(FadeOut(old_rects)) # Show diagonals again arrows = VGroup(*( Vector(0.5 * UP).next_to(polynomial_eq.select_part(f"{{{n}}}"), DOWN, buff=SMALL_BUFF) for n in conv_result )) arrows.set_color(YELLOW) curr_arrow = arrows[0].copy().shift(DOWN).set_opacity(0) for n, oval, arrow in zip(it.count(), ovals, arrows): self.play( oval.animate.set_stroke(opacity=1), Transform(curr_arrow, arrow), ovals[:n].animate.set_stroke(opacity=0.25), ) self.wait(0.5) self.play( FadeOut(curr_arrow), ovals.animate.set_stroke(opacity=0.5) ) def add_block_labels(self, blocks, letter, color=BLUE, font_size=30): labels = VGroup() for n, square in enumerate(blocks): label = OldTex(f"{letter}_{{{n}}}", font_size=font_size) label.set_color(color) label.next_to(square, UP, SMALL_BUFF) square.label = label square.add(label) labels.add(label) return labels class MovingAverageExample(InteractiveScene): dist1 = [*5 * [0.1], *5 * [1], *5 * [0.1], *5 * [1], *5 * [0.1]] dist2 = 5 * [0.2] march_anim_run_time = 1.0 always_preview_result = True def construct(self): # All bars self.camera.frame.scale(1.01) dist1 = np.array(self.dist1) dist2 = np.array(self.dist2) conv_dist = np.convolve(dist1, dist2) top_bars = dist_to_bars(dist1, height=1.5, bar_colors=(BLUE_D, TEAL_D)) low_bars = dist_to_bars(dist2, height=1.5, bar_colors=(RED_D, GOLD_E)) conv_bars = dist_to_bars(conv_dist, height=1.5, bar_colors=(GREEN_D, YELLOW_E)) top_bars.center().to_edge(UP) low_bars.stretch(max(dist2), 1, about_edge=DOWN) low_bars.arrange(LEFT, aligned_edge=DOWN, buff=0) low_bars.next_to(top_bars, DOWN, buff=1.2, aligned_edge=LEFT) conv_bars.match_x(top_bars) conv_bars.to_edge(DOWN, LARGE_BUFF) v_lines = get_bar_dividing_lines(conv_bars) add_labels_to_bars(top_bars, dist1, num_decimal_places=1, width_ratio=0.4) add_labels_to_bars(low_bars, dist2, num_decimal_places=1, width_ratio=0.4) add_labels_to_bars(conv_bars, conv_dist, num_decimal_places=2) self.add(v_lines) self.play(FadeIn(top_bars, lag_ratio=0.1, run_time=2)) self.play(FadeIn(low_bars)) lb_rect = SurroundingRectangle(low_bars) lb_rect.round_corners().set_stroke(YELLOW, 2) sum_label = Tex(R"\sum_i y_i = 1") sum_label.set_color(YELLOW) sum_label.next_to(lb_rect) self.play(ShowCreation(lb_rect)) self.play(Write(sum_label, run_time=1)) self.wait() self.play(FadeOut(lb_rect), FadeOut(sum_label)) # March! last_rects = VGroup() for n, conv_bar in enumerate(conv_bars): rect = conv_bar[0] value = conv_bar[1] rect.save_state() rect.stretch(0, 1, about_edge=DOWN) rect.set_opacity(0) self.play( get_row_shift(top_bars, low_bars, n), FadeOut(last_rects), run_time=self.march_anim_run_time, ) pairs = get_aligned_pairs(top_bars, low_bars, n) label_pairs = VGroup(*(VGroup(m1.value_label, m2.value_label) for m1, m2 in pairs)) rects = VGroup(*( SurroundingRectangle(lp, buff=0.05).set_stroke(YELLOW, 2).round_corners() for lp in label_pairs )) rects.set_stroke(YELLOW, 2) self.play( FadeIn(rects, lag_ratio=0.5), conv_bars[:n].animate.set_opacity(0.5), run_time=self.march_anim_run_time, ) self.play( *( FadeTransform(label.copy(), value) for lp in label_pairs for label in lp ), Restore(rect), run_time=self.march_anim_run_time, ) if self.always_preview_result: self.add(conv_bars) conv_bars.set_opacity(0.5) conv_bar.set_opacity(1) self.wait(0.5) last_rects = rects self.play( FadeOut(last_rects), conv_bars.animate.set_opacity(1), ) class MovingAverageFast(MovingAverageExample): march_anim_run_time = 0 class AltMovingAverage(MovingAverageExample): dist2 = [0.1, 0.2, 0.4, 0.2, 0.1] class AltMovingAverageFast(AltMovingAverage): march_anim_run_time = 0 class MovingAverageFast2(AltMovingAverageFast): always_preview_result = True class CompareSizes(InteractiveScene): def construct(self): # Show them all! int_arr1 = [3, 1, 4, 1, 5, 9] int_arr2 = [5, 7, 7] conv_arr = np.convolve(int_arr1, int_arr2) arrays = VGroup() for arr in (int_arr1, int_arr2, conv_arr): squares = Square().get_grid(1, len(arr), buff=0) squares.set_height(0.7) squares.set_stroke(WHITE, 1) squares.set_fill(GREY_E, 1) for square, elem in zip(squares, arr): int_mob = Integer(elem).move_to(square) square.add(int_mob) arrays.add(squares) top_arr, low_arr, conv_arr = arrays arrays.arrange(DOWN, buff=1.0) arrays[:2].shift(UP) VGroup(*(square[0] for square in arrays[2])).set_opacity(0) self.add(*arrays) # Length labels braces = VGroup(*(Brace(arr, vect, buff=SMALL_BUFF) for arr, vect in zip(arrays, [UP, DOWN, DOWN]))) brace_labels = VGroup(*(brace.get_tex(tex, buff=SMALL_BUFF) for brace, tex in zip(braces, ["n", "m", "n + m - 1"]))) braces[1].add_updater(lambda m: m.match_x(arrays[1])) brace_labels[1].add_updater(lambda m: m.match_x(arrays[1])) self.add(braces, brace_labels) # Flip self.remove(low_arr) fake_arr = low_arr.deepcopy() fake_arr.generate_target(use_deepcopy=True) fake_arr.target.rotate(PI) for square in fake_arr.target: square[0].rotate(PI) self.play(MoveToTarget(fake_arr, path_arc=PI, lag_ratio=0.01)) self.remove(fake_arr) low_arr.rotate(PI) for square in low_arr: square[0].rotate(PI) # March! for arr in (top_arr, low_arr): for index, square in enumerate(arr): square.index = index for n in range(len(conv_arr)): self.play( get_row_shift(top_arr, low_arr, n), run_time=0.5 ) pairs = get_aligned_pairs(top_arr, low_arr, n) rects = VGroup(*( SurroundingRectangle(pair, buff=-0.05) for pair in pairs )) self.add(rects) conv_arr[n].set_opacity(1) self.play(ShowIncreasingSubsets(rects, int_func=np.ceil), run_time=0.5) self.wait(0.25) self.remove(rects) # Truncate brace = braces[2] brace_label = brace_labels[2] small_brace = Brace(conv_arr[2:-2], DOWN, buff=SMALL_BUFF) small_brace_label = small_brace.get_text("Only consider full overlaps") mid_brace = Brace(conv_arr[1:-1], DOWN, buff=SMALL_BUFF) mid_brace_label = mid_brace.get_text("Match biggest input size") self.play( Transform(brace, small_brace), FadeTransform(brace_label, small_brace_label), conv_arr[:2].animate.set_opacity(0.25), conv_arr[-2:].animate.set_opacity(0.25), ) self.wait() self.play( Transform(brace, mid_brace), FadeTransform(small_brace_label, mid_brace_label), conv_arr[1].animate.set_opacity(1), conv_arr[-2].animate.set_opacity(1), ) self.wait() # Image processing class ImageConvolution(InteractiveScene): image_name = "MarioSmall" image_height = 6.0 kernel_tex = None scalar_conv = False pixel_stroke_width = 1.0 pixel_stroke_opacity = 1.0 kernel_decimal_places = 2 kernel_color = BLUE grayscale = False def setup(self): super().setup() # Set up the pixel grids pixels = self.get_pixel_value_array() / 255.0 kernel = self.get_kernel() if self.scalar_conv: conv = scipy.signal.convolve(pixels.mean(2), kernel, mode='same') else: conv = scipy.signal.convolve(pixels, np.expand_dims(kernel, 2), mode='same') conv = np.clip(conv, -1, 1) pixel_array = self.get_pixel_array(pixels) kernel_array = self.get_kernel_array(kernel, pixel_array, tex=self.kernel_tex) conv_array = self.get_pixel_array(conv) conv_array.set_fill(opacity=0) VGroup(pixel_array, conv_array).arrange(RIGHT, buff=2.0) kernel_array.move_to(pixel_array[0]) self.add(pixel_array) self.add(conv_array) self.add(kernel_array) # Set up index tracker index_tracker = ValueTracker(0) def get_index(): return int(clip(index_tracker.get_value(), 0, len(pixel_array) - 1)) kernel_array.add_updater(lambda m: m.move_to(pixel_array[get_index()])) conv_array.add_updater(lambda m: m.set_fill(opacity=0)) conv_array.add_updater(lambda m: m[:get_index() + 1].set_fill(opacity=1)) right_rect = conv_array[0].copy() right_rect.set_fill(opacity=0) right_rect.set_stroke(self.kernel_color, 4, opacity=1) right_rect.add_updater(lambda m: m.move_to(conv_array[get_index()])) self.add(right_rect) self.index_tracker = index_tracker self.pixel_array = pixel_array self.kernel_array = kernel_array self.conv_array = conv_array self.right_rect = right_rect def get_pixel_value_array(self): im_path = get_full_raster_image_path(self.image_name) image = Image.open(im_path) return np.array(image)[:, :, :3] def get_pixel_array(self, array: np.ndarray): height, width = array.shape[:2] pixel_array = Square().get_grid(height, width, buff=0) for pixel, value in zip(pixel_array, it.chain(*array)): if value.size == 3: # Value is rgb valued rgb = np.abs(value).clip(0, 1) if self.grayscale: rgb[:] = rgb.mean() else: # Treat as scalar, color red for negative green for positive rgb = [max(-value, 0), max(value, 0), max(value, 0)] pixel.set_fill(rgb_to_color(rgb), 1.0) pixel_array.set_height(self.image_height) pixel_array.set_max_width(5.75) pixel_array.set_stroke(WHITE, self.pixel_stroke_width, self.pixel_stroke_opacity) return pixel_array def get_kernel_array(self, kernel: np.ndarray, pixel_array: VGroup, tex=None): kernel_array = VGroup() values = VGroup() for row in kernel: for x in row: square = pixel_array[0].copy() square.set_fill(BLACK, 0) square.set_stroke(self.kernel_color, 2, opacity=1) if tex: value = OldTex(tex) else: value = DecimalNumber(x, num_decimal_places=self.kernel_decimal_places) value.set_width(square.get_width() * 0.7) value.set_backstroke(BLACK, 3) value.move_to(square) values.add(value) square.add(value) kernel_array.add(square) for value in values: value.set_height(values[0].get_height()) kernel_array.reverse_submobjects() kernel_array.arrange_in_grid(*kernel.shape, buff=0) kernel_array.move_to(pixel_array[0]) return kernel_array def get_kernel(self): return np.ones((3, 3)) / 9 # Setup combing and zooming def set_index(self, value, run_time=8, rate_func=linear): self.play( self.index_tracker.animate.set_value(value), run_time=run_time, rate_func=rate_func ) def zoom_to_kernel(self, run_time=2): ka = self.kernel_array self.play( self.camera.frame.animate.set_height(1.5 * ka.get_height()).move_to(ka), run_time=run_time ) def zoom_to_new_pixel(self, run_time=4): ka = self.kernel_array ca = self.conv_array frame = self.camera.frame curr_center = frame.get_center().copy() index = int(self.index_tracker.get_value()) new_center = ca[index].get_center() center_func = bezier([curr_center, curr_center, new_center, new_center]) target_height = 1.5 * ka.get_height() height_func = bezier([ frame.get_height(), frame.get_height(), FRAME_HEIGHT, target_height, target_height, ]) self.play( UpdateFromAlphaFunc(frame, lambda m, a: m.set_height(height_func(a)).move_to(center_func(a))), run_time=run_time, rate_func=linear, ) def reset_frame(self, run_time=2): self.play( self.camera.frame.animate.to_default_state(), run_time=run_time ) def show_pixel_sum(self, tex=None, convert_to_vect=True, row_len=9): # Setup sum ka = self.kernel_array pa = self.pixel_array frame = self.camera.frame rgb_vects = VGroup() lil_pixels = VGroup() expr = VGroup() ka_copy = VGroup() stroke_width = 2 * FRAME_HEIGHT / frame.get_height() lil_height = 1.0 for square in ka: ka_copy.add(square.copy().set_stroke(TEAL, stroke_width)) sc = square.get_center() pixel = pa[np.argmin([get_norm(p.get_center() - sc) for p in pa])] color = pixel.get_fill_color() rgb = color_to_rgb(color) rgb_vect = DecimalMatrix(rgb.reshape((3, 1)), num_decimal_places=2) rgb_vect.set_height(lil_height) rgb_vect.set_color(color) if get_norm(rgb) < 0.1: rgb_vect.set_color(WHITE) rgb_vects.add(rgb_vect) lil_pixel = pixel.copy() lil_pixel.match_width(rgb_vect) lil_pixel.set_stroke(WHITE, stroke_width) lil_pixels.add(lil_pixel) if tex: lil_coef = OldTex(tex, font_size=36) else: lil_coef = square[0].copy() lil_coef.set_height(lil_height * 0.5) expr.add(lil_coef, lil_pixel, OldTex("+", font_size=48)) expr[-1].scale(0, about_edge=LEFT) # Stray plus rows = VGroup(*( expr[n:n + 3 * row_len] for n in range(0, len(expr), 3 * row_len) )) for row in rows: row.arrange(RIGHT, buff=0.2) rows.arrange(DOWN, buff=0.4, aligned_edge=LEFT) expr.set_max_width(FRAME_WIDTH - 1) expr.to_edge(UP) expr.fix_in_frame() for vect, pixel in zip(rgb_vects, lil_pixels): vect.move_to(pixel) vect.set_max_width(pixel.get_width()) rgb_vects.fix_in_frame() # Reveal top top_bar = FullScreenRectangle().set_fill(BLACK, 1) top_bar.set_height(rgb_vects.get_height() + 0.5, stretch=True, about_edge=UP) top_bar.fix_in_frame() self.play( frame.animate.scale(1.2, about_edge=DOWN), FadeIn(top_bar, 2 * DOWN), ) # Show sum for n in range(len(ka_copy)): self.remove(*ka_copy) self.add(ka_copy[n]) self.add(expr[:3 * n + 2]) self.wait(0.25) self.remove(*ka_copy) if convert_to_vect: self.play(LaggedStart(*( Transform(lil_pixel, rgb_vect) for lil_pixel, rgb_vect in zip(lil_pixels, rgb_vects) ))) self.wait() result = VGroup(top_bar, expr) return result class BoxBlurMario(ImageConvolution): kernel_tex = "1 / 9" image_name = "MarioSmall" pixel_stroke_opacity = 0.5 stops = (131, 360) final_run_time = 8 def construct(self): # March for index in self.stops: self.set_index(index) self.zoom_to_kernel() if index == self.stops[0]: top_bar = self.show_pixel_sum(tex=R"\frac{1}{9}") self.wait() self.zoom_to_new_pixel(run_time=8) self.wait() if index == self.stops[0]: self.play(FadeOut(top_bar)) self.reset_frame() self.set_index(len(self.pixel_array) - 1, run_time=self.final_run_time) self.wait() class BoxBlurCat(BoxBlurMario): image_name = "PixelArtCat" stops = () final_run_time = 20 class GaussianBluMario(ImageConvolution): kernel_decimal_places = 3 focus_index = 256 final_run_time = 10 def construct(self): # March! self.set_index(self.focus_index) self.wait() self.zoom_to_kernel() self.wait() # Gauss surface kernel_array = self.kernel_array frame = self.camera.frame gaussian = ParametricSurface( lambda u, v: [u, v, np.exp(-(u**2) - v**2)], u_range=(-3, 3), v_range=(-3, 3), resolution=(101, 101), ) gaussian.set_color(BLUE, 0.8) gaussian.match_width(kernel_array) gaussian.stretch(2, 2) gaussian.add_updater(lambda m: m.move_to(kernel_array, IN)) self.play( FadeIn(gaussian), frame.animate.reorient(10, 70), run_time=3 ) self.wait() top_bar = self.show_pixel_sum(convert_to_vect=False) self.wait() self.zoom_to_new_pixel() self.wait() self.play( frame.animate.set_height(8).reorient(0, 60).move_to(ORIGIN), FadeOut(top_bar, time_span=(0, 1)), run_time=3, ) # More walking self.set_index(len(self.pixel_array), run_time=self.final_run_time) self.wait() def get_kernel(self): # Oh good, hard coded, I hope you feel happy with yourself. return np.array([ [0.00296902, 0.0133062, 0.0219382, 0.0133062, .00296902], [0.0133062, 0.0596343, 0.0983203, 0.0596343, 0.0133062], [0.0219382, 0.0983203, 0.162103, 0.0983203, 0.0219382], [0.0133062, 0.0596343, 0.0983203, 0.0596343, 0.0133062], [0.00296902, 0.0133062, 0.0219382, 0.0133062, 0.00296902], ]) class GaussianBlurCat(GaussianBluMario): image_name = "PixelArtCat" focus_index = 254 def construct(self): for arr in self.pixel_array, self.conv_array: arr.set_stroke(width=0.5, opacity=0.5) super().construct() class GaussianBlurCatNoPause(GaussianBlurCat): stops = () focus_index = 0 final_run_time = 30 class SobelFilter1(ImageConvolution): scalar_conv = True image_name = "BitRandy" pixel_stroke_width = 1 pixel_stroke_opacity = 0.2 kernel_color = YELLOW stops = (194, 400, 801) grayscale = True def construct(self): self.zoom_to_kernel() # Show kernel kernel = self.kernel_array kernel.generate_target() for square in kernel.target: v = square[0].get_value() square.set_fill( rgb_to_color([2 * max(-v, 0), 2 * max(v, 0), 2 * max(v, 0)]), opacity=0.5, recurse=False ) square.set_stroke(WHITE, 1, recurse=False) self.play(MoveToTarget(kernel)) self.wait() self.reset_frame() # Example walking for index in self.stops: self.set_index(index) self.zoom_to_kernel() self.play(*( square.animate.set_fill(opacity=0, recurse=False) for square in kernel ), rate_func=there_and_back_with_pause, run_time=3) self.add(kernel) self.wait() self.zoom_to_new_pixel() self.wait() self.reset_frame() self.set_index(len(self.pixel_array) - 1, run_time=20) def get_kernel(self): return np.array([ [-0.25, 0, 0.25], [-0.5, 0, 0.5], [-0.25, 0, 0.25], ]) class SobelFilter2(SobelFilter1): stops = () def get_kernel(self): return super().get_kernel().T class SobelFilterCat(SobelFilter1): scalar_conv = True image_name = "PixelArtCat" pixel_stroke_width = 1 pixel_stroke_opacity = 0.2 kernel_color = WHITE stops = () grayscale = False class SobelFilterKirby(SobelFilter1): image_name = "KirbySmall" grayscale = False class SharpenFilter(ImageConvolution): image_name = "KirbySmall" kernel_decimal_places = 1 grayscale = False def construct(self): for arr in self.pixel_array, self.conv_array: arr.set_stroke(WHITE, 0.25, 0.5) for square in self.kernel_array: square[0].scale(0.6) self.set_index(len(self.pixel_array) - 1, run_time=20) def get_kernel(self): return np.array([ [0.0, 0.0, -0.25, 0.0, 0.0], [0.0, -0.25, -0.5, -0.25, 0.0], [-0.25, -0.5, 5.0, -0.5, -0.25], [0.0, -0.25, -0.5, -0.25, 0.0], [0.0, 0.0, -0.25, 0.0, 0.0], ]) # Convolution theorem class ContrastConvolutionToMultiplication(InteractiveScene): def construct(self): # Set up divide v_line = Line(UP, DOWN).set_height(FRAME_HEIGHT) v_line.set_stroke(GREY, 2) kw = dict(font_size=60) conv_name = Text("Convolution", **kw) mult_name = Text("Multiplication", **kw) conv_name.set_x(-FRAME_WIDTH / 4).to_edge(UP) mult_name.set_x(FRAME_WIDTH / 4).to_edge(UP) self.add(v_line) self.add(conv_name) self.add(mult_name) # Set up arrays arr1 = np.arange(1, 6) arr2 = np.arange(6, 11) conv = np.convolve(arr1, arr2) prod = arr1 * arr2 quart = FRAME_WIDTH / 4 left_arrays, right_arrays = ( VGroup(*( self.get_array_mobject(arr, color) for arr, color in [(arr1, BLUE), (arr2, YELLOW)] )).arrange(DOWN, buff=1.0).move_to(vect * quart + UP) for vect in [LEFT, RIGHT] ) conv_array = self.get_array_mobject(conv, color=TEAL) prod_array = self.get_array_mobject(prod, color=TEAL) conv_array.next_to(left_arrays, DOWN, buff=1.5) prod_array.next_to(right_arrays, DOWN, buff=1.5) self.add(left_arrays) self.add(right_arrays) # Show convolution top_arr = left_arrays[0] low_arr = left_arrays[1] low_arr.generate_target() low_arr.target.rotate(PI, about_point=low_arr.elements[0].get_center()) for elem in low_arr.target[1:-1]: elem.rotate(PI) low_arr.target[2:-2:2].set_y(low_arr[1].get_y(DOWN)) self.play( FadeIn(VGroup(conv_array[0], conv_array[-1])), MoveToTarget(low_arr, path_arc=PI), ) for n, elem in enumerate(conv_array.elements): pairs = get_aligned_pairs(top_arr.elements, low_arr.elements, n) self.play( get_row_shift(top_arr.elements, low_arr.elements, n), MaintainPositionRelativeTo(low_arr[::2], low_arr.elements), run_time=0.25 ) lines = VGroup(*(Line(m1, m2, buff=0.1) for m1, m2 in pairs)) lines.set_stroke(TEAL, 1) self.add(lines, elem) tally = 0 for (m1, m2), line in zip(pairs, lines): tally += m1.get_value() * m2.get_value() lines.set_stroke(width=1) line.set_stroke(width=4) elem.set_value(tally) self.wait(0.25) self.wait(0.25) self.remove(lines) self.add(conv_array[2 * n + 2]) self.wait() # Show multiplication low_arr = right_arrays[0] top_arr = right_arrays[1] lines = VGroup(*( Line(e1, e2, buff=0.1) for e1, e2 in zip(top_arr.elements, low_arr.elements) )) lines.set_stroke(TEAL, 1) self.play( FadeIn(VGroup(prod_array[0], prod_array[-1])), FadeIn(lines), ) for n, elem in enumerate(prod_array.elements): lines.set_stroke(width=1) lines[n].set_stroke(width=4) self.add(elem) self.add(prod_array[2 * n + 2]) self.wait(0.5) self.play(FadeOut(lines)) def get_array_mobject(self, array, color=WHITE, font_size=48): kw = dict(font_size=font_size) result = VGroup(OldTex("[", **kw)) commas = VGroup() elements = VGroup() for index, elem in enumerate(array): int_mob = Integer(elem, **kw) int_mob.index = index elements.add(int_mob) result.add(int_mob) comma = OldTex(",", **kw) commas.add(comma) result.add(comma) result.remove(commas[-1]) commas.remove(commas[-1]) result.add(OldTex("]", **kw)) result.arrange(RIGHT, buff=0.1) commas.set_y(result[1].get_y(DOWN)) elements.set_color(color) result.elements = elements result.commas = commas return result class BigPolynomials(InteractiveScene): def construct(self): # Initialize grid N = 8 height = 6.5 grid = Square().get_grid(N, N, height=height, buff=0, group_by_rows=True) grid.set_stroke(WHITE, 1) grid.to_edge(DOWN, buff=MED_SMALL_BUFF) grid.shift(2 * LEFT) for i, row in enumerate(grid): if i == N - 2: for j, square in enumerate(row): if j == N - 2: self.replace_square(square, OldTex(R"\ddots")) else: self.replace_square(square, OldTex(R"\vdots")) else: self.replace_square(row[N - 2], OldTex(R"\cdots")) self.add(grid) # Polynomial terms a_terms, b_terms = all_terms = [ VGroup(*( Tex(RF"{letter}_{{{n}}} x^{{{n}}}", font_size=24) for n in (*range(N - 1), 99) )) for letter in ["a", "b"] ] for terms in all_terms: terms[0].remove(*terms[0][-2:]) terms[1].remove(*terms[1][-1:]) for terms, group, vect in [(a_terms, grid[0], UP), (b_terms, grid, LEFT)]: for term, square in zip(terms, group): term.next_to(square, vect, SMALL_BUFF) a_terms[-2].become(OldTex(R"\cdots", font_size=24).move_to(a_terms[-2]).shift(0.02 * DOWN)) b_terms[-2].become(OldTex(R"\vdots", font_size=24).move_to(b_terms[-2])) a_terms.set_color(BLUE_C) b_terms.set_color(TEAL_C) self.add(a_terms) self.add(b_terms) # Plusses for terms, vect in (a_terms, RIGHT), (b_terms, DOWN): terms.plusses = VGroup() for t1, t2 in zip(terms, terms[1:]): plus = OldTex("+", font_size=24).match_color(terms) plus.move_to(midpoint(t1.get_corner(vect), t2.get_corner(-vect))) terms.plusses.add(plus) self.add(terms.plusses) # Product terms prod_terms = VGroup() diags = VGroup(*(VGroup() for n in range(11))) for i, row in enumerate(grid): pre_b = b_terms[i][:2] if i == N - 2: continue if i == N - 1: i = 99 for j, square in enumerate(row): pre_a = a_terms[j][:2] if j == N - 2: continue if j == N - 1: j = 99 term = OldTex(f"a_{{{j}}}", f"b_{{{i}}}", f"x^{{{i + j}}}", font_size=20) if i + j == 0: term[2].remove(*term[2][:-2]) elif i + j == 1: term[2].remove(term[2][:-2]) term[0].match_color(a_terms) term[1].match_color(b_terms) term.set_max_width(0.9 * square.get_width()) term.pre_a = pre_a term.pre_b = pre_b term.move_to(square) prod_terms.add(term) if i + j < len(diags): diags[i + j].add(term) # Animate a_label = Text("100 terms", font_size=30) a_label.next_to(a_terms, UP) b_label = Text("100 terms", font_size=30) b_label.next_to(b_terms, UP, MED_LARGE_BUFF, aligned_edge=RIGHT) product_count = OldTexText(R"$100 \times 100 = 10{,}000$ \\ products", font_size=60) product_count.move_to(midpoint(grid.get_right(), RIGHT_SIDE)) self.play( FlashAround(a_terms, run_time=2, time_width=2), FadeIn(a_label) ) self.play( FlashAround(b_terms, run_time=2, time_width=2), FadeIn(b_label), FadeOut(a_label) ) self.play(FadeOut(b_label)) self.wait() self.play( LaggedStart(*( AnimationGroup( TransformFromCopy(term.pre_a, term[0]), TransformFromCopy(term.pre_b, term[1]), FadeIn(term[2], rate_func=squish_rate_func(smooth, 0.5, 1)), ) for term in prod_terms ), lag_ratio=0.1, run_time=5), Write(product_count), ) self.add(prod_terms) # Group along diagonals self.play(prod_terms.animate.set_opacity(0.2)) for n in range(len(diags)): diags.generate_target() diags.target.set_opacity(0.2) diags.target[n].set_opacity(1.0) self.play(MoveToTarget(diags)) self.wait() def replace_square(self, square, mob): mob.move_to(square) mob.set_max_width(square.get_width() / 2) mob.set_max_height(square.get_width() / 2) square.set_opacity(0) square.add(mob) class FunctionToCoefficientCommutativeDiagram(InteractiveScene): def construct(self): # Axes axes1, axes2, axes3 = all_axes = VGroup(*( Axes((-3, 3), (-2, 4), width=6, height=4) for x in range(3) )) all_axes.arrange(RIGHT, buff=1.0) axes3.shift(4 * RIGHT) all_axes.set_width(FRAME_WIDTH - 1) all_axes.move_to(UP) # Graphs def p1(x): return 0.2 * (x + 3) * x * (x - 2) def p2(x): return -0.1 * (x + 2) * (x - 2) * (x - 3) graphs = VGroup( axes1.get_graph(p1).set_stroke(BLUE), axes2.get_graph(p2).set_stroke(TEAL), axes3.get_graph(lambda x: p1(x) * p2(x)).set_stroke(YELLOW), ) graphs.set_stroke(width=2) kw = dict(font_size=30) graph_labels = VGroup(*( Tex(tex, **kw).next_to(axes.get_top(), RIGHT, aligned_edge=UP) for tex, axes in zip(["f(x)", "g(x)", R"f(x) \cdot g(x)"], all_axes) )) # Coefficients a_labels, b_labels, conv_label = coef_labels = VGroup( Tex(R"(a_0, a_1, \dots, a_n)", **kw), Tex(R"(b_0, b_1, \dots, b_m)", **kw), VGroup( Tex("c_0 = a_0 b_0", **kw), Tex("c_1 = a_0 b_1 + a_1 b_0", **kw), Tex("c_2 = a_0 b_2 + a_1 b_1 + a_2 b_0", **kw), Tex("c_3 = a_0 b_3 + a_1 b_2 + a_2 b_1 + a_3 b_0", **kw), Tex(R"\vdots", **kw), ).arrange(DOWN, aligned_edge=LEFT).scale(0.85) ) v_arrows = VGroup() for labels, graph, axes in zip(coef_labels, graphs, all_axes): arrow = Vector(0.8 * DOWN) arrow.next_to(axes, DOWN) v_arrows.add(arrow) labels.next_to(arrow, DOWN) labels.match_color(graph) arrow_label = Text("Coefficients", font_size=24) arrow_label.next_to(arrow, RIGHT, buff=0.2) arrow.add(arrow_label) conv_label.to_edge(RIGHT, buff=SMALL_BUFF) # Operations mult_arrow = Arrow(axes2, axes3, buff=0.1, stroke_width=6) mult_arrow_label = Text("Multiplication", font_size=30) mult_arrow_label.next_to(mult_arrow, UP, SMALL_BUFF) mult_arrow = VGroup(mult_arrow, mult_arrow_label) mult_arrow.set_color(RED) coef_rect = SurroundingRectangle(coef_labels[:2]) coef_rect.set_stroke(GREY, 2) conv_arrow = Arrow(coef_rect, conv_label[0], buff=0.3, stroke_width=6) conv_arrow_label = Text("Convolution", font_size=30) conv_arrow_label.next_to(conv_arrow, DOWN, SMALL_BUFF) conv_arrow = VGroup(conv_arrow, conv_arrow_label) conv_arrow.set_color(RED) # Animations self.play( LaggedStartMap(ShowCreation, graphs[:2]), LaggedStartMap(FadeIn, graph_labels[:2]), LaggedStartMap(FadeIn, all_axes[:2]), ) self.play(LaggedStart( Write(mult_arrow, run_time=1), TransformFromCopy(graphs[0], graphs[2].copy(), remover=True), TransformFromCopy(graphs[1], graphs[2]), TransformFromCopy(all_axes[0], all_axes[2].copy(), remover=True), TransformFromCopy(all_axes[1], all_axes[2]), TransformFromCopy(graph_labels[0], graph_labels[2][:5]), TransformFromCopy(graph_labels[1], graph_labels[2][5:]), ), lag_ratio=0.2) self.wait() self.play( LaggedStartMap(Write, v_arrows[:2], lag_ratio=0.7), LaggedStartMap(FadeIn, coef_labels[:2], shift=DOWN, lag_ratio=0.7), ) self.wait() self.play(ShowCreation(coef_rect), FadeIn(conv_arrow)) self.play( FadeTransformPieces(a_labels.copy(), conv_label), FadeTransformPieces(b_labels.copy(), conv_label), ) # Pointwise product all_dots = Group(*( Group(*( GlowDot(axes.i2gp(x, graph), radius=0.1, glow_factor=0.8, color=WHITE) for x in range(-3, 4) )) for axes, graph in zip(all_axes, graphs) )) all_circles = VGroup(*( VGroup(*( Circle(radius=0.1).set_stroke(YELLOW, 2).move_to(dot) for dot in dots )) for dots in all_dots )) self.play( LaggedStartMap(FadeIn, all_dots[0], scale=0.5, lag_ratio=0.5), LaggedStartMap(FadeIn, all_dots[1], scale=0.5, lag_ratio=0.5), ) self.wait() self.play( ShowSubmobjectsOneByOne(all_circles[0]), ShowSubmobjectsOneByOne(all_circles[1]), ShowSubmobjectsOneByOne(all_circles[2]), ShowIncreasingSubsets(all_dots[2]), run_time=4, rate_func=linear, ) self.remove(all_circles) self.wait() self.play(Write(v_arrows[2])) self.wait() class DataPointsToPolynomial(InteractiveScene): def construct(self): # Axes axes = Axes((-1, 10), (-3, 3), width=FRAME_WIDTH - 2, height=4) kw = dict(font_size=30) axes.add(OldTex("x", **kw).next_to(axes.x_axis.get_end(), DR, buff=0.2)) axes.add(OldTex("y", **kw).next_to(axes.y_axis.get_end(), LEFT, MED_SMALL_BUFF)) self.add(axes) # Graphs and data points y_values = [3, 1, 2, -3, -1, 2, 0, 0, 1] data = list(enumerate(y_values)) dots = Group(*( GlowDot(axes.c2p(x, y), glow_factor=0.8, radius=0.1) for x, y in data )) dots.set_color(TEAL) circles = VGroup(*( Circle(radius=0.075).set_stroke(YELLOW, 2).move_to(dot) for dot in dots )) graphs = VGroup(*( axes.get_graph(get_lagrange_polynomial(data[:n])) for n in range(1, len(data) + 1) )) graphs.set_stroke(BLUE, 2) # Increasing polynomials poly_tex = OldTex( "a_0", "+", "a_1 x", "+", *it.chain(*( (f"a_{n} x^{n}", "+") for n in range(2, len(data) - 1) )) ) poly_tex.to_corner(UR) graph = graphs[1].copy() self.play( LaggedStartMap(FadeIn, dots[:2], lag_ratio=0.7, run_time=1), LaggedStartMap(ShowCreationThenFadeOut, circles[:2], lag_ratio=0.2, run_time=1), ) self.play( ShowCreation(graph), FadeIn(poly_tex[:3]) ) self.wait() for n in range(2, len(data) - 1): self.play( ShowCreationThenFadeOut(circles[n], run_time=1.5), FadeIn(dots[n]), Transform(graph, graphs[n]), FadeIn(poly_tex[2 * n - 1:2 * n + 1], time_span=(0, 1), lag_ratio=0.1), run_time=2 ) self.wait() class PolynomialSystem(InteractiveScene): N = 8 def construct(self): # Setup polynomials frame = self.camera.frame N = self.N coefs = VGroup(*(Tex(Rf"c_{{{n}}}") for n in range(N))) coefs.set_submobject_colors_by_gradient(BLUE, TEAL) x_powers = VGroup(*(Tex(Rf"x^{{{n}}}") for n in range(N))) poly_x = self.get_polynomial(coefs, x_powers) top_lhs = Tex("h(x) = ") top_lhs.next_to(poly_x[0][0], LEFT, buff=0.1) top_eq = VGroup(top_lhs, poly_x) top_eq.center() fg = Tex(R"f(x) \cdot g(x)") eq = Tex("=") eq.rotate(PI / 2) eq.next_to(top_lhs[:4], UP) fg.next_to(eq, UP).shift_onto_screen() self.add(top_eq) # Suppose you don't know coefficients words = Text("Suppose these are a mystery") words.next_to(poly_x, UP, buff=2.0) arrows = VGroup(*( Arrow( interpolate( words.get_corner(DL) + 0.5 * RIGHT, words.get_corner(DR) + 0.5 * LEFT, n / (N - 1)), coef, color=coef.get_color(), ) for n, coef in enumerate(poly_x.coefs) )) self.play( FadeIn(words, lag_ratio=0.1), LaggedStartMap(GrowArrow, arrows), LaggedStart(*( FlashAround(coef, time_width=1) for coef in poly_x.coefs ), lag_ratio=0.1, run_time=3) ) self.wait() self.play( Write(eq), FadeIn(fg, 0.25 * UP) ) self.wait() # Sweep away self.play( LaggedStart( FadeOut(words, UP), FadeOut(arrows, 2 * UP, lag_ratio=0.05), FadeOut(fg, UP), FadeOut(eq, 1.5 * UP), top_eq.animate.to_edge(UP) ), frame.animate.set_height(11, about_edge=UR), run_time=2 ) # Set up the large system lhss = VGroup(*(Tex(f"h({n})=") for n in range(N))) rhss = VGroup(*( self.get_polynomial( coefs.copy(), # VGroup(*(Integer(x**n) for n in range(N))) VGroup(*(Tex(f"{x}^{{{n}}}") for n in range(N))) ) for x in range(N) )) equations = VGroup() for lhs, rhs in zip(lhss, rhss): lhs.next_to(rhs[0][0], LEFT, 0.1) equations.add(VGroup(lhs, rhs)) equations.arrange(DOWN, buff=0.5, aligned_edge=LEFT) equations.next_to(top_eq, DOWN, aligned_edge=LEFT, buff=1.5) self.play( LaggedStart(*( FadeTransform(top_eq.copy(), eq) for eq in equations ), lag_ratio=0.02, run_time=3), ) # Suppose you _do_ know h(0), h(1), h(2), etc. words2 = Text("But suppose\nyou do know\nthese", t2s={"do": ITALIC}) words2.set_color(YELLOW) words2.move_to(midpoint(equations.get_left(), frame.get_left())) words2.align_to(equations, UP) self.play( Write(words2), LaggedStart(*(FlashAround(lhs[:4], time_width=1.5) for lhs in lhss), run_time=5, lag_ratio=0.1) ) self.wait() # Trow out the inputs inputs = VGroup(*(lhs[2] for lhs in lhss)) inputs.save_state() consts = VGroup(*( power for eq in rhss for power in eq.powers )) boxes = VGroup(*(VGroup(SurroundingRectangle(const, buff=0)) for const in consts)) boxes.set_stroke(RED, 1) self.play( FadeOut(words2, LEFT, rate_func=running_start), inputs.animate.set_color(RED).shift(2 * LEFT).set_anim_args(run_time=1.5, lag_ratio=0.2, path_arc=PI / 2), Transform(consts, boxes, lag_ratio=0.01, run_time=3), ) self.play(FadeOut(inputs, LEFT, lag_ratio=0.2, rate_func=running_start)) inputs.restore() inputs.set_opacity(0) self.add(lhss) # Add roots of unity kw = dict(tex_to_color_map={R"\omega": YELLOW}) omega_def = OldTex( Rf""" \text{{Let }} \omega = e^{{2\pi i / {N}}} \qquad \text{{Notice }} \omega^{{{N}}} = 1 """, font_size=60, **kw ) omega_def.next_to(lhss, UP, buff=1.5, aligned_edge=LEFT) all_omega_powers = [ VGroup(*( Tex(Rf"\omega^{{{(k * n) % N}}}", **kw) for n in range(N) )) for k in range(0, N) ] new_rhss = VGroup(*( self.get_polynomial(coefs.copy(), omega_powers) for omega_powers in all_omega_powers )) new_lhss = VGroup( *(Tex(Rf"h(\omega^{n}) = ") for n in range(N)) ) self.play( frame.animate.set_height(13, about_edge=DR), FadeIn(omega_def), top_eq.animate.shift(1.75 * UP), ) for old_lhs, old_rhs, new_lhs, new_rhs in zip(lhss, rhss, new_lhss, new_rhss): new_lhs.move_to(old_lhs, LEFT) new_rhs.next_to(new_lhs, RIGHT, buff=0.1) new_lhs[2].set_color(YELLOW) self.play( FadeTransformPieces(old_lhs, new_lhs), FadeTransformPieces(old_rhs, new_rhs), ) self.wait() # Label as DFT brace = Brace(new_lhss, LEFT) kw = dict(font_size=60) label = OldTexText(R"Discrete\\Fourier\\Transform", alignment=R"\raggedright", isolate=list("DFT"), **kw) label.next_to(brace, LEFT) sub_label = OldTexText("of $(c_i)$", **kw)[0] sub_label[2:].set_color(BLUE) sub_label.next_to(label, DOWN, MED_LARGE_BUFF, aligned_edge=LEFT) self.play(GrowFromCenter(brace), FadeIn(label)) self.play(Write(sub_label)) self.wait() # Show redundancy last_rects = VGroup() for n in range(N): tex = Rf"\omega^{{{n}}}" rects = VGroup() for rhs in new_rhss: for power in rhs.powers[1:]: if power.get_tex() == tex: rects.add(SurroundingRectangle(power)) rects.set_stroke(RED, 3) self.play(FadeIn(rects), FadeOut(last_rects)) last_rects = rects self.play(FadeOut(last_rects)) # Set up two arrays pre_h_list = VGroup(*(lhs[:5] for lhs in new_lhss)) h_list = pre_h_list.copy() h_list.next_to(new_lhss, LEFT, buff=2.0) h_rect = SurroundingRectangle(h_list, buff=0.25) h_rect.set_stroke(WHITE, 1) h_rect.set_fill(GREY_E, 1) c_list = poly_x.coefs.copy() for c, h in zip(c_list, h_list): c.scale(1.25) c.move_to(h) c_rect = h_rect.copy() c_rect.shift(5 * LEFT) c_list.move_to(c_rect) short_label = OldTexText("DFT", isolate=list("DFT")) short_label.next_to(h_rect, UP, buff=0.5).shift(sub_label.get_width() * LEFT / 2) self.play( FadeIn(c_rect), TransformFromCopy(new_rhss[0].coefs, c_list, path_arc=-PI / 3) ) self.play( TransformMatchingTex(label, short_label), sub_label.animate.scale(48 / 60).next_to(short_label, RIGHT), FadeInFromPoint(h_rect, pre_h_list.get_center()), TransformFromCopy(pre_h_list, h_list), ) # Indicate fast back and forth top_arrow = Arrow(c_rect, h_rect).shift(2 * UP) low_arrow = Arrow(h_rect, c_rect).shift(2 * DOWN) for arrow in (top_arrow, low_arrow): fft_label = Text("FFT") fft_label.next_to(arrow, UP) run_time = OldTex(R"\mathcal{O}\big(N\log(N)\big)") run_time.next_to(arrow, DOWN) arrow.fft_label = fft_label arrow.run_time = run_time self.play( GrowArrow(arrow), FadeIn(fft_label, arrow.get_vector()) ) self.play(FadeIn(run_time, 0.5 * DOWN)) self.wait() def get_polynomial(self, coefs, powers, buff=0.1): result = VGroup() result.plusses = VGroup() result.dots = VGroup() for coef, power in zip(coefs, powers): if power is powers[0]: power.scale(0, about_edge=LEFT) plus = OldTex("+") # Font size? result.add(coef) if isinstance(power, Integer): dot = OldTex(R"\cdot") else: dot = VGroup(VectorizedPoint()) result.dots.add(dot) result.add(dot) result.add(power, plus) result.plusses.add(plus) result.remove(result[-1]) # Stray plus result.arrange(RIGHT, buff=buff) for mob in result: mob.shift(mob[0].get_y(DOWN) * DOWN) for coef, dot in zip(coefs, result.dots): if not isinstance(dot, Tex): coef.shift(buff * RIGHT) result.dots.set_y(result.get_y()) result.coefs = coefs result.powers = powers return result class RootsOfUnity(InteractiveScene): def construct(self): # Add plane plane = ComplexPlane((-2, 2), (-2, 2)) plane.scale(2.0 / 1.5) plane.to_corner(UL) plane.add_coordinate_labels([1, 1j], font_size=24) circle = Circle(radius=plane.x_axis.get_unit_size()) circle.move_to(plane.n2p(0)) circle.set_stroke(YELLOW, 2) N = 8 roots = [np.exp(TAU * 1j * k / N) for k in range(N)] root_dots = Group(*(GlowDot(plane.n2p(root)) for root in roots)) root_lines = VGroup(*(Line(plane.n2p(0), d.get_center()) for d in root_dots)) root_lines.set_stroke(YELLOW, 1) self.add(plane) self.add(root_lines[0], root_dots[0]) self.play( ShowCreation(circle), Rotate(Group(root_lines[0], root_dots[0]), TAU, about_point=plane.n2p(0)), run_time=2, ) self.wait() # Show powers kw = dict(tex_to_color_map={R"\omega": YELLOW}, font_size=36) max_power = 3 * N powers = VGroup(*( OldTex(Rf"\omega^{{{k}}}", **kw) for k in range(max_power) )) powers.set_backstroke(BLACK, 3) for power, line in zip(powers, it.cycle(root_lines)): vect = line.get_vector() vect += UP if line.get_vector()[1] > -0.1 else DOWN vect += RIGHT if line.get_vector()[0] > -0.1 else LEFT power.next_to(line.get_end(), normalize(vect), buff=SMALL_BUFF) shown_powers = VGroup(powers[0]) moving_power = powers[0].copy() for k in range(max_power - 1): shown_powers.generate_target() shown_powers.target.set_opacity(0.8) if k > N - 1: shown_powers.target[(k + 1) % N].set_opacity(0) kw = dict(path_arc=TAU / N) self.play( Transform(moving_power, powers[k + 1], **kw), Transform(root_lines[k % N].copy(), root_lines[(k + 1) % N], remover=True, **kw), Transform(root_dots[k % N].copy(), root_dots[(k + 1) % N], remover=True, **kw), MoveToTarget(shown_powers, **kw), ) self.add(root_lines[:k + 2], root_dots[:k + 2]) if k < N - 1: shown_powers.add(powers[k + 1]) self.play( FadeOut(moving_power), powers[:N].animate.set_opacity(1) ) self.wait() class AlgorithmOutline(InteractiveScene): def construct(self): # Title title = Text("Fast(?) convolution algorithm") title.to_edge(UP, buff=0.35) title.set_backstroke(BLACK, 3) underline = Underline(title, buff=-0.05).scale(1.5) underline.insert_n_curves(20) underline.set_stroke(GREY, (0, 3, 3, 3, 0)) self.add(underline, title) # Arrays t2c = { tex: BLUE for tex in [R"\textbf{a}", "a_0", "a_1", "a_2", "a_{n - 1}"] } t2c.update({ tex: TEAL for tex in [R"\textbf{b}", "b_0", "b_1", "b_2", "b_{m - 1}"] }) tex_kw = dict(tex_to_color_map=t2c, font_size=36) lists = VGroup( Tex(R"\textbf{a} = [a_0, a_1, a_2, \dots, a_{n - 1}]", **tex_kw), Tex(R"\textbf{b} = [b_0, b_1, b_2, \dots, b_{m - 1}]", **tex_kw), Tex(R"""\textbf{a} * \textbf{b} = \left[\begin{array}{l} a_0 b_0, \\ a_0 b_1 + a_1 b_0, \\ a_0 b_2 + a_1 b_1 + a_2 b_0, \\ \quad \vdots \\ a_{n - 1} b_{m - 1} \end{array}\right]""", **tex_kw), ) lists.arrange(DOWN, buff=1.7, aligned_edge=LEFT) lists.next_to(underline, DOWN, LARGE_BUFF) lists.to_edge(LEFT) lists[2][4:].scale(0.7, about_edge=LEFT) lists[2].refresh_bounding_box() lists[2].to_edge(DOWN, buff=MED_SMALL_BUFF) conv_rect = SurroundingRectangle(lists[2], buff=SMALL_BUFF) conv_rect.set_stroke(YELLOW, 2) q_marks = Text("???", color=YELLOW) q_marks.next_to(conv_rect, RIGHT, MED_SMALL_BUFF) self.add(lists[:2]) self.play(ShowCreation(underline)) self.play( TransformMatchingShapes(VGroup(*lists[0], *lists[1]).copy(), lists[2]), FadeIn(conv_rect), FadeIn(q_marks), ) self.wait() # Show polynomials polys = VGroup( Tex(R"f(x) = a_0 + a_1 x + a_2 x^2 + \cdots + a_{n - 1}x^{n - 1}", **tex_kw), Tex(R"g(x) = b_0 + b_1 x + b_2 x^2 + \cdots + b_{m - 1}x^{m - 1}", **tex_kw), ) for poly, listy in zip(polys, lists): poly.next_to(listy, DOWN, aligned_edge=LEFT) axes = VGroup(*( Axes((-3, 3), (-2, 2), width=5, height=1.5) for x in range(3) )) axes.to_edge(RIGHT) axes[0].match_y(polys[0]) axes[1].match_y(polys[1]) axes[2].move_to(2 * axes[1].get_origin() - axes[0].get_origin()) def f(x): return 0.2 * (x + 3) * (x + 1) * (x - 2) def g(x): return 0.1 * (x + 2) * (x + 0) * (x - 3.25) graphs = VGroup( axes[0].get_graph(f, color=BLUE), axes[1].get_graph(g, color=TEAL), axes[2].get_graph(lambda x: f(x) * g(x), color=YELLOW), ) graphs.set_stroke(width=2) label_kw = dict(font_size=24) graph_labels = VGroup( Tex("f(x)", **label_kw).move_to(axes[0], UL), Tex("g(x)", **label_kw).move_to(axes[1], UL), Tex(R"f(x) \cdot g(x)", **label_kw).move_to(axes[2], UL), ) self.play( LaggedStart(*( TransformFromCopy(listy.copy(), poly) for listy, poly in zip(lists, polys) )), LaggedStartMap(FadeIn, axes[:2]), LaggedStartMap(ShowCreation, graphs[:2]), LaggedStartMap(FadeIn, graph_labels[:2]), lag_ratio=0.5, ) self.wait() # Show samples x_samples = np.arange(-3, 3.5, 0.5) f_points, g_points, fg_points = all_points = [ [ax.i2gp(x, graph) for x in x_samples] for ax, graph in zip(axes, graphs) ] f_dots, g_dots, fg_dots = all_dots = Group(*( Group(*(GlowDot(point, color=WHITE, glow_factor=0.8, radius=0.07) for point in points)) for points in all_points )) self.play( FadeIn(f_dots, lag_ratio=0.7), FadeIn(g_dots, lag_ratio=0.7), run_time=5 ) self.wait() self.play( TransformFromCopy(axes[1], axes[2]), TransformMatchingShapes(graph_labels[:2].copy(), graph_labels[2]), LaggedStart(*( Transform(Group(fd, gd).copy(), Group(fgd), remover=True) for fd, gd, fgd in zip(*all_dots) ), lag_ratio=0.5, run_time=5) ) self.add(fg_dots) self.play(ShowCreation(graphs[2], run_time=2)) self.wait() # Show arrow final_arrow = Arrow(graph_labels[2], conv_rect.get_corner(UR), path_arc=PI / 5) final_arrow.set_color(RED) self.play(Write(final_arrow)) self.wait() # Erase graphs crosses = VGroup(*map(Cross, axes[:2])) for cross in crosses: cross.insert_n_curves(20) cross.set_stroke(RED, (0, 10, 10, 10, 0)) self.play( LaggedStartMap(ShowCreation, crosses, lag_ratio=0.5, run_time=2), polys[0].animate.scale(0.5, about_edge=DL), polys[1].animate.scale(0.5, about_edge=DL), LaggedStartMap(FadeOut, Group( final_arrow, axes[2], graph_labels[2], fg_dots, graphs[2], q_marks, )) ) self.play( LaggedStartMap(FadeOut, Group( axes[0], graphs[0], graph_labels[0], f_dots, crosses[0], axes[1], graphs[1], graph_labels[1], g_dots, crosses[1], ), shift=0.2 * RIGHT) ) # Show FFTs t2c = { tex: RED for tex in [R"\hat{\textbf{a}}", R"\hat{a}_0", R"\hat{a}_1", R"\hat{a}_2", R"\hat{a}_{m + n - 1}"] } t2c.update({ tex: MAROON_C for tex in [R"\hat{\textbf{b}}", R"\hat{b}_0", R"\hat{b}_1", R"\hat{b}_2", R"\hat{b}_{m + n - 1}"] }) fft_kw = dict(tex_to_color_map=t2c, font_size=36, isolate=["="]) fft_lists = VGroup( Tex(R"\hat{\textbf{a}} = [\hat{a}_0, \hat{a}_1, \hat{a}_2, \dots, \hat{a}_{m + n - 1}]", **fft_kw), Tex(R"\hat{\textbf{b}} = [\hat{b}_0, \hat{b}_1, \hat{b}_2, \dots, \hat{b}_{m + n - 1}]", **fft_kw), Tex(R"""\hat{\textbf{a}} \cdot \hat{\textbf{b}} = [ \hat{a}_0 \hat{b}_0, \hat{a}_1 \hat{b}_1, \hat{a}_2 \hat{b}_2, \dots, ]""", **fft_kw), ) for fft_list in fft_lists: fft_list.shift(-fft_list.select_part("=").get_center()) fft_lists.to_edge(RIGHT) arrows = VGroup() arrow_labels = VGroup() for orig_list, fft_list, n in zip(lists, fft_lists, it.count()): fft_list.match_y(orig_list) arrow = Arrow(orig_list, fft_list, buff=0.3) arrow.label = Text("Inverse FFT" if n == 2 else "FFT", font_size=36) arrow.label.next_to(arrow, UP) arrow_labels.add(arrow.label) arrows.add(arrow) arrows[2].rotate(PI) mult_arrow = Vector(2 * DOWN).move_to(VGroup(fft_lists[1], fft_lists[2]).get_center()) mult_arrow.label = Text("Multiply\n(pointwise)", font_size=36) mult_arrow.label.next_to(mult_arrow, RIGHT) kw = dict(lag_ratio=0.75, run_time=2) self.play( title[:4].animate.match_x(title[4:7], RIGHT), FadeOut(title[4:7], 0.1 * DOWN, lag_ratio=0.1), ) self.play( LaggedStartMap(FadeIn, fft_lists[:2], shift=1.5 * RIGHT, **kw), LaggedStartMap(GrowArrow, arrows[:2], **kw), LaggedStartMap(FadeIn, arrow_labels[:2], shift=0.5 * RIGHT, **kw), ) self.wait() self.play(LaggedStart( polys[0].animate.scale(1.5, about_edge=DL), polys[1].animate.scale(1.5, about_edge=DL), lag_ratio=0.5, )) self.wait() self.play( FadeIn(fft_lists[2], DOWN), GrowArrow(mult_arrow), FadeIn(mult_arrow.label, 0.5 * DOWN) ) self.wait() self.play( GrowArrow(arrows[2]), FadeIn(arrow_labels[2], shift=LEFT), ) self.wait() # TODO class FourierCoefficients(InteractiveScene): def construct(self): # Axes axes = Axes((0, 1, 0.1), (0, 2), width=8, height=4) axes.add_coordinate_labels(font_size=24, num_decimal_places=1) axes.to_edge(DOWN) self.add(axes) def f(x): return max(np.exp(-x**2) + math.cos(2 * PI * x) - 0.2 * math.sin(4 * PI * x), 0.25) graph = axes.get_graph(f) graph.set_stroke(BLUE, 2) self.add(graph) # Coefficients exp = R"{\left(e^{2\pi i \cdot t}\right)}" kw = dict(tex_to_color_map={ "{x}": BLUE, exp: TEAL, }) equations = VGroup( Tex(R"f(x) = c_0 + c_1 {x} + c_2 {x}^2 + c_3 {x}^3 + \dots", **kw), Tex(Rf"f(t) = c_0 + c_1 {exp} + c_2 {exp}^2 + c_3 {exp}^3 + \dots", **kw), Tex(Rf"f(t) = \cdots + c_{{-1}} {exp}^{{-1}} + c_0 + c_1 {exp} + c_2 {exp}^2 + \dots", **kw), # Tex(R"f(t) = \cdots + \hat f(-1) e^{-2\pi i t} + \hat f(0) + \hat f(1) e^{2\pi i t} + \hat f(2) e^{2\pi i \cdot 2t} + \dots"), ) equations = VGroup last = VMobject() last.move_to(FRAME_HEIGHT * UP / 2) for equation in equations: equation.next_to(last, DOWN, MED_LARGE_BUFF) self.play(FadeIn(equation, DOWN)) self.wait() self.play( FadeOut(last, UP), equation.animate.to_edge(UP) ) last = equation class EndScreen(PatreonEndScreen): pass
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from manim_imports_ext import * ARROW_CONFIG = {"stroke_width" : 2*DEFAULT_STROKE_WIDTH} LIGHT_RED = RED_E def matrix_to_string(matrix): return "--".join(["-".join(map(str, row)) for row in matrix]) def matrix_mobject(matrix): return OldTexText( """ \\left( \\begin{array}{%s} %d & %d \\\\ %d & %d \\end{array} \\right) """%tuple(["c"*matrix.shape[1]] + list(matrix.flatten())), size = "\\Huge" ) class ShowMultiplication(NumberLineScene): args_list = [ (2, True), (0.5, True), (-3, True), (-3, True), (2, True), (6, True), ] @staticmethod def args_to_string(num, show_original_line): end_string = "WithCopiedOriginalLine" if show_original_line else "" return str(num) + end_string @staticmethod def string_to_args(string): parts = string.split() if len(parts) == 2: num, original_line = parts show_original_line = original_line == "WithCopiedOriginalLine" return float(num), False else: return float(parts[0]), False def construct(self, num, show_original_line): config = { "density" : max(abs(num), 1)*DEFAULT_POINT_DENSITY_1D, "stroke_width" : 2*DEFAULT_STROKE_WIDTH } if abs(num) < 1: config["numerical_radius"] = FRAME_X_RADIUS/num NumberLineScene.construct(self, **config) if show_original_line: self.copy_original_line() self.wait() self.show_multiplication(num, run_time = 1.5) self.wait() def copy_original_line(self): copied_line = deepcopy(self.number_line) copied_num_mobs = deepcopy(self.number_mobs) self.play( ApplyFunction( lambda m : m.shift(DOWN).set_color("lightgreen"), copied_line ), *[ ApplyMethod(mob.shift, DOWN) for mob in copied_num_mobs ] ) self.wait() class ExamplesOfOneDimensionalLinearTransforms(ShowMultiplication): args_list = [] @staticmethod def args_to_string(): return "" def construct(self): for num in [2, 0.5, -3]: self.clear() ShowMultiplication.construct(self, num, False) class ExamplesOfNonlinearOneDimensionalTransforms(NumberLineScene): def construct(self): def sinx_plux_x(x_y_z): (x, y, z) = x_y_z return (np.sin(x) + 1.2*x, y, z) def shift_zero(x_y_z): (x, y, z) = x_y_z return (2*x+4, y, z) self.nonlinear = OldTexText("Not a Linear Transform") self.nonlinear.set_color(LIGHT_RED).to_edge(UP, buff = 1.5) pairs = [ (sinx_plux_x, "numbers don't remain evenly spaced"), (shift_zero, "zero does not remain fixed") ] for func, explanation in pairs: self.run_function(func, explanation) self.wait(3) def run_function(self, function, explanation): self.clear() self.add(self.nonlinear) config = { "stroke_width" : 2*DEFAULT_STROKE_WIDTH, "density" : 5*DEFAULT_POINT_DENSITY_1D, } NumberLineScene.construct(self, **config) words = OldTexText(explanation).set_color(LIGHT_RED) words.next_to(self.nonlinear, DOWN, buff = 0.5) self.add(words) self.play( ApplyPointwiseFunction(function, self.number_line), *[ ApplyMethod( mob.shift, function(mob.get_center()) - mob.get_center() ) for mob in self.number_mobs ], run_time = 2.0 ) class ShowTwoThenThree(ShowMultiplication): args_list = [] @staticmethod def args_to_string(): return "" def construct(self): config = { "stroke_width" : 2*DEFAULT_STROKE_WIDTH, "density" : 6*DEFAULT_POINT_DENSITY_1D, } NumberLineScene.construct(self, **config) self.copy_original_line() self.show_multiplication(2) self.wait() self.show_multiplication(3) self.wait() ######################################################## class TransformScene2D(Scene): def add_number_plane(self, density_factor = 1, use_faded_lines = True): config = { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "density" : DEFAULT_POINT_DENSITY_1D*density_factor, "stroke_width" : 2*DEFAULT_STROKE_WIDTH } if not use_faded_lines: config["x_faded_line_frequency"] = None config["y_faded_line_frequency"] = None self.number_plane = NumberPlane(**config) self.add(self.number_plane) def add_background(self): grey_plane = NumberPlane(color = "grey") num_mobs = grey_plane.get_coordinate_labels() self.paint_into_background(grey_plane, *num_mobs) def add_x_y_arrows(self): self.x_arrow = Arrow( ORIGIN, self.number_plane.num_pair_to_point((1, 0)), color = "lightgreen", **ARROW_CONFIG ) self.y_arrow = Arrow( ORIGIN, self.number_plane.num_pair_to_point((0, 1)), color = LIGHT_RED, **ARROW_CONFIG ) self.add(self.x_arrow, self.y_arrow) self.number_plane.filter_out( lambda x_y_z : (0 < x_y_z[0]) and (x_y_z[0] < 1) and (abs(x_y_z[1]) < 0.1) ) self.number_plane.filter_out( lambda x_y_z1 : (0 < x_y_z1[1]) and (x_y_z1[1] < 1) and (abs(x_y_z1[0]) < 0.1) ) return self class ShowMatrixTransform(TransformScene2D): args_list = [ ([[1, 3], [-2, 0]], False, False), ([[1, 3], [-2, 0]], True, False), ([[1, 0.5], [0.5, 1]], True, False), ([[2, 0], [0, 2]], True, False), ([[0.5, 0], [0, 0.5]], True, False), ([[-1, 0], [0, -1]], True, False), ([[0, 1], [1, 0]], True, False), ([[-2, 0], [-1, -1]], True, False), ([[0, -1], [1, 0]], True, False), ] @staticmethod def args_to_string(matrix, with_background, show_matrix): background_string = "WithBackground" if with_background else "WithoutBackground" show_string = "ShowingMatrix" if show_matrix else "" return matrix_to_string(matrix) + background_string + show_string def construct(self, matrix, with_background, show_matrix): matrix = np.array(matrix) number_plane_config = { "density_factor" : self.get_density_factor(matrix) } if with_background: self.add_background() number_plane_config["use_faded_lines"] = False self.add_number_plane(**number_plane_config) self.add_x_y_arrows() else: self.add_number_plane(**number_plane_config) if show_matrix: self.add(matrix_mobject(matrix).to_corner(UP+LEFT)) def func(mobject): mobject.get_points()[:, :2] = np.dot(mobject.get_points()[:, :2], np.transpose(matrix)) return mobject self.wait() kwargs = { "run_time" : 2.0, "path_func" : self.get_path_func(matrix) } anims = [ApplyFunction(func, self.number_plane, **kwargs)] if hasattr(self, "x_arrow") and hasattr(self, "y_arrow"): for arrow, index in (self.x_arrow, 0), (self.y_arrow, 1): new_arrow = Arrow( ORIGIN, self.number_plane.num_pair_to_point(matrix[:,index]), color = arrow.get_color(), **ARROW_CONFIG ) arrow.remove_tip() new_arrow.remove_tip() Mobject.align_data_and_family(arrow, new_arrow) arrow.add_tip() new_arrow.add_tip() anims.append(Transform(arrow, new_arrow, **kwargs)) self.play(*anims) self.wait() def get_density_factor(self, matrix): max_norm = max([ abs(get_norm(column)) for column in np.transpose(matrix) ]) return max(max_norm, 1) def get_path_func(self, matrix): rotational_components = np.array([ np.log(multiplier*complex(*matrix[:,i])).imag for i, multiplier in [(0, 1), (1, complex(0, -1))] ]) rotational_components[rotational_components == -np.pi] = np.pi return path_along_arc(np.mean(rotational_components)) class ExamplesOfTwoDimensionalLinearTransformations(ShowMatrixTransform): args_list = [] @staticmethod def args_to_string(): return "" def construct(self): matrices = [ [[1, 0.5], [0.5, 1]], [[0, -1], [2, 0]], [[1, 3], [-2, 0]], ] for matrix in matrices: self.clear() ShowMatrixTransform.construct(self, matrix, False, False) class ExamplesOfNonlinearTwoDimensionalTransformations(Scene): def construct(self): Scene.construct(self) def squiggle(x_y_z): (x, y, z) = x_y_z return (x+np.sin(y), y+np.cos(x), z) def shift_zero(x_y_z): (x, y, z) = x_y_z return (2*x + 3*y + 4, -1*x+y+2, z) self.nonlinear = OldTexText("Nonlinear Transform") self.nonlinear.set_color(LIGHT_RED) self.nonlinear.to_edge(UP, buff = 1.5) pairs = [ (squiggle, "lines do not remain straight"), (shift_zero, "the origin does not remain fixed") ] self.get_blackness() for function, explanation in pairs: self.apply_function(function, explanation) def apply_function(self, function, explanation): self.clear() config = { "x_radius" : FRAME_WIDTH, "y_radius" : FRAME_WIDTH, "density" : 3*DEFAULT_POINT_DENSITY_1D, "stroke_width" : 2*DEFAULT_STROKE_WIDTH } number_plane = NumberPlane(**config) numbers = number_plane.get_coordinate_labels() words = OldTexText(explanation) words.set_color(LIGHT_RED) words.next_to(self.nonlinear, DOWN, buff = 0.5) self.add(number_plane, *numbers) self.add(self.blackness, self.nonlinear, words) self.wait() self.play( ApplyPointwiseFunction(function, number_plane), *[ ApplyMethod( mob.shift, function(mob.get_center())-mob.get_center() ) for mob in numbers ] + [ Animation(self.blackness), Animation(words), Animation(self.nonlinear) ], run_time = 2.0 ) self.wait(3) def get_blackness(self): vertices = [ 3.5*LEFT+1.05*UP, 3.5*RIGHT+1.05*UP, 3.5*RIGHT+2.75*UP, 3.5*LEFT+2.75*UP, ] region = region_from_polygon_vertices(*vertices) image = disp.paint_region(region, color = WHITE) self.blackness = OldTexText("") ImageMobject.generate_points_from_image_array(self.blackness, image) self.blackness.set_color(BLACK) rectangle = Rectangle(width = 7, height=1.7) rectangle.set_color(WHITE) rectangle.shift(self.blackness.get_center()) self.blackness.add(rectangle) self.blackness.scale(0.95) class TrickyExamplesOfNonlinearTwoDimensionalTransformations(Scene): def construct(self): config = { "x_radius" : 0.6*FRAME_WIDTH, "y_radius" : 0.6*FRAME_WIDTH, "density" : 10*DEFAULT_POINT_DENSITY_1D, "stroke_width" : 2*DEFAULT_STROKE_WIDTH } number_plane = NumberPlane(**config) phrase1, phrase2 = OldTexText([ "These might look like they keep lines straight...", "but diagonal lines get curved" ]).to_edge(UP, buff = 1.5).split() phrase2.set_color(LIGHT_RED) diagonal = Line( DOWN*FRAME_Y_RADIUS+LEFT*FRAME_X_RADIUS, UP*FRAME_Y_RADIUS+RIGHT*FRAME_X_RADIUS, density = 10*DEFAULT_POINT_DENSITY_1D ) def sunrise(x_y_z): (x, y, z) = x_y_z return ((FRAME_Y_RADIUS+y)*x, y, z) def squished(x_y_z): (x, y, z) = x_y_z return (x + np.sin(x), y+np.sin(y), z) self.get_blackness() self.run_function(sunrise, number_plane, phrase1) self.run_function(squished, number_plane, phrase1) phrase1.add(phrase2) self.add(phrase1) self.play(ShowCreation(diagonal)) self.remove(diagonal) number_plane.add(diagonal) self.run_function(sunrise, number_plane, phrase1) self.run_function(squished, number_plane, phrase1, False) def run_function(self, function, plane, phrase, remove_plane = True): number_plane = deepcopy(plane) self.add(number_plane, self.blackness, phrase) self.wait() self.play( ApplyPointwiseFunction(function, number_plane, run_time = 2.0), Animation(self.blackness), Animation(phrase), ) self.wait(3) if remove_plane: self.remove(number_plane) def get_blackness(self): vertices = [ 4.5*LEFT+1.25*UP, 4.5*RIGHT+1.25*UP, 4.5*RIGHT+2.75*UP, 4.5*LEFT+2.75*UP, ] region = region_from_polygon_vertices(*vertices) image = disp.paint_region(region, color = WHITE) self.blackness = OldTexText("") ImageMobject.generate_points_from_image_array(self.blackness, image) self.blackness.set_color(BLACK) rectangle = Rectangle(width = 9, height=1.5) rectangle.set_color(WHITE) rectangle.shift(self.blackness.get_center()) self.blackness.add(rectangle) self.blackness.scale(0.95) ############# HORRIBLE! ########################## class ShowMatrixTransformWithDot(TransformScene2D): args_list = [ ([[1, 3], [-2, 0]], True, False), ] @staticmethod def args_to_string(matrix, with_background, show_matrix): background_string = "WithBackground" if with_background else "WithoutBackground" show_string = "ShowingMatrix" if show_matrix else "" return matrix_to_string(matrix) + background_string + show_string def construct(self, matrix, with_background, show_matrix): matrix = np.array(matrix) number_plane_config = { "density_factor" : self.get_density_factor(matrix), } if with_background: self.add_background() number_plane_config["use_faded_lines"] = False self.add_number_plane(**number_plane_config) self.add_x_y_arrows() else: self.add_number_plane(**number_plane_config) if show_matrix: self.add(matrix_mobject(matrix).to_corner(UP+LEFT)) def func(mobject): mobject.get_points()[:, :2] = np.dot(mobject.get_points()[:, :2], np.transpose(matrix)) return mobject dot = Dot((-1, 2, 0), color = "yellow") self.add(dot) x_arrow_copy = deepcopy(self.x_arrow) y_arrow_copy = Arrow(LEFT, LEFT+2*UP, color = LIGHT_RED, **ARROW_CONFIG) self.play(ApplyMethod(x_arrow_copy.rotate, np.pi)) self.play(ShowCreation(y_arrow_copy)) self.wait() self.remove(x_arrow_copy, y_arrow_copy) kwargs = { "run_time" : 2.0, "path_func" : self.get_path_func(matrix) } anims = [ ApplyFunction(func, self.number_plane, **kwargs), ApplyMethod(dot.shift, func(deepcopy(dot)).get_center()-dot.get_center(), **kwargs), ] if hasattr(self, "x_arrow") and hasattr(self, "y_arrow"): for arrow, index in (self.x_arrow, 0), (self.y_arrow, 1): new_arrow = Arrow( ORIGIN, self.number_plane.num_pair_to_point(matrix[:,index]), color = arrow.get_color(), **ARROW_CONFIG ) arrow.remove_tip() new_arrow.remove_tip() Mobject.align_data_and_family(arrow, new_arrow) arrow.add_tip() new_arrow.add_tip() anims.append(Transform(arrow, new_arrow, **kwargs)) self.play(*anims) self.wait() x_arrow_copy = deepcopy(self.x_arrow) y_arrow_copy = Arrow(LEFT+2*UP, 5*RIGHT+2*UP, color = LIGHT_RED, **ARROW_CONFIG) self.play(ApplyMethod(x_arrow_copy.rotate, np.pi)) self.play(ShowCreation(y_arrow_copy)) self.wait(3) self.remove(x_arrow_copy, y_arrow_copy) def get_density_factor(self, matrix): max_norm = max([ abs(get_norm(column)) for column in np.transpose(matrix) ]) return max(max_norm, 1) def get_path_func(self, matrix): rotational_components = [ sign*np.arccos(matrix[i,i]/get_norm(matrix[:,i])) for i in [0, 1] for sign in [((-1)**i)*np.sign(matrix[1-i, i])] ] average_rotation = sum(rotational_components)/2 if abs(average_rotation) < np.pi / 2: return straight_path elif average_rotation > 0: return counterclockwise_path() else: return clockwise_path() class Show90DegreeRotation(TransformScene2D): def construct(self): self.add_number_plane() self.add_background() self.add_x_y_arrows() self.wait() self.play(*[ RotationAsTransform(mob, run_time = 2.0) for mob in (self.number_plane, self.x_arrow, self.y_arrow) ]) self.wait()
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys import operator as op from random import sample from manim_imports_ext import * from script_wrapper import command_line_create_scene from functools import reduce # from inventing_math_images import * MOVIE_PREFIX = "inventing_math/" DIVERGENT_SUM_TEXT = [ "1", "+2", "+4", "+8", "+\\cdots", "+2^n", "+\\cdots", "= -1", ] CONVERGENT_SUM_TEXT = [ "\\frac{1}{2}", "+\\frac{1}{4}", "+\\frac{1}{8}", "+\\frac{1}{16}", "+\\cdots", "+\\frac{1}{2^n}", "+\\cdots", "=1", ] CONVERGENT_SUM_TERMS = [ "\\frac{1}{2}", "\\frac{1}{4}", "\\frac{1}{8}", "\\frac{1}{16}", ] PARTIAL_CONVERGENT_SUMS_TEXT = [ "\\frac{1}{2}", "", "", ",\\quad", "\\frac{1}{2} + \\frac{1}{4}", "=", "\\frac{3}{4}", ",\\quad", "\\frac{1}{2} + \\frac{1}{4} + \\frac{1}{8}", "=", "\\frac{7}{8}", ",\\quad", "\\frac{1}{2} + \\frac{1}{4} + \\frac{1}{8} + \\frac{1}{16}", "=", "\\frac{15}{16}", ",\\dots" ] def partial_sum(n): return sum([1.0/2**(k+1) for k in range(n)]) ALT_PARTIAL_SUM_TEXT = reduce(op.add, [ [str(partial_sum(n)), "&=", "+".join(CONVERGENT_SUM_TERMS[:n])+"\\\\"] for n in range(1, len(CONVERGENT_SUM_TERMS)+1) ])+ [ "\\vdots", "&", "\\\\", "1.0", "&=", "+".join(CONVERGENT_SUM_TERMS)+"+\\cdots+\\frac{1}{2^n}+\\cdots" ] NUM_WRITTEN_TERMS = 4 INTERVAL_RADIUS = 5 NUM_INTERVAL_TICKS = 16 def divergent_sum(): return OldTex(DIVERGENT_SUM_TEXT, size = "\\large").scale(2) def convergent_sum(): return OldTex(CONVERGENT_SUM_TEXT, size = "\\large").scale(2) def Underbrace(left, right): result = OldTex("\\Underbrace{%s}"%(14*"\\quad")) result.stretch_to_fit_width(right[0]-left[0]) result.shift(left - result.get_points()[0]) return result def zero_to_one_interval(): interval = NumberLine( radius = INTERVAL_RADIUS, interval_size = 2.0*INTERVAL_RADIUS/NUM_INTERVAL_TICKS ) interval.elongate_tick_at(-INTERVAL_RADIUS, 4) interval.elongate_tick_at(INTERVAL_RADIUS, 4) zero = OldTex("0").shift(INTERVAL_RADIUS*LEFT+DOWN) one = OldTex("1").shift(INTERVAL_RADIUS*RIGHT+DOWN) return Mobject(interval, zero, one) def draw_you(with_bubble = False): result = PiCreature() result.give_straight_face().set_color("grey") result.to_corner(LEFT+DOWN) result.rewire_part_attributes() if with_bubble: bubble = ThoughtBubble() bubble.stretch_to_fit_width(11) bubble.pin_to(result) return result, bubble return result def get_room_colors(): return list(Color("yellow").range_to("red", 4)) def power_of_divisor(n, d): result = 0 while n%d == 0: result += 1 n /= d return result class FlipThroughNumbers(Animation): def __init__(self, function = lambda x : x, start = 0, end = 10, start_center = ORIGIN, end_center = ORIGIN, **kwargs): self.function = function self.start = start self.end = end self.start_center = start_center self.end_center = end_center self.current_number = function(start) mobject = OldTex(str(self.current_number)).shift(start_center) Animation.__init__(self, mobject, **kwargs) def interpolate_mobject(self, alpha): new_number = self.function( self.start + int(alpha *(self.end-self.start)) ) if new_number != self.current_number: self.current_number = new_number self.mobject = OldTex(str(new_number)).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 ) ###################################### class IntroduceDivergentSum(Scene): def construct(self): equation = divergent_sum().split() sum_value = None brace = Underbrace( equation[0].get_boundary_point(DOWN+LEFT), equation[1].get_boundary_point(DOWN+RIGHT) ).shift(0.2*DOWN) min_x_coord = min(equation[0].get_points()[:,0]) for x in range(NUM_WRITTEN_TERMS): self.add(equation[x]) if x == 0: self.wait(0.75) continue brace.stretch_to_fit_width( max(equation[x].get_points()[:,0]) - min_x_coord ) brace.to_edge(LEFT, buff = FRAME_X_RADIUS+min_x_coord) if sum_value: self.remove(sum_value) sum_value = OldTex(str(2**(x+1) - 1)) sum_value.shift(brace.get_center() + 0.5*DOWN) self.add(brace, sum_value) self.wait(0.75) self.remove(sum_value) ellipses = Mobject( *[equation[NUM_WRITTEN_TERMS + i] for i in range(3)] ) end_brace = deepcopy(brace).stretch_to_fit_width( max(ellipses.get_points()[:,0])-min_x_coord ).to_edge(LEFT, buff = FRAME_X_RADIUS+min_x_coord) kwargs = {"run_time" : 5.0, "rate_func" : rush_into} flip_through = FlipThroughNumbers( lambda x : 2**(x+1)-1, start = NUM_WRITTEN_TERMS-1, end = 50, start_center = brace.get_center() + 0.5*DOWN, end_center = end_brace.get_center() + 0.5*DOWN, **kwargs ) self.add(ellipses) self.play( Transform(brace, end_brace, **kwargs), flip_through, ) self.clear() self.add(*equation) self.wait() class ClearlyNonsense(Scene): def construct(self): number_line = NumberLine().add_numbers() div_sum = divergent_sum() this_way = OldTexText("Sum goes this way...") this_way.to_edge(LEFT).shift(RIGHT*(FRAME_X_RADIUS+1) + DOWN) how_here = OldTexText("How does it end up here?") how_here.shift(1.5*UP+LEFT) neg_1_arrow = Arrow( (-1, 0.3, 0), tail=how_here.get_center()+0.5*DOWN ) right_arrow = Arrow( (FRAME_X_RADIUS-0.5)*RIGHT + DOWN, tail = (max(this_way.get_points()[:,0]), -1, 0) ) how_here.set_color("red") neg_1_arrow.set_color("red") this_way.set_color("yellow") right_arrow.set_color("yellow") self.play(Transform( div_sum, deepcopy(div_sum).scale(0.5).shift(3*UP) )) self.play(ShowCreation(number_line)) self.wait() self.add(how_here) self.play(ShowCreation(neg_1_arrow)) self.wait() self.add(this_way) self.play(ShowCreation(right_arrow)) self.wait() class OutlineOfVideo(Scene): def construct(self): conv_sum = convergent_sum().scale(0.5) div_sum = divergent_sum().scale(0.5) overbrace = Underbrace( conv_sum.get_left(), conv_sum.get_right() ).rotate(np.pi, RIGHT).shift(0.75*UP*conv_sum.get_height()) dots = conv_sum.split()[-2].set_color("green") dots.sort_points() arrow = Arrow( dots.get_bottom(), direction = UP+LEFT ) u_brace = Underbrace(div_sum.get_left(), div_sum.get_right()) u_brace.shift(1.5*div_sum.get_bottom()) for mob in conv_sum, overbrace, arrow, dots: mob.shift(2*UP) for mob in div_sum, u_brace: mob.shift(DOWN) texts = [ OldTexText(words).set_color("yellow") for words in [ "1. Discover this", "2. Clarify what this means", "3. Discover this", ["4. Invent ", "\\textbf{new math}"] ] ] last_one_split = texts[-1].split() last_one_split[1].set_color("skyblue") texts[-1] = Mobject(*last_one_split) texts[0].shift(overbrace.get_top()+texts[0].get_height()*UP) texts[1].shift(sum([ arrow.get_boundary_point(DOWN+RIGHT), texts[1].get_height()*DOWN ])) texts[2].shift(u_brace.get_bottom()+texts[3].get_height()*DOWN) texts[3].to_edge(DOWN) groups = [ [texts[0], overbrace, conv_sum], [texts[1], arrow, dots], [texts[2], u_brace, div_sum], [texts[3]] ] for group in groups: self.play(*[ DelayByOrder(FadeIn(element)) for element in group ]) self.wait() # # class ReasonsForMakingVideo(Scene): # # def construct(self): # # text = OldTexText([ # # """ # # \\begin{itemize} # # \\item Understand what ``$ # # """, # # "".join(DIVERGENT_SUM_TEXT), # # """ # # $'' is saying. # # """, # # """ # # \\item Nonsense-Driven Construction # # \\end{itemize} # # """ # # ], size = "\\Small") # # text.scale(1.5).to_edge(LEFT).shift(UP).set_color("white") # # text.set_color("green", lambda (x, y, z) : x < -FRAME_X_RADIUS + 1) # # line_one_first, equation, line_one_last, line_two = text.split() # # line_two.shift(2*DOWN) # # div_sum = divergent_sum().scale(0.5).shift(3*UP) # # self.add(div_sum) # # self.play( # # ApplyMethod(div_sum.replace, equation), # # FadeIn(line_one_first), # # FadeIn(line_one_last) # # ) # # self.wait() # # self.add(line_two) # # self.wait() # class DiscoverAndDefine(Scene): # def construct(self): # sum_mob = OldTex("\\sum_{n = 1}^\\infty a_n") # discover = OldTexText("What does it feel like to discover these?") # define = OldTexText([ # "What does it feel like to", # "\\emph{define} ", # "them?" # ]) # sum_mob.shift(2*UP) # define.shift(2*DOWN) # define_parts = define.split() # define_parts[1].set_color("skyblue") # self.add(sum_mob) # self.play(FadeIn(discover)) # self.wait() # self.play(FadeIn(Mobject(*define_parts))) # self.wait() class YouAsMathematician(Scene): def construct(self): you, bubble = draw_you(with_bubble = True) explanation = OldTexText( "You as a (questionably accurate portrayal of a) mathematician.", size = "\\small" ).shift([2, you.get_center()[1], 0]) arrow = Arrow(you.get_center(), direction = LEFT) arrow.nudge(you.get_width()) for mob in arrow, explanation: mob.set_color("yellow") equation = convergent_sum() bubble.add_content(equation) equation_parts = equation.split() equation.shift(0.5*RIGHT) bubble.clear() dot_pair = [ Dot(density = 3*DEFAULT_POINT_DENSITY_1D).shift(x+UP) for x in (LEFT, RIGHT) ] self.add(you, explanation) self.play( ShowCreation(arrow), BlinkPiCreature(you) ) self.wait() self.play(ShowCreation(bubble)) for part in equation_parts: self.play(DelayByOrder(FadeIn(part)), run_time = 0.5) self.wait() self.play( BlinkPiCreature(you), FadeOut(explanation), FadeOut(arrow) ) self.remove(bubble, *equation_parts) self.disapproving_friend() self.add(bubble, equation) self.play(Transform(equation, Mobject(*dot_pair))) self.remove(equation) self.add(*dot_pair) two_arrows = [ Arrow(x, direction = x).shift(UP).nudge() for x in (LEFT, RIGHT) ] self.play(*[ShowCreation(a) for a in two_arrows]) self.play(BlinkPiCreature(you)) self.remove(*dot_pair+two_arrows) everything = Mobject(*self.mobjects) self.clear() self.play( ApplyPointwiseFunction( lambda p : 3*FRAME_X_RADIUS*p/get_norm(p), everything ), *[ Transform(dot, deepcopy(dot).shift(DOWN).scale(3)) for dot in dot_pair ], run_time = 2.0 ) self.wait() def disapproving_friend(self): friend = Mortimer().to_corner(DOWN+RIGHT) bubble = SpeechBubble().pin_to(friend) bubble.write("It's simply not rigorous!") bubble.content.sort_points(lambda p : np.dot(p, DOWN+RIGHT)) self.add(friend, bubble) self.play(DelayByOrder(FadeIn(bubble.content))) self.wait() self.remove(friend, bubble, bubble.content) class DotsGettingCloser(Scene): def construct(self): dots = [ Dot(radius = 3*Dot.DEFAULT_RADIUS).shift(3*x) for x in (LEFT, RIGHT) ] self.add(*dots) self.wait() for x in range(10): distance = min(dots[1].get_points()[:,0])-max(dots[0].get_points()[:,0]) self.play(ApplyMethod(dots[0].shift, 0.5*distance*RIGHT)) class ZoomInOnInterval(Scene): def construct(self): number_line = NumberLine(density = 10*DEFAULT_POINT_DENSITY_1D) number_line.add_numbers() interval = zero_to_one_interval().split() new_line = deepcopy(number_line) new_line.set_color("black", lambda x_y_z1 : x_y_z1[0] < 0 or x_y_z1[0] > 1 or x_y_z1[1] < -0.2) # height = new_line.get_height() new_line.scale(2*INTERVAL_RADIUS) new_line.shift(INTERVAL_RADIUS*LEFT) # new_line.stretch_to_fit_height(height) self.add(number_line) self.wait() self.play(Transform(number_line, new_line)) self.clear() squish = lambda p : (p[0], 0, 0) self.play( ApplyMethod(new_line.apply_function, squish), ApplyMethod( interval[0].apply_function, squish, rate_func = lambda t : 1-t ), *[FadeIn(interval[x]) for x in [1, 2]] ) self.clear() self.add(*interval) self.wait() class DanceDotOnInterval(Scene): def construct(self, mode): num_written_terms = NUM_WRITTEN_TERMS prop = 0.5 sum_terms = [ "\\frac{1}{2}", "\\frac{1}{4}", "\\frac{1}{8}", "\\frac{1}{16}", ] num_height = 1.3*DOWN interval = zero_to_one_interval() dots = [ Dot(radius = 3*Dot.DEFAULT_RADIUS).shift(INTERVAL_RADIUS*x+UP) for x in (LEFT, RIGHT) ] color_range = Color("green").range_to("yellow", num_written_terms) conv_sum = OldTex(sum_terms, size = "\\large").split() self.add(interval) self.play(*[ ApplyMethod(dot.shift, DOWN) for dot in dots ]) self.wait() for count in range(num_written_terms): shift_val = 2*RIGHT*INTERVAL_RADIUS*(1-prop)*(prop**count) start = dots[0].get_center() line = Line(start, start + shift_val*RIGHT) line.set_color(next(color_range)) self.play( ApplyMethod(dots[0].shift, shift_val), ShowCreation(line) ) num = conv_sum[count] num.shift(RIGHT*(line.get_center()[0]-num.get_center()[0])) num.shift(num_height) arrow = Mobject() if num.get_width() > line.get_length(): num.center().shift(3*DOWN+2*(count-2)*RIGHT) arrow = Arrow( line.get_center()+2*DOWN, tail = num.get_center()+0.5*num.get_height()*UP ) self.play( ApplyMethod(line.shift, 2*DOWN), FadeIn(num), FadeIn(arrow), ) self.wait() self.write_partial_sums() self.wait() def write_partial_sums(self): partial_sums = OldTex(PARTIAL_CONVERGENT_SUMS_TEXT, size = "\\small") partial_sums.scale(1.5).to_edge(UP) partial_sum_parts = partial_sums.split() partial_sum_parts[0].set_color("yellow") for x in range(0, len(partial_sum_parts), 4): partial_sum_parts[x+2].set_color("yellow") self.play(*[ FadeIn(partial_sum_parts[y]) for y in range(x, x+4) ]) self.wait(2) class OrganizePartialSums(Scene): def construct(self): partial_sums = OldTex(PARTIAL_CONVERGENT_SUMS_TEXT, size = "\\small") partial_sums.scale(1.5).to_edge(UP) partial_sum_parts = partial_sums.split() for x in [0] + list(range(2, len(partial_sum_parts), 4)): partial_sum_parts[x].set_color("yellow") pure_sums = [ partial_sum_parts[x] for x in range(0, len(partial_sum_parts), 4) ] new_pure_sums = deepcopy(pure_sums) for pure_sum, count in zip(new_pure_sums, it.count(3, -1.2)): pure_sum.center().scale(1/1.25).set_color("white") pure_sum.to_edge(LEFT).shift(2*RIGHT+count*UP) self.add(*partial_sum_parts) self.wait() self.play(*[ ClockwiseTransform(*pair) for pair in zip(pure_sums, new_pure_sums) ]+[ FadeOut(mob) for mob in partial_sum_parts if mob not in pure_sums ]) down_arrow = OldTex("\\downarrow") down_arrow.to_edge(LEFT).shift(2*RIGHT+2*DOWN) dots = OldTex("\\vdots") dots.shift(down_arrow.get_center()+down_arrow.get_height()*UP) infinite_sum = OldTex("".join(CONVERGENT_SUM_TEXT[:-1]), size = "\\samll") infinite_sum.scale(1.5/1.25) infinite_sum.to_corner(DOWN+LEFT).shift(2*RIGHT) self.play(ShowCreation(dots)) self.wait() self.play(FadeIn(Mobject(down_arrow, infinite_sum))) self.wait() class SeeNumbersApproachOne(Scene): def construct(self): interval = zero_to_one_interval() arrow = Arrow(INTERVAL_RADIUS*RIGHT, tail=ORIGIN).nudge() arrow.shift(DOWN).set_color("yellow") num_dots = 6 colors = Color("green").range_to("yellow", num_dots) dots = Mobject(*[ Dot( density = 2*DEFAULT_POINT_DENSITY_1D ).scale(1+1.0/2.0**x).shift( INTERVAL_RADIUS*RIGHT +\ (INTERVAL_RADIUS/2.0**x)*LEFT ).set_color(next(colors)) for x in range(num_dots) ]) self.add(interval) self.play( ShowCreation(arrow), ShowCreation(dots), run_time = 2.0 ) self.wait() class OneAndInfiniteSumAreTheSameThing(Scene): def construct(self): one, equals, inf_sum = OldTex([ "1", "=", "\\sum_{n=1}^\\infty \\frac{1}{2^n}" ]).split() point = Point(equals.get_center()).set_color("black") self.add(one.shift(LEFT)) self.wait() self.add(inf_sum.shift(RIGHT)) self.wait() self.play( ApplyMethod(one.shift, RIGHT), ApplyMethod(inf_sum.shift, LEFT), CounterclockwiseTransform(point, equals) ) self.wait() class HowDoYouDefineInfiniteSums(Scene): def construct(self): you = draw_you().center().rewire_part_attributes() text = OldTexText( ["How", " do", " you,\\\\", "\\emph{define}"], size = "\\Huge" ).shift(UP).split() text[-1].shift(3*DOWN).set_color("skyblue") sum_mob = OldTex("\\sum_{n=0}^\\infty{a_n}") text[-1].shift(LEFT) sum_mob.shift(text[-1].get_center()+2*RIGHT) self.add(you) self.wait() for mob in text[:-1]: self.add(mob) self.wait(0.1) self.play(BlinkPiCreature(you)) self.wait() self.add(text[-1]) self.wait() self.add(sum_mob) self.wait() class LessAboutNewThoughts(Scene): def construct(self): words = generating, new, thoughts, to, definitions = OldTexText([ "Generating", " new", " thoughts", "$\\rightarrow$", "useful definitions" ], size = "\\large").split() gen_cross = OldTex("\\hline").set_color("red") new_cross = deepcopy(gen_cross) for cross, mob in [(gen_cross, generating), (new_cross, new)]: cross.replace(mob) cross.stretch_to_fit_height(0.03) disecting = OldTexText("Disecting").set_color("green") disecting.shift(generating.get_center() + 0.6*UP) old = OldTexText("old").set_color("green") old.shift(new.get_center()+0.6*UP) kwargs = {"run_time" : 0.25} self.add(*words) self.wait() self.play(ShowCreation(gen_cross, **kwargs)) self.play(ShowCreation(new_cross, **kwargs)) self.wait() self.add(disecting) self.wait(0.5) self.add(old) self.wait() class ListOfPartialSums(Scene): def construct(self): all_terms = np.array(OldTex( ALT_PARTIAL_SUM_TEXT, size = "\\large" ).split()) numbers, equals, sums = [ all_terms[list(range(k, 12, 3))] for k in (0, 1, 2) ] dots = all_terms[12] one = all_terms[-3] last_equal = all_terms[-2] infinite_sum = all_terms[-1] self.count( numbers, mode = "show", display_numbers = False, run_time = 1.0 ) self.play(ShowCreation(dots)) self.wait() self.play( FadeIn(Mobject(*equals)), *[ Transform(deepcopy(number), finite_sum) for number, finite_sum in zip(numbers, sums) ] ) self.wait() self.play(*[ ApplyMethod(s.set_color, "yellow", rate_func = there_and_back) for s in sums ]) self.wait() self.add(one.set_color("green")) self.wait() class ShowDecreasingDistance(Scene): args_list = [(1,), (2,)] @staticmethod def args_to_string(num): return str(num) def construct(self, num): number_line = NumberLine(interval_size = 1).add_numbers() vert_line0 = Line(0.5*UP+RIGHT, UP+RIGHT) vert_line1 = Line(0.5*UP+2*num*RIGHT, UP+2*num*RIGHT) horiz_line = Line(vert_line0.end, vert_line1.end) lines = [vert_line0, vert_line1, horiz_line] for line in lines: line.set_color("green") dots = Mobject(*[ Dot().scale(1.0/(n+1)).shift((1+partial_sum(n))*RIGHT) for n in range(10) ]) self.add(dots.split()[0]) self.add(number_line, *lines) self.wait() self.play( ApplyMethod(vert_line0.shift, RIGHT), Transform( horiz_line, Line(vert_line0.end+RIGHT, vert_line1.end).set_color("green") ), ShowCreation(dots), run_time = 2.5 ) self.wait() class CircleZoomInOnOne(Scene): def construct(self): number_line = NumberLine(interval_size = 1).add_numbers() dots = Mobject(*[ Dot().scale(1.0/(n+1)).shift((1+partial_sum(n))*RIGHT) for n in range(10) ]) circle = Circle().shift(2*RIGHT) text = OldTexText( "All but finitely many dots fall inside even the tiniest circle." ) numbers = [Tex("\\frac{1}{%s}"%s) for s in ["100", "1,000,000", "g_{g_{64}}"]] for num in numbers + [text]: num.shift(2*UP) num.sort_points(lambda p : np.dot(p, DOWN+RIGHT)) curr_num = numbers[0] arrow = Arrow(2*RIGHT, direction = 1.5*(DOWN+RIGHT)).nudge() self.add(number_line, dots) self.play( Transform(circle, Point(2*RIGHT).set_color("white")), run_time = 5.0 ) self.play(*[ DelayByOrder(FadeIn(mob)) for mob in (arrow, curr_num) ]) self.wait() for num in numbers[1:] + [text]: curr_num.set_points(list(reversed(curr_num.get_points()))) self.play( ShowCreation( curr_num, rate_func = lambda t : smooth(1-t) ), ShowCreation(num) ) self.remove(curr_num) curr_num = num self.wait() class ZoomInOnOne(Scene): def construct(self): num_iterations = 8 number_line = NumberLine(interval_size = 1, radius = FRAME_X_RADIUS+2) number_line.filter_out(lambda x_y_z2:abs(x_y_z2[1])>0.1) nl_with_nums = deepcopy(number_line).add_numbers() self.play(ApplyMethod(nl_with_nums.shift, 2*LEFT)) zero, one, two = [ OldTex(str(n)).scale(0.5).shift(0.4*DOWN+2*(-1+n)*RIGHT) for n in (0, 1, 2) ] self.play( FadeOut(nl_with_nums), *[Animation(mob) for mob in (zero, one, two, number_line)] ) self.remove(nl_with_nums, number_line, zero, two) powers_of_10 = [10**(-n) for n in range(num_iterations+1)] number_pairs = [(1-epsilon, 1+epsilon) for epsilon in powers_of_10] for count in range(num_iterations): self.zoom_with_numbers(number_pairs[count], number_pairs[count+1]) self.clear() self.add(one) def zoom_with_numbers(self, numbers, next_numbers): all_numbers = [Tex(str(n_u[0])).scale(0.5).shift(0.4*DOWN+2*n_u[1]*RIGHT) for n_u in zip(numbers+next_numbers, it.cycle([-1, 1]))] num_levels = 3 scale_factor = 10 number_lines = [ NumberLine( interval_size = 1, density = scale_factor*DEFAULT_POINT_DENSITY_1D ).filter_out( lambda x_y_z:abs(x_y_z[1])>0.1 ).scale(1.0/scale_factor**x) for x in range(num_levels) ] kwargs = {"rate_func" : None} self.play(*[ ApplyMethod(number_lines[x].scale, scale_factor, **kwargs) for x in range(1, num_levels) ]+[ ApplyMethod(number_lines[0].stretch, scale_factor, 0, **kwargs), ]+[ ApplyMethod( all_numbers[i].shift, 2*LEFT*(scale_factor-1)*(-1)**i, **kwargs ) for i in (0, 1) ]+[ Transform(Point(0.4*DOWN + u*0.2*RIGHT), num, **kwargs) for u, num in zip([-1, 1], all_numbers[2:]) ]) self.remove(*all_numbers) class DefineInfiniteSum(Scene): def construct(self): self.put_expression_in_corner() self.list_partial_sums() self.wait() def put_expression_in_corner(self): buff = 0.24 define, infinite_sum = OldTex([ "\\text{\\emph{Define} }", "\\sum_{n = 0}^\\infty a_n = X" ]).split() define.set_color("skyblue") expression = Mobject(define, infinite_sum) self.add(expression) self.wait() self.play(ApplyFunction( lambda mob : mob.scale(0.5).to_corner(UP+LEFT, buff = buff), expression )) bottom = (min(expression.get_points()[:,1]) - buff)*UP side = (max(expression.get_points()[:,0]) + buff)*RIGHT lines = [ Line(FRAME_X_RADIUS*LEFT+bottom, side+bottom), Line(FRAME_Y_RADIUS*UP+side, side+bottom) ] self.play(*[ ShowCreation(line.set_color("white")) for line in lines ]) self.wait() def list_partial_sums(self): num_terms = 10 term_strings = reduce(op.add, [ [ "s_%d"%n, "&=", "+".join(["a_%d"%k for k in range(n+1)])+"\\\\" ] for n in range(num_terms) ]) terms = OldTex(term_strings, size = "\\large").split() number_line = NumberLine() ex_point = 2*RIGHT ex = OldTex("X").shift(ex_point + LEFT + UP) arrow = Arrow(ex_point, tail = ex.get_points()[-1]).nudge() for term, count in zip(terms, it.count()): self.add(term) self.wait(0.1) if count % 3 == 2: self.wait(0.5) self.wait() esses = np.array(terms)[list(range(0, len(terms), 3))] other_terms = [m for m in terms if m not in esses] self.play(*[ ApplyMethod(ess.set_color, "yellow") for ess in esses ]) def move_s(s, n): s.center() s.scale(1.0/(n+1)) s.shift(ex_point-RIGHT*2.0/2**n) return s self.play(*[ FadeOut(term) for term in other_terms ]+[ ApplyFunction(lambda s : move_s(s, n), ess) for ess, n in zip(esses, it.count()) ]+[ FadeIn(number_line), FadeIn(ex), FadeIn(arrow) ]) lines = [ Line(x+0.25*DOWN, x+0.25*UP).set_color("white") for y in [-1, -0.01, 1, 0.01] for x in [ex_point+y*RIGHT] ] self.play(*[ Transform(lines[x], lines[x+1], run_time = 3.0) for x in (0, 2) ]) class YouJustInventedSomeMath(Scene): def construct(self): text = OldTexText([ "You ", "just ", "invented\\\\", "some ", "math" ]).split() for mob in text[:3]: mob.shift(UP) for mob in text[3:]: mob.shift(1.3*DOWN) # you = draw_you().center().rewire_part_attributes() # smile = PiCreature().mouth.center().shift(you.mouth.get_center()) you = PiCreature().set_color("grey") you.center().rewire_part_attributes() self.add(you) for mob in text: self.add(mob) self.wait(0.2) self.play(WaveArm(you)) self.play(BlinkPiCreature(you)) class SeekMoreGeneralTruths(Scene): def construct(self): summands = [ "\\frac{1}{3^n}", "2^n", "\\frac{1}{n^2}", "\\frac{(-1)^n}{n}", "\\frac{(-1)^n}{(2n)!}", "\\frac{2\sqrt{2}}{99^2}\\frac{(4n)!}{(n!)^4} \\cdot \\frac{26390n + 1103}{396^{4k}}", ] sums = OldTex([ "&\\sum_{n = 0}^\\infty" + summand + "= ? \\\\" for summand in summands ], size = "") sums.stretch_to_fit_height(FRAME_HEIGHT-1) sums.shift((FRAME_Y_RADIUS-0.5-max(sums.get_points()[:,1]))*UP) for qsum in sums.split(): qsum.sort_points(lambda p : np.dot(p, DOWN+RIGHT)) self.play(DelayByOrder(FadeIn(qsum))) self.wait(0.5) self.wait() class ChopIntervalInProportions(Scene): args_list = [("9", ), ("p", )] @staticmethod def args_to_string(*args): return args[0] def construct(self, mode): if mode == "9": prop = 0.1 num_terms = 2 left_terms, right_terms = [ [ OldTex("\\frac{%d}{%d}"%(k, (10**(count+1)))) for count in range(num_terms) ] for k in (9, 1) ] if mode == "p": num_terms = 4 prop = 0.7 left_terms = list(map(Tex, ["(1-p)", ["p","(1-p)"]]+[ ["p^%d"%(count), "(1-p)"] for count in range(2, num_terms) ])) right_terms = list(map(Tex, ["p"] + [ ["p", "^%d"%(count+1)] for count in range(1, num_terms) ])) interval = zero_to_one_interval() left = INTERVAL_RADIUS*LEFT right = INTERVAL_RADIUS*RIGHT left_paren = OldTex("(") right_paren = OldTex(")").shift(right + 1.1*UP) curr = left.astype("float") brace_to_replace = None term_to_replace = None self.add(interval) additional_anims = [] for lt, rt, count in zip(left_terms, right_terms, it.count()): last = deepcopy(curr) curr += 2*RIGHT*INTERVAL_RADIUS*(1-prop)*(prop**count) braces = [ Underbrace(a, b).rotate(np.pi, RIGHT) for a, b in [(last, curr), (curr, right)] ] for term, brace, count2 in zip([lt, rt], braces, it.count()): term.scale(0.75) term.shift(brace.get_center()+UP) if term.get_width() > brace.get_width(): term.shift(UP+1.5*(count-2)*RIGHT) arrow = Arrow( brace.get_center()+0.3*UP, tail = term.get_center()+0.5*DOWN ) arrow.set_points(list(reversed(arrow.get_points())) additional_anims = [ShowCreation(arrow)] if brace_to_replace is not None: if mode == "p": lt, rt = lt.split(), rt.split() if count == 1: new_term_to_replace = deepcopy(term_to_replace) new_term_to_replace.center().shift(last+UP+0.3*LEFT) left_paren.center().shift(last+1.1*UP) self.play( FadeIn(lt[1]), FadeIn(rt[0]), Transform( brace_to_replace.repeat(2), Mobject(*braces) ), FadeIn(left_paren), FadeIn(right_paren), Transform(term_to_replace, new_term_to_replace), *additional_anims ) self.wait() self.play( Transform( term_to_replace, Mobject(lt[0], rt[1]) ), FadeOut(left_paren), FadeOut(right_paren) ) self.remove(left_paren, right_paren) else: self.play( FadeIn(lt[1]), FadeIn(rt[0]), Transform( brace_to_replace.repeat(2), Mobject(*braces) ), Transform( term_to_replace, Mobject(lt[0], rt[1]) ), *additional_anims ) self.remove(*lt+rt) lt, rt = Mobject(*lt), Mobject(*rt) self.add(lt, rt) else: self.play( Transform( brace_to_replace.repeat(2), Mobject(*braces) ), Transform( term_to_replace, Mobject(lt, rt) ), *additional_anims ) self.remove(brace_to_replace, term_to_replace) self.add(lt, rt, *braces) else: self.play(*[ FadeIn(mob) for mob in braces + [lt, rt] ] + additional_anims) self.wait() brace_to_replace = braces[1] term_to_replace = rt if mode == "9": split_100 = OldTex("\\frac{9}{1000}+\\frac{1}{1000}") split_100.scale(0.5) split_100.shift(right_terms[-1].get_center()) split_100.to_edge(RIGHT) split_100.sort_points() right_terms[-1].sort_points() self.play(Transform( right_terms[-1], split_100 )) self.wait() class GeometricSum(RearrangeEquation): def construct(self): start_terms = "(1-p) + p (1-p) + p^2 (1-p) + p^3 (1-p) + \\cdots = 1" end_terms = "1 + p + p^2 + p^3 + \\cdots = \\frac{1}{(1-p)}" index_map = { 0 : 0, # 0 : -1, #(1-p) 1 : 1, #+ 2 : 2, #p # 3 : -1, #(1-p) 4 : 3, #+ 5 : 4, #p^2 # 6 : -1, #(1-p) 7 : 5, #+ 8 : 6, #p^3 # 9 : -1, #(1-p) 10: 7, #+ 11: 8, #\\cdots 12: 9, #= 13: 10, #1 } def start_transform(mob): return mob.scale(1.3).shift(2*UP) def end_transform(mob): return mob.scale(1.3).shift(DOWN) RearrangeEquation.construct( self, start_terms.split(" "), end_terms.split(" "), index_map, size = "\\large", path = counterclockwise_path(), start_transform = start_transform, end_transform = end_transform, leave_start_terms = True, transform_kwargs = {"run_time" : 2.0} ) class PointNineRepeating(RearrangeEquation): def construct(self): start_terms = [ "\\frac{9}{10}", "+", "\\frac{9}{100}", "+", "\\frac{9}{1000}", "+", "\\cdots=1", ] end_terms = "0 . 9 9 9 \\cdots=1".split(" ") index_map = { 0 : 2, 2 : 3, 4 : 4, 6 : 5, } for term in OldTex(start_terms).split(): self.add(term) self.wait(0.5) self.clear() RearrangeEquation.construct( self, start_terms, end_terms, index_map, path = straight_path ) class PlugNumbersIntoRightside(Scene): def construct(self): scale_factor = 1.5 lhs, rhs = OldTex( ["1 + p + p^2 + p^3 + \\cdots = ", "\\frac{1}{1-p}"], size = "\\large" ).scale(scale_factor).split() rhs = OldTex( ["1 \\over 1 - ", "p"], size = "\\large" ).replace(rhs).split() num_strings = [ "0.5", "3", "\pi", "(-1)", "3.7", "2", "0.2", "27", "i" ] nums = [ OldTex(num_string, size="\\large") for num_string in num_strings ] for num, num_string in zip(nums, num_strings): num.scale(scale_factor) num.shift(rhs[1].get_center()) num.shift(0.1*RIGHT + 0.08*UP) num.set_color("green") if num_string == "(-1)": num.shift(0.3*RIGHT) right_words = OldTexText( "This side makes sense for almost any value of $p$," ).shift(2*UP) left_words = OldTexText( "even if it seems like this side will not." ).shift(2*DOWN) right_words.add(Arrow( rhs[0].get_center(), tail = right_words.get_center()+DOWN+RIGHT ).nudge(0.5)) left_words.add(Arrow( lhs.get_center() + 0.3*DOWN, tail = left_words.get_center() + 0.3*UP )) right_words.set_color("green") left_words.set_color("yellow") self.add(lhs, *rhs) self.wait() self.play(FadeIn(right_words)) curr = rhs[1] for num, count in zip(nums, it.count()): self.play(CounterclockwiseTransform(curr, num)) self.wait() if count == 2: self.play(FadeIn(left_words)) class PlugInNegativeOne(RearrangeEquation): def construct(self): num_written_terms = 4 start_terms = reduce(op.add, [ ["(-", "1", ")^%d"%n, "+"] for n in range(num_written_terms) ]) + ["\\cdots=", "\\frac{1}{1-(-1)}"] end_terms = "1 - 1 + 1 - 1 + \\cdots= \\frac{1}{2}".split(" ") index_map = dict([ (4*n + 1, 2*n) for n in range(num_written_terms) ]+[ (4*n + 3, 2*n + 1) for n in range(num_written_terms) ]) index_map[-2] = -2 index_map[-1] = -1 RearrangeEquation.construct( self, start_terms, end_terms, index_map, path = straight_path, start_transform = lambda m : m.shift(2*UP), leave_start_terms = True, ) class PlugInTwo(RearrangeEquation): def construct(self): num_written_terms = 4 start_terms = reduce(op.add, [ ["2", "^%d"%n, "+"] for n in range(num_written_terms) ]) + ["\\cdots=", "\\frac{1}{1-2}"] end_terms = "1 + 2 + 4 + 8 + \\cdots= -1".split(" ") index_map = dict([ (3*n, 2*n) for n in range(num_written_terms) ]+[ (3*n + 2, 2*n + 1) for n in range(num_written_terms) ]) index_map[-2] = -2 index_map[-1] = -1 RearrangeEquation.construct( self, start_terms, end_terms, index_map, size = "\\Huge", path = straight_path, start_transform = lambda m : m.shift(2*UP), leave_start_terms = True, ) class ListPartialDivergentSums(Scene): args_list = [ ( lambda n : "1" if n%2 == 0 else "(-1)", lambda n : "1" if n%2 == 0 else "0" ), ( lambda n : "2^%d"%n if n > 1 else ("1" if n==0 else "2"), lambda n : str(2**(n+1)-1) ) ] @staticmethod def args_to_string(*args): if args[0](1) == "(-1)": return "Negative1" else: return args[0](1) def construct(self, term_func, partial_sum_func): num_lines = 8 rhss = [ partial_sum_func(n) for n in range(num_lines) ] lhss = [ "&=" + \ "+".join([term_func(k) for k in range(n+1)]) + \ "\\\\" for n in range(num_lines) ] terms = OldTex( list(it.chain.from_iterable(list(zip(rhss, lhss)))) + ["\\vdots&", ""], size = "\\large" ).shift(RIGHT).split() words = OldTexText("These numbers don't \\\\ approach anything") words.to_edge(LEFT) arrow = Arrow(3*DOWN+2*LEFT, direction = DOWN, length = 6) for x in range(0, len(terms), 2): self.play(FadeIn(terms[x]), FadeIn(terms[x+1])) self.play(FadeIn(words), ShowCreation(arrow)) for x in range(0, len(terms), 2): self.play( ApplyMethod(terms[x].set_color, "green"), run_time = 0.1 ) self.wait() class NotARobot(Scene): def construct(self): you = draw_you().center() top_words = OldTexText("You are a mathematician,") low_words = OldTexText("not a robot.") top_words.shift(1.5*UP) low_words.shift(1.5*DOWN) self.add(you) self.play(ShimmerIn(top_words)) self.play(ShimmerIn(low_words)) class SumPowersOfTwoAnimation(Scene): def construct(self): iterations = 5 dot = Dot(density = 3*DEFAULT_POINT_DENSITY_1D).scale(1.5) dot_width = dot.get_width()*RIGHT dot_buff = 0.2*RIGHT left = (FRAME_X_RADIUS-1)*LEFT right = left + 2*dot_width + dot_buff top_brace_left = left+dot_width+dot_buff+0.3*DOWN bottom_brace_left = left + 0.3*DOWN circle = Circle().scale(dot_width[0]/2).shift(left+dot_width/2) curr_dots = deepcopy(dot).shift(left+1.5*dot_width+dot_buff) topbrace = Underbrace(top_brace_left, right).rotate(np.pi, RIGHT) bottombrace = Underbrace(bottom_brace_left, right) colors = Color("yellow").range_to("purple", iterations) curr_dots.set_color(next(colors)) equation = OldTex( "1+2+4+\\cdots+2^n=2^{n+1} - 1", size = "\\Huge" ).shift(3*UP) full_top_sum = OldTex(["1", "+2", "+4", "+8", "+16"]).split() self.add(equation) self.wait() self.add(circle, curr_dots, topbrace, bottombrace) for n in range(1,iterations): bottom_num = OldTex(str(2**n)) new_bottom_num = OldTex(str(2**(n+1))) bottom_num.shift(bottombrace.get_center()+0.5*DOWN) top_sum = Mobject(*full_top_sum[:n]).center() top_sum_end = deepcopy(full_top_sum[n]).center() top_sum.shift(topbrace.get_center()+0.5*UP) new_top_sum = Mobject(*full_top_sum[:(n+1)]).center() self.add(top_sum, bottom_num) if n == iterations: continue new_dot = deepcopy(dot).shift(circle.get_center()) shift_val = (2**n)*(dot_width+dot_buff) right += shift_val new_dots = Mobject(new_dot, curr_dots) new_dots.set_color(next(colors)).shift(shift_val) alt_bottombrace = deepcopy(bottombrace).shift(shift_val) alt_bottom_num = deepcopy(bottom_num).shift(shift_val) alt_topbrace = deepcopy(alt_bottombrace).rotate(np.pi, RIGHT) top_sum_end.shift(alt_topbrace.get_center()+0.5*UP) new_topbrace = Underbrace(top_brace_left, right).rotate(np.pi, RIGHT) new_bottombrace = Underbrace(bottom_brace_left, right) new_bottom_num.shift(new_bottombrace.get_center()+0.5*DOWN) new_top_sum.shift(new_topbrace.get_center()+0.5*UP) for exp, brace in [ (top_sum, topbrace), (top_sum_end, alt_topbrace), (new_top_sum, new_topbrace), ]: if exp.get_width() > brace.get_width(): exp.stretch_to_fit_width(brace.get_width()) new_top_sum = new_top_sum.split() new_top_sum_start = Mobject(*new_top_sum[:-1]) new_top_sum_end = new_top_sum[-1] self.wait() self.play(*[ FadeIn(mob) for mob in [ new_dots, alt_topbrace, alt_bottombrace, top_sum_end, alt_bottom_num, ] ]) self.wait() self.play( Transform(topbrace, new_topbrace), Transform(alt_topbrace, new_topbrace), Transform(bottombrace, new_bottombrace), Transform(alt_bottombrace, new_bottombrace), Transform(bottom_num, new_bottom_num), Transform(alt_bottom_num, new_bottom_num), Transform(top_sum, new_top_sum_start), Transform(top_sum_end, new_top_sum_end) ) self.remove( bottom_num, alt_bottom_num, top_sum, top_sum_end, new_top_sum_end, alt_topbrace, alt_bottombrace ) curr_dots = Mobject(curr_dots, new_dots) class PretendTheyDoApproachNegativeOne(RearrangeEquation): def construct(self): num_lines = 6 da = "\\downarrow" columns = [ OldTex("\\\\".join([ n_func(n) for n in range(num_lines) ]+last_bits), size = "\\Large").to_corner(UP+LEFT) for n_func, last_bits in [ (lambda n : str(2**(n+1)-1), ["\\vdots", da, "-1"]), (lambda n : "+1", ["", "", "+1"]), (lambda n : "=", ["", "", "="]), (lambda n : str(2**(n+1)), ["\\vdots", da, "0"]), ] ] columns[-1].set_color() columns[2].shift(0.2*DOWN) shift_val = 3*RIGHT for column in columns: column.shift(shift_val) shift_val = shift_val + (column.get_width()+0.2)*RIGHT self.play(ShimmerIn(columns[0])) self.wait() self.add(columns[1]) self.wait() self.play( DelayByOrder(Transform(deepcopy(columns[0]), columns[-1])), FadeIn(columns[2]) ) self.wait() class DistanceBetweenRationalNumbers(Scene): def construct(self): locii = [2*LEFT, 2*RIGHT] nums = [ OldTex(s).shift(1.3*d) for s, d in zip(["\\frac{1}{2}", "3"], locii) ] arrows = [ Arrow(direction, tail = ORIGIN) for direction in locii ] dist = OldTex("\\frac{5}{2}").scale(0.5).shift(0.5*UP) text = OldTexText("How we define distance between rational numbers") text.to_edge(UP) self.add(text, *nums) self.play(*[ShowCreation(arrow) for arrow in arrows]) self.play(ShimmerIn(dist)) self.wait() class NotTheOnlyWayToOrganize(Scene): def construct(self): self.play(ShowCreation(NumberLine().add_numbers())) self.wait() words = "Is there any other reasonable way to organize numbers?" self.play(FadeIn(OldTexText(words).shift(2*UP))) self.wait() class DistanceIsAFunction(Scene): args_list = [ ("Euclidian",), ("Random",), ("2adic",), ] @staticmethod def args_to_string(word): return word def construct(self, mode): if mode == "Euclidian": dist_text = "dist" elif mode == "Random": dist_text = "random\\_dist" elif mode == "2adic": dist_text = "2\\_adic\\_dist" dist, r_paren, arg0, comma, arg1, l_paren, equals, result = OldTexText([ dist_text, "(", "000", ",", "000", ")", "=", "000" ]).split() point_origin = comma.get_center()+0.2*UP if mode == "Random": examples = [ ("2", "3", "7"), ("\\frac{1}{2}", "100", "\\frac{4}{5}"), ] dist.set_color("orange") self.add(dist) self.wait() elif mode == "Euclidian": examples = [ ("1", "5", "4"), ("\\frac{1}{2}", "3", "\\frac{5}{2}"), ("-3", "3", "6"), ("2", "3", "1"), ("0", "4", "x"), ("1", "5", "x"), ("2", "6", "x"), ] elif mode == "2adic": examples = [ ("2", "0", "\\frac{1}{2}"), ("-1", "15", "\\frac{1}{16}"), ("3", "7", "\\frac{1}{4}"), ("\\frac{3}{2}", "1", "2"), ] dist.set_color("green") self.add(dist) self.wait() example_mobs = [ ( OldTex(tup[0]).shift(arg0.get_center()), OldTex(tup[1]).shift(arg1.get_center()), OldTex(tup[2]).shift(result.get_center()) ) for tup in examples ] self.add(dist, r_paren, comma, l_paren, equals) previous = None kwargs = {"run_time" : 0.5} for mobs in example_mobs: if previous: self.play(*[ DelayByOrder(Transform(prev, mob, **kwargs)) for prev, mob in zip(previous, mobs)[:-1] ]) self.play(DelayByOrder(Transform( previous[-1], mobs[-1], **kwargs ))) self.remove(*previous) self.add(*mobs) previous = mobs self.wait() class ShiftInvarianceNumberLine(Scene): def construct(self): number_line = NumberLine().add_numbers() topbrace = Underbrace(ORIGIN, 2*RIGHT).rotate(np.pi, RIGHT) dist0 = OldTexText(["dist(", "$0$", ",", "$2$",")"]) dist1 = OldTexText(["dist(", "$2$", ",", "$4$",")"]) for dist in dist0, dist1: dist.shift(topbrace.get_center()+0.3*UP) dist1.shift(2*RIGHT) footnote = OldTexText(""" \\begin{flushleft} *yeah yeah, I know I'm still drawing them on a line, but until a few minutes from now I have no other way to draw them \\end{flushright} """).scale(0.5).to_corner(DOWN+RIGHT) self.add(number_line, topbrace, dist0, footnote) self.wait() self.remove(dist0) self.play( ApplyMethod(topbrace.shift, 2*RIGHT), *[ Transform(*pair) for pair in zip(dist0.split(), dist1.split()) ] ) self.wait() class NameShiftInvarianceProperty(Scene): def construct(self): prop = OldTexText([ "dist($A$, $B$) = dist(", "$A+x$, $B+x$", ") \\quad for all $x$" ]) mid_part = prop.split()[1] u_brace = Underbrace( mid_part.get_boundary_point(DOWN+LEFT), mid_part.get_boundary_point(DOWN+RIGHT) ).shift(0.3*DOWN) label = OldTexText("Shifted values") label.shift(u_brace.get_center()+0.5*DOWN) name = OldTexText("``Shift Invariance''") name.set_color("green").to_edge(UP) for mob in u_brace, label: mob.set_color("yellow") self.add(prop) self.play(ShimmerIn(label), ShimmerIn(u_brace)) self.wait() self.play(ShimmerIn(name)) self.wait() class TriangleInequality(Scene): def construct(self): symbols = ["A", "B", "C"] locations = [2*(DOWN+LEFT), UP, 4*RIGHT] ab, plus, bc, greater_than, ac = OldTexText([ "dist($A$, $B$)", "$+$", "dist($B$, $C$)", "$>$", "dist($A$, $C$)", ]).to_edge(UP).split() all_dists = [ab, ac, bc] ab_line, ac_line, bc_line = all_lines = [ Line(*pair).scale(0.8) for pair in it.combinations(locations, 2) ] def put_on_line(mob, line): result = deepcopy(mob).center().scale(0.5) result.rotate(np.arctan(line.get_slope())) result.shift(line.get_center()+0.2*UP) return result ab_copy, ac_copy, bc_copy = all_copies = [ put_on_line(dist, line) for dist, line in zip(all_dists, all_lines) ] for symbol, loc in zip(symbols, locations): self.add(OldTex(symbol).shift(loc)) self.play(ShowCreation(ac_line), FadeIn(ac_copy)) self.wait() self.play(*[ ShowCreation(line) for line in (ab_line, bc_line) ]+[ FadeIn(dist) for dist in (ab_copy, bc_copy) ]) self.wait() self.play(*[ Transform(*pair) for pair in zip(all_copies, all_dists) ]+[ FadeIn(mob) for mob in (plus, greater_than) ]) self.wait() class StruggleToFindFrameOfMind(Scene): def construct(self): you, bubble = draw_you(with_bubble = True) questions = OldTexText("???", size = "\\Huge").scale(1.5) contents = [ OldTex("2, 4, 8, 16, 32, \\dots \\rightarrow 0"), OldTexText("dist(0, 2) $<$ dist(0, 64)"), NumberLine().sort_points(lambda p : -p[1]).add( OldTexText("Not on a line?").shift(UP) ), ] kwargs = {"run_time" : 0.5} self.add(you, bubble) bubble.add_content(questions) for mob in contents: curr = bubble.content self.remove(curr) bubble.add_content(mob) for first, second in [(curr, questions), (questions, mob)]: copy = deepcopy(first) self.play(DelayByOrder(Transform( copy, second, **kwargs ))) self.remove(copy) self.add(mob) self.wait() class RoomsAndSubrooms(Scene): def construct(self): colors = get_room_colors() a_set = [3*RIGHT, 3*LEFT] b_set = [1.5*UP, 1.5*DOWN] c_set = [LEFT, RIGHT] rectangle_groups = [ [Rectangle(7, 12).set_color(colors[0])], [ Rectangle(6, 5).shift(a).set_color(colors[1]) for a in a_set ], [ Rectangle(2, 4).shift(a + b).set_color(colors[2]) for a in a_set for b in b_set ], [ Rectangle(1, 1).shift(a+b+c).set_color(colors[3]) for a in a_set for b in b_set for c in c_set ] ] for group in rectangle_groups: mob = Mobject(*group) mob.sort_points(get_norm) self.play(ShowCreation(mob)) self.wait() class RoomsAndSubroomsWithNumbers(Scene): def construct(self): zero_local = (FRAME_X_RADIUS-0.5)*LEFT zero_one_width = FRAME_X_RADIUS-0.3 zero, power_mobs = self.draw_numbers(zero_local, zero_one_width) self.wait() rectangles = self.draw_first_rectangles(zero_one_width) rect_clusters = self.draw_remaining_rectangles(rectangles) self.adjust_power_mobs(zero, power_mobs, rect_clusters[-1]) self.wait() num_mobs = self.draw_remaining_numbers( zero, power_mobs, rect_clusters ) self.wait() self.add_negative_one(num_mobs) self.wait() self.show_distances(num_mobs, rect_clusters) def draw_numbers(self, zero_local, zero_one_width): num_numbers = 5 zero = OldTex("0").shift(zero_local) self.add(zero) nums = [] for n in range(num_numbers): num = OldTex(str(2**n)) num.scale(1.0/(n+1)) num.shift( zero_local+\ RIGHT*zero_one_width/(2.0**n)+\ LEFT*0.05*n+\ (0.4*RIGHT if n == 0 else ORIGIN) #Stupid ) self.play(FadeIn(num, run_time = 0.5)) nums.append(num) return zero, nums def draw_first_rectangles(self, zero_one_width): side_buff = 0.05 upper_buff = 0.5 colors = get_room_colors() rectangles = [] for n in range(4): rect = Rectangle( FRAME_HEIGHT-(n+2)*upper_buff, zero_one_width/(2**n)-0.85*(n+1)*side_buff ) rect.sort_points(get_norm) rect.to_edge(LEFT, buff = 0.2).shift(n*side_buff*RIGHT) rect.set_color(colors[n]) rectangles.append(rect) for rect in rectangles: self.play(ShowCreation(rect)) self.wait() return rectangles def draw_remaining_rectangles(self, rectangles): clusters = [] centers = [ORIGIN] + list(map(Mobject.get_center, rectangles)) shift_vals = [ 2*(c2 - c1)[0]*RIGHT for c1, c2 in zip(centers[1:], centers) ] for rectangle, count in zip(rectangles, it.count(1)): cluster = [rectangle] for shift_val in shift_vals[:count]: cluster += [mob.shift(shift_val) for mob in deepcopy(cluster)] clusters.append(cluster) for rect in cluster[1:]: self.play(FadeIn(rect, run_time = 0.6**(count-1))) return clusters def adjust_power_mobs(self, zero, power_mobs, small_rects): new_zero = deepcopy(zero) self.center_in_closest_rect(new_zero, small_rects) new_power_mobs = deepcopy(power_mobs) for mob, count in zip(new_power_mobs, it.count(1)): self.center_in_closest_rect(mob, small_rects) new_power_mobs[-1].shift(DOWN) dots = OldTex("\\vdots") dots.scale(0.5).shift(new_zero.get_center()+0.5*DOWN) self.play( Transform(zero, new_zero), FadeIn(dots), *[ Transform(old, new) for old, new in zip(power_mobs, new_power_mobs) ] ) def draw_remaining_numbers(self, zero, power_mobs, rect_clusters): small_rects = rect_clusters[-1] max_width = 0.8*small_rects[0].get_width() max_power = 4 num_mobs = [None]*(2**max_power + 1) num_mobs[0] = zero powers = [2**k for k in range(max_power+1)] for p, index in zip(powers, it.count()): num_mobs[p] = power_mobs[index] for power, count in zip(powers[1:-1], it.count(1)): zero_copy = deepcopy(zero) power_mob_copy = deepcopy(num_mobs[power]) def transform(mob): self.center_in_closest_rect(mob, small_rects) mob.shift(UP) return mob self.play(*[ ApplyFunction(transform, mob) for mob in (zero_copy, power_mob_copy) ]) last_left_mob = zero for n in range(power+1, 2*power): left_mob = num_mobs[n-power] shift_val = left_mob.get_center()-last_left_mob.get_center() self.play(*[ ApplyMethod(mob.shift, shift_val) for mob in (zero_copy, power_mob_copy) ]) num_mobs[n] = OldTex(str(n)) num_mobs[n].scale(1.0/(power_of_divisor(n, 2)+1)) width_ratio = max_width / num_mobs[n].get_width() if width_ratio < 1: num_mobs[n].scale(width_ratio) num_mobs[n].shift(power_mob_copy.get_center()+DOWN) self.center_in_closest_rect(num_mobs[n], small_rects) point = Point(power_mob_copy.get_center()) self.play(Transform(point, num_mobs[n])) self.remove(point) self.add(num_mobs[n]) last_left_mob = left_mob self.remove(zero_copy, power_mob_copy) self.wait() return num_mobs @staticmethod def center_in_closest_rect(mobject, rectangles): center = mobject.get_center() diffs = [r.get_center()-center for r in rectangles] mobject.shift(diffs[np.argmin(list(map(get_norm, diffs)))]) def add_negative_one(self, num_mobs): neg_one = OldTex("-1").scale(0.5) shift_val = num_mobs[15].get_center()-neg_one.get_center() neg_one.shift(UP) self.play(ApplyMethod(neg_one.shift, shift_val)) def show_distances(self, num_mobs, rect_clusters): self.remove(*[r for c in rect_clusters for r in c]) text = None for cluster, count in zip(rect_clusters, it.count()): if text is not None: self.remove(text) if count == 0: dist_string = "1" else: dist_string = "$\\frac{1}{%d}$"%(2**count) text = OldTexText( "Any of these pairs are considered to be a distance " +\ dist_string +\ " away from each other" ).shift(2*UP) self.add(text) self.clear_way_for_text(text, cluster) self.add(*cluster) pairs = [a_b for a_b in it.combinations(list(range(16)), 2) if (a_b[0]-a_b[1])%(2**count) == 0 and (a_b[0]-a_b[1])%(2**(count+1)) != 0] for pair in sample(pairs, min(10, len(pairs))): for index in pair: num_mobs[index].set_color("green") self.play(*[ ApplyMethod( num_mobs[index].rotate, np.pi/10, rate_func = wiggle ) for index in pair ]) self.wait() for index in pair: num_mobs[index].set_color("white") @staticmethod def clear_way_for_text(text, mobjects): right, top, null = np.max(text.points, 0) left, bottom, null = np.min(text.points, 0) def filter_func(xxx_todo_changeme): (x, y, z) = xxx_todo_changeme return x>left and x<right and y>bottom and y<top for mobject in mobjects: mobject.filter_out(filter_func) class DeduceWhereNegativeOneFalls(Scene): def construct(self): part0, arg0, part1, part2, arg1, part3 = OldTexText([ "dist(-1, ", "0000", ") = ", "dist(0, ", "0000", ")" ]).scale(1.5).split() u_brace = Underbrace( part2.get_boundary_point(DOWN+LEFT), part3.get_boundary_point(DOWN+RIGHT) ).shift(0.3+DOWN) colors = list(get_room_colors()) num_labels = len(colors) texts = [ Mobject(parts[0], parts[1].set_color(color)) for count, color in zip(it.count(), colors) for parts in [TexText([ "Represented (heuristically) \\\\ by being in the same \\\\", (count*"sub-")+"room" ]).split()] ] target_text_top = u_brace.get_center()+0.5*DOWN for text in texts: text.shift(target_text_top - text.get_top()) self.add(part0, part1, part2, part3, u_brace) last_args = [arg0, arg1] for n in range(1, 15): rest_time = 0.3 + 1.0/(n+1) new_args = [ OldTexText("$%d$"%k).scale(1.5) for k in (2**n-1, 2**n) ] for new_arg, old_arg in zip(new_args, last_args): new_arg.shift(old_arg.get_center()) if last_args != [arg0, arg1]: self.play(*[ DelayByOrder(Transform(*pair, run_time = 0.5*rest_time)) for pair in zip(last_args, new_args) ]) if n-1 < num_labels: self.add(texts[n-1]) if n > 1: self.remove(texts[n-2]) else: self.remove(u_brace, *texts) self.remove(*last_args) self.add(*new_args) self.wait(rest_time) last_args = new_args class OtherRationalNumbers(Scene): def construct(self): import random self.add(OldTexText("Where do other \\\\ rational numbers fall?")) pairs = [ (1, 2), (1, 3), (4, 9), (-7, 13), (3, 1001), ] locii = [ 4*LEFT+2*UP, 4*RIGHT, 5*RIGHT+UP, 4*LEFT+2*DOWN, 3*DOWN, ] for pair, locus in zip(pairs, locii): fraction = OldTex("\\frac{%d}{%d}"%pair).shift(locus) self.play(ShimmerIn(fraction)) self.wait() class PAdicMetric(Scene): def construct(self): p_str, text = OldTexText(["$p$", "-adic metric"]).shift(2*UP).split() primes = [Tex(str(p)) for p in [2, 3, 5, 7, 11, 13, 17, 19, 23]] p_str.set_color("yellow") colors = Color("green").range_to("skyblue", len(primes)) new_numbers = OldTexText("Completely new types of numbers!") new_numbers.set_color("skyblue").shift(2.3*DOWN) arrow = Arrow(2*DOWN, tail = 1.7*UP) curr = deepcopy(p_str) self.add(curr, text) self.wait() for prime, count in zip(primes, it.count()): prime.scale(1.0).set_color(next(colors)) prime.shift(center_of_mass([p_str.get_top(), p_str.get_center()])) self.play(DelayByOrder(Transform(curr, prime))) self.wait() if count == 2: self.spill(Mobject(curr, text), arrow, new_numbers) self.remove(curr) curr = prime self.play(DelayByOrder(Transform(curr, p_str))) self.wait() def spill(self, start, arrow, end): start.sort_points(lambda p : p[1]) self.play( ShowCreation( arrow, rate_func = squish_rate_func(smooth, 0.5, 1.0) ), DelayByOrder(Transform( start, Point(arrow.get_points()[0]).set_color("white") )) ) self.play(ShimmerIn(end)) class FuzzyDiscoveryToNewMath(Scene): def construct(self): fuzzy = OldTexText("Fuzzy Discovery") fuzzy.to_edge(UP).shift(FRAME_X_RADIUS*LEFT/2) new_math = OldTexText("New Math") new_math.to_edge(UP).shift(FRAME_X_RADIUS*RIGHT/2) lines = Mobject( Line(DOWN*FRAME_Y_RADIUS, UP*FRAME_Y_RADIUS), Line(3*UP+LEFT*FRAME_X_RADIUS, 3*UP+RIGHT*FRAME_X_RADIUS) ) fuzzy_discoveries = [ OldTex("a^2 + b^2 = c^2"), OldTex("".join(CONVERGENT_SUM_TEXT)), OldTex("".join(DIVERGENT_SUM_TEXT)), OldTex("e^{\pi i} = -1"), ] triangle_lines = [ Line(ORIGIN, LEFT), Line(LEFT, UP), Line(UP, ORIGIN), ] for line, char in zip(triangle_lines, ["a", "c", "b"]): line.set_color("blue") char_mob = OldTex(char).scale(0.25) line.add(char_mob.shift(line.get_center())) triangle = Mobject(*triangle_lines) triangle.center().shift(1.5*fuzzy_discoveries[0].get_right()) how_length = OldTexText("But how is length defined?").scale(0.5) how_length.shift(0.75*DOWN) fuzzy_discoveries[0].add(triangle, how_length) new_maths = [ OldTexText(""" Define distance between points $(x_0, y_0)$ and $(x_1, y_1)$ as $\\sqrt{(x_1-x_0)^2 + (y_1-y_0)^2}$ """), OldTexText("Define ``approach'' and infinite sums"), OldTexText("Discover $2$-adic numbers"), OldTexText( "Realize exponentiation is doing something much \ different from repeated multiplication" ) ] midpoints = [] triplets = list(zip(fuzzy_discoveries, new_maths, it.count(2, -1.75))) for disc, math, count in triplets: math.scale(0.65) for mob in disc, math: mob.to_edge(LEFT).shift(count*UP) math.shift(FRAME_X_RADIUS*RIGHT) midpoints.append(count*UP) self.add(fuzzy, lines) self.play(*list(map(ShimmerIn, fuzzy_discoveries))) self.wait() self.play(DelayByOrder(Transform( deepcopy(fuzzy), new_math ))) self.play(*[ DelayByOrder(Transform(deepcopy(disc), math)) for disc, math in zip(fuzzy_discoveries, new_maths) ]) self.wait() class DiscoveryAndInvention(Scene): def construct(self): invention, vs, discovery = OldTexText([ "Invention ", "vs. ", "Discovery" ]).split() nrd = OldTexText( "Non-rigorous truths" ).shift(2*UP) rt = OldTexText( "Rigorous terms" ).shift(2*DOWN) arrows = [] self.add(discovery, vs, invention) self.wait() arrow = Arrow( nrd.get_bottom(), tail = discovery.get_top() ) self.play( FadeIn(nrd), ShowCreation(arrow) ) arrows.append(arrow) self.wait() arrow = Arrow( invention.get_top(), tail = nrd.get_bottom() ) self.play(ShowCreation(arrow)) arrows.append(arrow) self.wait() arrow = Arrow( rt.get_top(), tail = invention.get_bottom() ) self.play( FadeIn(rt), ShowCreation(arrow) ) arrows.append(arrow) self.wait() arrow = Arrow( discovery.get_bottom(), tail = rt.get_top() ) self.play(ShowCreation(arrow)) self.wait() arrows.append(arrow) for color in Color("yellow").range_to("red", 4): for arrow in arrows: self.play( ShowCreation(deepcopy(arrow).set_color(color)), run_time = 0.25 ) if __name__ == "__main__": command_line_create_scene(MOVIE_PREFIX)
import numpy as np import itertools as it from copy import deepcopy import sys from constants import * from scene.scene import Scene from geometry import Polygon from mobject.region import region_from_polygon_vertices, region_from_line_boundary A_COLOR = BLUE B_COLOR = MAROON_D C_COLOR = YELLOW TEX_MOB_SCALE_FACTOR = 0.5 POINTS = np.array([ DOWN, 2*UP, DOWN+RIGHT, 2*DOWN, 2*DOWN+RIGHT, DOWN+3*LEFT, 2*UP+3*LEFT, 4*RIGHT, 3*UP+3*RIGHT, ]) class Triangle(Polygon): def __init__(self, **kwargs): kwargs["color"] = C_COLOR Polygon.__init__( self, *POINTS[[0, 1, 2]], edge_colors = [B_COLOR, C_COLOR, A_COLOR], **kwargs ) nudge = 0.2 target = POINTS[0]+nudge*(UP+RIGHT) for direction in UP, RIGHT: self.add_line(POINTS[0]+nudge*direction, target, color = WHITE) def add_all_letters(self): for char in "abc": self.add_letter(char) return self def add_letter(self, char, nudge = 0.3): mob = OldTex(char).scale(TEX_MOB_SCALE_FACTOR) if char == "a": points = self.get_vertices()[[0, 2, 1]] elif char == "b": points = self.get_vertices()[[1, 0, 2]] elif char == "c": points = self.get_vertices()[[2, 1, 0]] center = 0.5*sum(points[:2]) #average of first two points mob.shift(center) normal_dir = rotate_vector(points[1] - points[0], np.pi/2, OUT) if np.dot(normal_dir, points[2]-center) > 0: normal_dir = -normal_dir normal_dir /= get_norm(normal_dir) mob.shift(nudge*normal_dir) self.add(mob) return self def place_hypotenuse_on(self, point1, point2): #self.vertices[1], self.vertices[2] start1, start2 = self.get_vertices()[[1, 2]] target_vect = np.array(point2)-np.array(point1) curr_vect = start2-start1 self.scale(get_norm(target_vect)/get_norm(curr_vect)) self.rotate(angle_of_vector(target_vect)-angle_of_vector(curr_vect)) self.shift(point1-self.get_vertices()[1]) return self def a_square(**kwargs): return Polygon(*POINTS[[0, 2, 4, 3]], color = A_COLOR, **kwargs) def b_square(**kwargs): return Polygon(*POINTS[[1, 0, 5, 6]], color = B_COLOR, **kwargs) def c_square(**kwargs): return Polygon(*POINTS[[1, 2, 7, 8]], color = C_COLOR, **kwargs) class DrawPointsReference(Scene): def construct(self): for point, count in zip(POINTS, it.count()): mob = OldTex(str(count)).scale(TEX_MOB_SCALE_FACTOR) mob.shift(POINTS[count]) self.add(mob) class DrawTriangle(Scene): def construct(self): self.add(Triangle().add_all_letters()) class DrawAllThreeSquares(Scene): def construct(self): a = a_square() b = b_square() c = c_square() self.add(Triangle(), a, b, c) for letter, mob in zip("abc", [a, b, c]): char_mob = OldTex(letter+"^2").scale(TEX_MOB_SCALE_FACTOR) char_mob.shift(mob.get_center()) self.add(char_mob) class AddParallelLines(DrawAllThreeSquares): args_list = [ (1, False), (2, False), (3, False), (3, True), ] @staticmethod def args_to_string(num, trim): return str(num) + ("Trimmed" if trim else "") def construct(self, num, trim): DrawAllThreeSquares.construct(self) shift_pairs = [ (4*RIGHT, 3*UP), (ORIGIN, DOWN), (3*LEFT, 2*DOWN) ] for side_shift, vert_shift in shift_pairs[:num]: line1 = Line(BOTTOM, TOP, color = WHITE) line1.shift(side_shift) line2 = Line(LEFT_SIDE, RIGHT_SIDE, color = WHITE) line2.shift(vert_shift) self.add(line1, line2) if trim: for mob in self.mobjects: mob.filter_out(lambda p : p[0] > 4) mob.filter_out(lambda p : p[0] < -3) mob.filter_out(lambda p : p[1] > 3) mob.filter_out(lambda p : p[1] < -2) class HighlightEmergentTriangles(AddParallelLines): args_list = [(3,True)] def construct(self, *args): AddParallelLines.construct(self, *args) triplets = [ [(0, 2), (0, -1), (1, -1)], [(1, -1), (4, -1), (4, 0)], [(4, 0), (4, 3), (3, 3)], [(3, 3), (0, 3), (0, 2)], ] for triplet in triplets: self.set_color_region( region_from_polygon_vertices(*triplet), color = "BLUE_D" ) class IndicateTroublePointFromParallelLines(AddParallelLines): args_list = [(3,True)] def construct(self, *args): AddParallelLines.construct(self, *args) circle = Circle(radius = 0.25) circle.shift(DOWN+RIGHT) vect = DOWN+RIGHT arrow = Arrow(circle.get_center()+2*vect, circle.get_boundary_point(vect)) arrow.set_color(circle.get_color()) self.add_mobjects_among(list(locals().values())) class DrawAllThreeSquaresWithMoreTriangles(DrawAllThreeSquares): args_list = [ (1, True), (2, True), (3, True), (4, True), (5, True), (6, True), (7, True), (8, True), (9, True), (10, True), (10, False) ] @staticmethod def args_to_string(num, fill): fill_string = "" if fill else "HollowTriangles" return str(num) + fill_string def construct(self, num, fill): DrawAllThreeSquares.construct(self) pairs = [ ((0, 2, 0), (1, -1, 0)), ((-3, -1, 0), (0, -2, 0)), ((4, -1, 0), (1, -2, 0)), ((0, -2, 0), (-3, -1, 0)), ((1, -2, 0), (4, -1, 0)), ((1, -1, 0), (4, 0, 0)), ((4, 0, 0), (3, 3, 0)), ((3, 3, 0), (0, 2, 0)), ((-3, 3, 0), (0, 2, 0)), ((0, 2, 0), (-3, 3, 0)) ] to_flip = [1, 3, 8, 9] for n in range(num): triangle = Triangle() if n in to_flip: triangle.rotate(np.pi, UP) self.add(triangle.place_hypotenuse_on(*pairs[n])) vertices = list(triangle.get_vertices()) if n not in to_flip: vertices.reverse() if fill: self.set_color_region( region_from_polygon_vertices(*vertices), color = BLUE_D ) class IndicateBigRectangleTroublePoint(DrawAllThreeSquaresWithMoreTriangles): args_list = [(10, False)] def construct(self, *args): DrawAllThreeSquaresWithMoreTriangles.construct(self, *args) circle = Circle(radius = 0.25, color = WHITE) circle.shift(4*RIGHT) vect = DOWN+RIGHT arrow = Arrow(circle.get_center()+vect, circle.get_boundary_point(vect)) self.add_mobjects_among(list(locals().values())) class ShowBigRectangleDimensions(DrawAllThreeSquaresWithMoreTriangles): args_list = [(10, False)] def construct(self, num, fill): DrawAllThreeSquaresWithMoreTriangles.construct(self, num, fill) u_brace = Underbrace((-3, -2, 0), (4, -2, 0)) side_brace = Underbrace((-3, -3, 0), (2, -3, 0)) for brace in u_brace, side_brace: brace.shift(0.2*DOWN) side_brace.rotate(-np.pi/2) a_plus_2b = OldTex("a+2b").scale(TEX_MOB_SCALE_FACTOR) b_plus_2a = OldTex("b+2a").scale(TEX_MOB_SCALE_FACTOR) a_plus_2b.next_to(u_brace, DOWN) b_plus_2a.next_to(side_brace, LEFT) self.add_mobjects_among(list(locals().values())) class FillInAreaOfBigRectangle(DrawAllThreeSquaresWithMoreTriangles): args_list = [(10, False)] def construct(self, *args): DrawAllThreeSquaresWithMoreTriangles.construct(self, *args) args_list = [(10, False)] color = Color("yellow") color.set_rgb(0.3*np.array(color.get_rgb())) self.set_color_region( region_from_polygon_vertices( (-3, 3), (-3, -2), (4, -2), (4, 3) ), color = color ) class DrawOnlyABSquares(Scene): def construct(self): a = a_square() b = b_square() for char, mob in zip("ab", [a, b]): symobl = OldTex(char+"^2").scale(TEX_MOB_SCALE_FACTOR) symobl.shift(mob.get_center()) self.add(symobl) triangle = Triangle() self.add_mobjects_among(list(locals().values())) class AddTriangleCopyToABSquares(DrawOnlyABSquares): def construct(self): DrawOnlyABSquares.construct(self) triangle = Triangle() triangle.rotate(np.pi, UP) triangle.place_hypotenuse_on(3*LEFT+DOWN, 2*DOWN) self.add(triangle) self.set_color_triangles() def set_color_triangles(self): for mob in self.mobjects: if isinstance(mob, Triangle): vertices = list(mob.get_vertices()) for x in range(2): self.set_color_region(region_from_polygon_vertices( *vertices ), color = BLUE_D) vertices.reverse()#silly hack class AddAllTrianglesToABSquares(AddTriangleCopyToABSquares): def construct(self): AddTriangleCopyToABSquares.construct(self) self.add(Triangle().place_hypotenuse_on(RIGHT+DOWN, 2*UP)) triangle = Triangle() triangle.rotate(np.pi, UP) triangle.place_hypotenuse_on(2*DOWN, 3*LEFT+DOWN) self.add(triangle) self.set_color_triangles() class DrawNakedCSqurae(Scene): def construct(self): c = c_square().center() triangle = Triangle().place_hypotenuse_on(*c.get_vertices()[[0,1]]) triangle.add_all_letters() self.add(triangle, c) class DrawCSquareWithAllTraingles(Scene): args_list = [ (False, False, False, False), (False, True, False, True), (True, True, False, False), (False, True, True, False), ] @staticmethod def args_to_string(*toggle_vector): return "".join(map(str, list(map(int, toggle_vector)))) def construct(self, *toggle_vector): if len(toggle_vector) == 0: toggle_vector = [False]*4 self.c_square = c_square().center() vertices = it.cycle(self.c_square.get_vertices()) last_vertex = next(vertices) have_letters = False self.triangles = [] for vertex, should_flip in zip(vertices, toggle_vector): triangle = Triangle() pair = np.array([last_vertex, vertex]) if should_flip: triangle.rotate(np.pi, UP) pair = pair[[1, 0]] triangle.place_hypotenuse_on(*pair) if not have_letters: triangle.add_all_letters() have_letters = True self.triangles.append(triangle) self.add(triangle) last_vertex = vertex self.add(self.c_square) class HighlightCSquareInBigSquare(DrawCSquareWithAllTraingles): args_list = [tuple([False]*4)] def construct(self, *args): DrawCSquareWithAllTraingles.construct(self, *args) self.set_color_region(region_from_polygon_vertices( *c_square().center().get_vertices() ), color = YELLOW) class IndicateCSquareTroublePoint(DrawCSquareWithAllTraingles): def construct(self, *toggle_vector): DrawCSquareWithAllTraingles.construct(self, *toggle_vector) circle = Circle(color = WHITE) circle.scale(0.25) vertex = self.c_square.get_vertices()[1] circle.shift(vertex) vect = 2*RIGHT+DOWN arrow = Arrow(vertex+vect, circle.get_boundary_point(vect)) self.add(circle, arrow) class ZoomInOnTroublePoint(Scene): args_list = list(it.product([True, False], [True, False])) @staticmethod def args_to_string(with_labels, rotate): label_string = "WithLabels" if with_labels else "WithoutLabels" rotate_string = "Rotated" if rotate else "" return label_string + rotate_string def construct(self, with_labels, rotate): zoom_factor = 10 density = zoom_factor*DEFAULT_POINT_DENSITY_1D c = c_square(density = density) c.shift(-c.get_vertices()[1]) c.scale(zoom_factor) vertices = c.get_vertices() for index in 0, 1: triangle = Triangle(density = density) triangle.place_hypotenuse_on(vertices[index], vertices[index+1]) self.add(triangle) circle = Circle(radius = 2.5, color = WHITE) angle1_arc = Circle(color = WHITE) angle2_arc = Circle(color = WHITE).scale(0.5) angle1_arc.filter_out(lambda x_y_z2 : not (x_y_z2[0] > 0 and x_y_z2[1] > 0 and x_y_z2[1] < x_y_z2[0]/3)) angle2_arc.filter_out(lambda x_y_z3 : not (x_y_z3[0] < 0 and x_y_z3[1] > 0 and x_y_z3[1] < -3*x_y_z3[0])) self.add_mobjects_among(list(locals().values())) self.add_elbow() if rotate: for mob in self.mobjects: mob.rotate(np.pi/2) if with_labels: alpha = OldTex("\\alpha").scale(TEX_MOB_SCALE_FACTOR) beta = OldTex("90-\\alpha").scale(TEX_MOB_SCALE_FACTOR) if rotate: alpha.next_to(angle1_arc, UP+0.1*LEFT) beta.next_to(angle2_arc, DOWN+0.5*LEFT) else: alpha.next_to(angle1_arc, RIGHT) beta.next_to(angle2_arc, LEFT) self.add(alpha, beta) def add_elbow(self): c = 0.1 p1 = c*LEFT + 3*c*UP p2 = 3*c*RIGHT + c*UP p3 = 2*c*RIGHT + 4*c*UP self.add(Line(p1, p3, color = WHITE)) self.add(Line(p2, p3, color = WHITE)) class DrawTriangleWithAngles(Scene): def construct(self): triangle = Triangle(density = 2*DEFAULT_POINT_DENSITY_1D) triangle.scale(2).center().add_all_letters() vertices = triangle.get_vertices() kwargs = {"color" : WHITE} angle1_arc = Circle(radius = 0.4, **kwargs).filter_out( lambda x_y_z : not(x_y_z[0] > 0 and x_y_z[1] < 0 and x_y_z[1] < -3*x_y_z[0]) ).shift(vertices[1]) angle2_arc = Circle(radius = 0.2, **kwargs).filter_out( lambda x_y_z1 : not(x_y_z1[0] < 0 and x_y_z1[1] > 0 and x_y_z1[1] < -3*x_y_z1[0]) ).shift(vertices[2]) alpha = OldTex("\\alpha") beta = OldTex("90-\\alpha") alpha.shift(vertices[1]+3*RIGHT+DOWN) beta.shift(vertices[2]+3*RIGHT+UP) arrow1 = Arrow(alpha, angle1_arc) arrow2 = Arrow(beta, angle2_arc) self.add(triangle, angle1_arc, angle2_arc, alpha, beta, arrow1, arrow2) class LabelLargeSquare(DrawCSquareWithAllTraingles): args_list = [] def construct(self): DrawCSquareWithAllTraingles.construct(self) everything = Mobject(*self.mobjects) u_brace = Underbrace(2*(DOWN+LEFT), 2*(DOWN+RIGHT)) u_brace.shift(0.2*DOWN) side_brace = deepcopy(u_brace).rotate(np.pi/2) upper_brace = deepcopy(u_brace).rotate(np.pi) a_plus_b = OldTex("a+b").scale(TEX_MOB_SCALE_FACTOR) upper_brace.add(a_plus_b.next_to(upper_brace, UP)) side_brace.add(a_plus_b.next_to(side_brace, RIGHT)) self.add(upper_brace, side_brace) class CompletelyFillLargeSquare(LabelLargeSquare): def construct(self): LabelLargeSquare.construct(self) vertices = [2*(DOWN+LEFT), 2*(DOWN+RIGHT), 2*(UP+RIGHT), 2*(UP+LEFT)] vertices.append(vertices[0]) pairs = list(zip(vertices, vertices[1:])) self.set_color_region(region_from_line_boundary(*pairs), color = BLUE) class FillComponentsOfLargeSquare(LabelLargeSquare): def construct(self): LabelLargeSquare.construct(self) points = np.array([ 2*UP+2*LEFT, UP+2*LEFT, 2*DOWN+2*LEFT, 2*DOWN+LEFT, 2*DOWN+2*RIGHT, DOWN+2*RIGHT, 2*UP+2*RIGHT, RIGHT+2*UP ]) for triplet in [[0, 1, 7], [2, 3, 1], [4, 5, 3], [6, 7, 5]]: triplet.append(triplet[0]) self.set_color_region(region_from_line_boundary(*[ [points[i], points[j]] for i, j in zip(triplet, triplet[1:]) ]), color = BLUE_D) vertices = points[[1, 3, 5, 7, 1]] self.set_color_region(region_from_line_boundary(*[ [p1, p2] for p1, p2 in zip(vertices, vertices[1:]) ]), color = YELLOW) class ShowRearrangementInBigSquare(DrawCSquareWithAllTraingles): args_list = [] def construct(self): self.add(Square(side_length = 4, color = WHITE)) DrawCSquareWithAllTraingles.construct(self) self.remove(self.c_square) self.triangles[1].shift(LEFT) for i, j in [(0, 2), (3, 1)]: self.triangles[i].place_hypotenuse_on( *self.triangles[j].get_vertices()[[2, 1]] ) class ShowRearrangementInBigSquareWithRegions(ShowRearrangementInBigSquare): def construct(self): ShowRearrangementInBigSquare.construct(self) self.set_color_region(region_from_polygon_vertices( 2*(LEFT+UP), 2*LEFT+DOWN, RIGHT+DOWN, RIGHT+2*UP ), color = B_COLOR) self.set_color_region(region_from_polygon_vertices( RIGHT+DOWN, RIGHT+2*DOWN, 2*RIGHT+2*DOWN, 2*RIGHT+DOWN ), color = A_COLOR)
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from animation import * from mobject import * from constants import * from mobject.region import * import displayer as disp from scene.scene import Scene, GraphScene from scene.graphs import * from .moser_main import EulersFormula from script_wrapper import command_line_create_scene MOVIE_PREFIX = "ecf_graph_scenes/" RANDOLPH_SCALE_FACTOR = 0.3 EDGE_ANNOTATION_SCALE_FACTOR = 0.7 DUAL_CYCLE = [3, 4, 5, 6, 1, 0, 2, 3] class EulersFormulaWords(Scene): def construct(self): self.add(OldTex("V-E+F=2")) class TheTheoremWords(Scene): def construct(self): self.add(OldTexText("The Theorem:")) class ProofAtLastWords(Scene): def construct(self): self.add(OldTexText("The Proof At Last...")) class DualSpanningTreeWords(Scene): def construct(self): self.add(OldTexText("Spanning trees have duals too!")) class PreferOtherProofDialogue(Scene): def construct(self): teacher = Face("talking").shift(2*LEFT) student = Face("straight").shift(2*RIGHT) teacher_bubble = SpeechBubble(LEFT).speak_from(teacher) student_bubble = SpeechBubble(RIGHT).speak_from(student) teacher_bubble.write("Look at this \\\\ elegant proof!") student_bubble.write("I prefer the \\\\ other proof.") self.add(student, teacher, teacher_bubble, teacher_bubble.text) self.wait(2) self.play(Transform( Dot(student_bubble.tip).set_color("black"), Mobject(student_bubble, student_bubble.text) )) self.wait(2) self.remove(teacher_bubble.text) teacher_bubble.write("Does that make this \\\\ any less elegant?") self.add(teacher_bubble.text) self.wait(2) class IllustrateDuality(GraphScene): def construct(self): GraphScene.construct(self) self.generate_dual_graph() self.add(OldTexText("Duality").to_edge(UP)) self.remove(*self.vertices) def special_alpha(t): if t > 0.5: t = 1 - t if t < 0.25: return smooth(4*t) else: return 1 kwargs = { "run_time" : 5.0, "rate_func" : special_alpha } self.play(*[ Transform(*edge_pair, **kwargs) for edge_pair in zip(self.edges, self.dual_edges) ] + [ Transform( Mobject(*[ self.vertices[index] for index in cycle ]), dv, **kwargs ) for cycle, dv in zip( self.graph.region_cycles, self.dual_vertices ) ]) self.wait() class IntroduceGraph(GraphScene): def construct(self): GraphScene.construct(self) tweaked_graph = deepcopy(self.graph) for index in 2, 4: tweaked_graph.vertices[index] += 2.8*RIGHT + 1.8*DOWN tweaked_self = GraphScene(tweaked_graph) edges_to_remove = [ self.edges[self.graph.edges.index(pair)] for pair in [(4, 5), (0, 5), (1, 5), (7, 1), (8, 3)] ] connected, planar, graph = OldTexText([ "Connected ", "Planar ", "Graph" ]).to_edge(UP).split() not_okay = OldTexText("Not Okay").set_color("red") planar_explanation = OldTexText(""" (``Planar'' just means we can draw it without intersecting lines) """, size = "\\small") planar_explanation.shift(planar.get_center() + 0.5*DOWN) self.draw_vertices() self.draw_edges() self.clear() self.add(*self.vertices + self.edges) self.wait() self.add(graph) self.wait() kwargs = { "rate_func" : there_and_back, "run_time" : 5.0 } self.add(not_okay) self.play(*[ Transform(*pair, **kwargs) for pair in zip( self.edges + self.vertices, tweaked_self.edges + tweaked_self.vertices, ) ]) self.remove(not_okay) self.add(planar, planar_explanation) self.wait(2) self.remove(planar_explanation) self.add(not_okay) self.remove(*edges_to_remove) self.play(ShowCreation( Mobject(*edges_to_remove), rate_func = lambda t : 1 - t, run_time = 1.0 )) self.wait(2) self.remove(not_okay) self.add(connected, *edges_to_remove) self.wait() class OldIntroduceGraphs(GraphScene): def construct(self): GraphScene.construct(self) self.draw_vertices() self.draw_edges() self.wait() self.clear() self.add(*self.edges) self.replace_vertices_with(Face().scale(0.4)) friends = OldTexText("Friends").scale(EDGE_ANNOTATION_SCALE_FACTOR) self.annotate_edges(friends.shift((0, friends.get_height()/2, 0))) self.play(*[ CounterclockwiseTransform(vertex, Dot(point)) for vertex, point in zip(self.vertices, self.points) ]+[ Transform(ann, line) for ann, line in zip( self.edge_annotations, self.edges ) ]) self.wait() class PlanarGraphDefinition(Scene): def construct(self): Not, quote, planar, end_quote = OldTexText([ "Not \\\\", "``", "Planar", "''", # "no matter how \\\\ hard you try" ]).split() shift_val = Mobject(Not, planar).to_corner().get_center() Not.set_color("red").shift(shift_val) graphs = [ Mobject(*GraphScene(g).mobjects) for g in [ CubeGraph(), CompleteGraph(5), OctohedronGraph() ] ] self.add(quote, planar, end_quote) self.wait() self.play( FadeOut(quote), FadeOut(end_quote), ApplyMethod(planar.shift, shift_val), FadeIn(graphs[0]), run_time = 1.5 ) self.wait() self.remove(graphs[0]) self.add(graphs[1]) planar.set_color("red") self.add(Not) self.wait(2) planar.set_color("white") self.remove(Not) self.remove(graphs[1]) self.add(graphs[2]) self.wait(2) class TerminologyFromPolyhedra(GraphScene): args_list = [(CubeGraph(),)] def construct(self): GraphScene.construct(self) rot_kwargs = { "radians" : np.pi / 3, "run_time" : 5.0 } vertices = [ point / 2 + OUT if abs(point[0]) == 2 else point + IN for point in self.points ] cube = Mobject(*[ Line(vertices[edge[0]], vertices[edge[1]]) for edge in self.graph.edges ]) cube.rotate(-np.pi/3, [0, 0, 1]) cube.rotate(-np.pi/3, [0, 1, 0]) dots_to_vertices = OldTexText("Dots $\\to$ Vertices").to_corner() lines_to_edges = OldTexText("Lines $\\to$ Edges").to_corner() regions_to_faces = OldTexText("Regions $\\to$ Faces").to_corner() self.clear() # self.play(TransformAnimations( # Rotating(Dodecahedron(), **rot_kwargs), # Rotating(cube, **rot_kwargs) # )) self.play(Rotating(cube, **rot_kwargs)) self.clear() self.play(*[ Transform(l1, l2) for l1, l2 in zip(cube.split(), self.edges) ]) self.wait() self.add(dots_to_vertices) self.play(*[ ShowCreation(dot, run_time = 1.0) for dot in self.vertices ]) self.wait(2) self.remove(dots_to_vertices, *self.vertices) self.add(lines_to_edges) self.play(ApplyMethod( Mobject(*self.edges).set_color, "yellow" )) self.wait(2) self.clear() self.add(*self.edges) self.add(regions_to_faces) self.generate_regions() for region in self.regions: self.set_color_region(region) self.wait(3.0) class ThreePiecesOfTerminology(GraphScene): def construct(self): GraphScene.construct(self) terms = cycles, spanning_trees, dual_graphs = [ OldTexText(phrase).shift(y*UP).to_edge() for phrase, y in [ ("Cycles", 3), ("Spanning Trees", 1), ("Dual Graphs", -1), ] ] self.generate_spanning_tree() scale_factor = 1.2 def accent(mobject, color = "yellow"): return mobject.scale(scale_factor).set_color(color) def tone_down(mobject): return mobject.scale(1.0/scale_factor).set_color("white") self.add(accent(cycles)) self.trace_cycle(run_time = 1.0) self.wait() tone_down(cycles) self.remove(self.traced_cycle) self.add(accent(spanning_trees)) self.play(ShowCreation(self.spanning_tree), run_time = 1.0) self.wait() tone_down(spanning_trees) self.remove(self.spanning_tree) self.add(accent(dual_graphs, "red")) self.generate_dual_graph() for mob in self.mobjects: mob.fade self.play(*[ ShowCreation(mob, run_time = 1.0) for mob in self.dual_vertices + self.dual_edges ]) self.wait() self.clear() self.play(ApplyMethod( Mobject(*terms).center )) self.wait() class WalkingRandolph(GraphScene): args_list = [ (SampleGraph(), [0, 1, 7, 8]), ] @staticmethod def args_to_string(graph, path): return str(graph) + "".join(map(str, path)) def __init__(self, graph, path, *args, **kwargs): self.path = path GraphScene.__init__(self, graph, *args, **kwargs) def construct(self): GraphScene.construct(self) point_path = [self.get_points()[i] for i in self.path] randy = Randolph() randy.scale(RANDOLPH_SCALE_FACTOR) randy.move_to(point_path[0]) for next, last in zip(point_path[1:], point_path): self.play( WalkPiCreature(randy, next), ShowCreation(Line(last, next).set_color("yellow")), run_time = 2.0 ) self.randy = randy class PathExamples(GraphScene): args_list = [(SampleGraph(),)] def construct(self): GraphScene.construct(self) paths = [ (1, 2, 4, 5, 6), (6, 7, 1, 3), ] non_paths = [ [(0, 1), (7, 8), (5, 6),], [(5, 0), (0, 2), (0, 1)], ] valid_path = OldTexText("Valid \\\\ Path").set_color("green") not_a_path = OldTexText("Not a \\\\ Path").set_color("red") for mob in valid_path, not_a_path: mob.to_edge(UP) kwargs = {"run_time" : 1.0} for path, non_path in zip(paths, non_paths): path_lines = Mobject(*[ Line( self.get_points()[path[i]], self.get_points()[path[i+1]] ).set_color("yellow") for i in range(len(path) - 1) ]) non_path_lines = Mobject(*[ Line( self.get_points()[pp[0]], self.get_points()[pp[1]], ).set_color("yellow") for pp in non_path ]) self.remove(not_a_path) self.add(valid_path) self.play(ShowCreation(path_lines, **kwargs)) self.wait(2) self.remove(path_lines) self.remove(valid_path) self.add(not_a_path) self.play(ShowCreation(non_path_lines, **kwargs)) self.wait(2) self.remove(non_path_lines) class IntroduceCycle(WalkingRandolph): args_list = [ (SampleGraph(), [0, 1, 3, 2, 0]) ] def construct(self): WalkingRandolph.construct(self) self.remove(self.randy) encompassed_cycles = [c for c in self.graph.region_cycles if set(c).issubset(self.path)] regions = [ self.region_from_cycle(cycle) for cycle in encompassed_cycles ] for region in regions: self.set_color_region(region) self.wait() class IntroduceRandolph(GraphScene): def construct(self): GraphScene.construct(self) randy = Randolph().move_to((-3, 0, 0)) name = OldTexText("Randolph") self.play(Transform( randy, deepcopy(randy).scale(RANDOLPH_SCALE_FACTOR).move_to(self.get_points()[0]), )) self.wait() name.shift((0, 1, 0)) self.add(name) self.wait() class DefineSpanningTree(GraphScene): def construct(self): GraphScene.construct(self) randy = Randolph() randy.scale(RANDOLPH_SCALE_FACTOR).move_to(self.get_points()[0]) dollar_signs = OldTexText("\\$\\$") dollar_signs.scale(EDGE_ANNOTATION_SCALE_FACTOR) dollar_signs = Mobject(*[ deepcopy(dollar_signs).shift(edge.get_center()) for edge in self.edges ]) unneeded = OldTexText("unneeded!") unneeded.scale(EDGE_ANNOTATION_SCALE_FACTOR) self.generate_spanning_tree() def green_dot_at_index(index): return Dot( self.get_points()[index], radius = 2*Dot.DEFAULT_RADIUS, color = "lightgreen", ) def out_of_spanning_set(point_pair): stip = self.spanning_tree_index_pairs return point_pair not in stip and \ tuple(reversed(point_pair)) not in stip self.add(randy) self.accent_vertices(run_time = 2.0) self.add(dollar_signs) self.wait(2) self.remove(dollar_signs) run_time_per_branch = 0.5 self.play( ShowCreation(green_dot_at_index(0)), run_time = run_time_per_branch ) for pair in self.spanning_tree_index_pairs: self.play(ShowCreation( Line( self.get_points()[pair[0]], self.get_points()[pair[1]] ).set_color("yellow"), run_time = run_time_per_branch )) self.play(ShowCreation( green_dot_at_index(pair[1]), run_time = run_time_per_branch )) self.wait(2) unneeded_edges = list(filter(out_of_spanning_set, self.graph.edges)) for edge, limit in zip(unneeded_edges, list(range(5))): line = Line(self.get_points()[edge[0]], self.get_points()[edge[1]]) line.set_color("red") self.play(ShowCreation(line, run_time = 1.0)) self.add(unneeded.center().shift(line.get_center() + 0.2*UP)) self.wait() self.remove(line, unneeded) class NamingTree(GraphScene): def construct(self): GraphScene.construct(self) self.generate_spanning_tree() self.generate_treeified_spanning_tree() branches = self.spanning_tree.split() branches_copy = deepcopy(branches) treeified_branches = self.treeified_spanning_tree.split() tree = OldTexText("``Tree''").to_edge(UP) spanning_tree = OldTexText("``Spanning Tree''").to_edge(UP) self.add(*branches) self.play( FadeOut(Mobject(*self.edges + self.vertices)), Animation(Mobject(*branches)), ) self.clear() self.add(tree, *branches) self.wait() self.play(*[ Transform(b1, b2, run_time = 2) for b1, b2 in zip(branches, treeified_branches) ]) self.wait() self.play(*[ FadeIn(mob) for mob in self.edges + self.vertices ] + [ Transform(b1, b2, run_time = 2) for b1, b2 in zip(branches, branches_copy) ]) self.accent_vertices(run_time = 2) self.remove(tree) self.add(spanning_tree) self.wait(2) class DualGraph(GraphScene): def construct(self): GraphScene.construct(self) self.generate_dual_graph() self.add(OldTexText("Dual Graph").to_edge(UP).shift(2*LEFT)) self.play(*[ ShowCreation(mob) for mob in self.dual_edges + self.dual_vertices ]) self.wait() class FacebookLogo(Scene): def construct(self): im = ImageMobject("facebook_full_logo", invert = False) self.add(im.scale(0.7)) class FacebookGraph(GraphScene): def construct(self): GraphScene.construct(self) account = ImageMobject("facebook_silhouette", invert = False) account.scale(0.05) logo = ImageMobject("facebook_logo", invert = False) logo.scale(0.1) logo.shift(0.2*LEFT + 0.1*UP) account.add(logo).center() account.shift(0.2*LEFT + 0.1*UP) friends = OldTex( "\\leftarrow \\text{friends} \\rightarrow" ).scale(0.5*EDGE_ANNOTATION_SCALE_FACTOR) self.clear() accounts = [ deepcopy(account).shift(point) for point in self.points ] self.add(*accounts) self.wait() self.annotate_edges(friends) self.wait() self.play(*[ CounterclockwiseTransform(account, vertex) for account, vertex in zip(accounts, self.vertices) ]) self.wait() self.play(*[ Transform(ann, edge) for ann, edge in zip(self.edge_annotations, self.edges) ]) self.wait() class FacebookGraphAsAbstractSet(Scene): def construct(self): names = [ "Louis", "Randolph", "Mortimer", "Billy Ray", "Penelope", ] friend_pairs = [ (0, 1), (0, 2), (1, 2), (3, 0), (4, 0), (1, 3), (1, 2), ] names_string = "\\\\".join(names + ["$\\vdots$"]) friends_string = "\\\\".join([ "\\text{%s}&\\leftrightarrow\\text{%s}"%(names[i],names[j]) for i, j in friend_pairs ] + ["\\vdots"]) names_mob = OldTexText(names_string).shift(3*LEFT) friends_mob = OldTex( friends_string, size = "\\Large" ).shift(3*RIGHT) accounts = OldTexText("\\textbf{Accounts}") accounts.shift(3*LEFT).to_edge(UP) friendships = OldTexText("\\textbf{Friendships}") friendships.shift(3*RIGHT).to_edge(UP) lines = Mobject( Line(UP*FRAME_Y_RADIUS, DOWN*FRAME_Y_RADIUS), Line(LEFT*FRAME_X_RADIUS + 3*UP, RIGHT*FRAME_X_RADIUS + 3*UP) ).set_color("white") self.add(accounts, friendships, lines) self.wait() for mob in names_mob, friends_mob: self.play(ShowCreation( mob, run_time = 1.0 )) self.wait() class ExamplesOfGraphs(GraphScene): def construct(self): buff = 0.5 self.graph.vertices = [v + DOWN + RIGHT for v in self.graph.vertices] GraphScene.construct(self) self.generate_regions() objects, notions = Mobject(*TexText( ["Objects \\quad\\quad ", "Thing that connects objects"] )).to_corner().shift(0.5*RIGHT).split() horizontal_line = Line( (-FRAME_X_RADIUS, FRAME_Y_RADIUS-1, 0), (max(notions.get_points()[:,0]), FRAME_Y_RADIUS-1, 0) ) vert_line_x_val = min(notions.get_points()[:,0]) - buff vertical_line = Line( (vert_line_x_val, FRAME_Y_RADIUS, 0), (vert_line_x_val,-FRAME_Y_RADIUS, 0) ) objects_and_notions = [ ("Facebook accounts", "Friendship"), ("English Words", "Differ by One Letter"), ("Mathematicians", "Coauthorship"), ("Neurons", "Synapses"), ( "Regions our graph \\\\ cuts the plane into", "Shared edges" ) ] self.clear() self.add(objects, notions, horizontal_line, vertical_line) for (obj, notion), height in zip(objects_and_notions, it.count(2, -1)): obj_mob = OldTexText(obj, size = "\\small").to_edge(LEFT) not_mob = OldTexText(notion, size = "\\small").to_edge(LEFT) not_mob.shift((vert_line_x_val + FRAME_X_RADIUS)*RIGHT) obj_mob.shift(height*UP) not_mob.shift(height*UP) if obj.startswith("Regions"): self.handle_dual_graph(obj_mob, not_mob) elif obj.startswith("English"): self.handle_english_words(obj_mob, not_mob) else: self.add(obj_mob) self.wait() self.add(not_mob) self.wait() def handle_english_words(self, words1, words2): words = list(map(TexText, ["graph", "grape", "gape", "gripe"])) words[0].shift(RIGHT) words[1].shift(3*RIGHT) words[2].shift(3*RIGHT + 2*UP) words[3].shift(3*RIGHT + 2*DOWN) lines = [ Line(*pair) for pair in [ ( words[0].get_center() + RIGHT*words[0].get_width()/2, words[1].get_center() + LEFT*words[1].get_width()/2 ),( words[1].get_center() + UP*words[1].get_height()/2, words[2].get_center() + DOWN*words[2].get_height()/2 ),( words[1].get_center() + DOWN*words[1].get_height()/2, words[3].get_center() + UP*words[3].get_height()/2 ) ] ] comp_words = Mobject(*words) comp_lines = Mobject(*lines) self.add(words1) self.play(ShowCreation(comp_words, run_time = 1.0)) self.wait() self.add(words2) self.play(ShowCreation(comp_lines, run_time = 1.0)) self.wait() self.remove(comp_words, comp_lines) def handle_dual_graph(self, words1, words2): words1.set_color("yellow") words2.set_color("yellow") connected = OldTexText("Connected") connected.set_color("lightgreen") not_connected = OldTexText("Not Connected") not_connected.set_color("red") for mob in connected, not_connected: mob.shift(self.get_points()[3] + UP) self.play(*[ ShowCreation(mob, run_time = 1.0) for mob in self.edges + self.vertices ]) self.wait() for region in self.regions: self.set_color_region(region) self.add(words1) self.wait() self.reset_background() self.add(words2) region_pairs = it.combinations(self.graph.region_cycles, 2) for x in range(6): want_matching = (x%2 == 0) found = False while True: try: cycle1, cycle2 = next(region_pairs) except: return shared = set(cycle1).intersection(cycle2) if len(shared) == 2 and want_matching: break if len(shared) != 2 and not want_matching: break for cycle in cycle1, cycle2: index = self.graph.region_cycles.index(cycle) self.set_color_region(self.regions[index]) if want_matching: self.remove(not_connected) self.add(connected) tup = tuple(shared) if tup not in self.graph.edges: tup = tuple(reversed(tup)) edge = deepcopy(self.edges[self.graph.edges.index(tup)]) edge.set_color("red") self.play(ShowCreation(edge), run_time = 1.0) self.wait() self.remove(edge) else: self.remove(connected) self.add(not_connected) self.wait(2) self.reset_background() class DrawDualGraph(GraphScene): def construct(self): GraphScene.construct(self) self.generate_regions() self.generate_dual_graph() region_mobs = [ ImageMobject(disp.paint_region(reg, self.background), invert = False) for reg in self.regions ] for region, mob in zip(self.regions, region_mobs): self.set_color_region(region, mob.get_color()) outer_region = self.regions.pop() outer_region_mob = region_mobs.pop() outer_dual_vertex = self.dual_vertices.pop() internal_edges = [e for e in self.dual_edges if abs(e.start[0]) < FRAME_X_RADIUS and \ abs(e.end[0]) < FRAME_X_RADIUS and \ abs(e.start[1]) < FRAME_Y_RADIUS and \ abs(e.end[1]) < FRAME_Y_RADIUS] external_edges = [e for e in self.dual_edges if e not in internal_edges] self.wait() self.reset_background() self.set_color_region(outer_region, outer_region_mob.get_color()) self.play(*[ Transform(reg_mob, dot) for reg_mob, dot in zip(region_mobs, self.dual_vertices) ]) self.wait() self.reset_background() self.play(ApplyFunction( lambda p : (FRAME_X_RADIUS + FRAME_Y_RADIUS)*p/get_norm(p), outer_region_mob )) self.wait() for edges in internal_edges, external_edges: self.play(*[ ShowCreation(edge, run_time = 2.0) for edge in edges ]) self.wait() class EdgesAreTheSame(GraphScene): def construct(self): GraphScene.construct(self) self.generate_dual_graph() self.remove(*self.vertices) self.add(*self.dual_edges) self.wait() self.play(*[ Transform(*pair, run_time = 2.0) for pair in zip(self.dual_edges, self.edges) ]) self.wait() self.add( OldTexText(""" (Or at least I would argue they should \\\\ be thought of as the same thing.) """, size = "\\small").to_edge(UP) ) self.wait() class ListOfCorrespondances(Scene): def construct(self): buff = 0.5 correspondances = [ ["Regions cut out by", "Vertices of"], ["Edges of", "Edges of"], ["Cycles of", "Connected components of"], ["Connected components of", "Cycles of"], ["Spanning tree in", "Complement of spanning tree in"], ["", "Dual of"], ] for corr in correspondances: corr[0] += " original graph" corr[1] += " dual graph" arrow = OldTex("\\leftrightarrow", size = "\\large") lines = [] for corr, height in zip(correspondances, it.count(3, -1)): left = OldTexText(corr[0], size = "\\small") right = OldTexText(corr[1], size = "\\small") this_arrow = deepcopy(arrow) for mob in left, right, this_arrow: mob.shift(height*UP) arrow_xs = this_arrow.get_points()[:,0] left.to_edge(RIGHT) left.shift((min(arrow_xs) - FRAME_X_RADIUS, 0, 0)) right.to_edge(LEFT) right.shift((max(arrow_xs) + FRAME_X_RADIUS, 0, 0)) lines.append(Mobject(left, right, this_arrow)) last = None for line in lines: self.add(line.set_color("yellow")) if last: last.set_color("white") last = line self.wait(1) class CyclesCorrespondWithConnectedComponents(GraphScene): args_list = [(SampleGraph(),)] def construct(self): GraphScene.construct(self) self.generate_regions() self.generate_dual_graph() cycle = [4, 2, 1, 5, 4] enclosed_regions = [0, 2, 3, 4] dual_cycle = DUAL_CYCLE enclosed_vertices = [0, 1] randy = Randolph() randy.scale(RANDOLPH_SCALE_FACTOR) randy.move_to(self.get_points()[cycle[0]]) lines_to_remove = [] for last, next in zip(cycle, cycle[1:]): line = Line(self.get_points()[last], self.get_points()[next]) line.set_color("yellow") self.play( ShowCreation(line), WalkPiCreature(randy, self.get_points()[next]), run_time = 1.0 ) lines_to_remove.append(line) self.wait() self.remove(randy, *lines_to_remove) for region in np.array(self.regions)[enclosed_regions]: self.set_color_region(region) self.wait(2) self.reset_background() lines = Mobject(*[ Line(self.dual_points[last], self.dual_points[next]) for last, next in zip(dual_cycle, dual_cycle[1:]) ]).set_color("red") self.play(ShowCreation(lines)) self.play(*[ Transform(v, Dot( v.get_center(), radius = 3*Dot.DEFAULT_RADIUS ).set_color("green")) for v in np.array(self.vertices)[enclosed_vertices] ] + [ ApplyMethod(self.edges[0].set_color, "green") ]) self.wait() class IntroduceMortimer(GraphScene): args_list = [(SampleGraph(),)] def construct(self): GraphScene.construct(self) self.generate_dual_graph() self.generate_regions() randy = Randolph().shift(LEFT) morty = Mortimer().shift(RIGHT) name = OldTexText("Mortimer") name.shift(morty.get_center() + 1.2*UP) randy_path = (0, 1, 3) morty_path = (-2, -3, -4) morty_crossed_lines = [ Line(self.get_points()[i], self.get_points()[j]).set_color("red") for i, j in [(7, 1), (1, 5)] ] kwargs = {"run_time" : 1.0} self.clear() self.add(randy) self.wait() self.add(morty, name) self.wait() self.remove(name) small_randy = deepcopy(randy).scale(RANDOLPH_SCALE_FACTOR) small_morty = deepcopy(morty).scale(RANDOLPH_SCALE_FACTOR) small_randy.move_to(self.get_points()[randy_path[0]]) small_morty.move_to(self.dual_points[morty_path[0]]) self.play(*[ FadeIn(mob) for mob in self.vertices + self.edges ] + [ Transform(randy, small_randy), Transform(morty, small_morty), ], **kwargs) self.wait() self.set_color_region(self.regions[morty_path[0]]) for last, next in zip(morty_path, morty_path[1:]): self.play(WalkPiCreature(morty, self.dual_points[next]),**kwargs) self.set_color_region(self.regions[next]) self.wait() for last, next in zip(randy_path, randy_path[1:]): line = Line(self.get_points()[last], self.get_points()[next]) line.set_color("yellow") self.play( WalkPiCreature(randy, self.get_points()[next]), ShowCreation(line), **kwargs ) self.wait() self.play(*[ ApplyMethod( line.rotate, np.pi/10, rate_func = wiggle) for line in morty_crossed_lines ], **kwargs) self.wait() class RandolphMortimerSpanningTreeGame(GraphScene): args_list = [(SampleGraph(),)] def construct(self): GraphScene.construct(self) self.generate_spanning_tree() self.generate_dual_graph() self.generate_regions() randy = Randolph().scale(RANDOLPH_SCALE_FACTOR) morty = Mortimer().scale(RANDOLPH_SCALE_FACTOR) randy.move_to(self.get_points()[0]) morty.move_to(self.dual_points[0]) attempted_dual_point_index = 2 region_ordering = [0, 1, 7, 2, 3, 5, 4, 6] dual_edges = [1, 3, 4, 7, 11, 9, 13] time_per_dual_edge = 0.5 self.add(randy, morty) self.play(ShowCreation(self.spanning_tree)) self.wait() self.play(WalkPiCreature( morty, self.dual_points[attempted_dual_point_index], rate_func = lambda t : 0.3 * there_and_back(t), run_time = 2.0, )) self.wait() for index in range(len(self.regions)): # if index > 0: # edge = self.edges[dual_edges[index-1]] # midpoint = edge.get_center() # self.play(*[ # ShowCreation(Line( # midpoint, # tip # ).set_color("red")) # for tip in edge.start, edge.end # ], run_time = time_per_dual_edge) self.set_color_region(self.regions[region_ordering[index]]) self.wait(time_per_dual_edge) self.wait() cycle_index = region_ordering[-1] cycle = self.graph.region_cycles[cycle_index] self.set_color_region(self.regions[cycle_index], "black") self.play(ShowCreation(Mobject(*[ Line(self.get_points()[last], self.get_points()[next]).set_color("green") for last, next in zip(cycle, list(cycle)[1:] + [cycle[0]]) ]))) self.wait() class MortimerCannotTraverseCycle(GraphScene): args_list = [(SampleGraph(),)] def construct(self): GraphScene.construct(self) self.generate_dual_graph() dual_cycle = DUAL_CYCLE trapped_points = [0, 1] morty = Mortimer().scale(RANDOLPH_SCALE_FACTOR) morty.move_to(self.dual_points[dual_cycle[0]]) time_per_edge = 0.5 text = OldTexText(""" One of these lines must be included in the spanning tree if those two inner vertices are to be reached. """).scale(0.7).to_edge(UP) all_lines = [] matching_edges = [] kwargs = {"run_time" : time_per_edge, "rate_func" : None} for last, next in zip(dual_cycle, dual_cycle[1:]): line = Line(self.dual_points[last], self.dual_points[next]) line.set_color("red") self.play( WalkPiCreature(morty, self.dual_points[next], **kwargs), ShowCreation(line, **kwargs), ) all_lines.append(line) center = line.get_center() distances = [get_norm(center - e.get_center()) for e in self.edges] matching_edges.append( self.edges[distances.index(min(distances))] ) self.play(*[ Transform(v, Dot( v.get_center(), radius = 3*Dot.DEFAULT_RADIUS, color = "green" )) for v in np.array(self.vertices)[trapped_points] ]) self.add(text) self.play(*[ Transform(line, deepcopy(edge).set_color(line.get_color())) for line, edge in zip(all_lines, matching_edges) ]) self.wait() class TwoPropertiesOfSpanningTree(Scene): def construct(self): spanning, tree = OldTexText( ["Spanning ", "Tree"], size = "\\Huge" ).split() spanning_explanation = OldTexText(""" Touches every vertex """).shift(spanning.get_center() + 2*DOWN) tree_explanation = OldTexText(""" No Cycles """).shift(tree.get_center() + 2*UP) self.add(spanning, tree) self.wait() for word, explanation, vect in [ (spanning, spanning_explanation, 0.5*UP), (tree, tree_explanation, 0.5*DOWN) ]: self.add(explanation) self.add(Arrow( explanation.get_center() + vect, tail = word.get_center() - vect, )) self.play(ApplyMethod(word.set_color, "yellow")) self.wait() class DualSpanningTree(GraphScene): def construct(self): GraphScene.construct(self) self.generate_dual_graph() self.generate_spanning_tree() randy = Randolph() randy.scale(RANDOLPH_SCALE_FACTOR) randy.move_to(self.get_points()[0]) morty = Mortimer() morty.scale(RANDOLPH_SCALE_FACTOR) morty.move_to(self.dual_points[0]) dual_edges = [1, 3, 4, 7, 11, 9, 13] words = OldTexText(""" The red edges form a spanning tree of the dual graph! """).to_edge(UP) self.add(self.spanning_tree, randy, morty) self.play(ShowCreation(Mobject( *np.array(self.edges)[dual_edges] ).set_color("red"))) self.add(words) self.wait() class TreeCountFormula(Scene): def construct(self): time_per_branch = 0.5 text = OldTexText(""" In any tree: $$E + 1 = V$$ """) gs = GraphScene(SampleGraph()) gs.generate_treeified_spanning_tree() branches = gs.treeified_spanning_tree.to_edge(LEFT).split() all_dots = [Dot(branches[0].get_points()[0])] self.add(text, all_dots[0]) for branch in branches: self.play( ShowCreation(branch), run_time = time_per_branch ) dot = Dot(branch.get_points()[-1]) self.add(dot) all_dots.append(dot) self.wait() self.remove(*all_dots) self.play( FadeOut(text), FadeIn(Mobject(*gs.edges + gs.vertices)), *[ Transform(*pair) for pair in zip(branches,gs.spanning_tree.split()) ] ) class FinalSum(Scene): def construct(self): lines = OldTex([ "(\\text{Number of Randolph's Edges}) + 1 &= V \\\\ \n", "(\\text{Number of Mortimer's Edges}) + 1 &= F \\\\ \n", " \\Downarrow \\\\", "E","+","2","&=","V","+","F", ], size = "\\large").split() for line in lines[:2] + [Mobject(*lines[2:])]: self.add(line) self.wait() self.wait() symbols = V, minus, E, plus, F, equals, two = OldTex( "V - E + F = 2".split(" ") ) plus = OldTex("+") anims = [] for mob, index in zip(symbols, [-3, -2, -7, -6, -1, -4, -5]): copy = plus if index == -2 else deepcopy(mob) copy.center().shift(lines[index].get_center()) copy.scale(lines[index].get_width()/mob.get_width()) anims.append(CounterclockwiseTransform(copy, mob)) self.clear() self.play(*anims, run_time = 2.0) self.wait() if __name__ == "__main__": command_line_create_scene(MOVIE_PREFIX)
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from animation import * from mobject import * from constants import * from mobject.region import * from scene.scene import Scene, SceneFromVideo from script_wrapper import command_line_create_scene from functools import reduce MOVIE_PREFIX = "counting_in_binary/" COUNT_TO_FRAME_NUM = { 0 : 0, 1 : 53, 2 : 84, 3 : 128, 4 : 169, 5 : 208, 6 : 238, 7 : 281, 8 : 331, 9 : 365, 10 : 395, 11 : 435, 12 : 475, 13 : 518, 14 : 556, 15 : 595, 16 : 636, 17 : 676, 18 : 709, 19 : 753, 20 : 790, 21 : 835, 22 : 869, 23 : 903, 24 : 950, 25 : 988, 26 : 1027, 27 : 1065, 28 : 1104, 29 : 1145, 30 : 1181, 31 : 1224, 32 : 1239, } class Hand(ImageMobject): def __init__(self, num, **kwargs): Mobject2D.__init__(self, **kwargs) path = os.path.join( VIDEO_DIR, MOVIE_PREFIX, "images", "Hand%d.png"%num ) invert = False if self.read_in_cached_attrs(path, invert): return ImageMobject.__init__(self, path, invert) center = self.get_center() self.center() self.rotate(np.pi, axis = RIGHT+UP) self.sort_points(lambda p : np.log(complex(*p[:2])).imag) self.rotate(np.pi, axis = RIGHT+UP) self.shift(center) self.cache_attrs(path, invert = False) class EdgeDetection(SceneFromVideo): args_list = [ ("CountingInBinary.m4v", 35, 70), ("CountingInBinary.m4v", 0, 100), ("CountingInBinary.m4v", 10, 50), ] @staticmethod def args_to_string(filename, t1, t2): return "-".join([filename.split(".")[0], str(t1), str(t2)]) def construct(self, filename, t1, t2): path = os.path.join(VIDEO_DIR, filename) SceneFromVideo.construct(self, path) self.apply_gaussian_blur() self.apply_edge_detection(t1, t2) class BufferedCounting(SceneFromVideo): def construct(self): path = os.path.join(VIDEO_DIR, "CountingInBinary.m4v") time_range = (3, 42) SceneFromVideo.construct(self, path, time_range = time_range) self.buffer_pixels(spreads = (3, 2)) # self.make_all_black_or_white() def buffer_pixels(self, spreads = (2, 2)): ksize = (5, 5) sigmaX = 10 threshold1 = 35 threshold2 = 70 matrices = [ thick_diagonal(dim, spread) for dim, spread in zip(self.shape, spreads) ] for frame, index in zip(self.frames, it.count()): print(index + "of" + len(self.frames)) blurred = cv2.GaussianBlur(frame, ksize, sigmaX) edged = cv2.Canny(blurred, threshold1, threshold2) buffed = reduce(np.dot, [matrices[0], edged, matrices[1]]) for i in range(3): self.frames[index][:,:,i] = buffed def make_all_black_or_white(self): self.frames = [ 255*(frame != 0).astype('uint8') for frame in self.frames ] class ClearLeftSide(SceneFromVideo): args_list = [ ("BufferedCounting",), ] @staticmethod def args_to_string(scenename): return scenename def construct(self, scenename): path = os.path.join(VIDEO_DIR, MOVIE_PREFIX, scenename + ".mp4") SceneFromVideo.construct(self, path) self.set_color_region_over_time_range( Region(lambda x, y : x < -1, shape = self.shape) ) class DraggedPixels(SceneFromVideo): args_list = [ ("BufferedCounting",), ("CountingWithLeftClear",), ] @staticmethod def args_to_string(*args): return args[0] def construct(self, video): path = os.path.join(VIDEO_DIR, MOVIE_PREFIX, video+".mp4") SceneFromVideo.construct(self, path) self.drag_pixels() def drag_pixels(self, num_frames_to_drag_over = 5): for index in range(len(self.frames)-1, 0, -1): self.frames[index] = np.max([ self.frames[k] for k in range( max(index-num_frames_to_drag_over, 0), index ) ], axis = 0) class SaveEachNumber(SceneFromVideo): def construct(self): path = os.path.join(VIDEO_DIR, MOVIE_PREFIX, "ClearLeftSideBufferedCounting.mp4") SceneFromVideo.construct(self, path) for count in COUNT_TO_FRAME_NUM: path = os.path.join( VIDEO_DIR, MOVIE_PREFIX, "images", "Hand%d.png"%count ) Image.fromarray(self.frames[COUNT_TO_FRAME_NUM[count]]).save(path) class ShowCounting(SceneFromVideo): args_list = [ ("CountingWithLeftClear",), ("ClearLeftSideBufferedCounting",), ] @staticmethod def args_to_string(filename): return filename def construct(self, filename): path = os.path.join(VIDEO_DIR, MOVIE_PREFIX, filename + ".mp4") SceneFromVideo.construct(self, path) total_time = len(self.frames)*self.frame_duration for count in range(32): print(count) mob = OldTex(str(count)).scale(1.5) mob.shift(0.3*LEFT).to_edge(UP, buff = 0.1) index_range = list(range( max(COUNT_TO_FRAME_NUM[count]-10, 0), COUNT_TO_FRAME_NUM[count+1]-10)) for index in index_range: self.frames[index] = disp.paint_mobject( mob, self.frames[index] ) class ShowFrameNum(SceneFromVideo): args_list = [ ("ClearLeftSideBufferedCounting",), ] @staticmethod def args_to_string(filename): return filename def construct(self, filename): path = os.path.join(VIDEO_DIR, MOVIE_PREFIX, filename+".mp4") SceneFromVideo.construct(self, path) for frame, count in zip(self.frames, it.count()): print(count + "of" + len(self.frames)) mob = Mobject(*[ OldTex(char).shift(0.3*x*RIGHT) for char, x, in zip(str(count), it.count()) ]) self.frames[count] = disp.paint_mobject( mob.to_corner(UP+LEFT), frame ) if __name__ == "__main__": command_line_create_scene(MOVIE_PREFIX)
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from manim_imports_ext import * from script_wrapper import command_line_create_scene MOVIE_PREFIX = "counting_in_binary/" BASE_HAND_FILE = os.path.join(VIDEO_DIR, MOVIE_PREFIX, "Base.mp4") FORCED_FRAME_DURATION = 0.02 TIME_RANGE = (0, 42) INITIAL_PADDING = 27 NUM_GOOD_FRAMES = 1223 ALGORITHM_TEXT = [ """ \\begin{flushleft} Turn up the rightmost finger that is down. """, """ Turn down all fingers to its right. \\end{flushleft} """ ] FINGER_WORDS = [ "Thumb", "Index Finger", "Middle Finger", "Ring Finger", "Pinky", ] COUNT_TO_FRAME_NUM = { 0 : 0, 1 : 27, 2 : 76, 3 : 110, 4 : 163, 5 : 189, 6 : 226, 7 : 264, 8 : 318, 9 : 356, 10 : 384, 11 : 423, 12 : 457, 13 : 513, 14 : 528, 15 : 590, 16 : 620, 17 : 671, 18 : 691, 19 : 740, 20 : 781, 21 : 810, 22 : 855, 23 : 881, 24 : 940, 25 : 970, 26 : 1014, 27 : 1055, 28 : 1092, 29 : 1143, 30 : 1184, 31 : 1219, } COUNT_TO_TIP_POS = { 0 : [5.0, 0.5, 0.0], 1 : [3.1, 2.5, 0.0], 2 : [1.5, 2.3, 0.0], 3 : [0.7, 2.0, 0.0], 4 : [0.0, 1.0, 0.0], } def finger_tip_power_of_2(finger_no): return OldTex(str(2**finger_no)).shift(COUNT_TO_TIP_POS[finger_no]) class Hand(ImageMobject): STARTING_BOTTOM_RIGHT = [4.61111111e+00, -3.98888889e+00, 9.80454690e-16] def __init__(self, num, small = False, **kwargs): Mobject2D.__init__(self, **kwargs) path = os.path.join( VIDEO_DIR, MOVIE_PREFIX, "images", "Hand%d.png"%num ) invert = False if not self.read_in_cached_attrs(path, invert): ImageMobject.__init__(self, path, invert = invert) center = self.get_center() self.center() self.rotate(np.pi, axis = RIGHT+UP) self.sort_points(lambda p : np.log(complex(*p[:2])).imag) self.rotate(np.pi, axis = RIGHT+UP) self.shift(center) self.cache_attrs(path, invert = False) self.shift(self.STARTING_BOTTOM_RIGHT-self.get_boundary_point(DOWN+RIGHT)) if small: self.shrink() def shrink(self): self.scale(0.8).to_edge(DOWN, buff = 0.0) # def set_color_thumb(self, color = "yellow"): # self.set_color( # color = color, # condition = lambda p : p[0] > 4.5 and p[1] > -1.5 # ) def get_algorithm(): return OldTexText(ALGORITHM_TEXT) def get_finger_colors(): return list(Color("yellow").range_to("red", 5)) def five_char_binary(num): result = bin(num)[2:] return (5-len(result))*"0" + result def read_reversed_binary(string): return sum([ 2**count if char == '1' else 0 for count, char in zip(it.count(), string) ]) class LeftHand(Hand): def __init__(self, num, **kwargs): Hand.__init__( self, read_reversed_binary(five_char_binary(num)), **kwargs ) self.rotate(np.pi, UP) self.shift(LEFT) def get_hand_map(which_hand = "right"): if which_hand == "right": Class = Hand elif which_hand == "left": Class = LeftHand else: print("Bad arg, bro") return return dict([ (num, Class(num, small=True)) for num in range(32) ]) class OverHand(SceneFromVideo): def construct(self): SceneFromVideo.construct(self, BASE_HAND_FILE) self.frame_duration = FORCED_FRAME_DURATION self.frames = self.frames[:NUM_GOOD_FRAMES] class SaveEachNumber(OverHand): def construct(self): OverHand.construct(self) for count in COUNT_TO_FRAME_NUM: path = os.path.join( VIDEO_DIR, MOVIE_PREFIX, "images", "Hand%d.png"%count ) Image.fromarray(self.frames[COUNT_TO_FRAME_NUM[count]]).save(path) def write_to_movie(self, name = None): print("Why bother writing to movie...") class ShowCounting(OverHand): def construct(self): OverHand.construct(self) self.frames = INITIAL_PADDING*[self.frames[0]] + self.frames num_frames = len(self.frames) self.frames = [ disp.paint_mobject( self.get_counting_mob(32*count // num_frames), frame ) for frame, count in zip(self.frames, it.count()) ] def get_counting_mob(self, count): mob = OldTex(str(count)) mob.scale(2) mob.shift(LEFT) mob.to_edge(UP, buff = 0.1) return mob class ShowFrameNum(OverHand): def construct(self): OverHand.construct(self) for frame, count in zip(self.frames, it.count()): print(count + "of" + len(self.frames)) mob = Mobject(*[ OldTex(char).shift(0.3*x*RIGHT) for char, x, in zip(str(count), it.count()) ]) self.frames[count] = disp.paint_mobject( mob.to_corner(UP+LEFT), frame ) class CountTo1023(Scene): def construct(self): rh_map = get_hand_map("right") lh_map = get_hand_map("left") def get_num(count): return Mobject(*[ OldTex(char).shift(0.35*x*RIGHT) for char, x, in zip(str(count), it.count()) ]).center().to_edge(UP) self.frames = [ disp.paint_mobject(Mobject( rh_map[count%32], lh_map[count//32], get_num(count) )) for count in range(2**10) ] class Introduction(Scene): def construct(self): words = OldTexText(""" First, let's see how to count to 31 on just one hand... """) hand = Hand(0) for mob in words, hand: mob.sort_points(lambda p : p[0]) self.add(words) self.wait() self.play(DelayByOrder(Transform(words, hand))) self.wait() class ShowReadingRule(Scene): def construct(self): sample_counts = [6, 17, 27, 31] question = OldTexText(""" How do you recognize what number a given configuration represents? """, size = "\\Huge").scale(0.75).to_corner(UP+LEFT) answer = OldTexText([ "Think of each finger as representing a power of 2, ", "then add up the numbers represented by the standing fingers." ], size = "\\Huge").scale(0.75).to_corner(UP+LEFT).split() self.add(question) for count in sample_counts: hand = Hand(count, small = True) self.add(hand) self.wait() self.remove(hand) self.add(hand) self.wait() self.remove(question) self.add(answer[0]) counts = list(map(finger_tip_power_of_2, list(range(5)))) for count in counts: self.play(SpinInFromNothing(count, run_time = 0.3)) self.wait() self.play(ShimmerIn(answer[1])) for count in sample_counts: self.clear() self.add(*answer) self.read_sample(count) def read_sample(self, num): hand = Hand(num, small = True) bool_arr = [c == '1' for c in five_char_binary(num)] counts = [4-count for count in range(5) if bool_arr[count]] count_mobs = list(map(finger_tip_power_of_2, counts)) if num in [6, 27]: count_mobs[1].shift(0.2*DOWN + 0.2*LEFT) if num in [6, 17]: hand.shift(0.8*LEFT) sum_mobs = OldTex( " + ".join([str(2**c) for c in counts]).split(" ") + ["=%d"%num] ).to_corner(UP+RIGHT).split() self.add(hand, *count_mobs) self.wait() self.play(*[ Transform(count_mobs[n/2], sum_mobs[n]) if n%2 == 0 and n/2 < len(counts) else FadeIn(sum_mobs[n]) for n in range(len(sum_mobs)) ]) self.wait(2.0) class ShowIncrementRule(Scene): def construct(self): #First count from 18 to 22 def to_left(words): return "\\begin{flushleft}" + words + "\\end{flushleft}" phrases = [ OldTexText(to_left(words), size = "\\Huge").scale(0.75).to_corner(UP+LEFT) for words in [ "But while you're counting, you don't need to think about powers of 2.", "Can you see the pattern for incrementing?", "If the thumb is down, turn it up.", "If the thumb is up, but the forefinger is down, flip them both.", "If the thumb and forefinger are up, but the middle finger is down, flip all three.", "In general, flip all of the fingers up to the rightmost one which is down.", "After practicing for a minute or two, you're mind starts doing it automatically.", "Question: Why does this rule for incrementation work?", ] ] ranges = [ (0, 14, False), (14, 28, False), (12, 13, True), (29, 31, True), (27, 29, True), (23, 24, True), (14, 20, False), (20, 26, False) ] oh = OverHand() for phrase, (start, end, pause) in zip(phrases, ranges): if pause: self.background = oh.frames[COUNT_TO_FRAME_NUM[start]] self.add(phrase) self.play(ShimmerIn(self.get_arrow_set(start))) self.wait() self.clear() self.reset_background() self.frames += [ disp.paint_mobject(phrase, frame) for frame in oh.frames[COUNT_TO_FRAME_NUM[start]:COUNT_TO_FRAME_NUM[end]] ] if pause: self.frames += [self.frames[-1]]*int(1.0/self.frame_duration) def get_arrow_set(self, num): arrow = OldTex("\\downarrow", size = "\\Huge") arrow.set_color("green") arrow.shift(-arrow.get_bottom()) if num == 12: tips = [(4, 1, 0)] elif num == 29: tips = [ (6, 1.5, 0), (3, 1.5, 0), ] elif num == 27: tips = [ (5.5, 1.5, 0), (2.75, 3.5, 0), (2, 1.0, 0), ] elif num == 23: tips = [ (6, 1, 0), (3.25, 3.5, 0), (2.25, 3.5, 0), (1.5, 0.75, 0), ] return Mobject(*[ deepcopy(arrow).shift(tip) for tip in tips ]) class MindFindsShortcuts(Scene): def construct(self): words1 = OldTexText(""" Before long, your mind starts to recognize certain patterns without needing to perform the addition. """, size = "\\Huge").scale(0.75).to_corner(LEFT+UP) words2 = OldTexText(""" Which makes it faster to recognize other patterns... """, size = "\\Huge").scale(0.75).to_corner(LEFT+UP) hand = Hand(7).scale(0.5).center().shift(DOWN+2*LEFT) sum421 = OldTex("4+2+1").shift(DOWN+2*RIGHT) seven = OldTex("7").shift(DOWN+6*RIGHT) compound = Mobject( Arrow(hand, sum421), sum421, Arrow(sum421, seven) ) self.add( words1, hand, compound, seven ) self.wait() self.play( Transform(compound, Arrow(hand, seven).set_color("yellow")), ShimmerIn(OldTexText("Directly recognize").shift(1.5*DOWN+2*RIGHT)) ) self.wait() self.clear() hands = dict([ (num, Hand(num).center().scale(0.5).shift(DOWN)) for num in [23, 16, 7] ]) hands[23].shift(5*LEFT) hands[16].shift(LEFT) hands[7].shift(3*RIGHT) for num in 7, 16: hands[num].add(OldTex(str(num)).shift(hands[num].get_top()+0.5*UP)) plus = OldTex("+").shift(DOWN + RIGHT) equals = OldTex("=").shift(DOWN + 2.5*LEFT) equals23 = OldTex("=23").shift(DOWN + 5.5*RIGHT) self.add(words2, hands[23]) self.wait() self.play( Transform( deepcopy(hands[16]).set_color("black").center().shift(hands[23].get_center()), hands[16] ), Transform( deepcopy(hands[7]).set_color("black").center().shift(hands[23].get_center()), hands[7] ), Animation(hands[23]), FadeIn(equals), FadeIn(plus) ) self.wait() self.play(ShimmerIn(equals23)) self.wait() class CountingExampleSentence(ShowCounting): def construct(self): words = "As an example, this is me counting the number of words in this sentence on just one hand!" self.words = OldTexText(words.split(), size = "\\Huge").scale(0.7).to_corner(UP+LEFT, buff = 0.25).split() ShowCounting.construct(self) def get_counting_mob(self, num): return Mobject(*self.words[:num]) class FinishCountingExampleSentence(Scene): def construct(self): words = "As an example, this is me counting the number of words in this sentence on just one hand!" words = OldTexText(words, size = "\\Huge").scale(0.7).to_corner(UP+LEFT, buff = 0.25) hand = Hand(18) sixteen = OldTex("16").shift([0, 2.25, 0]) two = OldTex("2").shift([3, 3.65, 0]) eightteen = OldTex("18").shift([1.5, 2.5, 0]) eightteen.sort_points() comp = Mobject(sixteen, two) self.add(hand, comp, words) self.wait() self.play(Transform(comp, eightteen)) self.wait() class Question(Scene): def construct(self): self.add(OldTexText("Left to ponder: Why does this rule for incrementing work?")) class TwoHandStatement(Scene): def construct(self): self.add(OldTexText( "With 10 fingers, you can count up to $2^{10} - 1 = 1023$..." )) class WithToes(Scene): def construct(self): words = OldTexText([ "If you were dexterous enough to use your toes as well,", "you could count to 1,048,575" ]).split() self.add(words[0]) self.wait() self.play(ShimmerIn(words[1])) self.wait() if __name__ == "__main__": command_line_create_scene(MOVIE_PREFIX)
#!/usr/bin/env python import numpy as np import itertools as it import operator as op from copy import deepcopy from manim_imports_ext import * RADIUS = FRAME_Y_RADIUS - 0.1 CIRCLE_DENSITY = DEFAULT_POINT_DENSITY_1D*RADIUS def logo_to_circle(): from .generate_logo import DARK_BROWN, LOGO_RADIUS sc = Scene() small_circle = Circle( density = CIRCLE_DENSITY, color = 'skyblue' ).scale(LOGO_RADIUS).set_color( DARK_BROWN, lambda x_y_z : x_y_z[0] < 0 and x_y_z[1] > 0 ) big_circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS) sc.add(small_circle) sc.wait() sc.animate(Transform(small_circle, big_circle)) return sc def count_sections(*radians): sc = Scene() circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS) sc.add(circle) points = [ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0) for angle in radians ] dots = [Dot(point) for point in points] interior = Region(lambda x, y : x**2 + y**2 < RADIUS**2) for x in range(1, len(points)): if x == 1: sc.animate(ShowCreation(dots[0]), ShowCreation(dots[1])) sc.add(dots[0], dots[1]) else: sc.animate(ShowCreation(dots[x])) sc.add(dots[x]) new_lines = Mobject(*[ Line(points[x], points[y]) for y in range(x) ]) sc.animate(Transform(deepcopy(dots[x]), new_lines, run_time = 2.0)) sc.add(new_lines) sc.wait() regions = plane_partition_from_points(*points[:x+1]) for reg in regions: reg.intersect(interior) regions = [reg for reg in regions if reg.bool_grid.any()] last_num = None for reg, count in zip(regions, it.count(1)): number = OldTex(str(count)).shift((RADIUS, 3, 0)) sc.set_color_region(reg) rt = 1.0 / (x**0.8) sc.add(number) sc.remove(last_num) last_num = number sc.wait(rt) sc.reset_background() sc.remove(last_num) sc.animate(Transform(last_num, deepcopy(last_num).center())) sc.wait() sc.remove(last_num) return sc def summarize_pattern(*radians): sc = Scene() circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS) sc.add(circle) points = [ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0) for angle in radians ] dots = [Dot(point) for point in points] last_num = None for x in range(len(points)): new_lines = Mobject(*[ Line(points[x], points[y]) for y in range(x) ]) num = OldTex(str(moser_function(x + 1))).center() sc.animate( Transform(last_num, num) if last_num else ShowCreation(num), FadeIn(new_lines), FadeIn(dots[x]), run_time = 0.5, ) sc.remove(last_num) last_num = num sc.add(num, dots[x], new_lines) sc.wait() return sc def connect_points(*radians): sc = Scene() circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS) sc.add(circle) points = [ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0) for angle in radians ] dots = [Dot(point) for point in points] sc.add(*dots) anims = [] all_lines = [] for x in range(len(points)): lines = [Line(points[x], points[y]) for y in range(len(points))] lines = Mobject(*lines) anims.append(Transform(deepcopy(dots[x]), lines, run_time = 3.0)) all_lines.append(lines) sc.animate(*anims) sc.add(*all_lines) sc.wait() return sc def interesting_problems(): sc = Scene() locales = [(6, 2, 0), (6, -2, 0), (-5, -2, 0)] fermat = Mobject(*Texs(["x^n","+","y^n","=","z^n"])) fermat.scale(0.5).shift((-2.5, 0.7, 0)) face = SimpleFace() tb = ThoughtBubble().shift((-1.5, 1, 0)) sb = SpeechBubble().shift((-2.4, 1.3, 0)) fermat_copies, face_copies, tb_copies, sb_copies = ( Mobject(*[ deepcopy(mob).scale(0.5).shift(locale) for locale in locales ]) for mob in [fermat, face, tb, sb] ) sc.add(face, tb) sc.animate(ShowCreation(fermat, run_time = 1)) sc.add(fermat) sc.wait() sc.animate( Transform( deepcopy(fermat).repeat(len(locales)), fermat_copies ), FadeIn(face_copies, run_time = 1.0) ) sc.animate(FadeIn(tb_copies)) sc.wait() sc.animate( Transform(tb, sb), Transform(tb_copies, sb_copies) ) return sc def response_invitation(): sc = Scene() video_icon = VideoIcon() mini_videos = Mobject(*[ deepcopy(video_icon).scale(0.5).shift((3, y, 0)) for y in [-2, 0, 2] ]) comments = Mobject(*[ Line((-1.2, y, 0), (1.2, y, 0), color = 'white') for y in [-1.5, -1.75, -2] ]) sc.add(video_icon) sc.wait() sc.animate(Transform(deepcopy(video_icon).repeat(3), mini_videos)) sc.add(mini_videos) sc.wait() sc.animate(ShowCreation(comments, run_time = 1.0)) return sc def different_points(radians1, radians2): sc = Scene() circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS) sc.add(circle) points1, points2 = ( [ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0) for angle in radians ] for radians in (radians1, radians2) ) dots1, dots2 = ( Mobject(*[Dot(point) for point in points]) for points in (points1, points2) ) lines1, lines2 = ( [ Line(point1, point2) for point1, point2 in it.combinations(points, 2) ] for points in (points1, points2) ) sc.add(dots1, *lines1) sc.animate( Transform(dots1, dots2, run_time = 3), *[ Transform(line1, line2, run_time = 3) for line1, line2 in zip(lines1, lines2) ] ) sc.wait() return sc def next_few_videos(*radians): sc = Scene() circle = Circle(density = CIRCLE_DENSITY).scale(RADIUS) points = [ (RADIUS * np.cos(angle), RADIUS * np.sin(angle), 0) for angle in radians ] dots = Mobject(*[ Dot(point) for point in points ]) lines = Mobject(*[ Line(point1, point2) for point1, point2 in it.combinations(points, 2) ]) thumbnail = Mobject(circle, dots, lines) frame = VideoIcon().set_color( "black", lambda point : get_norm(point) < 0.5 ) big_frame = deepcopy(frame).scale(FRAME_X_RADIUS) frame.shift((-5, 0, 0)) sc.add(thumbnail) sc.wait() sc.animate( Transform(big_frame, frame), Transform( thumbnail, deepcopy(thumbnail).scale(0.15).shift((-5, 0, 0)) ) ) sc.add(frame, thumbnail) sc.wait() last = frame for x in [-2, 1, 4]: vi = VideoIcon().shift((x, 0, 0)) sc.animate( Transform(deepcopy(last), vi), Animation(thumbnail)#Keeps it from getting burried ) sc.add(vi) last = vi return sc if __name__ == '__main__': radians = [1, 3, 5, 2, 4, 6] more_radians = radians + [10, 13, 20, 17, 15, 21, 18.5] different_radians = [1.7, 4.8, 3.2, 3.5, 2.1, 5.5] # logo_to_circle().write_to_movie("moser/LogoToCircle") # count_sections(*radians).write_to_movie("moser/CountingSections") # summarize_pattern(*radians).write_to_movie("moser/SummarizePattern") # interesting_problems().write_to_movie("moser/InterestingProblems") # summarize_pattern(*more_radians).write_to_movie("moser/ExtendedPattern") # connect_points(*radians).write_to_movie("moser/ConnectPoints") # response_invitation().write_to_movie("moser/ResponseInvitation") # different_points(radians, different_radians).write_to_movie("moser/DifferentPoints") # next_few_videos(*radians).write_to_movie("moser/NextFewVideos") # summarize_pattern(*different_radians).write_to_movie("moser/PatternWithDifferentPoints") #Images # OldTex(r""" # \Underbrace{1, 2, 4, 8, 16, 31, \dots}_\text{What?} # """).save_image("moser/NumberList31") # OldTex(""" # 1, 2, 4, 8, 16, 32, 63, \dots # """).save_image("moser/NumberList63") # OldTex(""" # 1, 2, 4, 8, 15, \dots # """).save_image("moser/NumberList15")
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from manim_imports_ext import * from functools import reduce DEFAULT_PLANE_CONFIG = { "stroke_width" : 2*DEFAULT_STROKE_WIDTH } class SuccessiveComplexMultiplications(ComplexMultiplication): args_list = [ (complex(1, 2), complex(1, -2)), (complex(-2, 1), complex(-2, -1)), ] @staticmethod def args_to_string(*multipliers): return "_".join([str(m)[1:-1] for m in multipliers]) @staticmethod def string_to_args(arg_string): args_string.replac("i", "j") return list(map(copmlex, arg_string.split())) def construct(self, *multipliers): norm = abs(reduce(op.mul, multipliers, 1)) shrink_factor = FRAME_X_RADIUS/max(FRAME_X_RADIUS, norm) plane_config = { "density" : norm*DEFAULT_POINT_DENSITY_1D, "unit_to_spatial_width" : shrink_factor, "x_radius" : shrink_factor*FRAME_X_RADIUS, "y_radius" : shrink_factor*FRAME_Y_RADIUS, } ComplexMultiplication.construct(self, multipliers[0], **plane_config) one_dot = self.draw_dot("1", 1, True) one_dot_copy = deepcopy(one_dot) for multiplier, count in zip(multipliers, it.count()): if multiplier == multipliers[0]: tex = "z" elif np.conj(multiplier) == multipliers[0]: tex = "\\bar z" else: tex = "z_%d"%count self.draw_dot(tex, multiplier) for multiplier in multipliers: self.multiplier = multiplier self.apply_multiplication() new_one = deepcopy(one_dot_copy) self.mobjects_to_move_without_molding.append(new_one) class ShowComplexPower(SuccessiveComplexMultiplications): args_list = [ (complex(0, 1), 1), (complex(0, 1), 2), (np.exp(complex(0, 2*np.pi/5)), 1), (np.exp(complex(0, 2*np.pi/5)), 5), (np.exp(complex(0, 4*np.pi/5)), 5), (np.exp(complex(0, -2*np.pi/5)), 5), (complex(1, np.sqrt(3)), 1), (complex(1, np.sqrt(3)), 3), ] @staticmethod def args_to_string(multiplier, num_repeats): start = ComplexMultiplication.args_to_string(multiplier) return start + "ToThe%d"%num_repeats @staticmethod def string_to_args(arg_string): parts = arg_string.split() if len(parts) < 2 or len(parts) > 3: raise Exception("Invalid arguments") multiplier = complex(parts[0]) num_repeats = int(parts[1]) return multiplier, num_repeats def construct(self, multiplier, num_repeats): SuccessiveComplexMultiplications.construct( [multiplier]*num_repeats ) class ComplexDivision(ComplexMultiplication): args_list = [ complex(np.sqrt(3), 1), complex(1./3, -1./3), complex(1, 2), ] def construct(self, num): ComplexMultiplication.construct(self, 1./num) self.draw_dot("1", 1, False), self.draw_dot("z", num, True) self.apply_multiplication() class ConjugateDivisionExample(ComplexMultiplication): args_list = [ complex(1, 2), ] def construct(self, num): ComplexMultiplication.construct(self, np.conj(num), radius = 2.5*FRAME_X_RADIUS) self.draw_dot("1", 1, True) self.draw_dot("\\bar z", self.multiplier) self.apply_multiplication() self.multiplier = 1./(abs(num)**2) self.anim_config["path_func"] = straight_path self.apply_multiplication() self.wait() class DrawSolutionsToZToTheNEqualsW(Scene): @staticmethod def args_to_string(n, w): return str(n) + "_" + complex_string(w) @staticmethod def string_to_args(args_string): parts = args_string.split() return int(parts[0]), complex(parts[1]) def construct(self, n, w): w = complex(w) plane_config = DEFAULT_PLANE_CONFIG.copy() norm = abs(w) theta = np.log(w).imag radius = norm**(1./n) zoom_value = (FRAME_Y_RADIUS-0.5)/radius plane_config["unit_to_spatial_width"] = zoom_value plane = ComplexPlane(**plane_config) circle = Circle( radius = radius*zoom_value, stroke_width = plane.stroke_width ) solutions = [ radius*np.exp(complex(0, 1)*(2*np.pi*k + theta)/n) for k in range(n) ] points = list(map(plane.number_to_point, solutions)) dots = [ Dot(point, color = BLUE_B, radius = 0.1) for point in points ] lines = [Line(*pair) for pair in adjacent_pairs(points)] self.add(plane, circle, *dots+lines) self.add(*plane.get_coordinate_labels()) class DrawComplexAngleAndMagnitude(Scene): args_list = [ ( ("1+i\\sqrt{3}", complex(1, np.sqrt(3)) ), ("\\frac{\\sqrt{3}}{2} - \\frac{1}{2}i", complex(np.sqrt(3)/2, -1./2)), ), (("1+i", complex(1, 1)),), ] @staticmethod def args_to_string(*reps_and_nums): return "--".join([ complex_string(num) for rep, num in reps_and_nums ]) def construct(self, *reps_and_nums): radius = max([abs(n.imag) for r, n in reps_and_nums]) + 1 plane_config = { "color" : "grey", "unit_to_spatial_width" : FRAME_Y_RADIUS / radius, } plane_config.update(DEFAULT_PLANE_CONFIG) self.plane = ComplexPlane(**plane_config) coordinates = self.plane.get_coordinate_labels() # self.plane.add_spider_web() self.add(self.plane, *coordinates) for rep, num in reps_and_nums: self.draw_number(rep, num) self.add_angle_label(num) self.add_lines(rep, num) def draw_number(self, tex_representation, number): point = self.plane.number_to_point(number) dot = Dot(point) label = OldTex(tex_representation) max_width = 0.8*self.plane.unit_to_spatial_width if label.get_width() > max_width: label.set_width(max_width) dot_to_label_dir = RIGHT if point[0] > 0 else LEFT edge = label.get_edge_center(-dot_to_label_dir) buff = 0.1 label.shift(point - edge + buff*dot_to_label_dir) label.set_color(YELLOW) self.add_mobjects_among(list(locals().values())) def add_angle_label(self, number): arc = Arc( np.log(number).imag, radius = 0.2 ) self.add_mobjects_among(list(locals().values())) def add_lines(self, tex_representation, number): point = self.plane.number_to_point(number) x_line, y_line, num_line = [ Line( start, end, color = color, stroke_width = self.plane.stroke_width ) for start, end, color in zip( [ORIGIN, point[0]*RIGHT, ORIGIN], [point[0]*RIGHT, point, point], [BLUE_D, GOLD_E, WHITE] ) ] # tex_representation.replace("i", "") # if "+" in tex_representation: # tex_parts = tex_representation.split("+") # elif "-" in tex_representation: # tex_parts = tex_representation.split("-") # x_label, y_label = map(Tex, tex_parts) # for label in x_label, y_label: # label.set_height(0.5) # x_label.next_to(x_line, point[1]*DOWN/abs(point[1])) # y_label.next_to(y_line, point[0]*RIGHT/abs(point[0])) norm = get_norm(point) brace = Underbrace(ORIGIN, ORIGIN+norm*RIGHT) if point[1] > 0: brace.rotate(np.pi, RIGHT) brace.rotate(np.log(number).imag) norm_label = OldTex("%.1f"%abs(number)) norm_label.scale(0.5) axis = OUT if point[1] > 0 else IN norm_label.next_to(brace, rotate_vector(point, np.pi/2, axis)) self.add_mobjects_among(list(locals().values()))
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from fractions import Fraction, gcd from manim_imports_ext import * from .inventing_math import Underbrace import random MOVIE_PREFIX = "music_and_measure/" INTERVAL_RADIUS = 6 NUM_INTERVAL_TICKS = 16 TICK_STRETCH_FACTOR = 4 INTERVAL_COLOR_PALETTE = [ "yellow", "green", "skyblue", "#AD1457", "#6A1B9A", "#26C6DA", "#FF8F00", ] def rationals(): curr = Fraction(1, 2) numerator, denominator = 1, 2 while True: yield curr if curr.numerator < curr.denominator - 1: new_numerator = curr.numerator + 1 while gcd(new_numerator, curr.denominator) != 1: new_numerator += 1 curr = Fraction(new_numerator, curr.denominator) else: curr = Fraction(1, curr.denominator + 1) def fraction_mobject(fraction): n, d = fraction.numerator, fraction.denominator return OldTex("\\frac{%d}{%d}"%(n, d)) def continued_fraction(int_list): if len(int_list) == 1: return int_list[0] return int_list[0] + Fraction(1, continued_fraction(int_list[1:])) def zero_to_one_interval(): interval = NumberLine( radius = INTERVAL_RADIUS, interval_size = 2.0*INTERVAL_RADIUS/NUM_INTERVAL_TICKS ) interval.elongate_tick_at(-INTERVAL_RADIUS, TICK_STRETCH_FACTOR) interval.elongate_tick_at(INTERVAL_RADIUS, TICK_STRETCH_FACTOR) interval.add(OldTex("0").shift(INTERVAL_RADIUS*LEFT+DOWN)) interval.add(OldTex("1").shift(INTERVAL_RADIUS*RIGHT+DOWN)) return interval class LeftParen(Mobject): def init_points(self): self.add(OldTex("(")) self.center() def get_center(self): return Mobject.get_center(self) + 0.04*LEFT class RightParen(Mobject): def init_points(self): self.add(OldTex(")")) self.center() def get_center(self): return Mobject.get_center(self) + 0.04*RIGHT class OpenInterval(Mobject): def __init__(self, center_point = ORIGIN, width = 2, **kwargs): digest_config(self, kwargs, locals()) left = LeftParen().shift(LEFT*width/2) right = RightParen().shift(RIGHT*width/2) Mobject.__init__(self, left, right, **kwargs) # scale_factor = width / 2.0 # self.stretch(scale_factor, 0) # self.stretch(0.5+0.5*scale_factor, 1) self.shift(center_point) class Piano(ImageMobject): CONFIG = { "stroke_width" : 1, "invert" : False, "scale_factorue" : 0.5 } def __init__(self, **kwargs): digest_config(self, kwargs) ImageMobject.__init__(self, "piano_keyboard") jump = self.get_width()/24 self.center() self.half_note_jump = self.get_width()/24 self.ivory_jump = self.get_width()/14 def split(self): left = self.get_left()[0] keys = [] for count in range(14): key = Mobject( color = "white", stroke_width = 1 ) x0 = left + count*self.ivory_jump x1 = x0 + self.ivory_jump key.add_points( self.get_points()[ (self.get_points()[:,0] > x0)*(self.get_points()[:,0] < x1) ] ) keys.append(key) return keys class Vibrate(Animation): CONFIG = { "num_periods" : 1, "overtones" : 4, "amplitude" : 0.5, "radius" : INTERVAL_RADIUS, "center" : ORIGIN, "color" : "white", "run_time" : 3.0, "rate_func" : None } def __init__(self, **kwargs): digest_config(self, kwargs) def func(x, t): return sum([ (self.amplitude/((k+1)**2.5))*np.sin(2*mult*t)*np.sin(k*mult*x) for k in range(self.overtones) for mult in [(self.num_periods+k)*np.pi] ]) self.func = func Animation.__init__(self, Mobject1D(color = self.color), **kwargs) def interpolate_mobject(self, alpha): self.mobject.reset_points() epsilon = self.mobject.epsilon self.mobject.add_points([ [x*self.radius, self.func(x, alpha*self.run_time)+y, 0] for x in np.arange(-1, 1, epsilon/self.radius) for y in epsilon*np.arange(3) ]) self.mobject.shift(self.center) class IntervalScene(NumberLineScene): def construct(self): self.number_line = UnitInterval() self.displayed_numbers = [0, 1] self.number_mobs = self.number_line.get_number_mobjects(*self.displayed_numbers) self.add(self.number_line, *self.number_mobs) def show_all_fractions(self, num_fractions = 27, pause_time = 1.0, remove_as_you_go = True): shrink = not remove_as_you_go for fraction, count in zip(rationals(), list(range(num_fractions))): frac_mob, tick = self.add_fraction(fraction, shrink) self.wait(pause_time) if remove_as_you_go: self.remove(frac_mob, tick) def add_fraction(self, fraction, shrink = False): point = self.number_line.number_to_point(fraction) tick_rad = self.number_line.tick_size*TICK_STRETCH_FACTOR frac_mob = fraction_mobject(fraction) if shrink: scale_factor = 2.0/fraction.denominator frac_mob.scale(scale_factor) tick_rad *= scale_factor frac_mob.shift(point + frac_mob.get_height()*UP) tick = Line(point + DOWN*tick_rad, point + UP*tick_rad) tick.set_color("yellow") self.add(frac_mob, tick) return frac_mob, tick def add_fraction_ticks(self, num_fractions = 1000, run_time = 0): long_tick_size = self.number_line.tick_size*TICK_STRETCH_FACTOR all_ticks = [] for frac, count in zip(rationals(), list(range(num_fractions))): point = self.number_line.number_to_point(frac) tick_rad = 2.0*long_tick_size/frac.denominator tick = Line(point+tick_rad*DOWN, point+tick_rad*UP) tick.set_color("yellow") all_ticks.append(tick) all_ticks = Mobject(*all_ticks) if run_time > 0: self.play(ShowCreation(all_ticks)) else: self.add(all_ticks) return all_ticks def cover_fractions(self, epsilon = 0.3, num_fractions = 10, run_time_per_interval = 0.5): intervals = [] lines = [] num_intervals = 0 all_rationals = rationals() count = 0 while True: fraction = next(all_rationals) count += 1 if num_intervals >= num_fractions: break if fraction < self.number_line.left_num or fraction > self.number_line.right_num: continue num_intervals += 1 interval, line = self.add_open_interval( fraction, epsilon / min(2**count, 2**30), run_time = run_time_per_interval ) intervals.append(interval) lines.append(line) return intervals, lines def add_open_interval(self, num, width, color = None, run_time = 0): spatial_width = width*self.number_line.unit_length_to_spatial_width center_point = self.number_line.number_to_point(num) open_interval = OpenInterval(center_point, spatial_width) color = color or "yellow" interval_line = Line( center_point+spatial_width*LEFT/2, center_point+spatial_width*RIGHT/2 ) interval_line.do_in_place(interval_line.sort_points, get_norm) interval_line.set_color(color) if run_time > 0: squished_interval = deepcopy(open_interval).stretch_to_fit_width(0) self.play( Transform(squished_interval, open_interval), ShowCreation(interval_line), run_time = run_time ) self.remove(squished_interval) self.add(open_interval, interval_line) return open_interval, interval_line class TwoChallenges(Scene): def construct(self): two_challenges = OldTexText("Two Challenges", size = "\\Huge").to_edge(UP) one, two = list(map(TexText, ["1.", "2."])) one.shift(UP).to_edge(LEFT) two.shift(DOWN).to_edge(LEFT) notes = ImageMobject("musical_notes").scale(0.3) notes.next_to(one) notes.set_color("blue") measure = OldTexText("Measure Theory").next_to(two) probability = OldTexText("Probability") probability.next_to(measure).shift(DOWN+RIGHT) integration = OldTex("\\int") integration.next_to(measure).shift(UP+RIGHT) arrow_to_prob = Arrow(measure, probability) arrow_to_int = Arrow(measure, integration) for arrow in arrow_to_prob, arrow_to_int: arrow.set_color("yellow") self.add(two_challenges) self.wait() self.add(one, notes) self.wait() self.add(two, measure) self.wait() self.play(ShowCreation(arrow_to_int)) self.add(integration) self.wait() self.play(ShowCreation(arrow_to_prob)) self.add(probability) self.wait() class MeasureTheoryToHarmony(IntervalScene): def construct(self): IntervalScene.construct(self) self.cover_fractions() self.wait() all_mobs = Mobject(*self.mobjects) all_mobs.sort_points() self.clear() radius = self.interval.radius line = Line(radius*LEFT, radius*RIGHT).set_color("white") self.play(DelayByOrder(Transform(all_mobs, line))) self.clear() self.play(Vibrate(rate_func = smooth)) self.clear() self.add(line) self.wait() class ChallengeOne(Scene): def construct(self): title = OldTexText("Challenge #1").to_edge(UP) start_color = Color("blue") colors = start_color.range_to("white", 6) self.bottom_vibration = Vibrate( num_periods = 1, run_time = 3.0, center = DOWN, color = start_color ) top_vibrations = [ Vibrate( num_periods = freq, run_time = 3.0, center = 2*UP, color = next(colors) ) for freq in [1, 2, 5.0/3, 4.0/3, 2] ] freq_220 = OldTexText("220 Hz") freq_r220 = OldTexText("$r\\times$220 Hz") freq_330 = OldTexText("1.5$\\times$220 Hz") freq_sqrt2 = OldTexText("$\\sqrt{2}\\times$220 Hz") freq_220.shift(1.5*DOWN) for freq in freq_r220, freq_330, freq_sqrt2: freq.shift(1.5*UP) r_constraint = OldTex("(1<r<2)", size = "\\large") self.add(title) self.wait() self.vibrate(1) self.add(freq_220) self.vibrate(1) self.add(r_constraint) self.vibrate(1) self.add(freq_r220) self.vibrate(2, top_vibrations[1]) self.remove(freq_r220, r_constraint) self.add(freq_330) self.vibrate(2, top_vibrations[2]) self.remove(freq_330) self.add(freq_sqrt2) self.vibrate(1, top_vibrations[3]) self.remove(freq_sqrt2) self.continuously_vary_frequency(top_vibrations[0], top_vibrations[4]) def vibrate(self, num_repeats, *top_vibrations): anims = [self.bottom_vibration] + list(top_vibrations) for count in range(num_repeats): self.play(*anims) self.remove(*[a.mobject for a in anims]) def continuously_vary_frequency(self, top_vib_1, top_vib_2): number_line = NumberLine(interval_size = 1).add_numbers() one, two = 2*number_line.interval_size*RIGHT, 4*number_line.interval_size*RIGHT arrow1 = Arrow(one+UP, one) arrow2 = Arrow(two+UP, two) r1 = OldTex("r").next_to(arrow1, UP) r2 = OldTex("r").next_to(arrow2, UP) kwargs = { "run_time" : 5.0, "rate_func" : there_and_back } run_time = 3.0 vibrations = [self.bottom_vibration, top_vib_1, top_vib_2] self.add(number_line, r1, arrow1) self.play(bottom_vibration, top_vib_1) for vib in vibrations: vib.set_run_time(kwargs["run_time"]) self.play( self.bottom_vibration, Transform(arrow1, arrow2, **kwargs), Transform(r1, r2, **kwargs), TransformAnimations(top_vib_1, top_vib_2, **kwargs) ) for vib in vibrations: vib.set_run_time(3.0) self.play(bottom_vibration, top_vib_1) class JustByAnalyzingTheNumber(Scene): def construct(self): nums = [ 1.5, np.sqrt(2), 2**(5/12.), 4/3., 1.2020569031595942, ] last = None r_equals = OldTex("r=").shift(2*LEFT) self.add(r_equals) for num in nums: mob = OldTex(str(num)).next_to(r_equals) mob.set_color() mob.sort_points() if last: self.play(DelayByOrder(Transform(last, mob, run_time = 0.5))) self.remove(last) self.add(mob) else: self.add(mob) self.wait() last = mob class QuestionAndAnswer(Scene): def construct(self): Q = OldTexText("Q:").shift(UP).to_edge(LEFT) A = OldTexText("A:").shift(DOWN).to_edge(LEFT) string1 = Vibrate(center = 3*UP, color = "blue") string2 = Vibrate(num_periods = 2, center = 3.5*UP, color = "green") twotwenty = OldTex("220").scale(0.25).next_to(string1.mobject, LEFT) r220 = OldTex("r\\times220").scale(0.25).next_to(string2.mobject, LEFT) question = OldTexText( "For what values of $r$ will the frequencies 220~Hz and \ $r\\times$220~Hz sound nice together?" ).next_to(Q) answer = OldTexText([ "When $r$ is", "sufficiently close to", "a rational number" ], size = "\\small").scale(1.5) answer.next_to(A) correction1 = OldTexText( "with sufficiently low denominator", size = "\\small" ).scale(1.5) correction1.set_color("yellow") correction1.next_to(A).shift(2*answer.get_height()*DOWN) answer = answer.split() answer[1].set_color("green") temp_answer_end = deepcopy(answer[-1]).next_to(answer[0], buff = 0.2) self.add(Q, A, question, twotwenty, r220) self.play(string1, string2) self.add(answer[0], temp_answer_end) self.play(string1, string2) self.play(ShimmerIn(correction1), string1, string2) self.play(string1, string2, run_time = 3.0) self.play( Transform(Point(answer[1].get_left()), answer[1]), Transform(temp_answer_end, answer[2]), string1, string2 ) self.play(string1, string2, run_time = 3.0) class PlaySimpleRatio(Scene): args_list = [ (Fraction(3, 2), "green"), (Fraction(4, 3), "purple"), (Fraction(8, 5), "skyblue"), (Fraction(211, 198), "orange"), (Fraction(1093, 826), "red"), ((np.exp(np.pi)-np.pi)/15, "#7e008e") ] @staticmethod def args_to_string(fraction, color): return str(fraction).replace("/", "_to_") def construct(self, fraction, color): string1 = Vibrate( num_periods = 1, run_time = 5.0, center = DOWN, color = "blue" ) string2 = Vibrate( num_periods = fraction, run_time = 5.0, center = 2*UP, color = color ) if isinstance(fraction, Fraction): mob = fraction_mobject(fraction).shift(0.5*UP) else: mob = OldTex("\\frac{e^\\pi - \\pi}{15} \\approx \\frac{4}{3}") mob.shift(0.5*UP) self.add(mob) self.play(string1, string2) class LongSine(Mobject1D): def init_points(self): self.add_points([ (x, np.sin(2*np.pi*x), 0) for x in np.arange(0, 100, self.epsilon/10) ]) class DecomposeMusicalNote(Scene): def construct(self): line = Line(FRAME_Y_RADIUS*DOWN, FRAME_Y_RADIUS*UP) sine = LongSine() kwargs = { "run_time" : 4.0, "rate_func" : None } words = OldTexText("Imagine 220 per second...") words.shift(2*UP) self.add(line) self.play(ApplyMethod(sine.shift, 4*LEFT, **kwargs)) self.add(words) kwargs["rate_func"] = rush_into self.play(ApplyMethod(sine.shift, 80*LEFT, **kwargs)) kwargs["rate_func"] = None kwargs["run_time"] = 1.0 sine.to_edge(LEFT, buff = 0) for x in range(5): self.play(ApplyMethod(sine.shift, 85*LEFT, **kwargs)) class DecomposeTwoFrequencies(Scene): def construct(self): line = Line(FRAME_Y_RADIUS*DOWN, FRAME_Y_RADIUS*UP) sine1 = LongSine().shift(2*UP).set_color("yellow") sine2 = LongSine().shift(DOWN).set_color("lightgreen") sine1.stretch(2.0/3, 0) comp = Mobject(sine1, sine2) self.add(line) self.play(ApplyMethod( comp.shift, 15*LEFT, run_time = 7.5, rate_func=linear )) class MostRationalsSoundBad(Scene): def construct(self): self.add(OldTexText("Most rational numbers sound bad!")) class FlashOnXProximity(Animation): def __init__(self, mobject, x_val, *close_mobjects, **kwargs): self.x_val = x_val self.close_mobjects = close_mobjects Animation.__init__(self, mobject, **kwargs) def interpolate_mobject(self, alpha): for mob in self.close_mobjects: if np.min(np.abs(mob.get_points()[:,0] - self.x_val)) < 0.1: self.mobject.set_color() return self.mobject.to_original_color() class PatternInFrequencies(Scene): args_list = [ (3, 2, "green"), (4, 3, "purple"), (8, 5, "skyblue"), (35, 43, "red"), ] @staticmethod def args_to_string(num1, num2, color): return "%d_to_%d"%(num1, num2) def construct(self, num1, num2, color): big_line = Line(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) big_line.set_color("white").shift(2*LEFT) line_template = Line(UP, DOWN) line_template.shift(2*UP+2*LEFT) setup_width = FRAME_WIDTH num_top_lines = int(setup_width) num_bot_lines = int(setup_width*num1/num2) top_lines = Mobject(*[ deepcopy(line_template).shift(k*(float(num1)/num2)*RIGHT) for k in range(num_top_lines) ]) line_template.shift(4*DOWN) bottom_lines = Mobject(*[ deepcopy(line_template).shift(k*RIGHT) for k in range(num_bot_lines) ]) bottom_lines.set_color("blue") top_lines.set_color(color) kwargs = { "run_time" : 10, "rate_func" : None } self.add(big_line) self.add(OldTex("%d:%d"%(num1, num2))) fracs = ( 1.0/(num_top_lines-1), 1.0/(num_bot_lines-1) ) anims = [ ApplyMethod(mob.shift, setup_width*LEFT, **kwargs) for mob in (top_lines, bottom_lines) ] anim_mobs = [anim.mobject for anim in anims] self.play( FlashOnXProximity(big_line, -2, *anim_mobs, **kwargs), *anims ) class CompareFractionComplexity(Scene): def construct(self): fractions = [] for num, den in [(4, 3), (1093,826)]: top = OldTex("%d \\over"%num) bottom = OldTex(str(den)).next_to(top, DOWN, buff = 0.3) fractions.append(Mobject(top, bottom)) frac0 = fractions[0].shift(3*LEFT).split() frac1 = fractions[1].shift(3*RIGHT).split() arrow1 = Arrow(UP, ORIGIN).next_to(frac0[0], UP) arrow2 = Arrow(UP, ORIGIN).next_to(frac1[0], UP) simple = OldTexText("Simple").next_to(arrow1, UP) simple.set_color("green") complicated = OldTexText("Complicated").next_to(arrow2, UP) complicated.set_color("red") indicates = OldTexText("Indicates complexity").shift(2*DOWN) arrow3 = Arrow(indicates.get_top(), frac0[1]) arrow4 = Arrow(indicates.get_top(), frac1[1]) self.add(*frac0 + frac1) self.wait() self.add(simple, complicated) self.play(*[ ShowCreation(arrow) for arrow in (arrow1, arrow2) ]) self.wait() self.play(*[ DelayByOrder(ApplyMethod(frac[1].set_color, "yellow")) for frac in (frac0, frac1) ]) self.play( FadeIn(indicates), ShowCreation(arrow3), ShowCreation(arrow4) ) self.wait() class IrrationalGang(Scene): def construct(self): randy = Randolph() randy.mouth.set_color(randy.DEFAULT_COLOR) randy.sync_parts() sqrt13 = OldTex("\\sqrt{13}").shift(2*LEFT) sqrt13.set_color("green") zeta3 = OldTex("\\zeta(3)").shift(2*RIGHT) zeta3.set_color("grey") eyes = Mobject(*randy.eyes) eyes.scale(0.5) sqrt13.add(eyes.next_to(sqrt13, UP, buff = 0).shift(0.25*RIGHT)) eyes.scale(0.5) zeta3.add(eyes.next_to(zeta3, UP, buff = 0).shift(0.3*LEFT+0.08*DOWN)) speech_bubble = SpeechBubble() speech_bubble.pin_to(randy) speech_bubble.write("We want to play too!") self.add(randy, sqrt13, zeta3, speech_bubble, speech_bubble.content) self.play(BlinkPiCreature(randy)) class ConstructPiano(Scene): def construct(self): piano = Piano() keys = piano.split() anims = [] askew = deepcopy(keys[-1]) keys[-1].rotate(np.pi/5) for key in keys: key.stroke_width = 1 key_copy = deepcopy(key).to_corner(DOWN+LEFT) key_copy.scale(0.25) key_copy.shift(1.8*random.random()*FRAME_X_RADIUS*RIGHT) key_copy.shift(1.8*random.random()*FRAME_Y_RADIUS*UP) key_copy.rotate(2*np.pi*random.random()) anims.append(Transform(key_copy, key)) self.play(*anims, run_time = 3.0) self.wait() self.play(Transform(anims[-1].mobject, askew)) self.wait() class PianoTuning(Scene): def construct(self): piano = self.piano = Piano() jump = piano.half_note_jump semicircle = Circle().filter_out(lambda p : p[1] < 0) semicircle.scale(jump/semicircle.get_width()) semicircles = Mobject(*[ deepcopy(semicircle).shift(jump*k*RIGHT) for k in range(23) ]) semicircles.set_color("white") semicircles.next_to(piano, UP, buff = 0) semicircles.shift(0.05*RIGHT) semicircles.sort_points(lambda p : p[0]) first_jump = semicircles.split()[0] twelfth_root = OldTex("2^{\\left(\\frac{1}{12}\\right)}") twelfth_root.scale(0.75).next_to(first_jump, UP, buff = 1.5) line = Line(twelfth_root, first_jump).set_color("grey") self.keys = piano.split() self.semicircles = semicircles.split() self.add(piano) self.wait() self.play(ShowCreation(first_jump)) self.play( ShowCreation(line), FadeIn(twelfth_root) ) self.wait() self.play(ShowCreation(semicircles, rate_func=linear)) self.wait() self.show_interval(5, 7) self.show_interval(4, 5) def show_interval(self, interval, half_steps): whole_notes_to_base = 5 half_notes_to_base = 9 self.clear() self.add(self.piano) colors = list(Color("blue").range_to("yellow", 7)) low = self.keys[whole_notes_to_base] high = self.keys[whole_notes_to_base + interval - 1] u_brace = Underbrace(low.get_bottom(), high.get_bottom()) u_brace.set_color("yellow") ratio = OldTex("2^{\\left(\\frac{%d}{12}\\right)}"%half_steps) ratio.next_to(u_brace, DOWN, buff = 0.2) semicircles = self.semicircles[half_notes_to_base:half_notes_to_base+half_steps] product = OldTex( ["\\left(2^{\\left(\\frac{1}{12}\\right)}\\right)"]*half_steps, size = "\\small" ).next_to(self.piano, UP, buff = 1.0) approximate_form = OldTex("\\approx"+str(2**(float(half_steps)/12))) approximate_form.scale(0.75) approximate_form.next_to(ratio) if interval == 5: num_den = (3, 2) elif interval == 4: num_den = (4, 3) should_be = OldTexText("Should be $\\frac{%d}{%d}$"%num_den) should_be.next_to(u_brace, DOWN) self.play(ApplyMethod(low.set_color, colors[0])) self.play( ApplyMethod(high.set_color, colors[interval]), Transform(Point(u_brace.get_left()), u_brace), ) self.wait() self.play(ShimmerIn(should_be)) self.wait() self.remove(should_be) terms = product.split() for term, semicircle in zip(terms, semicircles): self.add(term, semicircle) self.wait(0.25) self.wait() product.sort_points(lambda p : p[1]) self.play(DelayByOrder(Transform(product, ratio))) self.wait() self.play(ShimmerIn(approximate_form)) self.wait() class PowersOfTwelfthRoot(Scene): def construct(self): max_height = FRAME_Y_RADIUS-0.5 min_height = -max_height num_terms = 11 mob_list = [] fraction_map = { 1 : Fraction(16, 15), 2 : Fraction(9, 8), 3 : Fraction(6, 5), 4 : Fraction(5, 4), 5 : Fraction(4, 3), 7 : Fraction(3, 2), 8 : Fraction(8, 5), 9 : Fraction(5, 3), 10 : Fraction(16, 9), } approx = OldTex("\\approx").scale(0.5) curr_height = max_height*UP spacing = UP*(max_height-min_height)/(len(fraction_map)-1.0) for i in range(1, num_terms+1): if i not in fraction_map: continue term = OldTex("2^{\\left(\\frac{%d}{12}\\right)}"%i) term.shift(curr_height) curr_height -= spacing term.shift(4*LEFT) value = 2**(i/12.0) approx_form = OldTex(str(value)[:10]) approx_copy = deepcopy(approx).next_to(term) approx_form.scale(0.5).next_to(approx_copy) words = OldTexText("is close to") words.scale(approx_form.get_height()/words.get_height()) words.next_to(approx_form) frac = fraction_map[i] frac_mob = OldTex("%d/%d"%(frac.numerator, frac.denominator)) frac_mob.scale(0.5).next_to(words) percent_error = abs(100*((value - frac) / frac)) error_string = OldTexText([ "with", str(percent_error)[:4] + "\\%", "error" ]) error_string = error_string.split() error_string[1].set_color() error_string = Mobject(*error_string) error_string.scale(approx_form.get_height()/error_string.get_height()) error_string.next_to(frac_mob) mob_list.append(Mobject(*[ term, approx_copy, approx_form, words, frac_mob, error_string ])) self.play(ShimmerIn(Mobject(*mob_list), run_time = 3.0)) class InterestingQuestion(Scene): def construct(self): words = OldTexText("Interesting Question:", size = "\\Huge") words.scale(2.0) self.add(words) class SupposeThereIsASavant(Scene): def construct(self): words = "Suppose there is a musical savant " + \ "who finds pleasure in all pairs of " + \ "notes whose frequencies have a rational ratio" words = words.split(" ") word_mobs = OldTexText(words).split() word_mobs[4].set_color() word_mobs[5].set_color() for word, word_mob in zip(words, word_mobs): self.add(word_mob) self.wait(0.1*len(word)) class AllValuesBetween1And2(NumberLineScene): def construct(self): NumberLineScene.construct(self) irrational = 1.2020569031595942 cont_frac = [1, 4, 1, 18, 1, 1, 1, 4, 1, 9, 9, 2, 1, 1, 1, 2] one, two, irr = list(map( self.number_line.number_to_point, [1, 2, irrational] )) top_arrow = Arrow(one+UP, one) bot_arrow = Arrow(irr+2*DOWN, irr) r = OldTex("r").next_to(top_arrow, UP) irr_mob = OldTex(str(irrational)+"\\dots").next_to(bot_arrow, DOWN) approximations = [ continued_fraction(cont_frac[:k]) for k in range(1, len(cont_frac))[:8] ] kwargs = { "run_time" : 3.0, "rate_func" : there_and_back } self.play(*[ ApplyMethod(mob.shift, RIGHT, **kwargs) for mob in (r, top_arrow) ]) self.wait() self.remove(r, top_arrow) self.play( ShimmerIn(irr_mob), ShowCreation(bot_arrow) ) self.wait() self.add(irr_mob, bot_arrow) frac_mob = Point(top_arrow.get_top()) max_num_zooms = 4 num_zooms = 0 for approx in approximations: point = self.number_line.number_to_point(approx) new_arrow = Arrow(point+UP, point) mob = fraction_mobject(approx).next_to(new_arrow, UP) self.play( Transform(top_arrow, new_arrow), Transform(frac_mob, mob), run_time = 0.5 ) self.wait(0.5) points = list(map(self.number_line.number_to_point, [approx, irrational])) distance = get_norm(points[1]-points[0]) if distance < 0.3*FRAME_X_RADIUS and num_zooms < max_num_zooms: num_zooms += 1 new_distance = 0.75*FRAME_X_RADIUS self.zoom_in_on(irrational, new_distance/distance) for mob in irr_mob, bot_arrow: mob.shift(mob.get_center()[0]*LEFT) self.wait(0.5) class ChallengeTwo(Scene): def construct(self): self.add(OldTexText("Challenge #2")) class CoveringSetsWithOpenIntervals(IntervalScene): def construct(self): IntervalScene.construct(self) dots = Mobject(*[ Dot().shift(self.number_line.number_to_point(num)+UP) for num in set([0.2, 0.25, 0.45, 0.6, 0.65]) ]) theorems = [ OldTexText(words).shift(UP) for words in [ "Heine-Borel Theorem", "Lebesgue's Number Lemma", "Vitali Covering Lemma", "Besicovitch Covering Theorem", "$\\vdots$" ] ] self.add(dots) self.play(DelayByOrder(ApplyMethod(dots.shift, DOWN, run_time = 2))) self.wait() for center in 0.225, 0.475, 0.625: self.add_open_interval(center, 0.1, run_time = 1.0) self.wait() for x in range(2*len(theorems)): self.play(*[ ApplyMethod(th.shift, UP, rate_func=linear) for th in theorems[:x+1] ]) class DefineOpenInterval(IntervalScene): def construct(self): IntervalScene.construct(self) open_interval, line = self.add_open_interval(0.5, 0.75, run_time = 1.0) left, right = open_interval.get_left(), open_interval.get_right() a, less_than1, x, less_than2, b = \ OldTex(["a", "<", "x", "<", "b"]).shift(UP).split() left_arrow = Arrow(a.get_corner(DOWN+LEFT), left) right_arrow = Arrow(b.get_corner(DOWN+RIGHT), right) self.play(*[ShimmerIn(mob) for mob in (a, less_than1, x)]) self.play(ShowCreation(left_arrow)) self.wait() self.play(*[ShimmerIn(mob) for mob in (less_than2, b)]) self.play(ShowCreation(right_arrow)) self.wait() class ShowAllFractions(IntervalScene): def construct(self): IntervalScene.construct(self) self.show_all_fractions( num_fractions = 100, remove_as_you_go = False, pause_time = 0.3 ) self.wait() self.play(*[ CounterclockwiseTransform(mob, Point(mob.get_center())) for mob in self.mobjects if isinstance(mob, ImageMobject) ]) self.wait() class NaiveFractionCover(IntervalScene): def construct(self): IntervalScene.construct(self) self.add_fraction_ticks(100) self.add_fraction_ticks(run_time = 5.0) last_interval = None centers = np.arange(0, 1.1, .1) random.shuffle(centers) for num, count in zip(centers, it.count()): if count == 0: kwargs = { "run_time" : 1.0, "rate_func" : rush_into } elif count == 10: kwargs = { "run_time" : 1.0, "rate_func" : rush_from } else: kwargs = { "run_time" : 0.25, "rate_func" : None } open_interval, line = self.add_open_interval(num, 0.1) open_interval.shift(UP) self.remove(line) anims = [ApplyMethod(open_interval.shift, DOWN, **kwargs)] last_interval = open_interval self.play(*anims) self.wait() class CoverFractionsWithWholeInterval(IntervalScene): def construct(self): IntervalScene.construct(self) self.add_fraction_ticks() self.wait() self.add_open_interval(0.5, 1, color = "red", run_time = 2.0) self.wait() class SumOfIntervalsMustBeLessThan1(IntervalScene): def construct(self): IntervalScene.construct(self) self.add_fraction_ticks() anims = [] last_plus = Point((FRAME_X_RADIUS-0.5)*LEFT+2*UP) for num in np.arange(0, 1.1, .1): open_interval, line = self.add_open_interval(num, 0.1) self.remove(line) int_copy = deepcopy(open_interval) int_copy.scale(0.6).next_to(last_plus, buff = 0.1) last_plus = OldTex("+").scale(0.3) last_plus.next_to(int_copy, buff = 0.1) anims.append(Transform(open_interval, int_copy)) if num < 1.0: anims.append(FadeIn(last_plus)) less_than1 = OldTex("<1").scale(0.5) less_than1.next_to(int_copy) dots = OldTex("\\dots").replace(int_copy) words = OldTexText("Use infinitely many intervals") words.shift(UP) self.wait() self.play(*anims) self.play(ShimmerIn(less_than1)) self.wait() self.play(Transform(anims[-1].mobject, dots)) self.play(ShimmerIn(words)) self.wait() class RationalsAreDense(IntervalScene): def construct(self): IntervalScene.construct(self) words = OldTexText(["Rationals are", "\\emph{dense}", "in the reals"]) words.shift(2*UP) words = words.split() words[1].set_color() self.add(words[0]) self.play(ShimmerIn(words[1])) self.add(words[2]) self.wait() ticks = self.add_fraction_ticks(run_time = 5.0) self.wait() for center, width in [(0.5, 0.1), (0.2, 0.05), (0.7, 0.01)]: oi, line = self.add_open_interval(center, width, run_time = 1) self.remove(line) self.wait() for compound in oi, ticks: self.remove(compound) self.add(*compound.split()) self.zoom_in_on(0.7, 100) self.play(ShowCreation(ticks, run_time = 2.0)) self.wait() class SurelyItsImpossible(Scene): def construct(self): self.add(OldTexText("Surely it's impossible!")) class HowCanYouNotCoverEntireInterval(IntervalScene): def construct(self): IntervalScene.construct(self) small_words = OldTexText(""" In case you are wondering, it is indeed true that if you cover all real numbers between 0 and 1 with a set of open intervals, the sum of the lengths of those intervals must be at least 1. While intuitive, this is not actually as obvious as it might seem, just try to prove it for yourself! """) small_words.scale(0.5).to_corner(UP+RIGHT) big_words = OldTexText(""" Covering all numbers from 0 to 1 \\emph{will} force the sum of the lengths of your intervals to be at least 1. """) big_words.next_to(self.number_line, DOWN, buff = 0.5) ticks = self.add_fraction_ticks() left = self.number_line.number_to_point(0) right = self.number_line.number_to_point(1) full_line = Line(left, right) full_line.set_color("red") # dot = Dot().shift(left).set_color("red") # point = Point(left).set_color("red") intervals = [] for num in np.arange(0, 1.1, .1): open_interval, line = self.add_open_interval(num, 0.1) self.remove(line) intervals.append(open_interval) self.wait() self.remove(ticks) self.play(*[ Transform(tick, full_line) for tick in ticks.split() ]) self.play(ShimmerIn(big_words)) self.wait() # self.play(DelayByOrder(FadeToColor(full_line, "red"))) self.play(ShimmerIn(small_words)) self.wait() class PauseNow(Scene): def construct(self): top_words = OldTexText("Try for yourself!").scale(2).shift(3*UP) bot_words = OldTexText(""" If you've never seen this before, you will get the most out of the solution and the intuitions I illustrate only after pulling out a pencil and paper and taking a wack at it yourself. """).next_to(top_words, DOWN, buff = 0.5) self.add(top_words, bot_words) class StepsToSolution(IntervalScene): def construct(self): IntervalScene.construct(self) self.spacing = 0.7 steps = list(map(TexText, [ "Enumerate all rationals in (0, 1)", "Assign one interval to each rational", "Choose sum of the form $\\mathlarger{\\sum}_{n=1}^\\infty a_n = 1$", "Pick any $\\epsilon$ such that $0 < \\epsilon < 1$", "Stretch the $n$th interval to have length $\\epsilon/2^n$", ])) for step in steps: step.shift(DOWN) for step in steps[2:]: step.shift(DOWN) for step, count in zip(steps, it.count()): self.add(step) self.wait() if count == 0: self.enumerate_rationals() elif count == 1: self.assign_intervals_to_rationals() elif count == 2: self.add_terms() elif count == 3: self.multiply_by_epsilon() elif count == 4: self.stretch_intervals() self.remove(step) def enumerate_rationals(self): ticks = self.add_fraction_ticks(run_time = 2.0) anims = [] commas = Mobject() denom_to_mobs = {} for frac, count in zip(rationals(), list(range(1,28))): mob, tick = self.add_fraction(frac, shrink = True) self.wait(0.1) self.remove(tick) if frac.denominator not in denom_to_mobs: denom_to_mobs[frac.denominator] = [] denom_to_mobs[frac.denominator].append(mob) mob_copy = deepcopy(mob).center() mob_copy.shift((2.4-mob_copy.get_bottom()[1])*UP) mob_copy.shift((-FRAME_X_RADIUS+self.spacing*count)*RIGHT) comma = OldTexText(",").next_to(mob_copy, buff = 0.1, aligned_edge = DOWN) anims.append(Transform(mob, mob_copy)) commas.add(comma) anims.append(ShimmerIn(commas)) new_ticks = [] for tick, count in zip(ticks.split(), it.count(1)): tick_copy = deepcopy(tick).center().shift(1.6*UP) tick_copy.shift((-FRAME_X_RADIUS+self.spacing*count)*RIGHT) new_ticks.append(tick_copy) new_ticks = Mobject(*new_ticks) anims.append(DelayByOrder(Transform(ticks, new_ticks))) self.wait() self.play(*anims) self.wait() for denom in range(2, 10): for mob in denom_to_mobs[denom]: mob.set_color("green") self.wait() for mob in denom_to_mobs[denom]: mob.to_original_color() self.ticks = ticks.split()[:20] def assign_intervals_to_rationals(self): anims = [] for tick in self.ticks: interval = OpenInterval(tick.get_center(), self.spacing) interval.scale(0.5) squished = deepcopy(interval).stretch_to_fit_width(0) anims.append(Transform(squished, interval)) self.play(*anims) self.show_frame() self.wait() to_remove = [self.number_line] + self.number_mobs self.play(*[ ApplyMethod(mob.shift, FRAME_WIDTH*RIGHT) for mob in to_remove ]) self.remove(*to_remove) self.wait() self.intervals = [a.mobject for a in anims] kwargs = { "run_time" : 2.0, "rate_func" : there_and_back } self.play(*[ ApplyMethod(mob.scale, 0.5*random.random(), **kwargs) for mob in self.intervals ]) self.wait() def add_terms(self): self.ones = [] scale_factor = 0.6 plus = None for count in range(1, 10): frac_bottom = OldTex("\\over %d"%(2**count)) frac_bottom.scale(scale_factor) one = OldTex("1").scale(scale_factor) one.next_to(frac_bottom, UP, buff = 0.1) compound = Mobject(frac_bottom, one) if plus: compound.next_to(plus) else: compound.to_edge(LEFT) plus = OldTex("+").scale(scale_factor) plus.next_to(compound) frac_bottom, one = compound.split() self.ones.append(one) self.add(frac_bottom, one, plus) self.wait(0.2) dots = OldTex("\\dots").scale(scale_factor).next_to(plus) arrow = Arrow(ORIGIN, RIGHT).next_to(dots) one = OldTex("1").next_to(arrow) self.ones.append(one) self.play(*[ShowCreation(mob) for mob in (dots, arrow, one)]) self.wait() def multiply_by_epsilon(self): self.play(*[ CounterclockwiseTransform( one, OldTex("\\epsilon").replace(one) ) for one in self.ones ]) self.wait() def stretch_intervals(self): for interval, count in zip(self.intervals, it.count(1)): self.play( ApplyMethod(interval.scale, 1.0/(count**2)), run_time = 1.0/count ) self.wait() class OurSumCanBeArbitrarilySmall(Scene): def construct(self): step_size = 0.01 epsilon = OldTex("\\epsilon") equals = OldTex("=").next_to(epsilon) self.add(epsilon, equals) for num in np.arange(1, 0, -step_size): parts = list(map(Tex, str(num))) parts[0].next_to(equals) for i in range(1, len(parts)): parts[i].next_to(parts[i-1], buff = 0.1, aligned_edge = DOWN) self.add(*parts) self.wait(0.05) self.remove(*parts) self.wait() self.clear() words = OldTexText([ "Not only can the sum be $< 1$,\\\\", "it can be \\emph{arbitrarily small} !" ]).split() self.add(words[0]) self.wait() self.play(ShimmerIn(words[1].set_color())) self.wait() class ProofDoesNotEqualIntuition(Scene): def construct(self): self.add(OldTexText("Proof $\\ne$ Intuition")) class StillFeelsCounterintuitive(IntervalScene): def construct(self): IntervalScene.construct(self) ticks = self.add_fraction_ticks(run_time = 1.0) epsilon, equals, num = list(map(Tex, ["\\epsilon", "=", "0.3"])) epsilon.shift(2*UP) equals.next_to(epsilon) num.next_to(equals) self.add(epsilon, equals, num) self.cover_fractions() self.remove(ticks) self.add(*ticks.split()) self.zoom_in_on(np.sqrt(2)/2, 100) self.play(ShowCreation(ticks)) self.wait() class VisualIntuition(Scene): def construct(self): self.add(OldTexText("Visual Intuition:")) class SideNote(Scene): def construct(self): self.add(OldTexText("(Brief Sidenote)")) class TroubleDrawingSmallInterval(IntervalScene): def construct(self): IntervalScene.construct(self) interval, line = self.add_open_interval(0.5, 0.5) big = Mobject(interval, line) small_int, small_line = self.add_open_interval(0.5, 0.01) small = Mobject(small_int, line.scale(0.01/0.5)) shrunk = deepcopy(big).scale(0.01/0.5) self.clear() IntervalScene.construct(self) words = OldTexText("This tiny stretch") words.shift(2*UP+2*LEFT) arrow = Arrow(words, line) for target in shrunk, small: mob = deepcopy(big) self.play(Transform( mob, target, run_time = 2.0 )) self.wait() self.play(Transform(mob, big)) self.wait() self.remove(mob) self.play(Transform(big, small)) self.play(ShimmerIn(words), ShowCreation(arrow)) self.play(Transform( line, deepcopy(line).scale(10).shift(DOWN), run_time = 2.0, rate_func = there_and_back )) self.wait() class WhatDoesItLookLikeToBeOutside(Scene): def construct(self): self.add(OldTexText( "What does it look like for a number to be outside a dense set of intervals?" )) class ZoomInOnSqrt2Over2(IntervalScene): def construct(self): IntervalScene.construct(self) epsilon, equals, num = list(map(Tex, ["\\epsilon", "=", "0.3"])) equals.next_to(epsilon) num.next_to(equals) self.add(Mobject(epsilon, equals, num).center().shift(2*UP)) intervals, lines = self.cover_fractions() self.remove(*lines) irr = OldTex("\\frac{\\sqrt{2}}{2}") point = self.number_line.number_to_point(np.sqrt(2)/2) arrow = Arrow(point+UP, point) irr.next_to(arrow, UP) self.play(ShimmerIn(irr), ShowCreation(arrow)) for count in range(4): self.remove(*intervals) self.remove(*lines) self.zoom_in_on(np.sqrt(2)/2, 20) for mob in irr, arrow: mob.shift(mob.get_center()[0]*LEFT) intervals, lines = self.cover_fractions() class NotCoveredMeansCacophonous(Scene): def construct(self): statement1 = OldTexText("$\\frac{\\sqrt{2}}{2}$ is not covered") implies = OldTex("\\Rightarrow") statement2 = OldTexText("Rationals which are close to $\\frac{\\sqrt{2}}{2}$ must have large denominators") statement1.to_edge(LEFT) implies.next_to(statement1) statement2.next_to(implies) implies.sort_points() self.add(statement1) self.wait() self.play(ShowCreation(implies)) self.play(ShimmerIn(statement2)) self.wait() class ShiftSetupByOne(IntervalScene): def construct(self): IntervalScene.construct(self) new_interval = UnitInterval( number_at_center = 1.5, leftmost_tick = 1, numbers_with_elongated_ticks = [1, 2], ) new_interval.add_numbers(1, 2) side_shift_val = self.number_line.number_to_point(1) side_shift_val -= new_interval.number_to_point(1) new_interval.shift(side_shift_val) self.add(new_interval) self.number_line.add_numbers(0) self.remove(*self.number_mobs) epsilon_mob = OldTex("\\epsilon = 0.01").to_edge(UP) self.add(epsilon_mob) fraction_ticks = self.add_fraction_ticks() self.remove(fraction_ticks) intervals, lines = self.cover_fractions( epsilon = 0.01, num_fractions = 150, run_time_per_interval = 0, ) self.remove(*intervals+lines) for interval, frac in zip(intervals, rationals()): interval.scale(2.0/frac.denominator) for interval in intervals[:10]: squished = deepcopy(interval).stretch_to_fit_width(0) self.play(Transform(squished, interval), run_time = 0.2) self.remove(squished) self.add(interval) for interval in intervals[10:50]: self.add(interval) self.wait(0.1) for interval in intervals[50:]: self.add(interval) self.wait() mobs_shifts = [ (intervals, UP), ([self.number_line, new_interval], side_shift_val*LEFT), (intervals, DOWN) ] for mobs, shift_val in mobs_shifts: self.play(*[ ApplyMethod(mob.shift, shift_val) for mob in mobs ]) self.number_line = new_interval self.wait() words = OldTexText( "Almost all the covered numbers are harmonious!", size = "\\small" ).shift(2*UP) self.play(ShimmerIn(words)) self.wait() for num in [7, 5]: point = self.number_line.number_to_point(2**(num/12.)) arrow = Arrow(point+DOWN, point) mob = OldTex( "2^{\\left(\\frac{%d}{12}\\right)}"%num ).next_to(arrow, DOWN) self.play(ShimmerIn(mob), ShowCreation(arrow)) self.wait() self.remove(mob, arrow) self.remove(words) words = OldTexText( "Cacophonous covered numbers:", size = "\\small" ) words.shift(2*UP) answer1 = OldTexText("Complicated rationals,", size = "\\small") answer2 = OldTexText( "real numbers \\emph{very very very} close to them", size = "\\small" ) compound = Mobject(answer1, answer2.next_to(answer1)) compound.next_to(words, DOWN) answer1, answer2 = compound.split() self.add(words) self.wait() self.remove(*intervals) self.add(answer1) self.play(ShowCreation(fraction_ticks, run_time = 5.0)) self.add(answer2) self.wait() self.remove(words, answer1, answer2) words = OldTexText([ "To a", "savant,", "harmonious numbers could be ", "\\emph{precisely}", "those 1\\% covered by the intervals" ]).shift(2*UP) words = words.split() words[1].set_color() words[3].set_color() self.add(*words) self.play(ShowCreation( Mobject(*intervals), run_time = 5.0 )) self.wait() class FinalEquivalence(IntervalScene): def construct(self): IntervalScene.construct(self) ticks = self.add_fraction_ticks() intervals, lines = self.cover_fractions( epsilon = 0.01, num_fractions = 150, run_time_per_interval = 0, ) for interval, frac in zip(intervals, rationals()): interval.scale(2.0/frac.denominator) self.remove(*intervals+lines) intervals = Mobject(*intervals) arrow = OldTex("\\Leftrightarrow") top_words = OldTexText("Harmonious numbers are rare,") bot_words = OldTexText("even for the savant") bot_words.set_color().next_to(top_words, DOWN) words = Mobject(top_words, bot_words) words.next_to(arrow) self.play( ShowCreation(ticks), Transform( deepcopy(intervals).stretch_to_fit_height(0), intervals ) ) everything = Mobject(*self.mobjects) self.clear() self.play(Transform( everything, deepcopy(everything).scale(0.5).to_edge(LEFT) )) self.add(arrow) self.play(ShimmerIn(words)) self.wait() if __name__ == "__main__": command_line_create_scene(MOVIE_PREFIX)
#!/usr/bin/env python import numpy as np import itertools as it import operator as op from copy import deepcopy from random import random, randint import sys import inspect from manim_imports_ext import * from script_wrapper import command_line_create_scene from functools import reduce RADIUS = FRAME_Y_RADIUS - 0.1 CIRCLE_DENSITY = DEFAULT_POINT_DENSITY_1D*RADIUS MOVIE_PREFIX = "moser/" RADIANS = np.arange(0, 6, 6.0/7) MORE_RADIANS = np.append(RADIANS, RADIANS + 0.5) N_PASCAL_ROWS = 7 BIG_N_PASCAL_ROWS = 11 def int_list_to_string(int_list): return "-".join(map(str, int_list)) def moser_function(n): return choose(n, 4) + choose(n, 2) + 1 ########################################### class CircleScene(Scene): args_list = [ (RADIANS[:x],) for x in range(1, len(RADIANS)+1) ] @staticmethod def args_to_string(*args): return str(len(args[0])) #Length of radians def __init__(self, radians, radius = RADIUS, *args, **kwargs): Scene.__init__(self, *args, **kwargs) self.radius = radius self.circle = Circle(density = CIRCLE_DENSITY).scale(self.radius) self.points = [ (self.radius * np.cos(angle), self.radius * np.sin(angle), 0) for angle in radians ] self.dots = [Dot(point) for point in self.points] self.lines = [Line(p1, p2) for p1, p2 in it.combinations(self.points, 2)] self.n_equals = OldTex( "n=%d"%len(radians), ).shift((-FRAME_X_RADIUS+1, FRAME_Y_RADIUS-1.5, 0)) self.add(self.circle, self.n_equals, *self.dots + self.lines) def generate_intersection_dots(self): """ Generates and adds attributes intersection_points and intersection_dots, but does not yet add them to the scene """ self.intersection_points = [ intersection((p[0], p[2]), (p[1], p[3])) for p in it.combinations(self.points, 4) ] self.intersection_dots = [ Dot(point) for point in self.intersection_points ] def chop_lines_at_intersection_points(self): if not hasattr(self, "intersection_dots"): self.generate_intersection_dots() self.remove(*self.lines) self.lines = [] for point_pair in it.combinations(self.points, 2): int_points = [p for p in self.intersection_points if is_on_line(p, *point_pair)] points = list(point_pair) + int_points points = [(p[0], p[1], 0) for p in points] points.sort(cmp = lambda x,y: cmp(x[0], y[0])) self.lines += [ Line(points[i], points[i+1]) for i in range(len(points)-1) ] self.add(*self.lines) def chop_circle_at_points(self): self.remove(self.circle) self.circle_pieces = [] self.smaller_circle_pieces = [] for i in range(len(self.points)): pp = self.get_points()[i], self.get_points()[(i+1)%len(self.points)] transform = np.array([ [pp[0][0], pp[1][0], 0], [pp[0][1], pp[1][1], 0], [0, 0, 1] ]) circle = deepcopy(self.circle) smaller_circle = deepcopy(self.circle) for c in circle, smaller_circle: c.points = np.dot( c.points, np.transpose(np.linalg.inv(transform)) ) c.filter_out( lambda p : p[0] < 0 or p[1] < 0 ) if c == smaller_circle: c.filter_out( lambda p : p[0] > 4*p[1] or p[1] > 4*p[0] ) c.points = np.dot( c.points, np.transpose(transform) ) self.circle_pieces.append(circle) self.smaller_circle_pieces.append(smaller_circle) self.add(*self.circle_pieces) def generate_regions(self): self.regions = plane_partition_from_points(*self.points) interior = Region(lambda x, y : x**2 + y**2 < self.radius**2) list(map(lambda r : r.intersect(interior), self.regions)) self.exterior = interior.complement() class CountSections(CircleScene): def __init__(self, *args, **kwargs): CircleScene.__init__(self, *args, **kwargs) self.remove(*self.lines) self.play(*[ Transform(Dot(points[i]),Line(points[i], points[1-i])) for points in it.combinations(self.points, 2) for i in (0, 1) ], run_time = 2.0) regions = plane_partition_from_points(*self.points) interior = Region(lambda x, y : x**2 + y**2 < self.radius**2) list(map(lambda r : r.intersect(interior), regions)) regions = [r for r in regions if r.bool_grid.any()] self.count_regions(regions, num_offset = ORIGIN) class MoserPattern(CircleScene): args_list = [(MORE_RADIANS,)] def __init__(self, radians, *args, **kwargs): CircleScene.__init__(self, radians, *args, **kwargs) self.remove(*self.dots + self.lines + [self.n_equals]) n_equals, num = OldTex(["n=", "10"]).split() for mob in n_equals, num: mob.shift((-FRAME_X_RADIUS + 1.5, FRAME_Y_RADIUS - 1.5, 0)) self.add(n_equals) for n in range(1, len(radians)+1): self.add(*self.dots[:n]) self.add(*[Line(p[0], p[1]) for p in it.combinations(self.get_points()[:n], 2)]) tex_stuffs = [ OldTex(str(moser_function(n))), OldTex(str(n)).shift(num.get_center()) ] self.add(*tex_stuffs) self.wait(0.5) self.remove(*tex_stuffs) def hpsq_taylored_alpha(t): return 0.3*np.sin(5*t-5)*np.exp(-20*(t-0.6)**2) + smooth(t) class HardProblemsSimplerQuestions(Scene): def __init__(self, *args, **kwargs): Scene.__init__(self, *args, **kwargs) right_center = np.array((4, 1, 0)) left_center = np.array((-5, 1, 0)) scale_factor = 0.7 fermat = dict([ ( sym, Mobject(*Texs( ["x","^"+sym,"+","y","^"+sym,"=","z","^"+sym] )) ) for sym in ["n", "2", "3"] ]) # not_that_hard = OldTexText("(maybe not that hard...)").scale(0.5) fermat2, fermat2_jargon = OldTex([ r"&x^2 + y^2 = z^2 \\", r""" &(3, 4, 5) \\ &(5, 12, 13) \\ &(15, 8, 17) \\ &\quad \vdots \\ (m^2 - &n^2, 2mn, m^2 + n^2) \\ &\quad \vdots """ ]).split() fermat3, fermat3_jargon = OldTex([ r"&x^3 + y^3 = z^3\\", r""" &y^3 = (z - x)(z - \omega x)(z - \omega^2 x) \\ &\mathds{Z}[\omega] \text{ is a UFD...} """ ]).split() for mob in [fermat2, fermat3, fermat["2"], fermat["3"], fermat2_jargon, fermat3_jargon]: mob.scale(scale_factor) fermat["2"].shift(right_center) fermat["3"].shift(left_center) fermat["n"].shift((0, FRAME_Y_RADIUS - 1, 0)) shift_val = right_center - fermat2.get_center() fermat2.shift(shift_val) fermat2_jargon.shift(shift_val) shift_val = left_center - fermat3.get_center() fermat3.shift(shift_val) fermat3_jargon.shift(shift_val) copies = [ deepcopy(fermat["n"]).center().scale(scale_factor).shift(c) for c in [left_center, right_center] ] self.add(fermat["n"]) self.play(*[ Transform(deepcopy(fermat["n"]), f_copy) for f_copy in copies ]) self.remove(*self.mobjects) self.add(fermat["n"]) self.play(*[ CounterclockwiseTransform(mobs[0], mobs[1]) for f_copy, sym in zip(copies, ["3", "2"]) for mobs in zip(f_copy.split(), fermat[sym].split()) ]) self.remove(*self.mobjects) self.add(fermat["n"], fermat2, fermat3) self.wait() circle_grid = Mobject( Circle(), Grid(radius = 2), OldTex(r"\mathds{R}^2").shift((2, -2, 0)) ) start_line = Line((-1, 0, 0), (-1, 2, 0)) end_line = Line((-1, 0, 0), (-1, -2, 0)) for mob in circle_grid, start_line, end_line: mob.scale(0.5).shift(right_center + (0, 2, 0)) other_grid = Mobject( Grid(radius = 2), OldTex(r"\mathds{C}").shift((2, -2, 0)) ) omega = np.array((0.5, 0.5*np.sqrt(3), 0)) dots = Mobject(*[ Dot(t*np.array((1, 0, 0)) + s * omega) for t, s in it.product(list(range(-2, 3)), list(range(-2, 3))) ]) for mob in dots, other_grid: mob.scale(0.5).shift(left_center + (0, 2, 0)) self.add(circle_grid, other_grid) self.play( FadeIn(fermat2_jargon), FadeIn(fermat3_jargon), CounterclockwiseTransform(start_line, end_line), ShowCreation(dots) ) self.wait() all_mobjects = Mobject(*self.mobjects) self.remove(*self.mobjects) self.play( Transform( all_mobjects, Point((FRAME_X_RADIUS, 0, 0)) ), Transform( Point((-FRAME_X_RADIUS, 0, 0)), Mobject(*CircleScene(RADIANS).mobjects) ) ) class CountLines(CircleScene): def __init__(self, radians, *args, **kwargs): CircleScene.__init__(self, radians, *args, **kwargs) #TODO, Count things explicitly? text_center = (self.radius + 1, self.radius -1, 0) scale_factor = 0.4 text = OldTex(r"\text{How Many Lines?}", size = r"\large") n = len(radians) formula, answer = OldTex([ r"{%d \choose 2} = \frac{%d(%d - 1)}{2} = "%(n, n, n), str(choose(n, 2)) ]) text.scale(scale_factor).shift(text_center) x = text_center[0] new_lines = [ Line((x-1, y, 0), (x+1, y, 0)) for y in np.arange( -(self.radius - 1), self.radius - 1, (2*self.radius - 2)/len(self.lines) ) ] self.add(text) self.wait() self.play(*[ Transform(line1, line2, run_time = 2) for line1, line2 in zip(self.lines, new_lines) ]) self.wait() self.remove(text) self.count(new_lines) anims = [FadeIn(formula)] for mob in self.mobjects: if mob == self.number: anims.append(Transform(mob, answer)) else: anims.append(FadeOut(mob)) self.play(*anims, run_time = 1) class CountIntersectionPoints(CircleScene): def __init__(self, radians, *args, **kwargs): radians = [r % (2*np.pi) for r in radians] radians.sort() CircleScene.__init__(self, radians, *args, **kwargs) intersection_points = [ intersection((p[0], p[2]), (p[1], p[3])) for p in it.combinations(self.points, 4) ] intersection_dots = [Dot(point) for point in intersection_points] text_center = (self.radius + 0.5, self.radius -0.5, 0) size = r"\large" scale_factor = 0.4 text = OldTex(r"\text{How Many Intersection Points?}", size = size) n = len(radians) formula, answer = OldTex([ r"{%d \choose 4} = \frac{%d(%d - 1)(%d - 2)(%d-3)}{1\cdot 2\cdot 3 \cdot 4}="%(n, n, n, n, n), str(choose(n, 4)) ]).split() text.scale(scale_factor).shift(text_center) self.add(text) self.count(intersection_dots, mode="show", num_offset = ORIGIN) self.wait() anims = [] for mob in self.mobjects: if mob == self.number: #put in during count anims.append(Transform(mob, answer)) else: anims.append(FadeOut(mob)) anims.append(Animation(formula)) self.play(*anims, run_time = 1) class NonGeneralPosition(CircleScene): args_list = [] @staticmethod def args_to_string(*args): return "" def __init__(self, *args, **kwargs): radians = np.arange(1, 7) new_radians = (np.pi/3)*radians CircleScene.__init__(self, radians, *args, **kwargs) new_cs = CircleScene(new_radians) center_region = reduce( Region.intersect, [ HalfPlane((self.get_points()[x], self.get_points()[(x+3)%6])) for x in [0, 4, 2]#Ya know, trust it ] ) center_region text = OldTex(r"\text{This region disappears}", size = r"\large") text.center().scale(0.5).shift((-self.radius, self.radius-0.3, 0)) arrow = Arrow( point = (-0.35, -0.1, 0), direction = (1, -1, 0), length = self.radius + 1, color = "white", ) self.set_color_region(center_region, "green") self.add(text, arrow) self.wait(2) self.remove(text, arrow) self.reset_background() self.play(*[ Transform(mob1, mob2, run_time = DEFAULT_ANIMATION_RUN_TIME) for mob1, mob2 in zip(self.mobjects, new_self.mobjects) ]) class GeneralPositionRule(Scene): def __init__(self, *args, **kwargs): Scene.__init__(self, *args, **kwargs) tuples = [ ( np.arange(0, 2*np.pi, np.pi/3), "Not okay", list(zip(list(range(3)), list(range(3, 6)))) ), ( RADIANS, "Okay", [], ), ( np.arange(0, 2*np.pi, np.pi/4), "Not okay", list(zip(list(range(4)), list(range(4, 8)))) ), ( [2*np.pi*random() for x in range(5)], "Okay", [], ), ] first_time = True for radians, words, pairs in tuples: cs = CircleScene(radians) self.add(*cs.mobjects) words_mob = OldTexText(words).scale(2).shift((5, 3, 0)) if not first_time: self.add(words_mob) if words == "Okay": words_mob.set_color("green") self.wait(2) else: words_mob.set_color() intersecting_lines = [ line.scale(0.3).set_color() for i, j in pairs for line in [Line(cs.get_points()[i], cs.get_points()[j])] ] self.play(*[ ShowCreation(line, run_time = 1.0) for line in intersecting_lines ]) if first_time: self.play(Transform( Mobject(*intersecting_lines), words_mob )) first_time = False self.wait() self.remove(*self.mobjects) class LineCorrespondsWithPair(CircleScene): args_list = [ (RADIANS, 2, 5), (RADIANS, 0, 4) ] @staticmethod def args_to_string(*args): return int_list_to_string(args[1:]) def __init__(self, radians, dot0_index, dot1_index, *args, **kwargs): CircleScene.__init__(self, radians, *args, **kwargs) #Remove from self.lines list, so they won't be faded out radians = list(radians) r1, r2 = radians[dot0_index], radians[dot1_index] line_index = list(it.combinations(radians, 2)).index((r1, r2)) line, dot0, dot1 = self.lines[line_index], self.dots[dot0_index], self.dots[dot1_index] self.lines.remove(line) self.dots.remove(dot0) self.dots.remove(dot1) self.wait() self.play(*[ ApplyMethod(mob.fade, 0.2) for mob in self.lines + self.dots ]) self.play(*[ Transform( dot, Dot(dot.get_center(), 3*dot.radius), rate_func = there_and_back ) for dot in (dot0, dot1) ]) self.play(Transform(line, dot0)) class IllustrateNChooseK(Scene): args_list = [ (n, k) for n in range(1, 10) for k in range(n+1) ] @staticmethod def args_to_string(*args): return int_list_to_string(args) def __init__(self, n, k, *args, **kwargs): Scene.__init__(self, *args, **kwargs) nrange = list(range(1, n+1)) tuples = list(it.combinations(nrange, k)) nrange_mobs = OldTex([str(n) + r'\;' for n in nrange]).split() tuple_mobs = Texs( [ (r'\\&' if c%(20//k) == 0 else r'\;\;') + str(p) for p, c in zip(tuples, it.count()) ], size = r"\small", )#TODO, scale these up! tuple_terms = { 2 : "pairs", 3 : "triplets", 4 : "quadruplets", } tuple_term = tuple_terms[k] if k in tuple_terms else "tuples" if k == 2: str1 = r"{%d \choose %d} = \frac{%d(%d - 1)}{2}="%(n, k, n, n) elif k == 4: str1 = r""" {%d \choose %d} = \frac{%d(%d - 1)(%d-2)(%d-3)}{1\cdot 2\cdot 3 \cdot 4}= """%(n, k, n, n, n, n) else: str1 = r"{%d \choose %d} ="%(n, k) form1, count, form2 = OldTex([ str1, "%d"%choose(n, k), r" \text{ total %s}"%tuple_term ]) pronunciation = OldTexText( "(pronounced ``%d choose %d\'\')"%(n, k) ) for mob in nrange_mobs: mob.shift((0, 2, 0)) for mob in form1, count, form2: mob.scale(0.75).shift((0, -FRAME_Y_RADIUS + 1, 0)) count_center = count.get_center() for mob in tuple_mobs: mob.scale(0.6) pronunciation.shift( form1.get_center() + (0, 1, 0) ) self.add(*nrange_mobs) self.wait() run_time = 6.0 frame_time = run_time / len(tuples) for tup, count in zip(tuples, it.count()): count_mob = OldTex(str(count+1)) count_mob.center().shift(count_center) self.add(count_mob) tuple_copy = Mobject(*[nrange_mobs[index-1] for index in tup]) tuple_copy.set_color() self.add(tuple_copy) self.add(tuple_mobs[count]) self.wait(frame_time) self.remove(count_mob) self.remove(tuple_copy) self.add(count_mob) self.play(FadeIn(Mobject(form1, form2, pronunciation))) class IntersectionPointCorrespondances(CircleScene): args_list = [ (RADIANS, list(range(0, 7, 2))), ] @staticmethod def args_to_string(*args): return int_list_to_string(args[1]) def __init__(self, radians, indices, *args, **kwargs): assert(len(indices) == 4) indices.sort() CircleScene.__init__(self, radians, *args, **kwargs) intersection_point = intersection( (self.get_points()[indices[0]], self.get_points()[indices[2]]), (self.get_points()[indices[1]], self.get_points()[indices[3]]) ) if len(intersection_point) == 2: intersection_point = list(intersection_point) + [0] intersection_dot = Dot(intersection_point) intersection_dot_arrow = Arrow(intersection_point).nudge() self.add(intersection_dot) pairs = list(it.combinations(list(range(len(radians))), 2)) lines_to_save = [ self.lines[pairs.index((indices[p0], indices[p1]))] for p0, p1 in [(0, 2), (1, 3)] ] dots_to_save = [ self.dots[p] for p in indices ] line_statement = OldTex(r"\text{Pair of Lines}") dots_statement = OldTex(r"&\text{Quadruplet of} \\ &\text{outer dots}") for mob in line_statement, dots_statement: mob.center() mob.scale(0.7) mob.shift((FRAME_X_RADIUS-2, FRAME_Y_RADIUS - 1, 0)) fade_outs = [] line_highlights = [] dot_highlights = [] dot_pointers = [] for mob in self.mobjects: if mob in lines_to_save: line_highlights.append(Highlight(mob)) elif mob in dots_to_save: dot_highlights.append(Highlight(mob)) dot_pointers.append(Arrow(mob.get_center()).nudge()) elif mob != intersection_dot: fade_outs.append(FadeOut(mob, rate_func = not_quite_there)) self.add(intersection_dot_arrow) self.play(Highlight(intersection_dot)) self.remove(intersection_dot_arrow) self.play(*fade_outs) self.wait() self.add(line_statement) self.play(*line_highlights) self.remove(line_statement) self.wait() self.add(dots_statement, *dot_pointers) self.play(*dot_highlights) self.remove(dots_statement, *dot_pointers) class LinesIntersectOutside(CircleScene): args_list = [ (RADIANS, [2, 4, 5, 6]), ] @staticmethod def args_to_string(*args): return int_list_to_string(args[1]) def __init__(self, radians, indices, *args, **kwargs): assert(len(indices) == 4) indices.sort() CircleScene.__init__(self, radians, *args, **kwargs) intersection_point = intersection( (self.get_points()[indices[0]], self.get_points()[indices[1]]), (self.get_points()[indices[2]], self.get_points()[indices[3]]) ) intersection_point = tuple(list(intersection_point) + [0]) intersection_dot = Dot(intersection_point) pairs = list(it.combinations(list(range(len(radians))), 2)) lines_to_save = [ self.lines[pairs.index((indices[p0], indices[p1]))] for p0, p1 in [(0, 1), (2, 3)] ] self.play(*[ FadeOut(mob, rate_func = not_quite_there) for mob in self.mobjects if mob not in lines_to_save ]) self.play(*[ Transform( Line(self.get_points()[indices[p0]], self.get_points()[indices[p1]]), Line(self.get_points()[indices[p0]], intersection_point)) for p0, p1 in [(0, 1), (3, 2)] ] + [ShowCreation(intersection_dot)]) class QuadrupletsToIntersections(CircleScene): def __init__(self, radians, *args, **kwargs): CircleScene.__init__(self, radians, *args, **kwargs) quadruplets = it.combinations(list(range(len(radians))), 4) frame_time = 1.0 for quad in quadruplets: intersection_dot = Dot(intersection( (self.get_points()[quad[0]], self.get_points()[quad[2]]), (self.get_points()[quad[1]], self.get_points()[quad[3]]) )).repeat(3) dot_quad = [deepcopy(self.dots[i]) for i in quad] for dot in dot_quad: dot.scale(2) dot_quad = Mobject(*dot_quad) dot_quad.set_color() self.add(dot_quad) self.wait(frame_time / 3) self.play(Transform( dot_quad, intersection_dot, run_time = 3*frame_time/2 )) class GraphsAndEulersFormulaJoke(Scene): def __init__(self, *args, **kwargs): Scene.__init__(self, *args, **kwargs) axes = Mobject( NumberLine(), NumberLine().rotate(np.pi / 2) ) graph = ParametricCurve( lambda t : (10*t, ((10*t)**3 - 10*t), 0), expected_measure = 40.0 ) graph.filter_out(lambda x_y_z : abs(x_y_z[1]) > FRAME_Y_RADIUS) self.add(axes) self.play(ShowCreation(graph), run_time = 1.0) eulers = OldTex("e^{\pi i} = -1").shift((0, 3, 0)) self.play(CounterclockwiseTransform( deepcopy(graph), eulers )) self.wait() self.remove(*self.mobjects) self.add(eulers) self.play(CounterclockwiseTransform( Mobject(axes, graph), Point((-FRAME_X_RADIUS, FRAME_Y_RADIUS, 0)) )) self.play(CounterclockwiseTransform( eulers, Point((FRAME_X_RADIUS, FRAME_Y_RADIUS, 0)) )) class DefiningGraph(GraphScene): def __init__(self, *args, **kwargs): GraphScene.__init__(self, *args, **kwargs) word_center = (0, 3, 0) vertices_word = OldTexText("``Vertices\"").shift(word_center) edges_word = OldTexText("``Edges\"").shift(word_center) dots, lines = self.vertices, self.edges self.remove(*dots + lines) all_dots = Mobject(*dots) self.play(ShowCreation(all_dots)) self.remove(all_dots) self.add(*dots) self.play(FadeIn(vertices_word)) self.wait() self.remove(vertices_word) self.play(*[ ShowCreation(line) for line in lines ]) self.play(FadeIn(edges_word)) #Move to new graph # new_graph = deepcopy(self.graph) # new_graph.vertices = [ # (v[0] + 3*random(), v[1] + 3*random(), 0) # for v in new_graph.vertices # ] # new_graph_scene = GraphScene(new_graph) # self.play(*[ # Transform(m[0], m[1]) # for m in zip(self.mobjects, new_graph_scene.mobjects) # ], run_time = 7.0) class IntersectCubeGraphEdges(GraphScene): args_list = [] @staticmethod def args_to_string(*args): return "" def __init__(self, *args, **kwargs): GraphScene.__init__(self, CubeGraph(), *args, **kwargs) self.remove(self.edges[0], self.edges[4]) self.play(*[ Transform( Line(self.get_points()[i], self.get_points()[j]), CurvedLine(self.get_points()[i], self.get_points()[j]), ) for i, j in [(0, 1), (5, 4)] ]) class DoubledEdges(GraphScene): def __init__(self, *args, **kwargs): GraphScene.__init__(self, *args, **kwargs) lines_to_double = self.edges[:9:3] crazy_lines = [ ( line, Line(line.end, line.start), CurvedLine(line.start, line.end) , CurvedLine(line.end, line.start) ) for line in lines_to_double ] anims = [] outward_curved_lines = [] kwargs = {"run_time" : 3.0} for straight, backwards, inward, outward in crazy_lines: anims += [ Transform(straight, inward, **kwargs), Transform(backwards, outward, **kwargs), ] outward_curved_lines.append(outward) self.play(*anims) self.wait() self.remove(*outward_curved_lines) class EulersFormula(GraphScene): def __init__(self, *args, **kwargs): GraphScene.__init__(self, *args, **kwargs) terms = "V - E + F =2".split(" ") form = dict([ (key, mob) for key, mob in zip(terms, Texs(terms)) ]) for mob in list(form.values()): mob.shift((0, FRAME_Y_RADIUS-0.7, 0)) formula = Mobject(*[form[k] for k in list(form.keys()) if k != "=2"]) new_form = dict([ (key, deepcopy(mob).shift((0, -0.7, 0))) for key, mob in zip(list(form.keys()), list(form.values())) ]) self.add(formula) colored_dots = [ deepcopy(d).scale(1.5).set_color("red") for d in self.dots ] colored_edges = [ Mobject( Line(midpoint, start), Line(midpoint, end), ).set_color("red") for e in self.edges for start, end, midpoint in [ (e.start, e.end, (e.start + e.end)/2.0) ] ] frame_time = 0.3 self.generate_regions() parameters = [ (colored_dots, "V", "mobject", "-", "show"), (colored_edges, "E", "mobject", "+", "show"), (self.regions, "F", "region", "=2", "show_all") ] for items, letter, item_type, symbol, mode in parameters: self.count( items, item_type = item_type, mode = mode, num_offset = new_form[letter].get_center(), run_time = frame_time*len(items) ) self.wait() if item_type == "mobject": self.remove(*items) self.add(new_form[symbol]) class CannotDirectlyApplyEulerToMoser(CircleScene): def __init__(self, radians, *args, **kwargs): CircleScene.__init__(self, radians, *args, **kwargs) self.remove(self.n_equals) n_equals, intersection_count = OldTex([ r"&n = %d\\"%len(radians), r"&{%d \choose 4} = %d"%(len(radians), choose(len(radians), 4)) ]).split() shift_val = self.n_equals.get_center() - n_equals.get_center() for mob in n_equals, intersection_count: mob.shift(shift_val) self.add(n_equals) yellow_dots = [ d.set_color("yellow").scale(2) for d in deepcopy(self.dots) ] yellow_lines = Mobject(*[ l.set_color("yellow") for l in deepcopy(self.lines) ]) self.play(*[ ShowCreation(dot) for dot in yellow_dots ], run_time = 1.0) self.wait() self.remove(*yellow_dots) self.play(ShowCreation(yellow_lines)) self.wait() self.remove(yellow_lines) cannot_intersect = OldTexText(r""" Euler's formula does not apply to \\ graphs whose edges intersect! """ ) cannot_intersect.center() for mob in self.mobjects: mob.fade(0.3) self.add(cannot_intersect) self.wait() self.remove(cannot_intersect) for mob in self.mobjects: mob.fade(1/0.3) self.generate_intersection_dots() self.play(FadeIn(intersection_count), *[ ShowCreation(dot) for dot in self.intersection_dots ]) class ShowMoserGraphLines(CircleScene): def __init__(self, radians, *args, **kwargs): radians = list(set([x%(2*np.pi) for x in radians])) radians.sort() CircleScene.__init__(self, radians, *args, **kwargs) n, plus_n_choose_4 = OldTex(["n", "+{n \\choose 4}"]).split() n_choose_2, plus_2_n_choose_4, plus_n = OldTex([ r"{n \choose 2}",r"&+2{n \choose 4}\\",r"&+n" ]).split() for mob in n, plus_n_choose_4, n_choose_2, plus_2_n_choose_4, plus_n: mob.shift((FRAME_X_RADIUS - 2, FRAME_Y_RADIUS-1, 0)) self.chop_lines_at_intersection_points() self.add(*self.intersection_dots) small_lines = [ deepcopy(line).scale(0.5) for line in self.lines ] for mobs, symbol in [ (self.dots, n), (self.intersection_dots, plus_n_choose_4), (self.lines, n_choose_2) ]: self.add(symbol) compound = Mobject(*mobs) if mobs in (self.dots, self.intersection_dots): self.remove(*mobs) self.play(CounterclockwiseTransform( compound, deepcopy(compound).scale(1.05), rate_func = there_and_back, run_time = 2.0, )) else: compound.set_color("yellow") self.play(ShowCreation(compound)) self.remove(compound) if mobs == self.intersection_dots: self.remove(n, plus_n_choose_4) self.play(*[ Transform(line, small_line, run_time = 3.0) for line, small_line in zip(self.lines, small_lines) ]) yellow_lines = Mobject(*[ line.set_color("yellow") for line in small_lines ]) self.add(plus_2_n_choose_4) self.play(ShowCreation(yellow_lines)) self.wait() self.remove(yellow_lines) self.chop_circle_at_points() self.play(*[ Transform(p, sp, run_time = 3.0) for p, sp in zip(self.circle_pieces, self.smaller_circle_pieces) ]) self.add(plus_n) self.play(ShowCreation(Mobject(*[ mob.set_color("yellow") for mob in self.circle_pieces ]))) class HowIntersectionChopsLine(CircleScene): args_list = [ (RADIANS, list(range(0, 7, 2))), ] @staticmethod def args_to_string(*args): return int_list_to_string(args[1]) def __init__(self, radians, indices, *args, **kwargs): assert(len(indices) == 4) indices.sort() CircleScene.__init__(self, radians, *args, **kwargs) intersection_point = intersection( (self.get_points()[indices[0]], self.get_points()[indices[2]]), (self.get_points()[indices[1]], self.get_points()[indices[3]]) ) if len(intersection_point) == 2: intersection_point = list(intersection_point) + [0] pairs = list(it.combinations(list(range(len(radians))), 2)) lines = [ Line(self.get_points()[indices[p0]], self.get_points()[indices[p1]]) for p0, p1 in [(2, 0), (1, 3)] ] self.remove(*[ self.lines[pairs.index((indices[p0], indices[p1]))] for p0, p1 in [(0, 2), (1, 3)] ]) self.add(*lines) self.play(*[ FadeOut(mob) for mob in self.mobjects if mob not in lines ]) new_lines = [ Line(line.start, intersection_point) for line in lines ] + [ Line(intersection_point, line.end) for line in lines ] self.play(*[ Transform( line, Line( (-3, h, 0), (3, h, 0) ), rate_func = there_and_back, run_time = 3.0 ) for line, h in zip(lines, (-1, 1)) ]) self.remove(*lines) self.play(*[ Transform( line, deepcopy(line).scale(1.1).scale(1/1.1), run_time = 1.5 ) for line in new_lines ]) class ApplyEulerToMoser(CircleScene): def __init__(self, *args, **kwargs): radius = 2 CircleScene.__init__(self, *args, radius = radius, **kwargs) self.generate_intersection_dots() self.chop_lines_at_intersection_points() self.chop_circle_at_points() self.generate_regions() for dot in self.dots + self.intersection_dots: dot.scale(radius / RADIUS) self.remove(*self.mobjects) V = {} minus = {} minus1 = {} E = {} plus = {} plus1 = {} plus2 = {} F = {} equals = {} two = {} two1 = {} n = {} n1 = {} nc2 = {} nc4 = {} nc41 = {} dicts = [V, minus, minus1, E, plus, plus1, plus2, F, equals, two, two1, n, n1, nc2, nc4, nc41] V[1], minus[1], E[1], plus[1], F[1], equals[1], two[1] = \ OldTex(["V", "-", "E", "+", "F", "=", "2"]).split() F[2], equals[2], E[2], minus[2], V[2], plus[2], two[2] = \ OldTex(["F", "=", "E", "-", "V", "+", "2"]).split() F[3], equals[3], E[3], minus[3], n[3], minus1[3], nc4[3], plus[3], two[3] = \ OldTex(["F", "=", "E", "-", "n", "-", r"{n \choose 4}", "+", "2"]).split() F[4], equals[4], nc2[4], plus1[4], two1[4], nc41[4], plus2[4], n1[4], minus[4], n[4], minus1[4], nc4[4], plus[4], two[4] = \ OldTex(["F", "=", r"{n \choose 2}", "+", "2", r"{n \choose 4}", "+", "n","-", "n", "-", r"{n \choose 4}", "+", "2"]).split() F[5], equals[5], nc2[5], plus1[5], two1[5], nc41[5], minus1[5], nc4[5], plus[5], two[5] = \ OldTex(["F", "=", r"{n \choose 2}", "+", "2", r"{n \choose 4}", "-", r"{n \choose 4}", "+", "2"]).split() F[6], equals[6], nc2[6], plus1[6], nc4[6], plus[6], two[6] = \ OldTex(["F", "=", r"{n \choose 2}", "+", r"{n \choose 4}", "+", "2"]).split() F[7], equals[7], two[7], plus[7], nc2[7], plus1[7], nc4[7] = \ OldTex(["F", "=", "2", "+", r"{n \choose 2}", "+", r"{n \choose 4}"]).split() shift_val = (0, 3, 0) for d in dicts: if not d: continue main_key = list(d.keys())[0] for key in list(d.keys()): d[key].shift(shift_val) main_center = d[main_key].get_center() for key in list(d.keys()): d[key] = deepcopy(d[main_key]).shift( d[key].get_center() - main_center ) self.play(*[ CounterclockwiseTransform(d[1], d[2], run_time = 2.0) for d in [V, minus, E, plus, F, equals, two] ]) self.wait() F[1].set_color() self.add(*self.lines + self.circle_pieces) for region in self.regions: self.set_color_region(region) self.set_color_region(self.exterior, "blue") self.wait() self.reset_background() F[1].set_color("white") E[1].set_color() self.remove(*self.lines + self.circle_pieces) self.play(*[ Transform( deepcopy(line), deepcopy(line).scale(0.5), run_time = 2.0, ) for line in self.lines ] + [ Transform( deepcopy(cp), scp, run_time = 2.0 ) for cp, scp in zip(self.circle_pieces, self.smaller_circle_pieces) ]) self.wait() E[1].set_color("white") V[1].set_color() self.add(*self.dots + self.intersection_dots) self.remove(*self.lines + self.circle_pieces) self.play(*[ Transform( deepcopy(dot), deepcopy(dot).scale(1.4).set_color("yellow") ) for dot in self.dots + self.intersection_dots ] + [ Transform( deepcopy(line), deepcopy(line).fade(0.4) ) for line in self.lines + self.circle_pieces ]) self.wait() all_mobs = [mob for mob in self.mobjects] self.remove(*all_mobs) self.add(*[d[1] for d in [V, minus, E, plus, F, equals, two]]) V[1].set_color("white") two[1].set_color() self.wait() self.add(*all_mobs) self.remove(*[d[1] for d in [V, minus, E, plus, F, equals, two]]) self.play( Transform(V[2].repeat(2), Mobject(n[3], minus1[3], nc4[3])), *[ Transform(d[2], d[3]) for d in [F, equals, E, minus, plus, two] ] ) self.wait() self.remove(*self.mobjects) self.play( Transform(E[3], Mobject( nc2[4], plus1[4], two1[4], nc41[4], plus2[4], n1[4] )), *[ Transform(d[3], d[4]) for d in [F, equals, minus, n, minus1, nc4, plus, two] ] + [ Transform( deepcopy(line), deepcopy(line).scale(0.5), ) for line in self.lines ] + [ Transform(deepcopy(cp), scp) for cp, scp in zip(self.circle_pieces, self.smaller_circle_pieces) ], run_time = 2.0 ) self.wait() self.remove(*self.mobjects) self.play( Transform( Mobject(plus2[4], n1[4], minus[4], n[4]), Point((FRAME_X_RADIUS, FRAME_Y_RADIUS, 0)) ), *[ Transform(d[4], d[5]) for d in [F, equals, nc2, plus1, two1, nc41, minus1, nc4, plus, two] ] ) self.wait() self.remove(*self.mobjects) self.play( Transform(nc41[5], nc4[6]), Transform(two1[5], Point(nc4[6].get_center())), *[ Transform(d[5], d[6]) for d in [F, equals, nc2, plus1, nc4, plus, two] ] ) self.wait() self.remove(*self.mobjects) self.play( CounterclockwiseTransform(two[6], two[7]), CounterclockwiseTransform(plus[6], plus[7]), *[ Transform(d[6], d[7]) for d in [F, equals, nc2, plus1, nc4] ] ) self.wait() self.add(*self.lines + self.circle_pieces) for region in self.regions: self.set_color_region(region) self.wait() self.set_color_region(self.exterior, "blue") self.wait() self.set_color_region(self.exterior, "black") self.remove(two[6]) two = two[7] one = OldTex("1").shift(two.get_center()) two.set_color("red") self.add(two) self.play(CounterclockwiseTransform(two, one)) class FormulaRelatesToPowersOfTwo(Scene): def __init__(self, *args, **kwargs): Scene.__init__(self, *args, **kwargs) pof2_range = [1, 2, 3, 4, 5, 10] strings = [ [ r"&1 + {%d \choose 2} + {%d \choose 4} ="%(n, n), r"1 + %d + %d ="%(choose(n, 2), choose(n, 4)), r"%d \\"%moser_function(n) ] for n in [1, 2, 3, 4, 5, 10] ] everything = Texs(sum(strings, []), size = r"\large") scale_factor = 1 for mob in everything: mob.scale(scale_factor) Mobject(*everything).show() forms = everything[0::3] sums = everything[1::3] results = everything[2::3] self.add(*forms) self.play(*[ FadeIn(s) for s in sums ]) self.wait() self.play(*[ Transform(deepcopy(s), result) for s, result in zip(sums, results) ]) powers_of_two = [ OldTex("2^{%d}"%(i-1) ).scale(scale_factor ).shift(result.get_center() ).set_color() for i, result in zip(pof2_range, results) ] self.wait() self.remove(*self.mobjects) self.add(*forms + sums + results) self.play(*[ CounterclockwiseTransform(result, pof2) for result, pof2 in zip(results, powers_of_two) ]) class DrawPascalsTriangle(PascalsTriangleScene): def __init__(self, *args, **kwargs): PascalsTriangleScene.__init__(self, *args, **kwargs) self.remove(*self.mobjects) self.add(self.coords_to_mobs[0][0]) for n in range(1, nrows): starts = [deepcopy(self.coords_to_mobs[n-1][0])] starts += [ Mobject( self.coords_to_mobs[n-1][k-1], self.coords_to_mobs[n-1][k] ) for k in range(1, n) ] starts.append(deepcopy(self.coords_to_mobs[n-1][n-1])) self.play(*[ Transform(starts[i], self.coords_to_mobs[n][i], run_time = 1.5, black_out_extra_points = False) for i in range(n+1) ]) class PascalRuleExample(PascalsTriangleScene): def __init__(self, nrows, *args, **kwargs): assert(nrows > 1) PascalsTriangleScene.__init__(self, nrows, *args, **kwargs) self.wait() n = randint(2, nrows-1) k = randint(1, n-1) self.coords_to_mobs[n][k].set_color("green") self.wait() plus = OldTex("+").scale(0.5) nums_above = [self.coords_to_mobs[n-1][k-1], self.coords_to_mobs[n-1][k]] plus.center().shift(sum(map(Mobject.get_center, nums_above)) / 2) self.add(plus) for mob in nums_above + [plus]: mob.set_color("yellow") self.wait() class PascalsTriangleWithNChooseK(PascalsTriangleScene): def __init__(self, *args, **kwargs): PascalsTriangleScene.__init__(self, *args, **kwargs) self.generate_n_choose_k_mobs() mob_dicts = (self.coords_to_mobs, self.coords_to_n_choose_k) for i in [0, 1]: self.wait() self.remove(*self.mobjects) self.play(*[ CounterclockwiseTransform( deepcopy(mob_dicts[i][n][k]), mob_dicts[1-i][n][k] ) for n, k in self.coords ]) self.remove(*self.mobjects) self.add(*[mob_dicts[1-i][n][k] for n, k in self.coords]) class PascalsTriangleNChooseKExample(PascalsTriangleScene): args_list = [ (N_PASCAL_ROWS, 5, 3), ] @staticmethod def args_to_string(nrows, n, k): return "%d_n=%d_k=%d"%(nrows, n, k) def __init__(self, nrows, n, k, *args, **kwargs): PascalsTriangleScene.__init__(self, nrows, *args, **kwargs) wait_time = 0.5 triangle_terms = [self.coords_to_mobs[a][b] for a, b in self.coords] formula_terms = left, n_mob, k_mob, right = OldTex([ r"\left(", str(n), r"\atop %d"%k, r"\right)" ]) formula_center = (FRAME_X_RADIUS - 1, FRAME_Y_RADIUS - 1, 0) self.remove(*triangle_terms) self.add(*formula_terms) self.wait() self.play(* [ ShowCreation(mob) for mob in triangle_terms ]+[ ApplyMethod(mob.shift, formula_center) for mob in formula_terms ], run_time = 1.0 ) self.remove(n_mob, k_mob) for a in range(n+1): row = [self.coords_to_mobs[a][b] for b in range(a+1)] a_mob = OldTex(str(a)) a_mob.shift(n_mob.get_center()) a_mob.set_color("green") self.add(a_mob) for mob in row: mob.set_color("green") self.wait(wait_time) if a < n: for mob in row: mob.set_color("white") self.remove(a_mob) self.wait() for b in range(k+1): b_mob = OldTex(str(b)) b_mob.shift(k_mob.get_center()) b_mob.set_color("yellow") self.add(b_mob) self.coords_to_mobs[n][b].set_color("yellow") self.wait(wait_time) if b < k: self.coords_to_mobs[n][b].set_color("green") self.remove(b_mob) self.play(*[ ApplyMethod(mob.fade, 0.2) for mob in triangle_terms if mob != self.coords_to_mobs[n][k] ]) self.wait() class PascalsTriangleSumRows(PascalsTriangleScene): def __init__(self, *args, **kwargs): PascalsTriangleScene.__init__(self, *args, **kwargs) pluses = [] powers_of_two = [] equalses = [] powers_of_two_symbols = [] plus = OldTex("+") desired_plus_width = self.coords_to_mobs[0][0].get_width() if plus.get_width() > desired_plus_width: plus.scale(desired_plus_width / plus.get_width()) for n, k in self.coords: if k == 0: continue new_plus = deepcopy(plus) new_plus.center().shift(self.coords_to_mobs[n][k].get_center()) new_plus.shift((-self.cell_width / 2.0, 0, 0)) pluses.append(new_plus) equals = OldTex("=") equals.scale(min(1, 0.7 * self.cell_height / equals.get_width())) for n in range(self.nrows): new_equals = deepcopy(equals) pof2 = Texs(str(2**n)) symbol = OldTex("2^{%d}"%n) desired_center = np.array(( self.diagram_width / 2.0, self.coords_to_mobs[n][0].get_center()[1], 0 )) new_equals.shift(desired_center - new_equals.get_center()) desired_center += (1.5*equals.get_width(), 0, 0) scale_factor = self.coords_to_mobs[0][0].get_height() / pof2.get_height() for mob in pof2, symbol: mob.center().scale(scale_factor).shift(desired_center) symbol.shift((0, 0.5*equals.get_height(), 0)) #FUAH! Stupid powers_of_two.append(pof2) equalses.append(new_equals) powers_of_two_symbols.append(symbol) self.play(FadeIn(Mobject(*pluses))) run_time = 0.5 to_remove = [] for n in range(self.nrows): start = Mobject(*[self.coords_to_mobs[n][k] for k in range(n+1)]) to_remove.append(start) self.play( Transform(start, powers_of_two[n]), FadeIn(equalses[n]), run_time = run_time ) self.wait() self.remove(*to_remove) self.add(*powers_of_two) for n in range(self.nrows): self.play(CounterclockwiseTransform( powers_of_two[n], powers_of_two_symbols[n], run_time = run_time )) self.remove(powers_of_two[n]) self.add(powers_of_two_symbols[n]) class MoserSolutionInPascal(PascalsTriangleScene): args_list = [ (N_PASCAL_ROWS, n) for n in range(3, 8) ] + [ (BIG_N_PASCAL_ROWS, 10) ] @staticmethod def args_to_string(nrows, n): return "%d_n=%d"%(nrows,n) def __init__(self, nrows, n, *args, **kwargs): PascalsTriangleScene.__init__(self, nrows, *args, **kwargs) term_color = "green" self.generate_n_choose_k_mobs() self.remove(*[self.coords_to_mobs[n0][k0] for n0, k0 in self.coords]) terms = one, plus0, n_choose_2, plus1, n_choose_4 = OldTex([ "1", "+", r"{%d \choose 2}"%n, "+", r"{%d \choose 4}"%n ]).split() target_terms = [] for k in range(len(terms)): if k%2 == 0 and k <= n: new_term = deepcopy(self.coords_to_n_choose_k[n][k]) new_term.set_color(term_color) else: new_term = Point( self.coords_to_center(n, k) ) target_terms.append(new_term) self.add(*terms) self.wait() self.play(* [ FadeIn(self.coords_to_n_choose_k[n0][k0]) for n0, k0 in self.coords if (n0, k0) not in [(n, 0), (n, 2), (n, 4)] ]+[ Transform(term, target_term) for term, target_term in zip(terms, target_terms) ] ) self.wait() term_range = list(range(0, min(4, n)+1, 2)) target_terms = dict([ (k, deepcopy(self.coords_to_mobs[n][k]).set_color(term_color)) for k in term_range ]) self.play(* [ CounterclockwiseTransform( self.coords_to_n_choose_k[n0][k0], self.coords_to_mobs[n0][k0] ) for n0, k0 in self.coords if (n0, k0) not in [(n, k) for k in term_range] ]+[ CounterclockwiseTransform(terms[k], target_terms[k]) for k in term_range ] ) self.wait() for k in term_range: if k == 0: above_terms = [self.coords_to_n_choose_k[n-1][k]] elif k == n: above_terms = [self.coords_to_n_choose_k[n-1][k-1]] else: above_terms = [ self.coords_to_n_choose_k[n-1][k-1], self.coords_to_n_choose_k[n-1][k], ] self.add(self.coords_to_mobs[n][k]) self.play(Transform( terms[k], Mobject(*above_terms).set_color(term_color) )) self.remove(*above_terms) self.wait() terms_sum = OldTex(str(moser_function(n))) terms_sum.shift((FRAME_X_RADIUS-1, terms[0].get_center()[1], 0)) terms_sum.set_color(term_color) self.play(Transform(Mobject(*terms), terms_sum)) class RotatingPolyhedra(Scene): args_list = [ ([Cube, Dodecahedron],) ] @staticmethod def args_to_string(class_list): return "".join([c.__name__ for c in class_list]) def __init__(self, polyhedra_classes, *args, **kwargs): Scene.__init__(self, *args, **kwargs) rot_kwargs = { "radians" : np.pi / 2, "run_time" : 5.0, "axis" : [0, 1, 0] } polyhedra = [ Class().scale(1.5).shift((1, 0, 0)) for Class in polyhedra_classes ] curr_mob = polyhedra.pop() for mob in polyhedra: self.play(TransformAnimations( Rotating(curr_mob, **rot_kwargs), Rotating(mob, **rot_kwargs) )) for m in polyhedra: m.rotate(rot_kwargs["radians"], rot_kwargs["axis"]) self.play(Rotating(curr_mob, **rot_kwargs)) class ExplainNChoose2Formula(Scene): args_list = [(7,2,6)] @staticmethod def args_to_string(n, a, b): return "n=%d_a=%d_b=%d"%(n, a, b) def __init__(self, n, a, b, *args, **kwargs): Scene.__init__(self, *args, **kwargs) r_paren, a_mob, comma, b_mob, l_paren = Texs( ("( %d , %d )"%(a, b)).split(" ") ) parens = Mobject(r_paren, comma, l_paren) nums = [Tex(str(k)) for k in range(1, n+1)] height = 1.5*nums[0].get_height() for x in range(n): nums[x].shift((0, x*height, 0)) nums_compound = Mobject(*nums) nums_compound.shift(a_mob.get_center() - nums[0].get_center()) n_mob, n_minus_1, over_2 = OldTex([ str(n), "(%d-1)"%n, r"\over{2}" ]).split() for part in n_mob, n_minus_1, over_2: part.shift((FRAME_X_RADIUS-1.5, FRAME_Y_RADIUS-1, 0)) self.add(parens, n_mob) up_unit = np.array((0, height, 0)) self.play(ApplyMethod(nums_compound.shift, -(n-1)*up_unit)) self.play(ApplyMethod(nums_compound.shift, (n-a)*up_unit)) self.remove(nums_compound) nums = nums_compound.split() a_mob = nums.pop(a-1) nums_compound = Mobject(*nums) self.add(a_mob, nums_compound) self.wait() right_shift = b_mob.get_center() - a_mob.get_center() right_shift[1] = 0 self.play( ApplyMethod(nums_compound.shift, right_shift), FadeIn(n_minus_1) ) self.play(ApplyMethod(nums_compound.shift, (a-b)*up_unit)) self.remove(nums_compound) nums = nums_compound.split() b_mob = nums.pop(b-2 if a < b else b-1) self.add(b_mob) self.play(*[ CounterclockwiseTransform( mob, Point(mob.get_center()).set_color("black") ) for mob in nums ]) self.play(*[ ApplyMethod(mob.shift, (0, 1, 0)) for mob in (parens, a_mob, b_mob) ]) parens_copy = deepcopy(parens).shift((0, -2, 0)) a_center = a_mob.get_center() b_center = b_mob.get_center() a_copy = deepcopy(a_mob).center().shift(b_center - (0, 2, 0)) b_copy = deepcopy(b_mob).center().shift(a_center - (0, 2, 0)) self.add(over_2, deepcopy(a_mob), deepcopy(b_mob)) self.play( CounterclockwiseTransform(a_mob, a_copy), CounterclockwiseTransform(b_mob, b_copy), FadeIn(parens_copy), FadeIn(OldTexText("is considered the same as")) ) class ExplainNChoose4Formula(Scene): args_list = [(7,)] @staticmethod def args_to_string(n): return "n=%d"%n def __init__(self, n, *args, **kwargs): Scene.__init__(self, *args, **kwargs) # quad = list(it.combinations(range(1,n+1), 4))[randint(0, choose(n, 4)-1)] quad = (4, 2, 5, 1) tuple_mobs = Texs( ("( %d , %d , %d , %d )"%quad).split(" ") ) quad_mobs = tuple_mobs[1::2] parens = Mobject(*tuple_mobs[0::2]) form_mobs = OldTex([ str(n), "(%d-1)"%n, "(%d-2)"%n,"(%d-3)"%n, r"\over {4 \cdot 3 \cdot 2 \cdot 1}" ]).split() form_mobs = Mobject(*form_mobs).scale(0.7).shift((4, 3, 0)).split() nums = [Tex(str(k)) for k in range(1, n+1)] height = 1.5*nums[0].get_height() for x in range(n): nums[x].shift((0, x*height, 0)) nums_compound = Mobject(*nums) nums_compound.shift(quad_mobs[0].get_center() - nums[0].get_center()) curr_num = 1 self.add(parens) up_unit = np.array((0, height, 0)) for i in range(4): self.add(form_mobs[i]) self.play(ApplyMethod( nums_compound.shift, (curr_num-quad[i])*up_unit)) self.remove(nums_compound) nums = nums_compound.split() chosen = nums[quad[i]-1] nums[quad[i]-1] = Point(chosen.get_center()).set_color("black") nums_compound = Mobject(*nums) self.add(chosen) if i < 3: right_shift = quad_mobs[i+1].get_center() - chosen.get_center() right_shift[1] = 0 self.play( ApplyMethod(nums_compound.shift, right_shift) ) else: self.play(*[ CounterclockwiseTransform( mob, Point(mob.get_center()).set_color("black") ) for mob in nums ]) curr_num = quad[i] self.remove(*self.mobjects) num_perms_explain = OldTexText( r"There are $(4 \cdot 3 \cdot 2 \cdot 1)$ total permutations" ).shift((0, -2, 0)) self.add(parens, num_perms_explain, *form_mobs) perms = list(it.permutations(list(range(4)))) for count in range(6): perm = perms[randint(0, 23)] new_quad_mobs = [ deepcopy(quad_mobs[i]).shift( quad_mobs[perm[i]].get_center() - \ quad_mobs[i].get_center() ) for i in range(4) ] compound_quad = Mobject(*quad_mobs) self.play(CounterclockwiseTransform( compound_quad, Mobject(*new_quad_mobs) )) self.remove(compound_quad) quad_mobs = new_quad_mobs class IntersectionChoppingExamples(Scene): def __init__(self, *args, **kwargs): Scene.__init__(self, *args, **kwargs) pairs1 = [ ((-1,-1, 0), (-1, 0, 0)), ((-1, 0, 0), (-1, 1, 0)), ((-2, 0, 0), (-1, 0, 0)), ((-1, 0, 0), ( 1, 0, 0)), (( 1, 0, 0), ( 2, 0, 0)), (( 1,-1, 0), ( 1, 0, 0)), (( 1, 0, 0), ( 1, 1, 0)), ] pairs2 = pairs1 + [ (( 1, 1, 0), ( 1, 2, 0)), (( 0, 1, 0), ( 1, 1, 0)), (( 1, 1, 0), ( 2, 1, 0)), ] for pairs, exp in [(pairs1, "3 + 2(2) = 7"), (pairs2, "4 + 2(3) = 10")]: lines = [Line(*pair).scale(2) for pair in pairs] self.add(OldTex(exp).shift((0, FRAME_Y_RADIUS-1, 0))) self.add(*lines) self.wait() self.play(*[ Transform(line, deepcopy(line).scale(1.2).scale(1/1.2)) for line in lines ]) self.count(lines, run_time = 3.0, num_offset = ORIGIN) self.wait() self.remove(*self.mobjects)
from manim_imports_ext import * ## Warning, much of what is in this class ## likely not supported anymore. def drag_pixels(frames): curr = frames[0] new_frames = [] for frame in frames: curr += (curr == 0) * np.array(frame) new_frames.append(np.array(curr)) return new_frames class LogoGeneration(Scene): CONFIG = { "radius" : 1.5, "inner_radius_ratio" : 0.55, "circle_density" : 100, "circle_blue" : "skyblue", "circle_brown" : DARK_BROWN, "circle_repeats" : 5, "sphere_density" : 50, "sphere_blue" : BLUE_D, "sphere_brown" : LIGHT_BROWN, "interpolation_factor" : 0.3, "frame_duration" : 0.03, "run_time" : 3, } def construct(self): digest_config(self, {}) ## Usually shouldn't need this... self.frame_duration = self.CONFIG["frame_duration"] ## digest_config(self, {}) circle = Circle( density = self.circle_density, color = self.circle_blue ) circle.repeat(self.circle_repeats) circle.scale(self.radius) sphere = Sphere( density = self.sphere_density, color = self.sphere_blue ) sphere.scale(self.radius) sphere.rotate(-np.pi / 7, [1, 0, 0]) sphere.rotate(-np.pi / 7) iris = Mobject() iris.interpolate( circle, sphere, self.interpolation_factor ) for mob, color in [(iris, self.sphere_brown), (circle, self.circle_brown)]: mob.set_color(color, lambda x_y_z : x_y_z[0] < 0 and x_y_z[1] > 0) mob.set_color( "black", lambda point: get_norm(point) < \ self.inner_radius_ratio*self.radius ) self.name_mob = OldTexText("3Blue1Brown").center() self.name_mob.set_color("grey") self.name_mob.shift(2*DOWN) self.play(Transform( circle, iris, run_time = self.run_time )) self.frames = drag_pixels(self.frames) self.save_image(IMAGE_DIR) self.logo = MobjectFromPixelArray(self.frames[-1]) self.add(self.name_mob) self.wait()
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from manim_imports_ext import * from script_wrapper import command_line_create_scene from .generate_logo import LogoGeneration POEM_LINES = """Fixed poorly in notation with that two, you shine so loud that you deserve a name. Late though we are to make a change, it's true, We can extol you 'til you have pi's fame. One might object, ``Conventions matter not! Great formulae cast truths transcending names.'' I've noticed, though, how language molds my thoughts; the natural terms make heart and head the same. So lose the two inside your autograph, then guide our thoughts without your ``better'' half. Wonders math imparts become so neat when phrased with you, and pi remains off-screen. Sine and exp both cycle to your beat. Jive with Fourier, and forms are clean. ``Wait! Area of circles'', pi would say, ``sticks oddly to one half when tau's preferred.'' More to you then! For write it in this way, then links to triangles can be inferred. Nix pi, then all within geometry shines clean and clear, as if by poetry.""".split("\n") DIGIT_TO_WORD = { '0' : "Zero", '1' : "One", '2' : "Two", '3' : "Three", '4' : "Four", '5' : "Five", '6' : "Six", '7' : "Seven", '8' : "Eight", '9' : "Nine", } FORMULAE = [ "e^{x + \\tau i} = e^{x}", "&\\Leftrightarrow", "e^{x + 2\\pi i} = e^{x} \\\\", "A = \\frac{1}{2} \\tau r^2", "&\\Leftrightarrow", "A = \\pi r^2 \\\\", "n! \\sim \\sqrt{\\tau n}\\left(\\frac{n}{e}\\right)^n", "&\\Leftrightarrow", "n! \\sim \\sqrt{2\\pi n}\\left(\\frac{n}{e}\\right)^n \\\\", # "\\sum_{n = 0}^\\infty \\frac{(-1)^n}{2n+1} = \\frac{\\tau}{8}", # "&\\Leftrightarrow", # "\\sum_{n = 0}^\\infty \\frac{(-1)^n}{2n+1} = \\frac{\\pi}{4} \\\\", ] DIGITS = list(map(str, list("62831853071795864769"))) DIGITS[1] = "." + DIGITS[1] #2->.2 BUFF = 1.0 MOVIE_PREFIX = "tau_poem/" class Welcome(LogoGeneration): def construct(self): text = "Happy $\\tau$ Day, from 3Blue1Brown!" self.add(OldTexText(text).to_edge(UP)) LogoGeneration.construct(self) class HappyTauDayWords(Scene): def construct(self): words = OldTexText("Happy Tau Day Everybody!").scale(2) tau = TauCreature().move_to(2*LEFT + UP) pi = PiCreature().move_to(2*RIGHT + 3*DOWN) pi.set_color("red") self.add(words, tau, pi) self.wait() self.play(BlinkPiCreature(tau)) self.play(BlinkPiCreature(pi)) class TauPoem(Scene): args_list = [(x,) for x in range(len(POEM_LINES))] @staticmethod def args_to_string(line_num, *ignore): return str(line_num) def __init__(self, line_num, *args, **kwargs): self.line_num = line_num self.anim_kwargs = { "run_time" : 4.0, } self.line_num_to_method = { 0 : self.line0, 1 : self.line1, 2 : self.line2, 3 : self.line3, 4 : self.line4, 5 : self.line5, 6 : self.line6, 7 : self.line7, 8 : self.line8, 9 : self.line9, 10 : self.line10, 11 : self.line11, 12 : self.line12, 13 : self.line13, 14 : self.line14, 15 : self.line15, 16 : self.line16, 17 : self.line17, 18 : self.line18, 19 : self.line19, } Scene.__init__(self, *args, **kwargs) def construct(self): self.add_line_and_number() self.line_num_to_method[self.line_num]() self.first_word_to_last_digit() def add_line_and_number(self): self.first_digits, new_digit, last_digits = OldTex([ "".join(DIGITS[:self.line_num]), DIGITS[self.line_num], "".join(DIGITS[(self.line_num+1):]), ]).to_edge(UP, buff=0.2).split() line_str = POEM_LINES[self.line_num] if self.line_num == 0: index = line_str.index("ed ") elif self.line_num == 10: index = line_str.index("ders") else: index = line_str.index(" ") first_word, rest_of_line = OldTexText( [line_str[:index], line_str[index:]] ).to_edge(UP).shift(BUFF*DOWN).split() first_word.shift(0.15*RIGHT) #Stupid number_word = OldTexText(DIGIT_TO_WORD[DIGITS[self.line_num][-1]]) number_word.shift(first_word.get_center()) number_word.shift(BUFF * UP / 2) kwargs = { "rate_func" : squish_rate_func(smooth), } self.add(first_word, rest_of_line, self.first_digits) self.first_word = first_word self.number_word = number_word self.new_digit = new_digit def first_word_to_last_digit(self): if self.line_num == 19: shift_val = FRAME_Y_RADIUS*DOWN self.new_digit.shift(shift_val) self.play(ApplyMethod( self.first_digits.shift, shift_val, run_time = 2.0 )) self.wait(2) self.play_over_time_range(0, 2, Transform( deepcopy(self.first_word), self.number_word, rate_func = squish_rate_func(smooth) ) ) self.play_over_time_range(2, 4, Transform( self.number_word, self.new_digit, rate_func = squish_rate_func(smooth) ) ) def line0(self): two, pi = OldTex(["2", "\\pi"]).scale(2).split() self.add(two, pi) two_copy = deepcopy(two).rotate(np.pi/10).set_color("yellow") self.play(Transform( two, two_copy, rate_func = squish_rate_func( lambda t : wiggle(t), 0.4, 0.9, ), **self.anim_kwargs )) def line1(self): two_pi = OldTex(["2", "\\pi"]).scale(2) tau = TauCreature() tau.to_symbol() sphere = Mobject() sphere.interpolate( two_pi, Sphere().set_color("yellow"), 0.8 ) self.add(two_pi) self.wait() self.play(CounterclockwiseTransform( two_pi, sphere, rate_func = lambda t : 2*smooth(t/2) )) self.remove(two_pi) self.play(CounterclockwiseTransform( sphere, tau, rate_func = lambda t : 2*(smooth(t/2+0.5)-0.5) )) self.remove(sphere) self.add(tau) self.wait() def line2(self): tau = TauCreature() tau.make_sad() tau.mouth.points = np.array(sorted( tau.mouth.points, lambda p0, p1 : cmp(p0[0], p1[0]) )) blinked = deepcopy(tau).blink() for eye in blinked.eyes: eye.set_color("black") self.add(*set(tau.parts).difference(tau.white_parts)) self.play(*[ Transform(*eyes) for eyes in zip(blinked.eyes, tau.eyes) ]) self.play(ShowCreation(tau.mouth)) self.wait(2) def line3(self): tau = TauCreature().make_sad() pi = PiCreature() self.add(*tau.parts) self.wait() self.play( Transform(tau.leg, pi.left_leg), ShowCreation(pi.right_leg), run_time = 1.0, ) self.play(*[ Transform(*parts) for parts in zip(tau.white_parts, pi.white_parts) ]) self.remove(*tau.parts + pi.parts) self.play(BlinkPiCreature(pi)) def pi_speaking(self, text): pi = PiCreature() pi.set_color("red").give_straight_face() pi.shift(3*DOWN + LEFT) bubble = SpeechBubble().speak_from(pi) bubble.write(text) return pi, bubble def line4(self): pi, bubble = self.pi_speaking("Conventions matter \\\\ not!") self.add(pi) self.wait() self.play(Transform( Point(bubble.tip).set_color("black"), bubble )) def line5(self): pi, bubble = self.pi_speaking(""" Great formulae cast \\\\ truths transcending \\\\ names. """) self.add(pi, bubble) formulae = OldTex(FORMULAE, size = "\\small") formulae.scale(1.25) formulae.to_corner([1, -1, 0]) self.play(FadeIn(formulae)) def line6(self): bubble = ThoughtBubble() self.play(ApplyFunction( lambda p : 2 * p / get_norm(p), bubble, rate_func = wiggle, run_time = 3.0, )) def line7(self): bubble = ThoughtBubble() heart = ImageMobject("heart") heart.scale(0.5).shift(DOWN).set_color("red") for mob in bubble, heart: mob.sort_points(get_norm) self.add(bubble) self.wait() self.remove(bubble) bubble_copy = deepcopy(bubble) self.play(CounterclockwiseTransform(bubble_copy, heart)) self.wait() self.remove(bubble_copy) self.play(CounterclockwiseTransform(heart, bubble)) self.wait() def line8(self): pi = PiCreature().give_straight_face() tau = TauCreature() two = ImageMobject("big2").scale(0.5).shift(1.6*LEFT + 0.1*DOWN) self.add(two, *pi.parts) self.wait() self.play( Transform(pi.left_leg, tau.leg), Transform( pi.right_leg, Point(pi.right_leg.get_points()[0,:]).set_color("black") ), Transform(pi.mouth, tau.mouth), CounterclockwiseTransform( two, Dot(two.get_center()).set_color("black") ) ) def line9(self): tau = TauCreature() pi = PiCreature().set_color("red").give_straight_face() pi.scale(0.2).move_to(tau.arm.get_points()[-1,:]) point = Point(pi.get_center()).set_color("black") vanish_local = 3*(LEFT + UP) new_pi = deepcopy(pi) new_pi.scale(0.01) new_pi.rotate(np.pi) new_pi.shift(vanish_local) Mobject.set_color(new_pi, "black") self.add(tau) self.wait() self.play(Transform(point, pi)) self.remove(point) self.add(pi) self.play(WaveArm(tau),Transform(pi, new_pi)) def line10(self): formulae = OldTex(FORMULAE, "\\small") formulae.scale(1.5).to_edge(DOWN) self.add(formulae) def line11(self): formulae = OldTex(FORMULAE, "\\small") formulae.scale(1.5).to_edge(DOWN) formulae = formulae.split() f_copy = deepcopy(formulae) for mob, count in zip(f_copy, it.count()): if count%3 == 0: mob.to_edge(LEFT).shift(RIGHT*(FRAME_X_RADIUS-1)) else: mob.shift(FRAME_WIDTH*RIGHT) self.play(*[ Transform(*mobs, run_time = 2.0) for mobs in zip(formulae, f_copy) ]) def line12(self): interval_size = 0.5 axes_center = FRAME_X_RADIUS*LEFT/2 grid_center = FRAME_X_RADIUS*RIGHT/2 radius = FRAME_X_RADIUS / 2.0 axes = Axes( radius = radius, interval_size = interval_size ) axes.shift(axes_center) def sine_curve(t): t += 1 result = np.array((-np.pi*t, np.sin(np.pi*t), 0)) result *= interval_size result += axes_center return result sine = ParametricCurve(sine_curve) sine_period = Line( axes_center, axes_center + 2*np.pi*interval_size*RIGHT ) grid = Grid(radius = radius).shift(grid_center) circle = Circle().scale(interval_size).shift(grid_center) grid.add(OldTex("e^{ix}").shift(grid_center+UP+RIGHT)) circle.set_color("white") tau_line = Line( *[np.pi*interval_size*vect for vect in (LEFT, RIGHT)], density = 5*DEFAULT_POINT_DENSITY_1D ) tau_line.set_color("red") tau = OldTex("\\tau") tau.shift(tau_line.get_center() + 0.5*UP) self.add(axes, grid) self.play( TransformAnimations( ShowCreation(sine), ShowCreation(deepcopy(sine).shift(2*np.pi*interval_size*RIGHT)), run_time = 2.0, rate_func = smooth ), ShowCreation(circle) ) self.play( CounterclockwiseTransform(sine_period, tau_line), CounterclockwiseTransform(circle, deepcopy(tau_line)), FadeOut(axes), FadeOut(grid), FadeOut(sine), FadeIn(tau), ) self.wait() def line13(self): formula = form_start, two_pi, form_end = OldTex([ "\\hat{f^{(n)}}(\\xi) = (", "2\\pi", "i\\xi)^n \\hat{f}(\\xi)" ]).shift(DOWN).split() tau = TauCreature().center() tau.scale(two_pi.get_width()/tau.get_width()) tau.shift(two_pi.get_center()+0.2*UP) tau.rewire_part_attributes() self.add(*formula) self.wait() self.play(CounterclockwiseTransform(two_pi, tau)) self.remove(two_pi) self.play(BlinkPiCreature(tau)) self.wait() def line14(self): pi, bubble = self.pi_speaking( "Wait! Area \\\\ of circles" ) self.add(pi) self.play( Transform(Point(bubble.tip).set_color("black"), bubble) ) def line15(self): pi, bubble = self.pi_speaking( "sticks oddly \\\\ to one half when \\\\ tau's preferred." ) formula = form_start, half, form_end = OldTex([ "A = ", "\\frac{1}{2}", "\\tau r^2" ]).split() self.add(pi, bubble, *formula) self.wait(2) self.play(ApplyMethod(half.set_color, "yellow")) def line16(self): self.add(OldTex( "\\frac{1}{2}\\tau r^2" ).scale(2).shift(DOWN)) def line17(self): circle = Dot( radius = 1, density = 4*DEFAULT_POINT_DENSITY_1D ) blue_rgb = np.array(Color("blue").get_rgb()) white_rgb = np.ones(3) circle.rgbas = np.array([ alpha * blue_rgb + (1 - alpha) * white_rgb for alpha in np.arange(0, 1, 1.0/len(circle.rgbas)) ]) for index in range(circle.points.shape[0]): circle.rgbas def trianglify(xxx_todo_changeme): (x, y, z) = xxx_todo_changeme norm = get_norm((x, y, z)) comp = complex(x, y)*complex(0, 1) return ( norm * np.log(comp).imag, -norm, 0 ) tau_r = OldTex("\\tau r").shift(1.3*DOWN) r = OldTex("r").shift(0.2*RIGHT + 0.7*DOWN) lines = [ Line(DOWN+np.pi*LEFT, DOWN+np.pi*RIGHT), Line(ORIGIN, DOWN) ] for line in lines: line.set_color("red") self.play(ApplyFunction(trianglify, circle, run_time = 2.0)) self.add(tau_r, r) self.play(*[ ShowCreation(line, run_time = 1.0) for line in lines ]) self.wait() def line18(self): tau = TauCreature() tau.shift_eyes() tau.move_to(DOWN) pi = PiCreature() pi.set_color("red") pi.move_to(DOWN + 3*LEFT) mad_tau = deepcopy(tau).make_mean() mad_tau.arm.wag(0.5*UP, LEFT, 2.0) sad_pi = deepcopy(pi).shift_eyes().make_sad() blinked_tau = deepcopy(tau).blink() blinked_pi = deepcopy(pi).blink() self.add(*pi.parts + tau.parts) self.wait(0.8) self.play(*[ Transform(*eyes, run_time = 0.2, rate_func = rush_into) for eyes in [ (tau.left_eye, blinked_tau.left_eye), (tau.right_eye, blinked_tau.right_eye), ] ]) self.remove(tau.left_eye, tau.right_eye) self.play(*[ Transform(*eyes, run_time = 0.2, rate_func = rush_from) for eyes in [ (blinked_tau.left_eye, mad_tau.left_eye), (blinked_tau.right_eye, mad_tau.right_eye), ] ]) self.remove(blinked_tau.left_eye, blinked_tau.right_eye) self.add(mad_tau.left_eye, mad_tau.right_eye) self.play( Transform(tau.arm, mad_tau.arm), Transform(tau.mouth, mad_tau.mouth), run_time = 0.5 ) self.remove(*tau.parts + blinked_tau.parts) self.add(*mad_tau.parts) self.play(*[ Transform(*eyes, run_time = 0.2, rate_func = rush_into) for eyes in [ (pi.left_eye, blinked_pi.left_eye), (pi.right_eye, blinked_pi.right_eye), ] ]) self.remove(pi.left_eye, pi.right_eye) self.play(*[ Transform(*eyes, run_time = 0.2, rate_func = rush_from) for eyes in [ (blinked_pi.left_eye, sad_pi.left_eye), (blinked_pi.right_eye, sad_pi.right_eye), ] ] + [ Transform(pi.mouth, sad_pi.mouth, run_time = 0.2) ]) self.remove(*blinked_pi.parts + pi.parts + sad_pi.parts) self.play( WalkPiCreature(sad_pi, DOWN+4*LEFT), run_time = 1.0 ) self.wait() def line19(self): pass if __name__ == "__main__": command_line_create_scene(MOVIE_PREFIX)
#!/usr/bin/env python import numpy as np import itertools as it from copy import deepcopy import sys from manim_imports_ext import * from script_wrapper import command_line_create_scene from .inventing_math import divergent_sum, draw_you class SimpleText(Scene): args_list = [ ("Build the foundation of what we know",), ("What would that feel like?",), ("Arbitrary decisions hinder generality",), ("Section 1: Discovering and Defining Infinite Sums",), ("Section 2: Seeking Generality",), ("Section 3: Redefining Distance",), ("``Approach''?",), ("Rigor would dictate you ignore these",), ("dist($A$, $B$) = dist($A+x$, $B+x$) \\quad for all $x$",), ("How does a useful distance function differ from a random function?",), ("Pause now, if you like, and see if you can invent your own distance function from this.",), ("$p$-adic metrics \\\\ ($p$ is any prime number)",), ("This is not meant to match the history of discoveries",), ] @staticmethod def args_to_string(text): return initials([c for c in text if c in string.letters + " "]) def construct(self, text): self.add(OldTexText(text)) class SimpleTex(Scene): args_list = [ ( "\\frac{9}{10}+\\frac{9}{100}+\\frac{9}{1000}+\\cdots = 1", "SumOf9s" ), ( "0 < p < 1", "PBetween0And1" ), ] @staticmethod def args_to_string(expression, words): return words def construct(self, expression, words): self.add(OldTex(expression)) class OneMinusOnePoem(Scene): def construct(self): verse1 = OldTexText(""" \\begin{flushleft} When one takes one from one \\\\ plus one from one plus one \\\\ and on and on but ends \\\\ anon then starts again, \\\\ then some sums sum to one, \\\\ to zero other ones. \\\\ One wonders who'd have won \\\\ had stopping not been done; \\\\ had he summed every bit \\\\ until the infinite. \\\\ \\end{flushleft} """).scale(0.5).to_corner(UP+LEFT) verse2 = OldTexText(""" \\begin{flushleft} Lest you should think that such \\\\ less well-known sums are much \\\\ ado about nonsense \\\\ I do give these two cents: \\\\ The universe has got \\\\ an answer which is not \\\\ what most would first surmise, \\\\ it is a compromise, \\\\ and though it seems a laugh \\\\ the universe gives ``half''. \\\\ \\end{flushleft} """).scale(0.5).to_corner(DOWN+LEFT) equation = OldTex( "1-1+1-1+\\cdots = \\frac{1}{2}" ) self.add(verse1, verse2, equation) class DivergentSum(Scene): def construct(self): self.add(divergent_sum().scale(0.75)) class PowersOfTwoSmall(Scene): def construct(self): you, bubble = draw_you(with_bubble=True) bubble.write( "Is there any way in which apparently \ large powers of two can be considered small?" ) self.add(you, bubble, bubble.content) class FinalSlide(Scene): def construct(self): self.add(OldTexText(""" \\begin{flushleft} Needless to say, what I said here only scratches the surface of the tip of the iceberg of the p-adic metric. What is this new form of number I referred to? Why were distances in the 2-adic metric all powers of $\\frac{1}{2}$ and not some other base? Why does it only work for prime numbers? \\\\ \\quad \\\\ I highly encourage anyone who has not seen p-adic numbers to look them up and learn more, but even more edifying than looking them up will be to explore this idea for yourself directly. What properties make a distance function useful, and why? What do I mean by ``useful''? Useful for what purpose? Can you find infinite sums or sequences which feel like they should converge in the 2-adic metric, but don't converge to a rational number? Go on! Search! Invent! \\end{flushleft} """, size = "\\small"))
import numpy as np import itertools as it from mobject.mobject import Mobject, Mobject1D, Mobject2D, Mobject from geometry import Line from constants import * class OldStars(Mobject1D): CONFIG = { "stroke_width" : 1, "radius" : FRAME_X_RADIUS, "num_points" : 1000, } def init_points(self): radii, phis, thetas = [ scalar*np.random.random(self.num_points) for scalar in [self.radius, np.pi, 2*np.pi] ] self.add_points([ ( r * np.sin(phi)*np.cos(theta), r * np.sin(phi)*np.sin(theta), r * np.cos(phi) ) for r, phi, theta in zip(radii, phis, thetas) ]) class OldCubeWithFaces(Mobject2D): def init_points(self): self.add_points([ sgn * np.array(coords) for x in np.arange(-1, 1, self.epsilon) for y in np.arange(x, 1, self.epsilon) for coords in it.permutations([x, y, 1]) for sgn in [-1, 1] ]) self.pose_at_angle() self.set_color(BLUE) def unit_normal(self, coords): return np.array([1 if abs(x) == 1 else 0 for x in coords]) class OldCube(Mobject1D): def init_points(self): self.add_points([ ([a, b, c][p[0]], [a, b, c][p[1]], [a, b, c][p[2]]) for p in [(0, 1, 2), (2, 0, 1), (1, 2, 0)] for a, b, c in it.product([-1, 1], [-1, 1], np.arange(-1, 1, self.epsilon)) ]) self.pose_at_angle() self.set_color(YELLOW) class OldOctohedron(Mobject1D): def init_points(self): x = np.array([1, 0, 0]) y = np.array([0, 1, 0]) z = np.array([0, 0, 1]) vertex_pairs = [(x+y, x-y), (x+y,-x+y), (-x-y,-x+y), (-x-y,x-y)] vertex_pairs += [ (b[0]*x+b[1]*y, b[2]*np.sqrt(2)*z) for b in it.product(*[(-1, 1)]*3) ] for pair in vertex_pairs: self.add_points( Line(pair[0], pair[1], density = 1/self.epsilon).points ) self.pose_at_angle() self.set_color(MAROON_D) class OldDodecahedron(Mobject1D): def init_points(self): phi = (1 + np.sqrt(5)) / 2 x = np.array([1, 0, 0]) y = np.array([0, 1, 0]) z = np.array([0, 0, 1]) v1, v2 = (phi, 1/phi, 0), (phi, -1/phi, 0) vertex_pairs = [ (v1, v2), (x+y+z, v1), (x+y-z, v1), (x-y+z, v2), (x-y-z, v2), ] five_lines_points = Mobject(*[ Line(pair[0], pair[1], density = 1.0/self.epsilon) for pair in vertex_pairs ]).points #Rotate those 5 edges into all 30. for i in range(3): perm = [j%3 for j in range(i, i+3)] for b in [-1, 1]: matrix = b*np.array([x[perm], y[perm], z[perm]]) self.add_points(np.dot(five_lines_points, matrix)) self.pose_at_angle() self.set_color(GREEN) class OldSphere(Mobject2D): def init_points(self): self.add_points([ ( np.sin(phi) * np.cos(theta), np.sin(phi) * np.sin(theta), np.cos(phi) ) for phi in np.arange(self.epsilon, np.pi, self.epsilon) for theta in np.arange(0, 2 * np.pi, 2 * self.epsilon / np.sin(phi)) ]) self.set_color(BLUE) def unit_normal(self, coords): return np.array(coords) / get_norm(coords)
from manim_imports_ext import * def half_plane(): plane = NumberPlane( x_radius = FRAME_X_RADIUS/2, x_unit_to_spatial_width = 0.5, y_unit_to_spatial_height = 0.5, x_faded_line_frequency = 0, y_faded_line_frequency = 0, density = 4*DEFAULT_POINT_DENSITY_1D, ) plane.add_coordinates( x_vals = list(range(-6, 7, 2)), y_vals = list(range(-6, 7, 2)) ) return plane class SingleVariableFunction(Scene): args_list = [ (lambda x : x**2 - 3, "ShiftedSquare", True), (lambda x : x**2 - 3, "ShiftedSquare", False), ] @staticmethod def args_to_string(func, name, separate_lines): return name + ("SeparateLines" if separate_lines else "") def construct(self, func, name, separate_lines): base_line = NumberLine(color = "grey") moving_line = NumberLine( tick_frequency = 1, density = 3*DEFAULT_POINT_DENSITY_1D ) base_line.add_numbers() def point_function(xxx_todo_changeme): (x, y, z) = xxx_todo_changeme return (func(x), y, z) target = moving_line.copy().apply_function(point_function) transform_config = { "run_time" : 3, "path_func" : path_along_arc(np.pi/4) } if separate_lines: numbers = moving_line.get_number_mobjects(*list(range(-7, 7))) negative_numbers = [] for number in numbers: number.set_color(GREEN_E) number.shift(-2*moving_line.get_vertical_number_offset()) center = number.get_center() target_num = number.copy() target_num.shift(point_function(center) - center) target.add(target_num) if center[0] < -0.5: negative_numbers.append(number) moving_line.add(*numbers) base_line.shift(DOWN) target.shift(DOWN) moving_line.shift(UP) self.add(base_line, moving_line) self.wait(3) self.play(Transform(moving_line, target, **transform_config)) if separate_lines: self.play(*[ ApplyMethod(mob.shift, 0.4*UP) for mob in negative_numbers ]) self.wait(3) class LineToPlaneFunction(Scene): args_list = [ (lambda x : (np.cos(x), 0.5*x*np.sin(x)), "Swirl", []), (lambda x : (np.cos(x), 0.5*x*np.sin(x)), "Swirl", [ ("0", "(1, 0)", 0), ("\\frac{\\pi}{2}", "(0, \\pi / 4)", np.pi/2), ("\\pi", "(-1, 0)", np.pi), ]) ] @staticmethod def args_to_string(func, name, numbers_to_follow): return name + ("FollowingNumbers" if numbers_to_follow else "") def construct(self, func, name, numbers_to_follow): line = NumberLine( unit_length_to_spatial_width = 0.5, tick_frequency = 1, number_at_center = 6, numerical_radius = 6, numbers_with_elongated_ticks = [0, 12], density = 3*DEFAULT_POINT_DENSITY_1D ) line.to_edge(LEFT) line_copy = line.copy() line.add_numbers(*list(range(0, 14, 2))) divider = Line(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) plane = half_plane() plane.submobjects = [] plane.filter_out( lambda x_y_z2 : abs(x_y_z2[0]) > 0.1 and abs(x_y_z2[1]) > 0.1 ) plane.shift(0.5*FRAME_X_RADIUS*RIGHT) self.add(line, divider, plane) def point_function(point): x, y = func(line.point_to_number(point)) return plane.num_pair_to_point((x, y)) target = line_copy.copy().apply_function(point_function) target.set_color() anim_config = {"run_time" : 3} anims = [Transform(line_copy, target, **anim_config)] colors = iter([BLUE_B, GREEN_D, RED_D]) for input_tex, output_tex, number in numbers_to_follow: center = line.number_to_point(number) dot = Dot(center, color = next(colors)) anims.append(ApplyMethod( dot.shift, point_function(center) - center, **anim_config )) label = OldTex(input_tex) label.shift(center + 2*UP) arrow = Arrow(label, dot) self.add(label) self.play(ShowCreation(arrow), ShowCreation(dot)) self.wait() self.remove(arrow, label) self.wait(2) self.play(*anims) self.wait() for input_tex, output_tex, number in numbers_to_follow: point = plane.num_pair_to_point(func(number)) label = OldTex(output_tex) side_shift = LEFT if number == np.pi else RIGHT label.shift(point, 2*UP, side_shift) arrow = Arrow(label, point) self.add(label) self.play(ShowCreation(arrow)) self.wait(2) self.remove(arrow, label) class PlaneToPlaneFunctionSeparatePlanes(Scene): args_list = [ (lambda x_y3 : (x_y3[0]**2+x_y3[1]**2, x_y3[0]**2-x_y3[1]**2), "Quadratic") ] @staticmethod def args_to_string(func, name): return name def construct(self, func, name): shift_factor = 0.55 in_plane = half_plane().shift(shift_factor*FRAME_X_RADIUS*LEFT) out_plane = half_plane().shift(shift_factor*FRAME_X_RADIUS*RIGHT) divider = Line(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) self.add(in_plane, out_plane, divider) plane_copy = in_plane.copy() plane_copy.submobjects = [] def point_function(point): result = np.array(func((point*2 + 2*shift_factor*FRAME_X_RADIUS*RIGHT)[:2])) result = np.append(result/2, [0]) return result + shift_factor*FRAME_X_RADIUS*RIGHT target = plane_copy.copy().apply_function(point_function) target.set_color(GREEN_B) anim_config = {"run_time" : 5} self.wait() self.play(Transform(plane_copy, target, **anim_config)) self.wait() class PlaneToPlaneFunction(Scene): args_list = [ (lambda x_y4 : (x_y4[0]**2+x_y4[1]**2, x_y4[0]**2-x_y4[1]**2), "Quadratic") ] @staticmethod def args_to_string(func, name): return name def construct(self, func, name): plane = NumberPlane() plane.prepare_for_nonlinear_transform() background = NumberPlane(color = "grey") background.add_coordinates() anim_config = {"run_time" : 3} def point_function(point): return np.append(func(point[:2]), [0]) self.add(background, plane) self.wait(2) self.play(ApplyPointwiseFunction(point_function, plane, **anim_config)) self.wait(3) class PlaneToLineFunction(Scene): args_list = [ (lambda x_y : x_y[0]**2 + x_y[1]**2, "Bowl"), ] @staticmethod def args_to_string(func, name): return name def construct(self, func, name): line = NumberLine( color = GREEN, unit_length_to_spatial_width = 0.5, tick_frequency = 1, number_at_center = 6, numerical_radius = 6, numbers_with_elongated_ticks = [0, 12], ).to_edge(RIGHT) line.add_numbers() plane = half_plane().to_edge(LEFT, buff = 0) divider = Line(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) line_left = line.number_to_point(0) def point_function(point): shifter = 0.5*FRAME_X_RADIUS*RIGHT return func((point+shifter)[:2])*RIGHT + line_left self.add(line, plane, divider) self.wait() plane.submobjects = [] self.play(ApplyPointwiseFunction(point_function, plane)) self.wait() class PlaneToSpaceFunction(Scene): args_list = [ (lambda x_y1 : (x_y1[0]*x_y1[0], x_y1[0]*x_y1[1], x_y1[1]*x_y1[1]), "Quadratic"), ] @staticmethod def args_to_string(func, name): return name def construct(self, func, name): plane = half_plane().shift(0.5*FRAME_X_RADIUS*LEFT) divider = Line(FRAME_Y_RADIUS*UP, FRAME_Y_RADIUS*DOWN) axes = XYZAxes() axes.filter_out(lambda p : get_norm(p) > 3) rot_kwargs = { "run_time" : 3, "radians" : 0.3*np.pi, "axis" : [0.1, 1, 0.1], } axes.to_edge(RIGHT).shift(DOWN) dampening_factor = 0.1 def point_function(xxx_todo_changeme5): (x, y, z) = xxx_todo_changeme5 return dampening_factor*np.array(func((x, y))) target = NumberPlane().apply_function(point_function) target.set_color("yellow") target.shift(axes.get_center()) self.add(plane, divider, axes) self.play(Rotating(axes, **rot_kwargs)) target.rotate(rot_kwargs["radians"]) self.play( TransformAnimations( Animation(plane.copy()), Rotating(target, **rot_kwargs), rate_func = smooth ), Rotating(axes, **rot_kwargs) ) axes.add(target) self.clear() self.add(plane, divider, axes) self.play(Rotating(axes, **rot_kwargs)) self.clear() for i in range(5): self.play(Rotating(axes, **rot_kwargs)) class SpaceToSpaceFunction(Scene): args_list = [ (lambda x_y_z : (x_y_z[1]*x_y_z[2], x_y_z[0]*x_y_z[2], x_y_z[0]*x_y_z[1]), "Quadratic"), ] @staticmethod def args_to_string(func, name): return name def construct(self, func, name): space = SpaceGrid() rot_kwargs = { "run_time" : 10, "radians" : 2*np.pi/5, "axis" : [0.1, 1, 0.1], "in_place" : False, } axes = XYZAxes() target = space.copy().apply_function(func) self.play( TransformAnimations( Rotating(space, **rot_kwargs), Rotating(target, **rot_kwargs), rate_func = squish_rate_func(smooth, 0.3, 0.7) ), Rotating(axes, **rot_kwargs) ) axes.add(space) self.play(Rotating(axes, **rot_kwargs))
from manim_imports_ext import * class FluidFlow(Scene): CONFIG = { "vector_spacing" : 1, "dot_spacing" : 0.5, "dot_color" : BLUE_C, "text_color" : WHITE, "vector_color" : YELLOW, "vector_length" : 0.5, "points_height" : FRAME_Y_RADIUS, "points_width" : FRAME_X_RADIUS, } def use_function(self, function): self.function = function def get_points(self, spacing): x_radius, y_radius = [ val-val%spacing for val in self.points_width, self.points_height ] return map(np.array, it.product( np.arange(-x_radius, x_radius+spacing, spacing), np.arange(-y_radius, y_radius+spacing, spacing), [0] )) def add_axes(self, show_creation = False): self.axes = Axes(color = WHITE, tick_frequency = 1) self.add(self.axes) if show_creation: self.play(ShowCreation(self.axes)) self.wait() def add_dots(self, show_creation = False): points = self.get_points(self.dot_spacing) self.dots = VMobject(*map(Dot, points)) self.dots.set_color(self.dot_color) self.add(self.dots) if show_creation: self.play(ShowCreation(self.dots)) self.wait() def add_vectors(self, true_length = False, show_creation = False): if not hasattr(self, "function"): raise Exception("Must run use_function first") points = self.get_points(self.vector_spacing) points = filter( lambda p : get_norm(self.function(p)) > 0.01, points ) directions = map(self.function, points) if not true_length: directions = [ self.vector_length*d/get_norm(d) for d in directions ] self.vectors = VMobject(*[ Vector( direction, color = self.vector_color, tip_length = 0.1, ).shift(point) for point, direction in zip(points, directions) ]) self.add(self.vectors) if show_creation: self.play(ShowCreation(self.vectors)) self.wait() def flow(self, **kwargs): if not hasattr(self, "function"): raise Exception("Must run use_function first") # Warning, this is now depricated self.play(ApplyToCenters( PhaseFlow, self.dots.split(), function = self.function, **kwargs )) def label(self, text, time = 5): mob = OldTexText(text) mob.scale(1.5) mob.to_edge(UP) mob.set_color(self.text_color) rectangle = Polygon(*[ mob.get_corner(vect) + 0.3*vect for vect in [ UP+RIGHT, UP+LEFT, DOWN+LEFT, DOWN+RIGHT ] ]) rectangle.set_fill(BLACK, 1.0) self.add(rectangle, mob) self.wait(time) self.remove(mob, rectangle) class VectorFieldExample(FluidFlow): CONFIG = { "points_height" : 4, "points_width" : 4, "vector_spacing" : 0.5, "vector_length" : 0.3 } def construct(self): self.use_function( lambda (x, y, z) : 0.5*((2*y)**3-9*(2*y))*RIGHT+0.5*((2*x)**3-9*(2*x))*UP ) self.add_axes(show_creation = True) self.add_vectors(show_creation = True) self.add_dots(show_creation = True) self.show_frame() self.flow(run_time = 30, virtual_time = 3) class VectorFieldExampleWithoutArrows(FluidFlow): def construct(self): self.use_function( lambda (x, y, z) : 0.5*(y**3-9*y)*RIGHT+0.5*(x**3-9*x)*UP ) self.add_axes(show_creation = True) self.add_dots(show_creation = True) self.flow(run_time = 30, virtual_time = 3) class VectorFieldExampleTwo(FluidFlow): CONFIG = { "points_width" : 3*FRAME_X_RADIUS, "points_height" : 1.4*FRAME_Y_RADIUS } def construct(self): self.use_function( lambda (x, y, z) : RIGHT+np.sin(x)*UP ) self.add_axes() self.add_vectors() self.add_dots(show_creation = True) for x in range(10): self.flow( run_time = 1, rate_func=linear, ) class VectorFieldExampleThree(FluidFlow): def construct(self): self.use_function( lambda p : p/(2*get_norm(0.5*p)**0.5+0.01) ) self.add_axes() self.add_vectors() self.add_dots(show_creation = True) self.flow(run_time = 2, virtual_time = 2) self.wait(2) class VectorFieldExampleFour(FluidFlow): CONFIG = { "points_height" : 1.FRAME_WIDTH, "points_width" : 1.FRAME_WIDTH, } def construct(self): self.use_function( lambda (x, y, z) : (x*UP - y*RIGHT)/5 ) self.add_axes() self.add_vectors(true_length = True) self.add_dots(show_creation = True) self.show_frame() self.play(Rotating( self.dots, run_time = 10, axis = OUT )) self.wait(2) class FluxArticleExample(FluidFlow): CONFIG = { "vector_length" : 0.4, "vector_color" : BLUE_D, "points_height" : FRAME_Y_RADIUS, "points_width" : FRAME_X_RADIUS, } def construct(self): self.use_function( lambda (x, y, z) : (x**2+y**2)*((np.sin(x)**2)*RIGHT + np.cos(y)*UP) ) # self.add_axes() self.add_vectors() self.show_frame() self.add_dots() self.flow(run_time = 2, virtual_time = 0.1) self.wait(2) class NegativeDivergenceExamlpe(FluidFlow): CONFIG = { "points_width" : FRAME_WIDTH, "points_height" : FRAME_HEIGHT, } def construct(self): circle = Circle(color = YELLOW_C) self.use_function( lambda p : -p/(2*get_norm(0.5*p)**0.5+0.01) ) self.add_axes() self.add_vectors() self.play(ShowCreation(circle)) self.wait() self.add_dots(show_creation = True) self.flow( run_time = 1, virtual_time = 1, rate_func = smooth ) self.wait(2) class PositiveDivergenceExample(FluidFlow): def construct(self): circle = Circle(color = YELLOW_C) self.use_function( lambda p : p/(2*get_norm(0.5*p)**0.5+0.01) ) self.add_axes() self.add_vectors() self.play(ShowCreation(circle)) self.wait() self.add_dots(show_creation = True) self.flow( run_time = 1, virtual_time = 1, rate_func = smooth ) self.wait(2) class DivergenceArticleExample(FluidFlow): def construct(self): def raw_function((x, y, z)): return (2*x-y, y*y, 0) def normalized_function(p): result = raw_function(p) return result/(get_norm(result)+0.01) self.use_function(normalized_function) self.add_axes() self.add_vectors() self.add_dots() self.flow( virtual_time = 4, run_time = 5 ) class QuadraticField(FluidFlow): def construct(self): self.use_function( lambda (x, y, z) : 0.25*((x*x-y*y)*RIGHT+x*y*UP) ) self.add_axes() self.add_vectors() self.add_dots() self.flow( virtual_time = 10, run_time = 20, rate_func=linear ) class IncompressibleFluid(FluidFlow): CONFIG = { "points_width" : FRAME_WIDTH, "points_height" : 1.4*FRAME_Y_RADIUS } def construct(self): self.use_function( lambda (x, y, z) : RIGHT+np.sin(x)*UP ) self.add_axes() self.add_vectors() self.add_dots() for x in range(8): self.flow( run_time = 1, rate_func=linear, ) class ConstantInwardFlow(FluidFlow): CONFIG = { "points_height" : FRAME_HEIGHT, "points_width" : FRAME_WIDTH, } def construct(self): self.use_function( lambda p : -3*p/(get_norm(p)+0.1) ) self.add_axes() self.add_vectors() self.add_dots() for x in range(5): self.flow( run_time = 5, rate_func=linear, ) class ConstantOutwardFlow(FluidFlow): def construct(self): self.use_function( lambda p : p/(2*get_norm(0.5*p)**0.5+0.01) ) self.add_axes() self.add_vectors() self.add_dots() for x in range(10): self.flow(rate_func=linear) dot = self.dots.split()[0].copy() dot.center() new_dots = [ dot.copy().shift(0.5*vect) for vect in [ UP, DOWN, LEFT, RIGHT, UP+RIGHT, UP+LEFT, DOWN+RIGHT, DOWN+LEFT ] ] self.dots.add(*new_dots) class ConstantPositiveCurl(FluidFlow): CONFIG = { "points_height" : FRAME_X_RADIUS, } def construct(self): self.use_function( lambda p : 0.5*(-p[1]*RIGHT+p[0]*UP) ) self.add_axes() self.add_vectors(true_length = True) self.add_dots() for x in range(10): self.flow( rate_func=linear ) class ComplexCurlExample(FluidFlow): def construct(self): self.use_function( lambda (x, y, z) : np.cos(x+y)*RIGHT+np.sin(x*y)*UP ) self.add_axes() self.add_vectors(true_length = True) self.add_dots() for x in range(4): self.flow( run_time = 5, rate_func=linear, ) class SingleSwirl(FluidFlow): CONFIG = { "points_height" : FRAME_X_RADIUS, } def construct(self): self.use_function( lambda p : (-p[1]*RIGHT+p[0]*UP)/get_norm(p) ) self.add_axes() self.add_vectors() self.add_dots() for x in range(10): self.flow(rate_func=linear) class CurlArticleExample(FluidFlow): CONFIG = { "points_height" : 3*FRAME_Y_RADIUS, "points_width" : 3*FRAME_X_RADIUS } def construct(self): self.use_function( lambda (x, y, z) : np.cos(0.5*(x+y))*RIGHT + np.sin(0.25*x*y)*UP ) circle = Circle().shift(3*UP) self.add_axes() self.add_vectors() self.play(ShowCreation(circle)) self.add_dots() self.show_frame() self.flow( rate_func=linear, run_time = 15, virtual_time = 10 ) class FourSwirlsWithoutCircles(FluidFlow): CONFIG = { "points_height" : FRAME_X_RADIUS, } def construct(self): circles = [ Circle().shift(3*vect) for vect in compass_directions() ] self.use_function( lambda (x, y, z) : 0.5*(y**3-9*y)*RIGHT+(x**3-9*x)*UP ) self.add_axes() self.add_vectors() # for circle in circles: # self.play(ShowCreation(circle)) self.add_dots() self.add_extra_dots() self.flow( virtual_time = 2, run_time = 20, rate_func=linear ) def add_extra_dots(self): dots = self.dots.split() for vect in UP+LEFT, DOWN+RIGHT: for n in range(5, 15): dots.append( dots[0].copy().center().shift(n*vect) ) self.dots = VMobject(*dots) class CopyPlane(Scene): def construct(self): def special_rotate(mob): mob.rotate(0.9*np.pi/2, RIGHT, about_point = ORIGIN) mob.rotate(-np.pi/4, UP, about_point = ORIGIN) return mob plane = NumberPlane() copies = [ special_rotate(plane.copy().shift(u*n*OUT)) for n in range(1, 3) for u in -1, 1 ] line = Line(4*IN, 4*OUT) self.add(plane) self.play(*[ ApplyFunction(special_rotate, mob, run_time = 3) for mob in plane, line ]) self.wait() for copy in copies: self.play(Transform(plane.copy(), copy)) self.wait() class DropletFlow(FluidFlow): def construct(self): seconds = 60*5 droplets = Group(*[ PointDot(x*RIGHT+y*UP, radius = 0.15, density = 120) for x in range(-7, 9) for y in range(-3, 4) ]) droplets.set_color_by_gradient(BLUE, GREEN, YELLOW) self.use_function( lambda (x, y, z) : y*RIGHT+np.sin(2*np.pi*x)*UP, ) self.add(NumberPlane().fade()) self.play(ShowCreation(droplets)) n_steps = int(seconds * self.camera.frame_rate) from tqdm import tqdm as ProgressDisplay for x in ProgressDisplay(range(n_steps)): for d in droplets: if x%10 == 0: d.filter_out( lambda p : abs(p[0]) > 1.5*FRAME_X_RADIUS or abs(p[1]) > 1.5*FRAME_Y_RADIUS ) for p in d.points: p += 0.001*self.function(p) self.wait(1 / self.camera.frame_rate) class AltDropletFlow(FluidFlow): def construct(self): self.use_function(lambda (x, y, z): (np.sin(x)+np.sin(y))*RIGHT+\ (np.sin(x)-np.sin(y))*UP ) self.add_dots() self.flow( rate_func=linear, run_time = 10, virtual_time = 2 )
#!/usr/bin/env python from manim_imports_ext import * from zeta import * class ExampleLinearTransformation(LinearTransformationScene): CONFIG = { "show_coordinates" : True } def construct(self): self.wait() self.apply_transposed_matrix([[2, 1], [-3, 1]]) self.wait() def example_function(point): x, y, z = point return np.array([ x + np.sin(y), y + np.sin(x), 0 ]) class ExampleMultivariableFunction(LinearTransformationScene): CONFIG = { "show_basis_vectors" : False, "show_coordinates" : True, } def construct(self): self.wait() self.apply_nonlinear_transformation(example_function) self.wait() class ExampleMultivariableFunctionWithZoom(ZoomedScene, ExampleMultivariableFunction): def construct(self): self.activate_zooming() self.little_rectangle.set_color(YELLOW) point = 2*LEFT + UP self.little_rectangle.move_to(point) dense_lines = self.get_dense_lines(point) self.play(ShowCreation(dense_lines)) self.plane.add(dense_lines) self.wait() self.apply_nonlinear_transformation( example_function, added_anims = [ApplyMethod( self.little_rectangle.move_to, example_function(point), run_time = 3 )] ) self.wait() def get_dense_lines(self, point): radius = 0.4*self.little_rectangle.get_height() n_steps = 5 vert_lines = VGroup(*[ Line(DOWN, UP).scale(FRAME_Y_RADIUS).shift(x*RIGHT) for x in np.linspace(point[0]-radius, point[0]+radius, n_steps) ]) horiz_lines = VGroup(*[ Line(LEFT, RIGHT).scale(FRAME_X_RADIUS).shift(y*UP) for y in np.linspace(point[1]-radius, point[1]+radius, n_steps) ]) dense_lines = VGroup(vert_lines, horiz_lines) dense_lines.set_stroke(BLUE, width = 2) for group in vert_lines, horiz_lines: group[n_steps/2].set_color(WHITE) return dense_lines def capture_mobjects_in_camera(self, mobjects, **kwargs): self.camera.capture_mobjects(mobjects, **kwargs) if self.zoom_activated: filter_mobjects = [m for m in mobjects if m not in self.background_plane.get_family()] self.zoomed_camera.capture_mobjects( filter_mobjects, **kwargs ) class ExampleMultivariableFunctionWithMuchZoom(ExampleMultivariableFunctionWithZoom): CONFIG = { "zoom_factor" : 20 } class ExampleDeterminantAnimation(LinearTransformationScene): CONFIG = { "show_coordinates" : True, } def construct(self): self.add_unit_square() self.wait() self.apply_transposed_matrix([[3, 0], [1, 2]]) self.wait(2) class JacobianDeterminantAnimation(ExampleMultivariableFunctionWithMuchZoom): CONFIG = { "point" : 2*LEFT+UP } def construct(self): self.activate_zooming() self.little_rectangle.set_color(YELLOW) point = self.point self.little_rectangle.move_to(point) dense_lines = self.get_dense_lines(point) self.add_unit_square() tiny_unit = get_norm( dense_lines[0][1].get_center()-dense_lines[0][0].get_center() ) self.square.scale(tiny_unit) self.square.shift(point) self.play(ShowCreation(dense_lines)) self.plane.add(dense_lines) self.wait() self.apply_nonlinear_transformation( example_function, added_anims = [ApplyMethod( self.little_rectangle.move_to, example_function(point), run_time = 3 )] ) self.wait() class SmallJacobianDeterminant(JacobianDeterminantAnimation): CONFIG = { "point" : UP, }
#!/usr/bin/env python from manim_imports_ext import * class VectorDraw(Animation): CONFIG = { "vector_color" : GREEN_B, "line_color" : YELLOW, "t_min" : 0, "t_max" : 10, "run_time" : 7, } def __init__(self, func, **kwargs): digest_config(self, kwargs, locals()) self.curve = ParametricCurve( func, t_min = self.t_min, t_max = self.t_max, color = self.line_color ) self.vector = Vector( func(self.t_min), color = self.vector_color ) mobject = VMobject(self.vector, self.curve) ##First is filler Animation.__init__(self, mobject, **kwargs) def interpolate_mobject(self, alpha): t = alpha*self.t_max + (1 - alpha)*self.t_min self.vector.put_start_and_end_on(ORIGIN, self.func(t)) old_curve = self.starting_mobject.split()[1] self.curve.pointwise_become_partial(old_curve, 0, alpha) return self class Test(Scene): def construct(self): axes = Axes() def func(t): return 0.5*(t*np.cos(t)*RIGHT + t*np.sin(t)*UP) words = OldTexText("Parametric functions") words.set_color(YELLOW) words.to_edge(UP+LEFT) self.add(words) # v = Vector(ORIGIN) # v.put_start_and_end_on(LEFT, RIGHT) # v.show() self.play(ShowCreation(axes)) self.wait(2) self.play(VectorDraw(func)) self.wait(3) self.clear() self.add(axes, words) self.wait() self.play(VectorDraw(func, rate_func = rush_from)) self.wait()
from manim_imports_ext import * class Resistor(Line): def init_points(self): midpoints = [ interpolate(self.start, self.end, alpha) for alpha in [0.25]+list(np.arange(0.3, 0.71, 0.1))+[0.75] ] perp = rotate_vector(self.end-self.start, np.pi/2) for midpoint, n in zip(midpoints[1:-1], it.count()): midpoint += 0.1*((-1)**n)*perp points = [self.start]+midpoints+[self.end] self.set_points_as_corners(points) class LongResistor(Line): def init_points(self): mid1 = interpolate(self.start, self.end, 1./5) mid2 = interpolate(self.start, self.end, 4./5) self.add(Line(self.start, mid1)) self.add(Resistor(mid1, mid2)) self.add(Line(mid2, self.end)) class Source(VMobject): def init_points(self): self.add(Circle(color = self.color)) self.add(OldTex("+").scale(1.5).set_color(GREEN).shift(0.5*UP)) self.add(OldTex("-").scale(1.5).set_color(RED).shift(0.5*DOWN)) self.set_height(1) self.add(Line(self.get_top(), self.get_top()+UP)) self.add(Line(self.get_bottom(), self.get_bottom()+DOWN)) class CircuitReduction(Scene): def construct(self): pos = dict([ (x, { 0 : (1.8*x-6)*RIGHT+2*UP, 0.5 : (1.8*x-6)*RIGHT, 1 : (1.8*x-6)*RIGHT+2*DOWN, }) for x in range(8) ]) source = Mobject( Line(0.5*UP, 2*UP), Source().scale(0.5), Line(2*DOWN, 0.5*DOWN) ) source.shift(pos[0][0][0]*RIGHT) self.add(source) ohms = dict([ (n, OldTex("%d\\Omega"%int(n)).scale(0.75)) for n in (1, 2, 3, 4, 6, 12, 1.1, 5, 10.1, 10, 8, 2.1) ]) ohms[1].shift(0.5*pos[1][0]+0.5*pos[2][0]+0.7*UP) ohms[2].shift(pos[2][0.5]+0.7*LEFT) ohms[3].shift(pos[1][0.5]+0.7*LEFT) ohms[12].shift(pos[2][0.5]+0.7*LEFT) ohms[4].shift(pos[3][0.5]+0.7*LEFT) ohms[6].shift(pos[4][0.5]+0.7*LEFT) ohms[1.1].shift(0.5*pos[4][0]+0.5*pos[5][0]+0.7*UP) ohms[5].shift(pos[5][0.5]+0.7*LEFT) ohms[10.1].shift(pos[5][0.5]+0.7*LEFT) ohms[10].shift(pos[6][0.5]+0.7*LEFT) ohms[8].shift(pos[7][0.5]+0.7*LEFT) ohms[2.1].shift(0.5*pos[6][0]+0.5*pos[7][0]+0.7*UP) line1 = Line(pos[0][0], pos[1][0]) line2 = Line(pos[0][1], pos[1][1]) resistor = LongResistor(pos[1][0], pos[1][1]) self.add(line1, line2, resistor, ohms[3]) self.wait(3) combo_parts = [ Resistor(pos[1][0], pos[2][0]), LongResistor(pos[2][0], pos[2][1]), Line(pos[2][1], pos[1][1]) ] combo = Mobject(*combo_parts).ingest_submobjects() self.play( Transform(resistor, combo), Transform(ohms[3], ohms[2]), Transform(ohms[3].copy(), ohms[1]) ) self.wait(3) self.remove(ohms[3]) self.add(ohms[2]) self.remove(resistor) self.add(*combo_parts) resistor = combo_parts[1] top_point = Point(pos[2][0]) line = Point(pos[2][0]) bottom_point = Point(pos[2][1]) self.play( Transform(top_point, Line(pos[2][0], pos[3][0])), Transform(line, Line(pos[3][0], pos[4][0])), Transform(bottom_point, Line(pos[2][1], pos[4][1])), Animation(resistor.copy()), Transform(resistor.copy(), LongResistor(pos[3][0], pos[3][1])), Transform(resistor, LongResistor(pos[4][0], pos[4][1])), Transform(ohms[2].copy(), ohms[12]), Transform(ohms[2].copy(), ohms[4]), Transform(ohms[2], ohms[6]) ) self.wait(3) self.remove(ohms[2]) self.add(ohms[6]) combo_parts = [ Resistor(pos[4][0], pos[5][0]), LongResistor(pos[5][0], pos[5][1]), Line(pos[5][1], pos[4][1]) ] combo = Mobject(*combo_parts).ingest_submobjects() self.play( # Transform(resistor, LongResistor(pos[5][0], pos[5][1])), # Transform(line, LongResistor(pos[3][0], pos[5][0])), # Transform(bottom_point, Line(pos[2][1], pos[5][1])), Transform(resistor, combo), Transform(ohms[6], ohms[5]), Transform(ohms[6].copy(), ohms[1.1]) ) self.wait(3) self.remove(ohms[6]) self.add(ohms[5]) self.remove(resistor) self.add(*combo_parts) resistor = combo_parts[1] line1 = Point(pos[5][0]) line2 = Point(pos[5][1]) self.play( Transform(line1, Line(pos[5][0], pos[6][0])), Transform(line2, Line(pos[5][1], pos[6][1])), Animation(resistor.copy()), Transform(resistor, LongResistor(pos[6][0], pos[6][1])), Transform(ohms[5].copy(), ohms[10.1]), Transform(ohms[5], ohms[10]) ) self.wait(3) self.remove(ohms[5]) self.add(ohms[10]) point1 = Point(pos[6][0]) point2 = Point(pos[6][1]) self.play( Transform(resistor, Mobject( Resistor(pos[6][0], pos[7][0]), LongResistor(pos[7][0], pos[7][1]), Line(pos[7][1], pos[6][1]), ).ingest_submobjects()), Transform(ohms[10], ohms[8]), Transform(ohms[10].copy(), ohms[2.1]) ) self.wait(3) # self.reverse_frames() self.invert_colors() # circuit = Mobject(*[ # source, # # # LongResistor(pos[0][0], pos[2][0]), # Line(pos[0][1], pos[2][1]), # # # LongResistor(pos[2][0], pos[2][1]), # Line(pos[2][0], pos[3][0]), # Line(pos[2][1], pos[3][1]), # LongResistor(pos[3][0], pos[3][1]), # # # LongResistor(pos[3][0], pos[5][0]), # Line(pos[3][1], pos[5][1]), # # # LongResistor(pos[5][0], pos[5][1]), # # # Line(pos[5][0], pos[6][0]), # Resistor(pos[6][0], pos[7][0]), # Line(pos[5][1], pos[7][1]), # # # LongResistor(pos[7][0], pos[7][1]) # ])
from manim_imports_ext import * class StacksApproachBellCurve(Scene): CONFIG = { "n_iterations": 70, } def construct(self): bar = Square(side_length=1) bar.set_fill(BLUE, 1) bar.set_stroke(BLUE, 1) bars = VGroup(bar) max_width = FRAME_WIDTH - 2 max_height = FRAME_Y_RADIUS - 1.5 for x in range(self.n_iterations): bars_copy = bars.copy() #Copy and shift for mob, vect in (bars, DOWN), (bars_copy, UP): mob.generate_target() if mob.target.get_height() > max_height: mob.target.stretch_to_fit_height(max_height) if mob.target.get_width() > max_width: lx1 = mob.target[1].get_left()[0] rx0 = mob.target[0].get_right()[0] curr_buff = lx1 - rx0 mob.target.arrange( RIGHT, buff=0.9 * curr_buff, aligned_edge=DOWN ) mob.target.stretch_to_fit_width(max_width) mob.target.next_to(ORIGIN, vect, MED_LARGE_BUFF) colors = color_gradient([BLUE, YELLOW], len(bars) + 1) for color, bar in zip(colors, bars.target): bar.set_color(color) for color, bar in zip(colors[1:], bars_copy.target): bar.set_color(color) bars_copy.set_fill(opacity=0) bars_copy.set_stroke(width=0) if x == 0: distance = 1.5 else: cx1 = bars.target[-1].get_center()[0] cx0 = bars.target[0].get_center()[0] distance = (cx1 - cx0) / (len(bars) - 1) self.play(*list(map(MoveToTarget, [bars, bars_copy]))) self.play( bars.shift, distance * LEFT / 2, bars_copy.shift, distance * RIGHT / 2, ) # Stack bars_copy.generate_target() for i in range(len(bars) - 1): top_bar = bars_copy.target[i] low_bar = bars[i + 1] top_bar.move_to(low_bar.get_top(), DOWN) bars_copy.target[-1].align_to(bars, DOWN) self.play(MoveToTarget( bars_copy, lag_ratio=0.5, run_time=np.sqrt(x + 1) )) # Resize lower bars for top_bar, low_bar in zip(bars_copy[:-1], bars[1:]): bottom = low_bar.get_bottom() low_bar.replace( VGroup(low_bar, top_bar), stretch=True ) low_bar.move_to(bottom, DOWN) bars.add(bars_copy[-1]) self.remove(bars_copy) self.add(bars)
from manim_imports_ext import * class HyperSlinky(Scene): def construct(self): self.play( ApplyPointwiseFunction( lambda x_y_z: (1 + x_y_z[1]) * np.array(( np.cos(2 * np.pi * x_y_z[0]), np.sin(2 * np.pi * x_y_z[0]), x_y_z[2] )), NumberPlane().prepare_for_nonlinear_transform(), rate_func=there_and_back, run_time=10, ) ) class CircleAtaphogy(Scene): def construct(self): self.play( ApplyMethod(Circle(radius=3).repeat, 7), run_time=3.0 )
from manim_imports_ext import * class VennDiagram(InteractiveScene): def construct(self): # Add circles radius = 3.0 c1, c2 = circles = Circle(radius=radius).replicate(2) c1.set_stroke(BLUE, 3) c2.set_stroke(YELLOW, 3) c1.move_to(radius * LEFT / 2) c2.move_to(radius * RIGHT / 2) circles.to_edge(DOWN) self.add(circles) self.wait() # Labels l1 = Text(""" People who take the geometry of keynote slides way too literally """, alignment="LEFT") l1.to_corner(UL) l2 = Text(""" People who enjoy facts about 4-dimensional geometry """, alignment="RIGHT") l2.to_corner(UR) labels = VGroup(l1, l2) self.play( FadeIn(l1), c1.animate.set_fill(BLUE, 0.5) ) self.wait() self.play( FadeIn(l2), c2.animate.set_fill(YELLOW, 0.5) ) # Show centers rad_line = Line(c1.get_center(), c2.get_center()) rad_line_label = Text("radius") rad_line_label.next_to(rad_line, UP, SMALL_BUFF) dot1, dot2 = dots = VGroup(*(Dot(c.get_center()) for c in circles)) self.remove(l1, l2) circles.set_fill(opacity=0) self.add(dots, rad_line, rad_line_label) self.wait() # Ask about proportion arc = Arc(radius=radius, start_angle=TAU / 3, angle=TAU / 3, arc_center=c2.get_center()) arc.set_stroke(YELLOW, 6) c2.match_style(c1) c1.set_stroke(GREY_B, 3) self.remove(rad_line_label) self.add(arc) self.wait() question = Text("What proportion of the circle?", font_size=60) question.to_corner(UL) question.to_edge(UP, buff=MED_SMALL_BUFF) arrow = Arrow( question.get_bottom() + LEFT, arc.pfp(0.3), buff=0.2, stroke_width=8, color=WHITE ) self.add(question, arrow) self.wait() # Show hexagon hexagon = RegularPolygon(6) hexagon.replace(c2, dim_to_match=0) hexagon.add(*( Line(v1, v2) for v1, v2 in zip(hexagon.get_vertices()[:3], hexagon.get_vertices()[3:]) )) hexagon.set_stroke(GREY_A, 2) answer = OldTex("1 / 3", font_size=72, color=YELLOW) answer.next_to(question, RIGHT, buff=LARGE_BUFF) self.add(hexagon, answer) self.wait() class Spheres(InteractiveScene): def construct(self): # Add spheres radius = 2.5 s1, s2 = spheres = Sphere(radius=radius).replicate(2) s1.shift(radius * LEFT / 2) s2.shift(radius * RIGHT / 2) spheres.set_opacity(0.35) spheres.set_color(BLUE) meshes = VGroup() for sphere in spheres: sphere.always_sort_to_camera(self.camera) meshes.add(SurfaceMesh(sphere)) meshes.set_stroke(width=1, opacity=0.25) cap = Sphere(v_range=(0, PI / 3), radius=radius) cap.rotate(90 * DEGREES, axis=UP, about_point=ORIGIN) cap.shift(s2.get_center()) cap.set_color(YELLOW) cap.set_opacity(0.8) cap.always_sort_to_camera(self.camera) self.camera.frame.reorient(-20, 60) self.add(cap, spheres, meshes)
from manim_imports_ext import * class PodcastIntro(Scene): def construct(self): tower = self.get_radio_tower() n_rings = 15 min_radius = 0.5 max_radius = 9 max_width = 20 min_width = 0 max_opacity = 1 min_opacity = 0 rings = VGroup(*( self.get_circle(radius=r) for r in np.linspace(min_radius, max_radius, n_rings) )) tuples = zip( rings, np.linspace(max_width, min_width, n_rings), np.linspace(max_opacity, min_opacity, n_rings), ) for ring, width, opacity in tuples: ring.set_stroke(width=width, opacity=opacity) ring.save_state() ring.scale(0) ring.set_stroke(WHITE, width=2) self.play( ShowCreation(tower[0], lag_ratio=0.1), run_time=3 ) self.play( FadeIn(tower[1], scale=10, run_time=1), LaggedStart( *( Restore(ring, rate_func=linear) for ring in reversed(rings) ), run_time=4, lag_ratio=0.08 ) ) def get_radio_tower(self): base = VGroup() line1 = Line(DL, UP) line2 = Line(DR, UP) base.add(line1, line2) base.set_width(2, stretch=True) base.set_height(4, stretch=True) base.to_edge(DOWN, buff=1.5) # alphas = [0, 0.2, 0.4, 0.6, 0.7, 0.8, 0.85] values = np.array([0, *(1 / n for n in range(1, 11))]) alphas = np.cumsum(values) alphas /= alphas[-1] for a1, a2 in zip(alphas, alphas[1:]): base.add( Line(line1.pfp(a1), line2.pfp(a2)), Line(line2.pfp(a1), line1.pfp(a2)), ) base.set_stroke(GREY_A, width=2) VGroup(line1, line2).set_stroke(width=4) dot = Dot(line1.get_end(), radius=0.125) dot.set_color(WHITE) dot.set_gloss(0.5) tower = VGroup(base, dot) tower.set_height(3) tower.shift(-line1.get_end()) tower.set_stroke(background=True) return tower def get_circle(self, center=ORIGIN, radius=1): arc1 = Arc(PI, 3 * PI / 2) arc2 = Arc(PI / 2, PI / 2) arc1.set_color(BLUE) arc2.set_color(GREY_BROWN) circle = VGroup(arc1, arc2) circle.set_width(2 * radius) circle.move_to(center) return circle
from manim_imports_ext import * class PascalColored(Scene): CONFIG = { "colors": [BLUE_E, BLUE_D, BLUE_B], "dot_radius": 0.16, "n_layers": 2 * 81, "rt_reduction_factor": 0.5, } def construct(self): max_height = 6 rt = 1.0 layers = self.get_dots(self.n_layers) triangle = VGroup(layers[0]) triangle.to_edge(UP, buff=LARGE_BUFF) self.add(triangle) last_layer = layers[0] for layer in layers[1:]: height = last_layer.get_height() layer.set_height(height) layer.next_to(last_layer, DOWN, 0.3 * height) for i, dot in enumerate(layer): pre_dots = VGroup(*last_layer[max(i - 1, 0):i + 1]) self.play(*[ ReplacementTransform( pre_dot.copy(), dot, run_time=rt ) for pre_dot in pre_dots ]) last_layer = layer triangle.add(layer) if triangle.get_height() > max_height: self.play( triangle.set_height, 0.5 * max_height, triangle.to_edge, UP, LARGE_BUFF ) rt *= self.rt_reduction_factor print(rt) self.wait() def get_pascal_point(self, n, k): return n * rotate_vector(RIGHT, -2 * np.pi / 3) + k * RIGHT def get_dot_layer(self, n): n_to_mod = len(self.colors) dots = VGroup() for k in range(n + 1): point = self.get_pascal_point(n, k) # p[0] *= 2 nCk_residue = choose(n, k) % n_to_mod dot = Dot( point, radius=2 * self.dot_radius, color=self.colors[nCk_residue] ) if n <= 9: num = OldTex(str(nCk_residue)) num.set_height(0.5 * dot.get_height()) num.move_to(dot) dot.add(num) # num = DecimalNumber(choose(n, k), num_decimal_points = 0) # num.set_color(dot.get_color()) # max_width = 2*dot.get_width() # max_height = dot.get_height() # if num.get_width() > max_width: # num.set_width(max_width) # if num.get_height() > max_height: # num.set_height(max_height) # num.move_to(dot, aligned_edge = DOWN) dots.add(dot) return dots 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 TriominoGrid(Scene): CONFIG = { "random_seed": 4, "n": 4, } def construct(self): n = self.n grid = VGroup(*[ VGroup(*[ Square() for x in range(2**n) ]).arrange(RIGHT, buff=0) for y in range(2**n) ]).arrange(UP, buff=0) for row in grid: for square in row: square.is_covered = False grid.set_fill(BLUE, 1) grid.set_stroke(WHITE, 1) covered_x = random.randint(0, 2**n - 1) covered_y = random.randint(0, 2**n - 1) covered = grid[covered_x][covered_y] covered.is_covered = True covered.set_fill(RED) grid.set_height(6) self.add(grid) self.triominos = VGroup() self.add(self.triominos) self.cover_grid(grid) colors = [ BLUE_C, BLUE_E, BLUE_D, BLUE_B, MAROON_C, MAROON_E, MAROON_D, MAROON_B, YELLOW, GREY_BROWN, GREY_B, GREEN_C, GREEN_E, GREEN_D, GREEN_B, ] random.shuffle(colors) for triomino, color in zip(self.triominos, it.cycle(colors)): triomino.set_color(color) triomino.scale(0.95) self.play(ShowIncreasingSubsets( self.triominos, run_time=5 )) def cover_grid(self, grid): N = len(grid) # N = 2**n if N == 1: return q1 = VGroup(*[row[:N // 2] for row in grid[:N // 2]]) q2 = VGroup(*[row[:N // 2] for row in grid[N // 2:]]) q3 = VGroup(*[row[N // 2:] for row in grid[:N // 2]]) q4 = VGroup(*[row[N // 2:] for row in grid[N // 2:]]) quads = [q1, q2, q3, q4] for q in quads: squares = [ square for row in q for square in row ] q.has_covered = any([s.is_covered for s in squares]) corner_index = np.argmin([ get_norm(s.get_center() - grid.get_center()) for s in squares ]) q.inner_corner = squares[corner_index] covered_quad_index = [q.has_covered for q in quads].index(True) covered_quad = quads[covered_quad_index] hugging_triomino = VGroup() for q in quads: if q is not covered_quad: hugging_triomino.add(q.inner_corner.copy()) q.inner_corner.is_covered = True hugging_triomino.set_stroke(width=0) hugging_triomino.set_fill(random_color(), opacity=1.0) self.triominos.add(hugging_triomino) for q in quads: self.cover_grid(q)
from manim_imports_ext import * class FakeAreaManipulation(Scene): CONFIG = { "unit": 0.5 } def construct(self): unit = self.unit group1, group2 = groups = self.get_diagrams() for group in groups: group.set_width(10 * unit, stretch=True) group.set_height(12 * unit, stretch=True) group.move_to(3 * DOWN, DOWN) group[2].append_points(3 * [group[2].get_left() + LEFT]) group[3].append_points(3 * [group[3].get_right() + RIGHT]) grid = NumberPlane( x_range=(-30, 30), y_range=(-30, 30), faded_line_ratio=0, ) grid.set_stroke(width=1) grid.scale(unit) grid.shift(3 * DOWN - grid.c2p(0, 0)) vertex_dots = VGroup( Dot(group1.get_top()), Dot(group1.get_corner(DR)), Dot(group1.get_corner(DL)), ) self.add(grid) self.add(group1) self.add(vertex_dots) # group1.save_state() kw = { "lag_ratio": 0.1, "run_time": 2, "rate_func": bezier([0, 0, 1, 1]), } path_arc_factors = [-1, 1, 0, 0, -1, 1] for target in (group2, group1.copy()): self.play(group1.space_out_submobjects, 1.2) self.play(*[ Transform( sm1, sm2, path_arc=path_arc_factors[i] * 60 * DEGREES, **kw ) for i, sm1, sm2 in zip(it.count(), group1, target) ]) self.wait(2) lines = VGroup( Line(group1.get_top(), group1.get_corner(DR)), Line(group1.get_top(), group1.get_corner(DL)), ) lines.set_stroke(YELLOW, 2) frame = self.camera.frame frame.save_state() self.play(ShowCreation(lines, lag_ratio=0)) self.play( frame.scale, 0.15, frame.move_to, group1[1].get_corner(DR), run_time=4, ) self.wait(3) self.play(Restore(frame, run_time=2)) # Another switch self.play(*[ Transform(sm1, sm2, **kw) for i, sm1, sm2 in zip(it.count(), group1, group2) ]) # Another zooming self.play( frame.scale, 0.15, frame.move_to, group1[1].get_corner(UL), run_time=4, ) self.wait(2) self.play(Restore(frame, run_time=4)) self.embed() def get_diagrams(self): unit = self.unit tri1 = Polygon(2 * LEFT, ORIGIN, 5 * UP) tri2 = tri1.copy() tri2.flip() tri2.next_to(tri1, RIGHT, buff=0) tris = VGroup(tri1, tri2) tris.scale(unit) tris.move_to(3 * UP, UP) tris.set_stroke(width=0) tris.set_fill(BLUE_D) tris[1].set_color(BLUE_C) ell = Polygon( ORIGIN, 4 * RIGHT, 4 * RIGHT + 2 * UP, 2 * RIGHT + 2 * UP, 2 * RIGHT + 5 * UP, 5 * UP, ) ell.scale(unit) ells = VGroup(ell, ell.copy().rotate(PI).shift(2 * unit * UP)) ells.next_to(tris, DOWN, buff=0) ells.set_stroke(width=0) ells.set_fill(GREY) ells[1].set_fill(GREY_BROWN) big_tri = Polygon(ORIGIN, 3 * LEFT, 7 * UP) big_tri.set_stroke(width=0) big_tri.scale(unit) big_tri.move_to(ells.get_corner(DL), DR) big_tris = VGroup(big_tri, big_tri.copy().rotate(PI, UP, about_point=ORIGIN)) big_tris[0].set_fill(RED_E, 1) big_tris[1].set_fill(RED_C, 1) full_group = VGroup(*tris, *ells, *big_tris) full_group.set_height(5, about_edge=UP) alt_group = full_group.copy() alt_group[0].move_to(alt_group, DL) alt_group[1].move_to(alt_group, DR) alt_group[4].move_to(alt_group[0].get_corner(UR), DL) alt_group[5].move_to(alt_group[1].get_corner(UL), DR) alt_group[2].rotate(90 * DEGREES) alt_group[2].move_to(alt_group[1].get_corner(DL), DR) alt_group[2].rotate(-90 * DEGREES) alt_group[2].move_to(alt_group[0].get_corner(DR), DL) alt_group[3].move_to(alt_group[1].get_corner(DL), DR) full_group.set_opacity(0.75) alt_group.set_opacity(0.75) return full_group, alt_group class LogarithmicSpiral(Scene): def construct(self): exp_n_tracker = ValueTracker(1) group = VGroup() def update_group(gr): n = 3 * int(np.exp(exp_n_tracker.get_value())) gr.set_submobjects(self.get_group(n)) group.add_updater(update_group) self.add(group) self.play( exp_n_tracker.set_value, 7, # exp_n_tracker.set_value, 4, run_time=10, rate_func=linear, ) self.wait() def get_group(self, n, n_spirals=50): n = int(n) theta = TAU / n R = 10 lines = VGroup(*[ VMobject().set_points_as_corners([ORIGIN, R * v]) for v in compass_directions(n) ]) lines.set_stroke(WHITE, min(1, 25 / n)) # points = [3 * RIGHT] # transform = np.array(rotation_matrix_transpose(90 * DEGREES + theta, OUT)) # transform *= math.sin(theta) points = [RIGHT] transform = np.array(rotation_matrix_transpose(90 * DEGREES, OUT)) transform *= math.tan(theta) for x in range(n_spirals * n): p = points[-1] dp = np.dot(p, transform) points.append(p + dp) vmob = VMobject() vmob.set_points_as_corners(points) vmob.scale(math.tan(theta), about_point=ORIGIN) vmob.set_stroke(BLUE, clip(1000 / n, 1, 3)) return VGroup(lines, vmob)
from manim_imports_ext import * class MugToTorus(ThreeDScene): def construct(self): frame = self.camera.frame frame.reorient(-20, 60) R1, R2 = (2, 0.75) def torus_func(u, v): v1 = np.array([-math.sin(u), 0, math.cos(u)]) v2 = math.cos(v) * v1 + math.sin(v) * UP return R1 * v1 + R2 * v2 def cylinder_func(u, v): return (math.cos(v), math.sin(v), u) left_half_torus = ParametricSurface( torus_func, u_range=(-PI / 2, PI + PI / 2), v_range=(0, TAU), ) right_half_torus = ParametricSurface( torus_func, u_range=(PI, TAU), v_range=(0, TAU), ) cylinder = ParametricSurface( cylinder_func, u_range=(PI, TAU), v_range=(0, TAU), ) cylinder.set_width(3) cylinder.set_depth(5, stretch=True) cylinder.move_to(ORIGIN, LEFT) disk = Disk3D(resolution=(2, 50)) disk.match_width(cylinder) disk.move_to(cylinder, IN) disk.scale(1.001) low_disk = disk.copy() for mob in (left_half_torus, right_half_torus, cylinder, low_disk, disk): mob.set_color(GREY) mob.set_gloss(0.7) left_half_torus.save_state() left_half_torus.set_depth(3, about_point=ORIGIN) self.add(left_half_torus) self.add(cylinder) self.add(low_disk, disk) self.add(frame) self.play(disk.animate.move_to(cylinder, OUT), run_time=2) for mob in (disk, low_disk): mob.generate_target() mob.target.rotate(90 * DEGREES, DOWN) mob.target.set_depth(2 * R2) disk.target.move_to(right_half_torus, OUT + LEFT) low_disk.target.rotate(PI, UP) low_disk.target.move_to(right_half_torus, IN + LEFT) self.play( MoveToTarget(disk), MoveToTarget(low_disk), Transform(cylinder, right_half_torus), Restore(left_half_torus, rate_func=squish_rate_func(smooth, 0, 0.75)), frame.animate.reorient(-10, 80), run_time=5, ) self.wait()
from manim_imports_ext import * class DemoScene(InteractiveScene): def construct(self): # Demo animation square = Square() square.set_fill(BLUE, 0.5) square.set_stroke(WHITE, 1) grid = square.get_grid(10, 10, buff=0.5) grid.set_height(7) labels = index_labels(grid) self.add(grid) self.add(labels) # Animations def flip(square): if square.get_fill_color() == BLUE: target_color = GREY_C else: target_color = BLUE return square.animate.set_color(target_color).flip(RIGHT) for n in range(2, 100): highlights = grid[::n].copy() highlights.set_stroke(RED, 3) highlights.set_fill(opacity=0) self.play( ShowCreation(highlights, lag_ratio=0.05), run_time = 1 / math.sqrt(n), ) self.wait() self.remove(labels) self.play( LaggedStartMap(flip, grid[::n], lag_ratio=0.05), FadeOut(highlights), Animation(labels), run_time = 1 / math.sqrt(n), ) # New randy = PiCreature() self.play(randy.change("hooray"))
from manim_imports_ext import * class CleanBanner(Banner): message = " " class ShortsBanner(Banner): message = "3b1b shorts" def get_pis(self): pis = VGroup( Randolph(color=BLUE_E, mode="pondering"), Randolph(color=BLUE_D, mode="hooray"), Randolph(color=BLUE_C, mode="tease"), Randolph(color=GREY_BROWN, mode="pondering") ) height = 0.7 for pi in pis: pi.set_height(1) pi.body.stretch(math.sqrt(height), 1, about_edge=UP) diff = height - pi.get_height() new_points = np.array(pi.body.get_points()) new_points[3:26] += diff * DOWN new_points[63:82] += diff * DOWN new_points[2] += 0.05 * LEFT new_points[25] += 0.02 * DOWN pi.body.set_points(new_points) pi.mouth.shift(0.02 * UP) pis[3].flip() pis[1].mouth.shift(0.01 * UP) pis[1].eyes.shift(0.01 * UP) # for i, point in enumerate(pis[0].body.get_points()): # pis[0].add(Integer(i).set_height(0.02).move_to(point)) return pis
from manim_imports_ext import * class DoingMathVsHowMathIsPresented(Scene): def construct(self): titles = VGroup( OldTexText("How math is presented"), OldTexText("Actually doing math"), ) for title, vect in zip(titles, [LEFT, RIGHT]): title.scale(1.2) title.to_edge(UP) title.shift(vect * FRAME_WIDTH / 4) blocks = VGroup( self.get_block(0.98), self.get_block(0.1), ) self.add(titles) v_line = DashedLine(FRAME_WIDTH * UP / 2, FRAME_WIDTH * DOWN / 2) self.add(v_line) for block, title in zip(blocks, titles): block.next_to(title, DOWN) self.play(LaggedStartMap(FadeInFromLarge, block)) self.wait(2) def get_block(self, prob): block = VGroup(*[ self.get_mark(prob) for x in range(100) ]) block.arrange_in_grid() block.set_width(5) return block def get_mark(self, prob): if random.random() < prob: mark = OldTex("\\checkmark").set_color(GREEN) else: mark = OldTex("\\times").set_color(RED) mark.set_height(1) mark.set_width(1, stretch=True) return mark class PiCharts(Scene): def construct(self): # Add top lines equation = OldTex( "\\frac{1}{10}", "+", "\\frac{2}{5}", "=", "\\; ?" ) equation.scale(2) equation.to_edge(UP) vs = OldTexText("vs.") vs.scale(3) vs.next_to(equation, DOWN, LARGE_BUFF) self.add(equation, vs) # Add pi charts pi_equation = VGroup( self.get_pi_chart(10), OldTex("+").scale(2), self.get_pi_chart(5), OldTex("=").scale(2), OldTex("?").scale(2), ) pi_equation[0][0].set_fill(RED) pi_equation[2][:2].set_fill(RED) pi_equation.arrange(RIGHT) pi_equation.next_to(vs, DOWN) self.add(pi_equation) vs.shift(UL * MED_SMALL_BUFF) # Swap pi_equation.to_edge(UP) arrow = OldTex("\\downarrow").scale(3) arrow.next_to(pi_equation[1], DOWN, LARGE_BUFF) equation.next_to(arrow, DOWN) equation.shift(0.7 * RIGHT) self.remove(vs) self.add(arrow) def get_pi_chart(self, n): result = VGroup(*[ Sector( start_angle=TAU / 4 - k * TAU / n, angle=-TAU / n, stroke_color=WHITE, stroke_width=2, fill_color=BLUE_E, fill_opacity=1, ) for k in range(n) ]) result.scale(1.5) return result class AskAboutCircleProportion(Scene): def construct(self): R = 2.5 circle = Circle(radius=R) circles = VGroup(circle, circle.copy()) circles[0].move_to(R * LEFT / 2) circles[1].move_to(R * RIGHT / 2) circles[0].set_stroke(WHITE, 2) circles[1].set_stroke(BLUE, 4) dots = VGroup() for circle in circles: dots.add(Dot(circle.get_center())) arc = Arc( radius=R, start_angle=TAU / 3, angle=TAU / 3, ) arc.set_stroke(YELLOW, 4) arc.move_arc_center_to(circles[1].get_center()) question = OldTexText("What proportion of the circle?") question.set_height(0.6) question.to_corner(UL) arrow = Arrow( question.get_bottom() + LEFT, arc.point_from_proportion(0.25), ) self.add(circles) self.add(dots) self.add(arc) self.add(question) self.add(arrow) answer = OldTex("1/3") answer.set_height(0.9) answer.set_color(YELLOW) answer.next_to(question, RIGHT, LARGE_BUFF) self.add(answer) class BorweinIntegrals(Scene): def construct(self): ints = VGroup( OldTex( "\\int_0^\\infty", "\\frac{\\sin(x)}{x}", "dx = \\frac{\\pi}{2}" ), OldTex( "\\int_0^\\infty", "\\frac{\\sin(x)}{x}", "\\frac{\\sin(x/3)}{x/3}", "dx = \\frac{\\pi}{2}" ), OldTex( "\\int_0^\\infty", "\\frac{\\sin(x)}{x}", "\\frac{\\sin(x/3)}{x/3}", "\\frac{\\sin(x/5)}{x/5}", "dx = \\frac{\\pi}{2}" ), OldTex("\\vdots"), OldTex( "\\int_0^\\infty", "\\frac{\\sin(x)}{x}", "\\frac{\\sin(x/3)}{x/3}", "\\frac{\\sin(x/5)}{x/5}", "\\dots", "\\frac{\\sin(x/13)}{x/13}", "dx = \\frac{\\pi}{2}" ), OldTex( "\\int_0^\\infty", "\\frac{\\sin(x)}{x}", "\\frac{\\sin(x/3)}{x/3}", "\\frac{\\sin(x/5)}{x/5}", "\\dots", "\\frac{\\sin(x/13)}{x/13}", "\\frac{\\sin(x/15)}{x/15}", "dx = \\frac{\\pi}{2}", "- 0.0000000000231006..." ), ) ints.arrange(DOWN, buff=LARGE_BUFF, aligned_edge=RIGHT) ints.set_height(FRAME_HEIGHT - 1) ints[-1][:-1].align_to(ints[:-1], RIGHT) ints[-1][-1].next_to(ints[-1][:-1], RIGHT, SMALL_BUFF) ints[3].shift(SMALL_BUFF * LEFT) ints.center() for integral in ints: integral.set_color_by_tex("\\sin(x)", BLUE) integral.set_color_by_tex("x/3", TEAL) integral.set_color_by_tex("x/5", GREEN) integral.set_color_by_tex("x/13", YELLOW) integral.set_color_by_tex("x/15", RED_B) self.add(ints)
from manim_imports_ext import * class LinalgThumbnail(ThreeDScene): CONFIG = { "camera_config": { "anti_alias_width": 0, } } def construct(self): grid = NumberPlane((-10, 10), (-10, 10), faded_line_ratio=1) grid.set_stroke(width=6) grid.faded_lines.set_stroke(width=1) grid.apply_matrix([[3, 2], [1, -1]]) # self.add(grid) frame = self.camera.frame frame.reorient(0, 75) cube = Cube() cube.set_color(BLUE) cube.set_opacity(0.5) edges = VGroup() for vect in [OUT, RIGHT, UP, LEFT, DOWN, IN]: face = Square() face.shift(OUT) face.apply_matrix(z_to_vector(vect)) edges.add(face) for sm in edges.family_members_with_points(): sm.flat_stroke = False sm.joint_type = "round" edges.set_stroke(WHITE, 4) edges.replace(cube) edges.apply_depth_test() cube = Group(cube, edges) cube2 = cube.copy().apply_matrix( [[1, 0, 1], [0, 1, 0], [0, 0, 1]] ) # cube2.match_height(cube) arrow = Vector(RIGHT) arrow.rotate(PI / 2, RIGHT) group = Group(cube, arrow, cube2) group.arrange(RIGHT, buff=MED_LARGE_BUFF) self.add(group) # kw ={ # "thickness": 0.1, # # "max_tip_length_to_length_ratio": 0.2, # } # self.add(Vector(grid.c2p(1, 0), fill_color=GREEN, **kw)) # self.add(Vector(grid.c2p(0, 1), fill_color=RED, **kw)) # self.add(FullScreenFadeRectangle(fill_opacity=0.1)) class CSThumbnail(Scene): def construct(self): self.add(self.get_background()) def get_background(self, n=12, k=50, zero_color=GREY_C, one_color=GREY_B): choices = (Integer(0, color=zero_color), Integer(1, color=one_color)) background = VGroup(*( random.choice(choices).copy() for x in range(n * k) )) background.arrange_in_grid(n, k) background.set_height(FRAME_HEIGHT) return background class GroupThumbnail(ThreeDScene): def construct(self): cube = Cube() cubes = Group(cube) for axis in [[1, 1, 1], [1, 1, -1], [1, -1, 1], [1, -1, -1]]: for angle in [60 * DEGREES]: cubes.add(cube.copy().rotate(angle, axis)) cubes.rotate(95 * DEGREES, RIGHT) cubes.rotate(30 * DEGREES, UP) cubes.set_height(6) cubes.center() # cubes.set_y(-0.5) cubes.set_color(BLUE_D) cubes.set_shadow(0.65) cubes.set_gloss(0.5) self.add(cubes) class BaselThumbnail(Scene): def construct(self): # Lake lake_radius = 6 lake_center = ORIGIN lake = Circle( fill_color=BLUE, fill_opacity=0.0, radius=lake_radius, stroke_color=BLUE_D, stroke_width=3, ) lake.move_to(lake_center) R = 2 light_template = VGroup() rs = np.linspace(0, 1, 100) for r1, r2 in zip(rs, rs[1:]): dot1 = Dot(radius=R * r1).flip() dot2 = Dot(radius=R * r2) dot2.append_vectorized_mobject(dot1) dot2.insert_n_curves(100) dot2.set_fill(YELLOW, opacity=0.5 * (1 - r1)**2) dot2.set_stroke(width=0) light_template.add(dot2) houses = VGroup() lights = VGroup() for i in range(16): theta = -TAU / 4 + (i + 0.5) * TAU / 16 pos = lake_center + lake_radius * np.array([np.cos(theta), np.sin(theta), 0]) house = Lighthouse() house.set_fill(GREY_B) house.set_stroke(width=0) house.set_height(0.5) house.move_to(pos) light = light_template.copy() light.move_to(pos) houses.add(house) lights.add(light) self.add(lake) self.add(houses) self.add(lights) # Equation equation = OldTex( "1", "+", "{1 \\over 4}", "+", "{1 \\over 9}", "+", "{1 \\over 16}", "+", "{1 \\over 25}", "+", "\\cdots" ) equation.scale(1.8) equation.move_to(2 * UP) answer = OldTex("= \\frac{\\pi^2}{6}", color=YELLOW) answer.scale(3) answer.move_to(1.25 * DOWN) equation.add(answer) shadow = VGroup() for w in np.linspace(20, 0, 50): shadow.add(equation.copy().set_fill(opacity=0).set_stroke(BLACK, width=w, opacity=0.02)) self.add(shadow) self.add(equation) self.wait() class Eola1Thumbnail(Scene): def construct(self): plane = NumberPlane( x_range=(-2, 2), y_range=(-5, 5), ) plane.set_width(FRAME_WIDTH / 3) plane.to_edge(LEFT, buff=0) plane.shift(1.5 * DOWN) vect = Arrow( plane.get_origin(), plane.c2p(1, 2), buff=0, thickness=0.1, ) vect.set_color(YELLOW) self.add(plane, vect) coords = IntegerMatrix([[1], [2]]) coords.set_height(3) coords.set_color(TEAL) coords.center() coords.match_y(vect) self.add(coords) symbol = OldTex("\\vec{\\textbf{v} } \\in V") symbol.set_color(BLUE) symbol.set_width(FRAME_WIDTH / 3 - 1) symbol.set_x(FRAME_WIDTH / 3) symbol.match_y(vect) self.add(symbol) lines = VGroup(*(Line(DOWN, UP) for x in range(2))) lines.set_height(FRAME_HEIGHT) lines.arrange(RIGHT, buff=FRAME_WIDTH / 3) lines.set_stroke(GREY_A, 5) self.add(lines) title = Text("Vectors", font_size=120) title.to_edge(UP, buff=MED_SMALL_BUFF) shadow = VGroup() for w in np.linspace(50, 0, 100): shadow.add(title.copy().set_fill(opacity=0).set_stroke(BLACK, width=w, opacity=0.01)) self.add(shadow) self.add(title) def pendulum_vector_field_func(theta, omega, mu=0.3, g=9.8, L=3): return [omega, -np.sqrt(g / L) * np.sin(theta) - mu * omega] class ODEThumbnail(Scene): def construct(self): plane = NumberPlane() field = VectorField( pendulum_vector_field_func, plane, step_multiple=0.5, magnitude_range=(0, 5), length_func=lambda norm: 0.35 * sigmoid(norm), ) field.set_opacity(0.75) # self.add(plane) # self.add(field) # return # Solution curve dt = 0.1 t = 0 total_time = 50 def func(point): return plane.c2p(*pendulum_vector_field_func(*plane.p2c(point))) points = [plane.c2p(-4 * TAU / 4, 4.0)] while t < total_time: t += dt points.append(points[-1] + dt * func(points[-1])) line = VMobject() line.set_points_smoothly(points) line.set_stroke([WHITE, WHITE, BLACK], width=[5, 1]) # line.set_stroke((BLUE_C, BLUE_E), width=(10, 1)) line_fuzz = VGroup() N = 50 for width in np.linspace(50, 0, N): line_fuzz.add(line.copy().set_stroke(BLACK, width=width, opacity=2 / N)) self.add(line_fuzz) self.add(line) class PrimeSpirals(InteractiveScene): def construct(self): N = 10000 primes = np.array(list(sympy.primerange(0, 10000))) points = np.array([ primes * np.cos(primes), primes * np.sin(primes), np.zeros(len(primes)) ]).T dots = DotCloud(points) dots.set_width(15, about_point=ORIGIN) dots.make_3d() dots.set_color(TEAL) dots.set_radii(np.linspace(0.02, 0.1, len(primes))) self.add(dots) class EGraph(InteractiveScene): def construct(self): # Test axes = Axes((-4, 4), (0, 20, 2), width=14, height=5.5) axes.center().to_edge(DOWN) axes.set_stroke(width=3) graph = axes.get_graph(np.exp) graph.set_stroke(YELLOW, 10) self.add(axes, graph) equation = Tex("e = 2.71828...", t2c={"e": BLUE}) equation["e"].match_height(equation, about_edge=DR) equation.set_width(10) equation.to_edge(UP) self.add(equation) qmarks = Text("??", font_size=200) qmarks.move_to(DOWN).to_edge(LEFT, buff=1.0) arrow = Arrow( qmarks.get_corner(UR), equation["2."].get_corner(DL), stroke_width=10, stroke_color=WHITE ) VGroup(qmarks, arrow).set_color(TEAL) self.add(qmarks, arrow)
from manim_imports_ext import * class QBitDiagram(InteractiveScene): def construct(self): # Axes axes = Axes( (-1.5, 1.5, 0.5), (-1.5, 1.5, 0.5), height=7, width=7, ) axes.set_height(7) x_label = Tex(R"|0\rangle") y_label = Tex(R"|1\rangle") x_label.next_to(axes.x_axis.get_right(), UP, buff=0.15) y_label.next_to(axes.y_axis.get_top(), RIGHT, buff=0.15) axes.add(x_label, y_label) axes.add_coordinate_labels(font_size=16, num_decimal_places=1) circle = Circle(radius=axes.x_axis.get_unit_size()) circle.move_to(axes.c2p(0, 0)) circle.set_stroke(YELLOW, 2) self.add(circle) self.add(axes) # State vector vect = Arrow(axes.c2p(0, 0), circle.pfp(0.2), buff=0) vect.set_color(RED) coefs = DecimalNumber(edge_to_fix=RIGHT).replicate(2) coefs.set_color(RED) coefs[0].add_updater(lambda m: m.set_value(axes.x_axis.p2n(vect.get_end()))) coefs[1].add_updater(lambda m: m.set_value(axes.y_axis.p2n(vect.get_end()))) vect_label = VGroup( coefs[0], Tex(R"|0\rangle"), Tex("+"), coefs[1], Tex(R"|1\rangle"), ) vect_label.arrange(RIGHT, buff=0.25) coefs.shift(0.1 * RIGHT) vect_label.scale(1.25) vect_label.to_corner(UR) self.add(vect) self.add(vect_label) # Probabilities prob_labels = VGroup( self.get_prob_label(coefs[0], "0"), self.get_prob_label(coefs[1], "1"), ) prob_labels.arrange(DOWN, aligned_edge=LEFT) prob_labels.to_corner(UL) self.add(prob_labels) # Move around self.play( Rotate(vect, -1, about_point=axes.c2p(0, 0)), run_time=5 ) self.wait() # Show some flips line1 = DashedLine(2.5 * DL, 2.5 * UR) line2 = line1.copy().rotate(-30 * DEGREES) line3 = line1.copy().rotate(-63 * DEGREES) lines = [line1, line2, line3] last_line = VGroup() for line in lines: self.play(ShowCreation(line), FadeOut(last_line)) self.wait() vect.generate_target() vect.target.flip( axis=line.get_vector(), about_point=axes.c2p(0, 0) ) angle = vect.target.get_angle() - vect.get_angle() self.play( MoveToTarget(vect, path_arc=angle) ) self.wait() last_line = line self.play(FadeOut(last_line)) def get_prob_label(self, coef, bit="0"): # Test label = Tex( Rf"P(\text{{Measure a }}{bit}) = (0.00)^2 = 0.00", font_size=36 ) numbers = label.make_number_changable("0.00", replace_all=True) for number in numbers: number.edge_to_fix = ORIGIN width = numbers[0].get_width() numbers[0].add_updater(lambda m: m.set_value(coef.get_value()).set_width(width)) numbers[1].add_updater(lambda m: m.set_value(coef.get_value()**2).set_width(width)) numbers.set_color(RED) return label class BlocksToQuantum(InteractiveScene): def construct(self): # Wall wall_height = 2 block_height = 1.0 block_style = dict( stroke_color=WHITE, stroke_width=1, fill_color=BLUE_E, fill_opacity=1, shading=(0.5, 0.25, 0), ) floor = Line(LEFT, RIGHT).set_width(FRAME_WIDTH) floor.to_edge(DOWN, buff=0.5) floor.shift(RIGHT) wall = Line(DOWN, UP).set_height(wall_height) wall.move_to(floor.get_left(), DOWN) VGroup(floor, wall).set_stroke(WHITE, 2) self.add(floor, wall) # Blocks left_block = Square(side_length=block_height) left_block.set_style(**block_style) left_block.move_to(floor, DOWN) left_block.shift(2 * LEFT) right_blocks = left_block.get_grid(3, 3, buff=0) right_blocks.move_to(floor, DOWN) right_blocks.to_edge(RIGHT) self.add(left_block) self.add(right_blocks) all_blocks = VGroup(left_block, *right_blocks) # Add names names = [ "David", "Bob", "Charlie", "Eve", "Alice", "Joan", "Kathy", "Morty", "Lily", "Randy" ] name_labels = VGroup(*map(Text, names)) name_labels.set_width(0.8 * left_block.get_width()) for block, label in zip(all_blocks, name_labels): label.move_to(block) block.add(label) # Show state vector coefs = DecimalNumber(-math.sqrt(0.1), edge_to_fix=RIGHT).replicate(4) coefs.set_color(RED) state_tex = VGroup( coefs[0], Tex(fR"|\text{{{names[0]}}}\rangle"), Tex("+"), coefs[1], Tex(fR"|\text{{{names[1]}}}\rangle"), Tex("+"), coefs[2], Tex(fR"|\text{{{names[2]}}}\rangle"), Tex("+"), Tex(R"\cdots"), Tex("+"), coefs[-1], Tex(fR"|\text{{{names[-1]}}}\rangle"), ) state_tex.arrange(RIGHT, buff=0.15) state_tex.set_width(FRAME_WIDTH - 1) state_tex.to_edge(UP) self.add(state_tex) # Arrows arrows = VGroup() for block in all_blocks: arrow = Vector(0.75 * LEFT) arrow.set_color(RED) arrow.move_to(block.get_left(), RIGHT) arrow.shift(0.25 * block_height * UP) arrows.add(arrow) arrows.add(arrow) block.arrow = arrow self.add(arrows) # Slide dist = (left_block.get_left() - wall.get_center())[0] self.add(all_blocks, arrows) self.play( all_blocks.animate.shift(dist * LEFT), arrows.animate.shift(dist * LEFT), rate_func=linear, run_time=3, ) left_block.arrow.flip(UP, about_point=left_block.get_center()) coefs[0].set_value(-coefs[0].get_value()) self.wait() dist = (right_blocks.get_left() - left_block.get_right())[0] self.play( left_block.animate.shift(0.5 * dist * RIGHT), right_blocks.animate.shift(0.5 * dist * LEFT), arrows[0].animate.shift(0.5 * dist * RIGHT), arrows[1:].animate.shift(0.5 * dist * LEFT), run_time=1.5, rate_func=linear ) left_block.arrow.flip(UP, about_point=left_block.get_center()) for arrow in arrows[1:]: arrow.scale(0.5, about_edge=RIGHT) coefs[0].set_value(-0.42) for coef in coefs[1:]: coef.set_value(-0.29) self.wait()
from manim_imports_ext import * from manimlib.once_useful_constructs.fractals import * # Fractal posters class ShowHilbertCurve(Scene): CONFIG = { "FractalClass": HilbertCurve, "orders": [3, 5, 7], "stroke_widths": [20, 15, 7], } def construct(self): curves = VGroup(*[ self.FractalClass( order=order, ).scale(scale_factor) for order, scale_factor in zip( self.orders, np.linspace(1, 2, 3) ) ]) for curve, stroke_width in zip(curves, self.stroke_widths): curve.set_stroke(width=stroke_width) curves.arrange(DOWN, buff=LARGE_BUFF) curves.set_height(FRAME_HEIGHT - 1) self.add(*curves) class ShowFlowSnake(ShowHilbertCurve): CONFIG = { "FractalClass": FlowSnake, "orders": [2, 3, 4], "stroke_widths": [20, 15, 10], } class FlippedSierpinski(Sierpinski): def __init__(self, *args, **kwargs): Sierpinski.__init__(self, *args, **kwargs) self.rotate(np.pi, RIGHT, about_point=ORIGIN) class ShowSierpinski(ShowHilbertCurve): CONFIG = { "FractalClass": FlippedSierpinski, "orders": [3, 6, 9], "stroke_widths": [20, 15, 6], } # Socks class SquareWave(Scene): def construct(self): L = FRAME_WIDTH / 4 waves = VGroup(*[ FunctionGraph( lambda x: self.approx_square_wave(x, L, n_terms), x_range=[-2 * L, 2 * L, L / 50], ) for n_terms in range(1, 5) ]) waves.set_color_by_gradient(BLUE, YELLOW, RED) stroke_widths = np.linspace(3, 1, len(waves)) for wave, stroke_width in zip(waves, stroke_widths): # wave.set_stroke(width=stroke_width) wave.set_stroke(width=3) # waves.to_edge(UP) tex_mob = OldTex(""" {4 \\over \\pi} \\sum_{n=0}^\\infty {\\sin\\big((2n + 1)\\pi x\\big) \\over (2n + 1)} """) tex_mob.scale(1.5) # tex_mob.next_to(waves, DOWN, MED_LARGE_BUFF) self.add(waves) # self.add(tex_mob) def approx_square_wave(self, x, L, n_terms=3): return 1.0 * sum([ (1.0 / n) * np.sin(n * PI * x / L) for n in range(1, 2 * n_terms + 1, 2) ]) class PendulumPhaseSpace(Scene): def construct(self): axes = Axes( x_min=-PI, x_max=PI, y_min=-2, y_max=2, x_axis_config={ "tick_frequency": PI / 4, "unit_size": FRAME_WIDTH / TAU, "include_tip": False, }, y_axis_config={ "unit_size": 4, "tick_frequency": 0.25, }, ) def func(point, mu=0.1, k=0.5): theta, theta_dot = axes.p2c(point) return axes.c2p( theta_dot, -mu * theta_dot - k * np.sin(theta), ) field = VectorField( func, delta_x=1.5 * FRAME_WIDTH / 12, delta_y=1.5, y_min=-6, y_max=6, length_func=lambda norm: 1.25 * sigmoid(norm), max_magnitude=4, vector_config={ "tip_length": 0.75, "max_tip_length_to_length_ratio": 0.35, }, ) field.set_stroke(width=12) colors = list(Color(BLUE).range_to(RED, 5)) for vect in field: mag = get_norm(1.18 * func(vect.get_start())) vect.set_color(colors[min(int(mag), len(colors) - 1)]) line = VMobject() line.start_new_path(axes.c2p( -3 * TAU / 4, 1.75, )) dt = 0.1 t = 0 total_time = 60 while t < total_time: t += dt last_point = line.get_last_point() new_point = last_point + dt * func(last_point) if new_point[0] > FRAME_WIDTH / 2: new_point = last_point + FRAME_WIDTH * LEFT line.start_new_path(new_point) else: line.add_smooth_curve_to(new_point) line.set_stroke(WHITE, 6) # self.add(axes) self.add(field) # line.set_stroke(BLACK) # self.add(line)
from manim_imports_ext import * from _2016.zeta import zeta def approx_exp(x, n): return sum([ x**k / math.factorial(k) for k in range(n + 1) ]) class ExpPlay(Scene): def construct(self): for n in [2, 4, 6, 8, 10]: self.show_sum_up_to(n) self.clear() self.show_sum_up_to(40, 10, include_dots=True) self.wait(2) def show_sum_up_to(self, n, shown_n=None, include_dots=False): plane = ComplexPlane() plane.add_coordinate_labels() self.add(plane) plane.shift(DOWN) if shown_n is None: shown_n = n t_tracker = ValueTracker(0) vectors = always_redraw( lambda: self.get_sum_vectors( t_tracker.get_value(), n, center=plane.n2p(0), ) ) path = ParametricCurve( lambda t: plane.n2p(approx_exp(complex(0, t), n)), t_min=0, t_max=TAU, ) path.set_color(WHITE) formula = OldTex( "e^{it} \\approx", *[ "{(ti)^{%d} \\over %d!} +" % (k, k) for k in range(shown_n + 1) ], "\\cdots" if include_dots else "", ) for vect, part in zip(vectors, formula[1:]): part.match_color(vect) part[-1].set_color(WHITE) if include_dots: formula[-1].set_color(WHITE) else: formula[-1][-1].set_opacity(0) if formula.get_width() > FRAME_WIDTH - 1: formula.set_width(FRAME_WIDTH - 1) formula.to_edge(UP, buff=MED_SMALL_BUFF) formula.set_stroke(BLACK, 5, background=True) formula.add_background_rectangle(buff=MED_SMALL_BUFF) number_line = NumberLine( x_min=0, x_max=7.5, ) number_line.set_width(5) number_line.add_numbers() number_line.move_to(1.25 * UP) number_line.to_edge(RIGHT) rect = BackgroundRectangle(number_line, buff=MED_SMALL_BUFF) rect.stretch(2, 1, about_edge=DOWN) rect.set_width(7, stretch=True) tip = ArrowTip() tip.rotate(-PI / 2) tip.set_color(WHITE) tip.add_updater( lambda m: m.move_to( number_line.n2p(t_tracker.get_value()), DOWN, ) ) t_eq = VGroup( OldTex("t="), DecimalNumber(0), ) t_eq.add_updater(lambda m: m.arrange(RIGHT, buff=SMALL_BUFF)) t_eq.add_updater(lambda m: m.next_to(tip, UP, SMALL_BUFF)) t_eq.add_updater(lambda m: m[1].set_value(t_tracker.get_value())) self.add(rect, number_line, tip, t_eq) self.add(vectors, path, formula) self.play( t_tracker.set_value, TAU, ShowCreation(path), run_time=4, rate_func=bezier([0, 0, 1, 1]), ) self.wait() def get_sum_vectors(self, t, n, center=ORIGIN): vectors = VGroup() template_vect = Vector(RIGHT) last_tip = center for k in range(n + 1): vect = template_vect.copy() vect.rotate(k * PI / 2) vect.scale(t**k / math.factorial(k)) vect.set_stroke( width=max(2, vect.get_stroke_width()) ) # vect.tip.set_stroke(width=0) vect.shift(last_tip - vect.get_start()) last_tip = vect.get_end() vectors.add(vect) self.color_vectors(vectors) return vectors def color_vectors(self, vectors, colors=[BLUE, YELLOW, RED, PINK]): for vect, color in zip(vectors, it.cycle(colors)): vect.set_color(color) def get_paths(self): paths = VGroup(*[ ParametricCurve( lambda t: plane.n2p(approx_exp(complex(0, t), n)), t_min=-PI, t_max=PI, ) for n in range(10) ]) paths.set_color_by_gradient(BLUE, YELLOW, RED) return paths # for path in paths: # self.play(ShowCreation(path)) # self.wait() class ZetaSum(Scene): def construct(self): plane = ComplexPlane() self.add(plane) plane.scale(0.2) s = complex(0.5, 14.135) N = int(1e6) lines = VGroup() color = it.cycle([BLUE, RED]) r = int(1e3) for k in range(1, N + 1, r): c = sum([ L**(-s) * (N - L + 1) / N for L in range(k, k + r) ]) line = Line(plane.n2p(0), plane.n2p(c)) line.set_color(next(color)) if len(lines) > 0: line.shift(lines[-1].get_end()) lines.add(line) self.add(lines) self.add( Dot(lines[-1].get_end(), color=YELLOW), Dot( center_of_mass([line.get_end() for line in lines]), color=YELLOW ), ) class ZetaSpiral(Scene): def construct(self): max_t = 50 spiral = VGroup(*[ ParametricCurve( lambda t: complex_to_R3( zeta(complex(0.5, t)) ), t_min=t1, t_max=t2 + 0.1, ) for t1, t2 in zip(it.count(), range(1, max_t)) ]) spiral.set_stroke(width=0, background=True) # spiral.set_color_by_gradient(BLUE, GREEN, YELLOW, RED) # spiral.set_color_by_gradient(BLUE, YELLOW) spiral.set_color(YELLOW) width = 10 for piece in spiral: piece.set_stroke(width=width) width *= 0.98 dot = Dot() dot.scale(0.25) dot.match_color(piece) dot.set_stroke(BLACK, 1, background=True) dot.move_to(piece.get_start()) # piece.add(dot) label = OldTex( "\\zeta\\left(0.5 + i{t}\\right)", tex_to_color_map={"{t}": YELLOW}, background_stroke_width=0, ) label.scale(1.5) label.next_to(spiral, DOWN) group = VGroup(spiral, label) group.set_height(FRAME_HEIGHT - 1) group.center() self.add(group) class SumRotVectors(Scene): CONFIG = { "n_vects": 100, } def construct(self): plane = ComplexPlane() circle = Circle(color=YELLOW) t_tracker = ValueTracker(0) get_t = t_tracker.get_value vects = always_redraw(lambda: self.get_vects(get_t())) self.add(plane, circle) self.add(t_tracker, vects) self.play( t_tracker.set_value, 1, run_time=10, rate_func=linear, ) self.play(ShowIncreasingSubsets(vects, run_time=5)) def get_vects(self, t): vects = VGroup() last_tip = ORIGIN for n in range(self.n_vects): vect = Vector(RIGHT) vect.rotate(n * TAU * t, about_point=ORIGIN) vect.shift(last_tip) last_tip = vect.get_end() vects.add(vect) vects.set_submobject_colors_by_gradient(BLUE, GREEN, YELLOW, RED) vects.set_opacity(0.5) return vects class Spirals(Scene): CONFIG = { "n_lines": 1200 } def construct(self): s_tracker = ComplexValueTracker(complex(2, 1)) get_s = s_tracker.get_value spiral = always_redraw( lambda: self.get_spiral(get_s()) ) s_dot = always_redraw( lambda: Dot(s_tracker.get_center(), color=YELLOW) ) s_label = always_redraw( lambda: DecimalNumber(get_s()).to_corner(UR) ) self.add(ComplexPlane().set_stroke(width=0.5)) self.add(spiral, s_dot, s_label) self.play(s_tracker.set_value, complex(1, 1), run_time=3) sigma = 0.5 zero_ts = [ 14.134725, 21.022040, 25.010858, 30.424876, 32.935062, 37.586178, ] self.wait() self.play(s_tracker.set_value, complex(sigma, 1), run_time=3) self.wait() for zero_t in zero_ts: self.play( s_tracker.set_value, complex(sigma, zero_t), run_time=3 ) updaters = spiral.get_updaters() spiral.clear_updaters() self.play(FadeOut(spiral)) self.play(ShowCreation(spiral, run_time=3)) for updater in updaters: spiral.add_updater(updater) self.wait() def get_spiral(self, s, colors=[RED, BLUE]): n_lines = self.n_lines lines = VGroup() colors = it.cycle(colors) for n in range(1, n_lines + 1): z = self.n_to_z(n, s, n_lines) if abs(z) == 0: continue line = Line(ORIGIN, complex_to_R3(z)) line.set_stroke( colors.__next__(), width=3 * abs(z)**0.1 ) if len(lines) > 0: line.shift(lines[-1].get_end()) lines.add(line) return lines def n_to_z(self, n, s, n_lines): # if is_prime(n): # return -np.log(1 - n**(-s)) # else: # return 0 # return n**(-s) return (n**(-s)) * (n_lines - n) / n_lines # factors = factorize(n) # if len(set(factors)) != 1: # return 0 # else: # return (1.0 / len(factors)) * n**(-s)
#!/usr/bin/env python2 # -*- coding: utf-8 -*- from manim_imports_ext import * from _2019.diffyq.part2.fourier_series import FourierOfTexPaths # I'm guessing most of this needs to be fixed... # class ComplexMorphingNames(ComplexTransformationScene): class ComplexMorphingNames(Scene): CONFIG = { "patron_name": "Janel", "function": lambda z: 0.2 * (z**3), "default_apply_complex_function_kwargs": { "run_time": 5, }, "output_directory": os.path.join(get_output_dir(), "EightDollarPatrons"), "include_coordinate_labels": False, "vert_start_color": YELLOW, # TODO "vert_end_color": PINK, "horiz_start_color": GREEN, "horiz_end_color": BLUE, "use_multicolored_plane": True, # "plane_config" : { # "unit_size" : 1.5, # }, } def construct(self): name = self.patron_name self.clear() self.frames = [] self.setup() self.add_transformable_plane() self.plane.fade() name_mob = OldTexText(name) name_mob.set_width(4) name_mob.next_to(ORIGIN, UP, LARGE_BUFF) self.start_vect = name_mob.get_center() for submob in name_mob.family_members_with_points(): submob.insert_n_curves(100) name_mob_copy = name_mob.copy() self.play(Write(name_mob)) self.play( self.get_rotation(name_mob), run_time=5, ) self.wait() self.add_transformable_mobjects(name_mob) self.apply_complex_function(self.function) self.wait() self.play( self.get_post_transform_rotation(name_mob, name_mob_copy), run_time=10 ) self.wait(3) def get_rotation(self, name_mob): return UpdateFromAlphaFunc( name_mob, lambda mob, alpha: mob.move_to(rotate_vector( self.start_vect, 2 * np.pi * alpha )) ) def get_post_transform_rotation(self, name_mob, name_mob_copy): simple_rotation = self.get_rotation(name_mob_copy) def update(name_mob, alpha): simple_rotation.update(alpha) new_name = simple_rotation.mobject.copy() new_name.apply_complex_function(self.function) Transform(name_mob, new_name).update(1) return name_mob return UpdateFromAlphaFunc(name_mob, update) class FlowNameAnimation(Scene): CONFIG = { "patron_name": "Test Name" } def construct(self): name_mob = OldTexText(self.patron_name) name_mob.scale(2) max_width = FRAME_WIDTH - 2 if name_mob.get_width() > max_width: name_mob.set_width(max_width) name_strokes = VGroup() for mob in name_mob.family_members_with_points(): mob.insert_n_curves(20) anchors1, handles1, handles2, anchors2 = mob.get_anchors_and_handles() for a1, h1, h2, a2 in zip(anchors1, handles1, handles2, anchors2): stroke = VMobject() stroke.set_points([a1, h1, h2, a2]) stroke.set_stroke(WHITE, width=2) name_strokes.add(stroke) stroke.save_state() from _2017.eoc.div_curl import four_swirls_function from _2017.eoc.div_curl import VectorField from _2017.eoc.div_curl import move_submobjects_along_vector_field func = four_swirls_function vector_field = VectorField(func) vector_field.submobjects.sort( key=lambda a: a.get_length() ) flow = move_submobjects_along_vector_field(name_strokes, func) self.add_foreground_mobjects(name_strokes) self.play(Write(name_strokes)) self.play(LaggedStartMap(GrowArrow, vector_field)) self.add(flow) self.wait(60) self.remove(flow) self.play( FadeOut(vector_field), LaggedStartMap( ApplyMethod, name_strokes, lambda m: (m.restore,), lag_ratio=0.2 ), run_time=5, ) self.wait() class NameAnimationScene(Scene): CONFIG = { "animated_name": "Test name", "all_names": [ "范英睿", ], "animate_all_names": True, "linger_after_completion": False, } def run(self): if self.animate_all_names: for name in self.all_names: self.__init__() self.camera.frame_rate = 30 try: self.file_writer.file_name = name.replace(" ", "") + self.__class__.__name__ self.file_writer.init_output_directories() self.file_writer.begin() self.num_plays = 0 # Allow subclasses to alter this name, for example by lengthening it. name = self.edit_name_text(name) self.animated_name = name self.clear() self.setup() self.construct() self.tear_down() except Exception as inst: raise inst # print(inst) # print(f"Problem with {name}") else: super().__init__(**kwargs) def edit_name_text(self, name): return name class RotatingNameLetters(NameAnimationScene): def edit_name_text(self, name): if len(name) < 8: name += " Is Delightful" return name def construct(self): diameter = 3.0 radius = diameter / 2 letter_scale = 1 name = self.animated_name.replace(" ", "$\\cdot$") name += "$\\cdot$" text_mob = OldTexText(name) text_mob.set_stroke(BLACK, 2, background=True) # for part in text_mob.get_parts_by_tex("$\\cdot$"): # part.set_opacity(0) letter_mobs = text_mob[0] nb_letters = len(letter_mobs) randy = PiCreature() randy.move_to(ORIGIN).set_height(0.5 * diameter) randy.set_color(BLUE_E) randy.look_at(UP + RIGHT) self.add(randy) dtheta = TAU / nb_letters angles = np.arange(TAU / 4, -3 * TAU / 4, -dtheta) name_mob = VGroup() for (letter_mob, angle) in zip(letter_mobs, angles): letter_mob.scale(letter_scale) pos = radius * np.cos(angle) * RIGHT + radius * np.sin(angle) * UP letter_mob.move_to(pos) name_mob.add(letter_mob) pos2 = radius * np.cos(angles[2]) * RIGHT + \ radius * np.sin(angles[2]) * UP times_n_label = VGroup( OldTex("\\times"), Integer(1) ) times_n_label.arrange(RIGHT) times_n_label.shift(FRAME_WIDTH * RIGHT / 4) times_n_label.to_edge(UP) self.play( LaggedStartMap(FadeIn, name_mob, run_time=3), ApplyMethod(randy.change, "pondering", pos2, run_time=1), FadeIn(times_n_label) ) for n in range(2, nb_letters + 2): group = [] for (j, letter_mob) in enumerate(name_mob.submobjects): new_angle = TAU / 4 - n * j * dtheta new_pos = radius * np.cos(new_angle) * \ RIGHT + radius * np.sin(new_angle) * UP letter_mob.target = letter_mob.copy().move_to(new_pos) anim = MoveToTarget(letter_mob, path_arc=- j * dtheta) group.append(anim) new_n = Integer(n) new_n.move_to(times_n_label[1]) self.play( AnimationGroup(*group, run_time=3), UpdateFromFunc(randy, lambda r: r.look_at(name_mob.submobjects[2])), FadeOut(times_n_label[1]), FadeIn(new_n) ) times_n_label.submobjects[1] = new_n self.wait(0.5) thank_you = OldTexText("Thank You!").next_to(randy, DOWN) new_randy = randy.copy() new_randy.change("hooray") new_randy.set_color(BLUE_E) new_randy.look_at(ORIGIN) self.play( ReplacementTransform(name_mob, VGroup(*thank_you)), Transform(randy, new_randy) ) self.play(Blink(randy)) class ModularMultiplicationNameAnimation(RotatingNameLetters): def construct(self): max_width = FRAME_WIDTH - 4 char_radius = 3 index_radius = 2.5 text = OldTexText(self.animated_name)[0] N = len(text) text.scale(2) text.set_stroke(BLACK, 5, background=True) if text.get_width() > max_width: text.set_width(max_width) circle_text = text.copy() alphas = np.arange(0, TAU, TAU / N) for char, theta in zip(circle_text, alphas): char.move_to(char_radius * np.array([ np.sin(theta), np.cos(theta), 0, ])) index_mobs = VGroup() for i, char in enumerate(circle_text): index = Integer(i) index.move_to((index_radius / char_radius) * char.get_center()) index.scale(0.5) index.set_color(YELLOW) char.index = 0 index_mobs.add(index) self.play(FadeInFromDown(text)) self.wait() self.play( Transform(text, circle_text), FadeIn(index_mobs), lag_ratio=0.2, run_time=3, ) self.wait() # Multiplications # last_lines = VMobject() # last_label = VMobject() for k in range(2, N + 1): text.generate_target() text.save_state() for i, char in enumerate(text.target): char.move_to(circle_text[(i * k) % N]) lines = VGroup(*[ Line( index_mobs[i], index_mobs[(i * k) % N], buff=SMALL_BUFF, ).add_tip(0.1).set_opacity( 0 if (i * k) % N == i else 1 ) for i in range(N) ]) lines.set_color(MAROON_B) lines.set_stroke(width=1) label = VGroup(OldTex("\\times"), Integer(k)) label.arrange(RIGHT, buff=SMALL_BUFF) label.scale(2) label.next_to(circle_text, UR) label.shift_onto_screen() label.set_color(MAROON_B) kw = { "run_time": 5, "lag_ratio": 0.5, "rate_func": lambda t: smooth(t, 2), } self.play( MoveToTarget(text, **kw), ShowCreation(lines, **kw), FadeIn(label), ) self.wait() text_copy = text.copy() self.add(text_copy) self.remove(text) text.restore() self.play( FadeOut(lines), FadeOut(label), FadeOut(text_copy), FadeIn(text), ) class FourierNameAnimation(FourierOfTexPaths, NameAnimationScene): pass class QuaternionNameAnimation(Scene): CONFIG = { "R": 2, } def construct(self): surface = ParametricSurface(lambda u, v: (u, v, 0), resolution=16) surface.set_width(self.R * TAU) surface.set_height(1.8 * self.R, stretch=True) surface.center() surface.set_fill(opacity=0.5) name = OldTexText(self.name_text) name.set_width(self.R * TAU - 1) max_height = 0.4 * surface.get_height() if name.get_height() > max_height: name.set_height(max_height) name.next_to(surface.get_top(), DOWN) for letter in name: letter.add(VectorizedPoint(letter.get_center() + 2 * OUT)) letter.set_shade_in_3d(True, z_index_as_group=True) # for submob in letter.family_members_with_points(): # submob.pre_function_handle_to_anchor_scale_factor = 0.001 axes = self.get_axes() self.play( Write(surface), Write(name), ) surface.add(name) self.wait() self.move_camera( phi=70 * DEGREES, theta=-140 * DEGREES, added_anims=[ ApplyPointwiseFunction(self.plane_to_cylinder, surface), FadeIn(axes), ], run_time=3, ) self.begin_ambient_camera_rotation(0.01) self.wait(2) self.play( ApplyPointwiseFunction(self.cylinder_to_sphere, surface), run_time=3 ) # self.play(Rotating( # surface, angle=-TAU, axis=OUT, # about_point=ORIGIN, # run_time=4, # rate_func=smooth # )) self.wait(2) for i in range(3): axis = np.zeros(3) axis[i] = 1 self.play(Homotopy( self.get_quaternion_homotopy(axis), surface, run_time=10, )) self.wait(5) def plane_to_cylinder(self, p): x, y, z = p R = self.R + z return np.array([ R * np.cos(x / self.R - 0), R * np.sin(x / self.R - 0), 1.0 * y, ]) def cylinder_to_sphere(self, p): x, y, z = p R = self.R r = np.sqrt(R**2 - z**2) return np.array([ x * fdiv(r, R), y * fdiv(r, R), z ]) def get_quaternion_homotopy(self, axis=[1, 0, 0]): def result(x, y, z, t): alpha = t quaternion = np.array([np.cos(TAU * alpha), 0, 0, 0]) quaternion[1:] = np.sin(TAU * alpha) * np.array(axis) new_quat = q_mult(quaternion, [0, x, y, z]) return new_quat[1:] return result
from manim_imports_ext import * class WhyPi(Scene): def construct(self): title = OldTexText("Why $\\pi$?") title.scale(3) title.to_edge(UP) formula1 = OldTex( "1 +" "\\frac{1}{4} +" "\\frac{1}{9} +" "\\frac{1}{16} +" "\\frac{1}{25} + \\cdots" "=\\frac{\\pi^2}{6}" ) formula1.set_color(YELLOW) formula1.set_width(FRAME_WIDTH - 2) formula1.next_to(title, DOWN, MED_LARGE_BUFF) formula2 = OldTex( "1 -" "\\frac{1}{3} +" "\\frac{1}{5} -" "\\frac{1}{7} +" "\\frac{1}{9} - \\cdots" "=\\frac{\\pi}{4}" ) formula2.set_color(BLUE_C) formula2.set_width(FRAME_WIDTH - 2) formula2.next_to(formula1, DOWN, LARGE_BUFF) self.add(title) self.add(formula1) self.add(formula2) class GeneralExpositionIcon(Scene): def construct(self): title = OldTexText("What is \\underline{\\qquad \\qquad}?") title.scale(3) title.to_edge(UP) randy = Randolph() randy.change("pondering") randy.set_height(4.5) randy.to_edge(DOWN) randy.look_at(title[0][0]) self.add(title) self.add(randy) class GeometryIcon(Scene): def construct(self): im = ImageMobject("geometry_icon_base.jpg") im.set_height(FRAME_HEIGHT) im.scale(0.9, about_edge=DOWN) word = OldTexText("Geometry") word.scale(3) word.to_edge(UP) self.add(im, word) class PhysicsIcon(Scene): def construct(self): im = ImageMobject("physics_icon_base.png") im.set_height(FRAME_HEIGHT) im.shift(UP) title = OldTexText("Physics") title.scale(3) title.to_edge(UP) self.add(im) self.add(title) class SupportIcon(Scene): def construct(self): randy = Randolph(mode="coin_flip_2") morty = Mortimer(mode="gracious") pis = VGroup(randy, morty) pis.arrange(RIGHT, buff=3) pis.to_edge(DOWN) randy.make_eye_contact(morty) heart = SuitSymbol("hearts") heart.set_height(1) heart.next_to(randy, UR, buff=-0.5) heart.shift(0.5 * RIGHT) # rect = FullScreenFadeRectangle(opacity=0.85) # self.add(rect) self.add(pis) self.add(heart) class SupportPitch1(Scene): CONFIG = { "camera_config": { "background_opacity": 0.85, }, "mode1": "happy", "mode2": "hooray", "words1": "So what do\\\\you do?", "words2": "Oh, I make\\\\videos about\\\\math.", } def construct(self): randy = Randolph() randy.to_corner(DL) morty = Mortimer() morty.to_corner(DR) randy.change(self.mode1, morty.eyes) morty.change(self.mode2, randy.eyes) b1 = randy.get_bubble( self.words1, bubble_type=SpeechBubble, height=3, width=4, ) b1.add(b1.content) b1.shift(0.25 * UP) b2 = morty.get_bubble( self.words2, bubble_type=SpeechBubble, height=3, width=4, ) # b2.content.scale(0.9) b2.add(b2.content) b2.shift(0.25 * DOWN) self.add(randy) self.add(morty) self.add(b2) self.add(b1) class SupportPitch2(SupportPitch1): CONFIG = { "mode1": "confused", "mode2": "speaking", "words1": "Wait, how does\\\\that work?", "words2": "People pay\\\\for them.", } class SupportPitch3(SupportPitch1): CONFIG = { "mode1": "hesitant", "mode2": "coin_flip_2", "words1": "Oh, so like\\\\a paid course?", "words2": "Well, no,\\\\everything\\\\is free.", } class SupportPitch4(SupportPitch1): CONFIG = { "mode1": "confused", "mode2": "hesitant", "words1": "Wait, what?", "words2": "I know,\\\\it's weird...", } class RantPage(Scene): CONFIG = { } def construct(self): squares = VGroup(Square(), Square()) squares.arrange(DOWN, buff=MED_SMALL_BUFF) squares.set_height(FRAME_HEIGHT - 0.5) squares.set_width(5, stretch=True) squares.set_stroke(WHITE, 2) squares.set_fill(BLACK, opacity=0.75) s1, s2 = squares # Group1 morty = Mortimer(mode="maybe") for eye, pupil in zip(morty.eyes, morty.pupils): pupil.move_to(eye) morty.shift(MED_SMALL_BUFF * UL) words = OldTexText( "What were you\\\\expecting to be here?" ) bubble = SpeechBubble(direction=RIGHT) bubble.match_style(s1) bubble.add_content(words) bubble.resize_to_content() bubble.add(bubble.content) bubble.pin_to(morty) group1 = VGroup(morty, bubble) group1.set_height(s1.get_height() - MED_SMALL_BUFF) group1.next_to(s1.get_corner(DR), UL, SMALL_BUFF) # Group 2 morty = Mortimer(mode="surprised") morty.shift(MED_SMALL_BUFF * UL) words = OldTexText( "Go on!\\\\Give the rant!" ) bubble = SpeechBubble(direction=RIGHT) bubble.match_style(s1) bubble.add_content(words) bubble.resize_to_content() bubble.add(bubble.content) bubble.pin_to(morty) group2 = VGroup(morty, bubble) group2.set_height(s2.get_height() - MED_SMALL_BUFF) group2.next_to(s2.get_corner(DR), UL, SMALL_BUFF) self.add(squares) self.add(group1) self.add(group2) class ClipsLogo(Scene): def construct(self): logo = Logo() logo.set_height(FRAME_HEIGHT - 0.5) square = Square(stroke_width=0, fill_color=BLACK, fill_opacity=1) square.scale(5) square.rotate(45 * DEGREES) square.move_to(ORIGIN, LEFT) self.add(logo, square)
from manim_imports_ext import * class AdditionAnagram(Scene): def construct(self): words1 = Text("twelve + one", font_size=120) words2 = Text("eleven + two", font_size=120) VGroup(words1, words2).shift(DOWN) twelve = words1.get_part_by_text("twelve") one = words1.get_part_by_text("one") eleven = words2.get_part_by_text("eleven") two = words2.get_part_by_text("two") buff = 1.0 dots1 = VGroup( *Dot().get_grid(3, 4).next_to(twelve, UP, buff=buff), Dot().next_to(one, UP, buff=buff) ).set_color(BLUE) dots2 = VGroup( *Dot().replicate(11).arrange_in_grid(3, 4).next_to(eleven, UP, buff=buff), *Dot().get_grid(2, 1).next_to(two, UP, buff=buff) ).set_color(BLUE) self.add(words1, dots1) self.wait() for w1, w2, d1, d2 in [(words1, words2, dots1, dots2), (words2, words1, dots2, dots1)]: self.clear() self.play( TransformMatchingShapes( w1.copy(), w2.copy(), path_arc=PI / 2, ), Transform(d1.copy(), d2.copy()), run_time=3 ) self.wait(2)
from manim_imports_ext import * class DoorPuzzle(InteractiveScene): def construct(self): # Setup squares = Square().get_grid(10, 10) squares.set_stroke(WHITE, 1) squares.set_height(FRAME_HEIGHT - 1) labels = VGroup(*( Integer(n, font_size=24).move_to(square) for n, square in zip(it.count(1), squares) )) for square in squares: square.n_hits = 0 self.add(squares, labels) # Run operation for n in range(1, len(squares) + 1): to_toggle = squares[n - 1::n] outlines = to_toggle.copy() squares.generate_target() for square in to_toggle: target = squares.target[squares.submobjects.index(square)] square.n_hits += 1 if square.n_hits % 2 == 0: target.set_fill(BLACK, 0) else: target.set_fill(BLUE, 0.5) outlines = to_toggle.copy() outlines.set_fill(opacity=0) outlines.set_stroke(YELLOW, 3) time_per_anim = min(2, 4 / n) self.play(Write(outlines, run_time=time_per_anim)) self.add(squares, labels) self.play( MoveToTarget(squares, lag_ratio=0.5), FadeOut(outlines), run_time=time_per_anim ) self.wait(time_per_anim) self.wait(3)
from manim_imports_ext import * def stereo_project_point(point, axis=0, r=1, max_norm=10000): point = fdiv(point * r, point[axis] + r) point[axis] = 0 norm = get_norm(point) if norm > max_norm: point *= max_norm / norm return point class StarryStarryNight(Scene): def construct(self): n_points = int(1e4) dots = DotCloud(np.random.random((n_points, 3))) dots.set_width(FRAME_WIDTH) dots.set_height(FRAME_WIDTH, stretch=True) dots.set_depth(FRAME_HEIGHT, stretch=True) dots.set_radius(0.25).set_glow_factor(5) dots.set_color(WHITE) dots.set_radii( 0.2 * np.random.random(dots.get_num_points())**3 ) frame = self.camera.frame frame.add_updater(lambda m, dt: m.increment_theta(0.02 * dt)) frame.reorient(-20, 80) self.add(frame) self.add(dots) self.play(dots.animate.apply_function(lambda p: 3 * normalize(p)), run_time=7) self.wait() self.play(dots.animate.apply_function(lambda p: stereo_project_point(p, r=3, axis=2)), run_time=7) self.wait() self.play( dots.animate.apply_complex_function(lambda z: z**2 / 5), run_time=7 ) self.play(Rotate(dots, PI / 2, UP, about_point=ORIGIN), run_time=5) self.play( dots.animate.apply_complex_function(np.exp), run_time=7 ) self.play(dots.animate.apply_function(lambda p: 3 * normalize(p)), run_time=10) self.wait(5) dots.generate_target() random.shuffle(dots.target.get_points()) dots.target.apply_function(lambda p: (10 + 100 * random.random()) * normalize(p)) self.play(MoveToTarget(dots, run_time=20)) self.embed()
from manim_imports_ext import * # Broken, but fixable class ImagesMod256(Scene): CONFIG = { } def construct(self): lion = ImageMobject("Lion") lion.set_height(6) lion.to_edge(DOWN) integer = Integer(1) expression = VGroup( OldTex("n \\rightarrow"), integer, OldTex("\\times n \\mod 256") ) expression.arrange(RIGHT) expression[-2:].shift(MED_SMALL_BUFF * RIGHT) integer.next_to(expression[-1], LEFT, SMALL_BUFF) expression.to_edge(UP) self.add(lion) self.add(expression) self.wait(0.5) self.remove(lion) total_time = 10 wait_time = 1.0 / 15 alpha_range = np.linspace(0, 1, int(total_time / wait_time)) for start, end in (1, 128), (128, 257): for alpha in ProgressDisplay(alpha_range): m = int(interpolate(start, end, smooth(alpha))) im = Image.fromarray(lion.pixel_array) new_im = Image.eval(im, lambda n: (n * m) % 256) alt_lion = ImageMobject(np.array(new_im)) alt_lion.replace(lion) self.add(alt_lion) new_int = Integer(m) new_int.next_to(expression[-1], LEFT, SMALL_BUFF) self.remove(integer) self.add(new_int) integer = new_int self.wait(1.0 / 15) self.remove(alt_lion) self.add(alt_lion) self.wait()
from manim_imports_ext import * class PowersOfTwo(Scene): def construct(self): max_n = 22 self.colors = [ [BLUE_B, BLUE_D, BLUE_C, GREY_BROWN][n % 4] for n in range(max_n) ] def update_group(group, alpha): n = int(interpolate(0, max_n, alpha)) group.set_submobjects([ self.get_label(n), self.get_dots(n), ]) label = self.get_label(0) dots = self.get_dots(0) for n in range(1, max_n + 1): new_label = self.get_label(n) new_dots = self.get_dots(n) self.play( FadeTransform(label, new_label), FadeTransform(dots, new_dots[0]), FadeIn(new_dots[1]), run_time=0.4, ) self.remove(dots) self.add(new_dots) self.wait(0.1) label = new_label dots = new_dots self.wait(2) def get_label(self, n): lhs = Tex("2^{", "10", "} =") exp = Integer(n) exp.match_height(lhs[1]) exp.move_to(lhs[1], LEFT) lhs.replace_submobject(1, exp) rhs = Integer(2**n) rhs.next_to(lhs, RIGHT) rhs.shift((lhs[0].get_bottom() - rhs[0].get_bottom())[1] * UP) result = VGroup(lhs, rhs) result.center().to_edge(UP) # result.set_x(-1, LEFT) return result def get_dots(self, n, height=6): if n == 0: result = self.get_marginal_dots(0) else: old_dots = self.get_dots(n - 1) new_dots = self.get_marginal_dots(n - 1) result = Group(old_dots, new_dots) for sm in result.get_family(): if isinstance(sm, DotCloud): sm.set_radius(0) if len(result) > 0: result[0].replace(result[1], stretch=True) radius = min(0.3 * height / (2**(int(np.ceil(n / 2)))), 0.1) buff = 1 if n % 2 == 0: result.arrange(DOWN, buff=buff) else: result.arrange(RIGHT, buff=buff) # result.set_height(min(1 + n / 2, 6)) result.set_width(min(1 + n / 2, 6)) result.move_to(0.5 * DOWN) for sm in result.get_family(): if isinstance(sm, DotCloud): sm.set_radius(radius) return result def get_marginal_dots(self, n): dots = DotCloud() rows = 2**(int(np.floor(n / 2))) cols = 2**(int(np.ceil(n / 2))) dots.to_grid(rows, cols) # dots.set_glow_factor(0.25) dots.set_color(self.colors[n]) dots.set_width(min(1 + n / 2, 10)) return dots
from manim_imports_ext import * def stereo_project_point(point, axis=0, r=1, max_norm=10000): point = fdiv(point * r, point[axis] + r) point[axis] = 0 norm = get_norm(point) if norm > max_norm: point *= max_norm / norm return point def sudanese_band_func(eta, phi): z1 = math.sin(eta) * np.exp(complex(0, phi)) z2 = math.cos(eta) * np.exp(complex(0, phi / 2)) r4_point = np.array([z1.real, z1.imag, z2.real, z2.imag]) r4_point[:3] = rotate_vector(r4_point[:3], PI / 3, axis=[1, 1, 1]) return stereo_project_point(r4_point, axis=0)[1:] def mobius_strip_func(u, phi): vect = rotate_vector(RIGHT, phi / 2, axis=UP) vect = rotate_vector(vect, phi, axis=OUT) ref_point = np.array([np.cos(phi), np.sin(phi), 0]) return ref_point + 0.7 * (u - 0.5) * vect def reversed_band(band_func): return lambda x, phi: band_func(x, -phi) def get_full_surface(band_func, x_range): surface = ParametricSurface( band_func, x_range, (0, TAU), ) surface.set_color(BLUE_D) surface.set_shadow(0.5) surface.add_updater(lambda m: m.sort_faces_back_to_front(DOWN)) # surface = TexturedSurface(surface, "EarthTextureMap", "NightEarthTextureMap") # surface = TexturedSurface(surface, "WaterColor") # inv_surface = ParametricSurface( # reversed_band(band_func), x_range[::-1], (0, TAU), # ) m1, m2 = meshes = VGroup( SurfaceMesh(surface, normal_nudge=1e-3), SurfaceMesh(surface, normal_nudge=-1e-3), ) bound = VGroup( ParametricCurve(lambda t: band_func(x_range[0], t), (0, TAU)), ParametricCurve(lambda t: band_func(x_range[1], t), (0, TAU)), ) bound.set_stroke(RED, 3) bound.apply_depth_test() meshes.set_stroke(WHITE, 0.5, 0.5) return Group(surface, m1, m2, bound) return Group(surface, bound) def get_sudanese_band(circle_on_xy_plane=False): s_band = get_full_surface( sudanese_band_func, (0, PI), ) angle = angle_of_vector(s_band[-1][0].get_start() - s_band[-1][1].get_start()) s_band.rotate(PI / 2 - angle) if circle_on_xy_plane: s_band.rotate(90 * DEGREES, DOWN) s_band.shift(-s_band[-1][0].get_start()) return s_band class SudaneseBand(ThreeDScene): circle_on_xy_plane = True def construct(self): frame = self.camera.frame frame.reorient(-45, 70) frame.add_updater( lambda m, dt: m.increment_theta(2 * dt * DEGREES) ) self.add(frame) s_band = get_sudanese_band(self.circle_on_xy_plane) m_band = get_full_surface(mobius_strip_func, (0, 1)) for band in s_band, m_band: band.set_height(6) # self.play(ShowCreation(m_band[0])) # self.play( # FadeIn(m_band[1]), # FadeIn(m_band[2]), # ShowCreation(m_band[3]), # ) self.add(m_band) self.wait() m_band.save_state() self.play( Transform(m_band, s_band), run_time=8, ) # self.wait() self.play(frame.animate.reorient(-30, 110), run_time=4) # self.play(frame.animate.reorient(-30, 70), run_time=3) self.wait(2) frame.clear_updaters() self.play( m_band.animate.restore(), frame.animate.reorient(-45, 70), run_time=8, ) # self.embed() class SudaneseBandToKleinBottle(ThreeDScene): def construct(self): frame = self.camera.frame frame.reorient(-70, 70) # frame.add_updater( # lambda m, dt: m.increment_theta(2 * dt * DEGREES) # ) # self.add(frame) s_band = get_sudanese_band() s_band[1:3].set_opacity(0) circ = s_band[-1] s_band.shift(-circ.get_center()) sb_copy = s_band.copy() self.add(s_band) self.play( Rotate(sb_copy, PI, axis=RIGHT, about_point=ORIGIN), run_time=4 ) self.play(frame.animate.reorient(360 - 70, 70), run_time=15) self.wait() self.embed()
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)
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)
#!/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)
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)
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)
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)
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)
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)
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)
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))
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)
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)
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", ] }
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)
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
#!/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)
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)
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)
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)
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, )
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)
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)
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)
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)
# -*- 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)
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)
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)
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)
#!/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()
""" 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)
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("3blue1brown@amplifypartners.com") 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)
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", ] }
""" 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